text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 25 22:05:19 2016 Neural network for digit classification (MNIST) Kaggle competition conv/conv/pool/dense/readout Backend is Tensorflow @author: dario """ # import the packages from keras.models import Sequential, load_model from keras.layers import Dense, Activation, Dropout, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.utils.np_utils import to_categorical #from keras.datasets import mnist import pandas as pd import numpy as np import matplotlib.pyplot as plt #%% # load the training data df_train = pd.read_csv('digit-recognizer/train.csv') y_train = df_train['label'].values X_train = df_train.drop('label', axis=1).values # load the test data df_test = pd.read_csv('digit-recognizer/test.csv') X_test = df_test.values # number of samples n_train, _ = X_train.shape n_test, _ = X_test.shape # dims of the pictures in pixels height = 28 width = 28 #%% reshaping # we have to preprocess the data into the right form # in this case it must be explicitly stated that it's only grayscale # otherwise for RGB pictures (n_train, height, width, 3) X_train = X_train.reshape(n_train, height, width, 1).astype('float32') X_test = X_test.reshape(n_test, height, width, 1).astype('float32') # confirm that reshaping worked by plotting one digit example pixels = X_train[9:10:,::,::] pixels = pixels.reshape(height,width).astype('float32') plt.imshow(pixels, cmap='gray') plt.show() # normalize from [0, 255] to [0, 1] X_train /= 255 X_test /= 255 # numbers 0-9, so ten classes n_classes = 10 # one-hot-encode the training labels y_train = to_categorical(y_train, n_classes) #%% Set up the neural network # number of convolutional filters (neurons) n_filters = 10 # convolution filter size # i.e. we will use a n_conv x n_conv filter n_conv = 5 # pooling window size # i.e. we will use a n_pool x n_pool pooling window n_pool = 2 # 2x2 reduces time for running model in half compared to 1x1 # build the neural network model = Sequential() # layer 1 model.add(Convolution2D( n_filters, n_conv, n_conv, # apply the filter to only full parts of the image # (i.e. do not "spill over" the border) # this is called a narrow convolution border_mode='valid', # we have a 28x28 single channel (grayscale) image # so the input shape should be (28, 28, 1) input_shape=(height, width, 1) )) model.add(Activation('relu')) # layer 2 model.add(Convolution2D(n_filters, n_conv, n_conv)) model.add(Activation('relu')) # layer 3: pooling model.add(MaxPooling2D(pool_size=(n_pool, n_pool))) model.add(Dropout(0.25)) # flatten the data for the 1D layers model.add(Flatten()) # Dense(n_outputs) model.add(Dense(50)) model.add(Activation('relu')) model.add(Dropout(0.5)) # softmax output layer gives probablity for each class model.add(Dense(n_classes)) model.add(Activation('softmax')) #%% compile model model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) #%% from keras.utils.visualize_util import plot plot(model, to_file='digit-recognizer/model.png') #%% fit the model with validation hist = model.fit(X_train, y_train, nb_epoch=5, validation_split=0.2, batch_size=32) print(hist.history) #save model to file model.save('digit-recognizer/model_kaggle.h5') #%% # Plot accuracy plt.plot(hist.history['acc']) plt.plot(hist.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() #%% # Plot loss plt.plot(hist.history['loss']) plt.plot(hist.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() #%% fit model without validation #model.fit(X_train, y_train, nb_epoch=10, batch_size=32) #%% evaluate on test data #loss, accuracy = model.evaluate(X_test, y_test) #print('loss:', loss) #print('accuracy:', accuracy) #%% predict #model = load_model('digit-recognizer/model_kaggle.h5') y_predict = model.predict(X_test, batch_size=32) df_predict = pd.DataFrame(y_predict) # each sample has 10 features df_predict = df_predict.idxmax(axis=1) # each sample has 1 feature (softmax) df_submit = pd.DataFrame() df_submit['ImageId'] = np.arange(1,28001) df_submit['Label'] = df_predict.astype(int) df_submit.to_csv('digit-recognizer/submission.csv', index=False)
import tkinter as tk from tkinter import messagebox from math import pi main_window = tk.Tk() main_window.title("Checkout System") CONTAINERS = ['Cube', 'Cuboid', 'Cylinder'] COLOURS = [ 'purple', 'DarkSlateGray4', 'deep sky blue', 'light sea green', 'VioletRed2', 'gold' ] CHEAP = 0.4 EXPENSIVE = 0.75 BOW = 1.5 CARD = 0.5 CARD_LETTER = 0.02 basket = {} bow = tk.IntVar() button_font = "default 12" gift_tag = tk.IntVar() gift_tag_text = tk.StringVar() no_of_items = tk.StringVar() paper_type = tk.StringVar() selection = tk.StringVar() selected_color = tk.StringVar() tag_text = '' total_cost_str = tk.StringVar() total_cost = 0.0 height_sv = tk.StringVar() width_sv = tk.StringVar() length_sv = tk.StringVar() diameter_sv = tk.StringVar() canvas_wh = 300 canvas = tk.Canvas(main_window, width=canvas_wh, height=canvas_wh) frame = tk.Frame(main_window) def create_main_window(): '''initialises the main window of the system''' selected_color.set(COLOURS[0]) # initialise variables paper_type.set('Cheap') total_cost_str.set('£0.00') no_of_items.set('0') title = tk.Label(main_window, text="Wrapping ordering system", font="default 16 bold") title.grid(column=0, row=0, columnspan=3, padx=10, pady=10) # column 1 & 2 selection.set(CONTAINERS[0]) selection_label = tk.Label(main_window, text="Please select which container the wrapping is for:", padx=10) selection_label.grid(column=0, row=1, columnspan=3) container_label = tk.Label(main_window, text="Container type:", padx=10) container_label.grid(column=0, row=2) container_om = tk.OptionMenu(main_window, selection, *CONTAINERS, command=create_form) container_om.grid(column=1, row=2, padx=10) paper_label = tk.Label(main_window, text="Paper type:") paper_label.grid(column=0, row=3) paper_om = tk.OptionMenu(main_window, paper_type, 'Cheap', 'Expensive', command=create_canvas) paper_om.grid(column=1, row=3) colour_label = tk.Label(main_window, text="Colour choice:") colour_label.grid(column=0, row=4) colour_om = tk.OptionMenu(main_window, selected_color, *COLOURS, command=create_canvas) colour_om.grid(column=1, row=4, padx=10) create_form() # column 3 canvas_label = tk.Label(main_window, text="Paper preview:") canvas_label.grid(column=3, row=1) canvas.grid(column=3, row=2, rowspan=10, padx=10) create_canvas() # column 4 add_button = tk.Button(main_window, text="Add to Basket", command=add_to_basket, font=button_font, padx=5, pady=5) add_button.grid(column=4, row=2, padx=20, pady=5) view_basket_button = tk.Button(main_window, text="View Basket", command=view_basket, font=button_font, padx=5, pady=5) view_basket_button.grid(column=4, row=3, padx=20, pady=5) print_button = tk.Button(main_window, text="Print Quote", command=print_quote, font=button_font, padx=5, pady=5) print_button.grid(column=4, row=4, padx=20, pady=5) # column 5 & 6 basket_label = tk.Label(main_window, text="Basket:") basket_label.grid(column=5, row=1, sticky=tk.W) no_label = tk.Label(main_window, text="Number of items:") no_label.grid(column=5, row=2, sticky=tk.W) items_label = tk.Label(main_window, textvariable=no_of_items) items_label.grid(column=6, row=2, sticky=tk.W) total_cost_lbl = tk.Label(main_window, text="Total cost:") total_cost_lbl.grid(column=5, row=3, sticky=tk.W) total_cost_label = tk.Label(main_window, textvariable=total_cost_str) total_cost_label.grid(column=6, row=3, sticky=tk.W) quit_button = tk.Button(main_window, text="Quit", font=button_font, command=main_window.quit, padx=5, pady=5) quit_button.grid(column=6, row=20, padx=10, pady=10) def add_to_basket(): '''gets container from form variables, calculates area and price, adds add-on elements to price and then adds item to basket dict''' noi = int(no_of_items.get()) # get variables from stringvars into ints try: height = float(height_sv.get()) width = float(width_sv.get()) length = float(length_sv.get()) diameter = float(diameter_sv.get()) except ValueError: # if value other than number input messagebox.showerror('Error', 'Inputs must be numbers') # show user error box return # and return to prevent further running if gift_tag.get(): tag_text = gift_tag_text.get() if not tag_text: messagebox.showerror('Gift tag text not set', 'You have selected a gift tag but given no text to put onto it. Please provide a message.') return # to prevent further running colour = selected_color.get() height_sv.set('0') # reset variables width_sv.set('0') length_sv.set('0') diameter_sv.set('0') bow_added = 'no' tag_added = 'no' tag_text = '' selected = selection.get() # get selection from selection dropdown if selected == CONTAINERS[0]: # cube wrapper_size = (height * 4 + 6) * (height * 3 + 6) elif selected == CONTAINERS[1]: # cuboid wrapper_size = ((height * 2) + width + 6) * ((length*2) + (height*2) + 6) elif selected == CONTAINERS[2]: # cylinder circumference = pi * diameter wrapper_size = (circumference + 6) * (height + (diameter*2) + 6) pt = paper_type.get() # get paper type from paper type dropdown if pt == 'Cheap': price = wrapper_size * CHEAP elif pt == 'Expensive': price = wrapper_size * EXPENSIVE price = price / 100 # convert to pounds if bow.get(): # if bow checkbox selected price += BOW bow_added = 'yes' bow.set(0) if gift_tag.get(): # if gift tag checkbox selected price += CARD price += len(tag_text) * CARD_LETTER tag_added = 'yes' gift_tag.set(0) gift_tag_text.set('') global total_cost total_cost += price total_cost_str.set(f'£{total_cost:.2f}') noi += 1 no_of_items.set(f'{noi}') basket.setdefault(f'Item {noi}', [ f'Price: £ {price:.2f}', f'Container Type: {selected}', f'Paper type: {pt}', f'Colour: {colour}', f'Bow: {bow_added}', f'Gift Card: {tag_added}', f'Card text: {tag_text}' ]) def create_canvas(*args): '''creates canvas for paper preview on user selection of paper type or colour''' canvas.delete('all') paper_selection = paper_type.get() if paper_selection == 'Cheap': draw_hexagon() elif paper_selection == 'Expensive': draw_triangles() def create_form(*args): '''initialises and switches form on user selection of container type''' global frame # use globally defined frame try: frame.destroy() # if frame already exists, destroy it to reset old form finally: pass # reset all variables to default values height_sv.set('0') width_sv.set('0') length_sv.set('0') diameter_sv.set('0') # reinitialise frame frame = tk.Frame(main_window) frame.grid(column=0, row=5, columnspan=2) selected_type = selection.get() # get the selected type for decision if selected_type == "Cube": height_label = tk.Label(frame, text="Height:") height_label.grid(column=0, row=0, padx=10) height_entry = tk.Entry(frame, textvariable=height_sv) height_entry.grid(column=1, row=0, padx=10, pady=10) elif selected_type == "Cuboid": height_label = tk.Label(frame, text="Height:") height_label.grid(column=0, row=0, padx=10) height_entry = tk.Entry(frame, textvariable=height_sv) height_entry.grid(column=1, row=0, padx=10, pady=10) width_label = tk.Label(frame, text="Width:") width_label.grid(column=0, row=1, padx=10) width_entry = tk.Entry(frame, textvariable=width_sv) width_entry.grid(column=1, row=1, padx=10, pady=10) length_label = tk.Label(frame, text="Length:") length_label.grid(column=0, row=2, padx=10) length_entry = tk.Entry(frame, textvariable=length_sv) length_entry.grid(column=1, row=2, padx=10, pady=10) elif selected_type == 'Cylinder': height_label = tk.Label(frame, text="Height:") height_label.grid(column=0, row=0, padx=10) height_entry = tk.Entry(frame, textvariable=height_sv) height_entry.grid(column=1, row=0, padx=10, pady=10) diameter_label = tk.Label(frame, text="Diameter:") diameter_label.grid(column=0, row=1, padx=10) diameter_entry = tk.Entry(frame, textvariable=diameter_sv) diameter_entry.grid(column=1, row=1, padx=10, pady=10) bow_label = tk.Label(frame, text="Bow needed:") bow_label.grid(column=0, row=3) bow_check = tk.Checkbutton(frame, variable=bow) bow_check.grid(column=1, row=3) tag_label = tk.Label(frame, text="Gift tag needed:") tag_label.grid(column=0, row=4) tag_check = tk.Checkbutton(frame, variable=gift_tag) tag_check.grid(column=1, row=4) tag_needed_label = tk.Label(frame, text="Gift tag text") tag_needed_label.grid(column=0, row=5) tag_entry = tk.Entry(frame, textvariable=gift_tag_text) tag_entry.grid(column=1, row=5) def draw_hexagon(): '''draws hexagon "cheap" wrapping paper in the canvas''' default_x_point = [0, 15, 45, 60, 45, 15] x_point = default_x_point y_point = [30, 0, 0, 30, 60, 60] offset = 60 fill = selected_color.get() for row in range(5): if row % 2 == 0: even_row = False columns = 5 else: even_row = True columns = 6 for x in range(columns): canvas.create_polygon( x_point[0], y_point[0], x_point[1], y_point[1], x_point[2], y_point[2], x_point[3], y_point[3], x_point[4], y_point[4], x_point[5], y_point[5], fill=fill, outline="black" ) x_point = [x + offset for x in x_point] if not even_row: x_point = [x - 45 for x in default_x_point] else: x_point = default_x_point y_point = [y + offset for y in y_point] def draw_triangles(): ''' draws triangle paper in the canvas ''' fill = selected_color.get() point1 = (0, canvas_wh) point2 = (canvas_wh / 2, 0) point3 = (canvas_wh, canvas_wh) for x in range(5): canvas.create_polygon( point1[0], point1[1], point2[0], point2[1], point3[0], point3[1], fill=fill, outline="black" ) point1 = ( (point1[0] + 30, point1[1]) ) point2 = ( (point2[0], point2[1] + 60) ) point3 = ( (point3[0] - 30, point3[1]) ) if fill == selected_color.get(): fill = "white" else: fill = selected_color.get() def print_quote(): '''creates or overwrites quote file with new information by iterating through basket dictionary''' if basket: # if basket has contents with open("quote.txt", "w+") as f: f.write('Quote: \n \n') for k, v in basket.items(): f.write(k + '\n \n') for value in v: f.write(value + '\n') f.write('\n') f.write(f'Total cost: £ {total_cost:.2f} pounds.' + '\n') vat = total_cost * 0.2 f.write(f'VAT: {vat:.2f}' + '\n') cost_w_vat = total_cost + vat f.write(f'Total cost (with VAT): {cost_w_vat:.2f}') messagebox.showinfo('Saved to file', 'Quote was saved to file "quote.txt" in main directory.') else: # basket must be empty, no point writing to file messagebox.showerror("Error", "There is nothing in the basket.") def view_basket(): '''creates new window with title and blank label, fills in contents of label by iterating basket dict''' if not basket: messagebox.showerror('Error', 'Basket currently empty.') return basket_contents = tk.StringVar() add_window = tk.Toplevel(main_window) add_window.title("Basket") title = tk.Label(add_window, text="Basket", font="default 16 bold") title.grid(column=0, row=0, padx=10) content = tk.Label(add_window, textvariable=basket_contents) content.grid(column=0, row=1, padx=50) for k, v in basket.items(): contents = basket_contents.get() contents = contents + '---\n' + k for value in v: contents = contents + '\n' contents = contents + value contents += '\n---' basket_contents.set(contents) create_main_window() main_window.mainloop()
def integer_number(): num_list = [] for i in range(1, 51): if i % 2 == 0: num_list.append(i) else: False # return num return num_list print(integer_number())
import random from tkinter import * import tkinter import math running = False sizeOfWindowX = 1000 sizeOfWindowY = 1000 linesEachSide = 600 firstCube = [] lastCube = [] currentCount = 0 lastMovedCubes = [] grid = [] walls = [] noSol = False foundIt = False pathPlaces = [] window = Tk() window.title("Graph Generator") window.resizable(False, False) mainCanvas = Canvas(window, width=sizeOfWindowX, height=sizeOfWindowY, background="gray") mainCanvas.pack() fInfo = Frame(window, width=200, height=sizeOfWindowY) fInfo.pack() creditLabel = Label(fInfo, text="Made By Ofek Grego").pack(side=tkinter.BOTTOM) def drawFirst(): global firstCube, lastCube, lastMovedCubes, grid, walls mainCanvas.delete("all") for n in range(linesEachSide): mainCanvas.create_line(0, n * sizeOfWindowY / linesEachSide, sizeOfWindowX, n * sizeOfWindowY / linesEachSide) grid.append([-1] * linesEachSide) for n in range(linesEachSide): mainCanvas.create_line(n * sizeOfWindowX / linesEachSide, 0, n * sizeOfWindowX / linesEachSide, sizeOfWindowY) while firstCube == lastCube: firstCube = [random.randint(0, linesEachSide - 1), random.randint(0, linesEachSide - 1)] lastCube = [random.randint(0, linesEachSide - 1), random.randint(0, linesEachSide - 1)] for n in range(round((linesEachSide * linesEachSide) / 3)): xAxe = random.randint(0, linesEachSide - 1) yAxe = random.randint(0, linesEachSide - 1) walls.append([xAxe, yAxe]) grid[xAxe][yAxe] = -5 lastMovedCubes = [firstCube] grid[firstCube[0]][firstCube[1]] = 0 grid[lastCube[0]][lastCube[1]] = -2 for n in walls: mainCanvas.create_rectangle(n[0] * sizeOfWindowX / linesEachSide, n[1] * sizeOfWindowY / linesEachSide, (n[0] + 1) * sizeOfWindowX / linesEachSide, (n[1] + 1) * sizeOfWindowY / linesEachSide, fill="#FFF") mainCanvas.create_rectangle(firstCube[0] * sizeOfWindowX / linesEachSide, firstCube[1] * sizeOfWindowY / linesEachSide, (firstCube[0] + 1) * sizeOfWindowX / linesEachSide, (firstCube[1] + 1) * sizeOfWindowY / linesEachSide, fill="#00FF00") mainCanvas.create_rectangle(lastCube[0] * sizeOfWindowX / linesEachSide, lastCube[1] * sizeOfWindowY / linesEachSide, (lastCube[0] + 1) * sizeOfWindowX / linesEachSide, (lastCube[1] + 1) * sizeOfWindowY / linesEachSide, fill="#FF0000") def drawUpdate(): for n in lastMovedCubes: mainCanvas.create_rectangle(n[0] * sizeOfWindowX / linesEachSide, n[1] * sizeOfWindowY / linesEachSide, (n[0] + 1) * sizeOfWindowX / linesEachSide, (n[1] + 1) * sizeOfWindowY / linesEachSide, fill="#444") if pathPlaces != []: for n in range(len(pathPlaces)): mainCanvas.create_rectangle(pathPlaces[n][0] * sizeOfWindowX / linesEachSide, pathPlaces[n][1] * sizeOfWindowY / linesEachSide, (pathPlaces[n][0] + 1) * sizeOfWindowX / linesEachSide, (pathPlaces[n][1] + 1) * sizeOfWindowY / linesEachSide, fill="#0000FF") def foundPath(xAxe, yAxe): global foundIt, pathPlaces foundIt = True currentWay = currentCount pathPlaces = [[xAxe, yAxe]] while (currentWay != 0): # X+ next = False if ((grid[pathPlaces[len(pathPlaces) - 1][0] - 1][pathPlaces[len(pathPlaces) - 1][1]] != -1) & (grid[pathPlaces[len(pathPlaces) - 1][0] - 1][pathPlaces[len(pathPlaces) - 1][1]] != -2) & (grid[pathPlaces[len(pathPlaces) - 1][0] - 1][pathPlaces[len(pathPlaces) - 1][1]] != -5) & (grid[pathPlaces[len(pathPlaces) - 1][0] - 1][pathPlaces[len(pathPlaces) - 1][1]] < currentWay) & (next == False)): pathPlaces.append([pathPlaces[len(pathPlaces) - 1][0] - 1, pathPlaces[len(pathPlaces) - 1][1]]) next = True # X- if (pathPlaces[len(pathPlaces) - 1][0] + 1 < linesEachSide): if (((grid[pathPlaces[len(pathPlaces) - 1][0] + 1][pathPlaces[len(pathPlaces) - 1][1]] != -1)) & (grid[pathPlaces[len(pathPlaces) - 1][0] + 1][pathPlaces[len(pathPlaces) - 1][1]] != -2) & (grid[pathPlaces[len(pathPlaces) - 1][0] + 1][pathPlaces[len(pathPlaces) - 1][1]] != -5) & (grid[pathPlaces[len(pathPlaces) - 1][0] + 1][pathPlaces[len(pathPlaces) - 1][1]] < currentWay) & (next == False)): pathPlaces.append([pathPlaces[len(pathPlaces) - 1][0] + 1, pathPlaces[len(pathPlaces) - 1][1]]) next = True # Y- if ((grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] - 1] != -1) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] - 1] != -2) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] - 1] != -5) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] - 1] < currentWay) & (next == False)): pathPlaces.append([pathPlaces[len(pathPlaces) - 1][0], pathPlaces[len(pathPlaces) - 1][1] - 1]) next = True # Y+ if (pathPlaces[len(pathPlaces) - 1][1] + 1 < linesEachSide): if ((grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] + 1] != -1) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] + 1] != -2) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] + 1] != -5) & (grid[pathPlaces[len(pathPlaces) - 1][0]][pathPlaces[len(pathPlaces) - 1][1] + 1] < currentWay) & (next == False)): pathPlaces.append([pathPlaces[len(pathPlaces) - 1][0], pathPlaces[len(pathPlaces) - 1][1] + 1]) next = True currentWay -= 1 print(pathPlaces) drawUpdate() def findLine(): global lastMovedCubes, currentCount, grid, noSol currentCount += 1 newLastMovedCubes = [] hasSoultion = False for n in range(len(lastMovedCubes)): # X- if (lastMovedCubes[n][0] != 0): if (grid[lastMovedCubes[n][0] - 1][lastMovedCubes[n][1]] == -5): do = False elif (grid[lastMovedCubes[n][0] - 1][lastMovedCubes[n][1]] == -2): foundPath(lastMovedCubes[n][0], lastMovedCubes[n][1]) hasSoultion = True break elif (grid[lastMovedCubes[n][0] - 1][lastMovedCubes[n][1]] == -1): grid[lastMovedCubes[n][0] - 1][lastMovedCubes[n][1]] = currentCount newLastMovedCubes.append([lastMovedCubes[n][0] - 1, lastMovedCubes[n][1]]) hasSoultion = True # X+ if (lastMovedCubes[n][0] != linesEachSide - 1): if (grid[lastMovedCubes[n][0] + 1][lastMovedCubes[n][1]] == -5): do = False elif (grid[lastMovedCubes[n][0] + 1][lastMovedCubes[n][1]] == -2): foundPath(lastMovedCubes[n][0], lastMovedCubes[n][1]) hasSoultion = True break elif (grid[lastMovedCubes[n][0] + 1][lastMovedCubes[n][1]] == -1): grid[lastMovedCubes[n][0] + 1][lastMovedCubes[n][1]] = currentCount newLastMovedCubes.append([lastMovedCubes[n][0] + 1, lastMovedCubes[n][1]]) hasSoultion = True # Y- if (lastMovedCubes[n][1] != 0): if (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] - 1] == -5): do = False elif (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] - 1] == -2): foundPath(lastMovedCubes[n][0], lastMovedCubes[n][1]) hasSoultion = True break elif (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] - 1] == -1): grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] - 1] = currentCount newLastMovedCubes.append([lastMovedCubes[n][0], lastMovedCubes[n][1] - 1]) hasSoultion = True # Y+ if (lastMovedCubes[n][1] != linesEachSide - 1): if (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] + 1] == -5): do = False elif (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] + 1] == -2): foundPath(lastMovedCubes[n][0], lastMovedCubes[n][1]) hasSoultion = True break elif (grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] + 1] == -1): grid[lastMovedCubes[n][0]][lastMovedCubes[n][1] + 1] = currentCount newLastMovedCubes.append([lastMovedCubes[n][0], lastMovedCubes[n][1] + 1]) hasSoultion = True lastMovedCubes = newLastMovedCubes if (hasSoultion == False): noSol = True drawUpdate() def untilFind(): global running if (noSol == False): running = True findLine() if (foundIt == False): print(" - " + str(currentCount)) print(str(len(lastMovedCubes)) + " Cubes") window.after(1, untilFind) else: print("No Sol..") drawFirst() def clickAction(event): global grid, walls if (running == False): if ((grid[math.floor(event.x / (sizeOfWindowX / linesEachSide))][ math.floor(event.y / (sizeOfWindowY / linesEachSide))] != -5)): if (grid[math.floor(event.x / (sizeOfWindowX / linesEachSide))][ math.floor(event.y / (sizeOfWindowY / linesEachSide))] != -2): if (grid[math.floor(event.x / (sizeOfWindowX / linesEachSide))][ math.floor(event.y / (sizeOfWindowY / linesEachSide))] != 0): grid[math.floor(event.x / (sizeOfWindowX / linesEachSide))][ math.floor(event.y / (sizeOfWindowY / linesEachSide))] = -5 walls.append([math.floor(event.x / (sizeOfWindowX / linesEachSide)), math.floor(event.y / (sizeOfWindowY / linesEachSide))]) mainCanvas.create_rectangle( math.floor(event.x / (sizeOfWindowX / linesEachSide)) * sizeOfWindowX / linesEachSide, math.floor(event.y / (sizeOfWindowY / linesEachSide)) * sizeOfWindowY / linesEachSide, (math.floor(event.x / (sizeOfWindowX / linesEachSide)) + 1) * sizeOfWindowX / linesEachSide, (math.floor(event.y / (sizeOfWindowY / linesEachSide)) + 1) * sizeOfWindowY / linesEachSide, fill="#FFF") else: grid[math.floor(event.x / (sizeOfWindowX / linesEachSide))][ math.floor(event.y / (sizeOfWindowY / linesEachSide))] = -1 mainCanvas.create_rectangle( math.floor(event.x / (sizeOfWindowX / linesEachSide)) * sizeOfWindowX / linesEachSide, math.floor(event.y / (sizeOfWindowY / linesEachSide)) * sizeOfWindowY / linesEachSide, (math.floor(event.x / (sizeOfWindowX / linesEachSide)) + 1) * sizeOfWindowX / linesEachSide, (math.floor(event.y / (sizeOfWindowY / linesEachSide)) + 1) * sizeOfWindowY / linesEachSide, fill="#888") mainCanvas.bind("<Button-1>", clickAction) runButton = Button(fInfo, text="Run!", command=untilFind).pack(side=tkinter.TOP) window.mainloop()
import math import os import random import re import sys def main(n): if n == 3: print('Weird') elif n == 5: print('Weird') elif n > 1 and n < 6: print('Not Weird') elif n >= 6 and n <= 20: print('Weird') elif n > 20 and n <= 28: print('Not Weird') elif n > 28 and n < 100: print('Weird') elif n >= 100: print('Not Weird') if __name__ == '__main__': n = int(input().strip()) main(n)
""" This module implements a simple function which discretizes point locations into images """ __author__="Igor Volobouev ([email protected])" __version__="0.2" __date__ ="Feb 25 2016" from numpy import zeros def imageArray2d(xSequence, ySequence, nx, xmin, xmax, ny, ymin, ymax): """ This function fills elements which correspond to point locations in a 2-d array with ones, for subsequent use with "imshow". Function arguments as follows: xSequence -- first coordinates of the points ySequence -- second coordinates of the points nx -- number of cells to use for discretizing the first coordinate xmin, xmax -- minimum and maximum values of the first coordinate. Points with coordinates outside this range will be ignored. ny -- number of cells to use for discretizing the second coordinate ymin, ymax -- minimum and maximum values of the second coordinate. Points with coordinates outside this range will be ignored. """ data = zeros((ny, nx)) x_image_width = (xmax - xmin)*1.0/nx y_image_width = (ymax - ymin)*1.0/ny for x, y in zip(xSequence, ySequence): ix = int((x - xmin)/x_image_width) iy = int((y - ymin)/y_image_width) if ix >= 0 and ix < nx and iy >= 0 and iy < ny: data[iy][ix] = 1.0 return data
""" This module provides a reasonably complete vector class for 3-d calculations. """ __author__="Igor Volobouev ([email protected])" __version__="0.5" __date__ ="Jan 29 2018" import math class V3: "Basic 3-d vector class." def __init__(self, x=0.0, y=0.0, z=0.0): # Use floats for internal representation self.x = x*1.0 self.y = y*1.0 self.z = z*1.0 def lengthSquared(self): "Spatial length of the vector, squared." return self.x*self.x + self.y*self.y + self.z*self.z def length(self): "Spatial length of the vector." return math.sqrt(self.lengthSquared()) def direction(self): "Direction of the vector as a 3-d vector with unit length." if (self.__nonzero__()): return self / self.length() else: return V3(1.0, 0.0, 0.0) def phi(self): "Azimuthal angle." return math.atan2(self.y, self.x) def cosTheta(self): "Cosine of the polar angle." if (self.__nonzero__()): return self.z/self.length() else: return 0.0 def theta(self): "Polar angle." cosTheta = self.cosTheta() if (math.fabs(cosTheta) < 0.99): return math.acos(cosTheta) else: # acos would loose too much numerical precision th = math.asin(math.sqrt((self.x*self.x + \ self.y*self.y)/self.lengthSquared())) if (cosTheta > 0.0): return th else: return math.pi - th def dot(self, other): "Scalar product with another vector, unit metric." return self.x*other.x + self.y*other.y + self.z*other.z def cross(self, other): "Cross product with another vector, unit metric." return V3(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def project(self, other): "Projection onto the direction of another vector." othermag2 = other.lengthSquared() assert othermag2 > 0.0 return other * (self.dot(other)/othermag2) def angle(self, other): "Angle between two vectors in radians." u = self.direction() v = other.direction() cosa = u.dot(v) if (math.fabs(cosa) < 0.99): return math.acos(cosa) else: # acos would loose too much numerical precision if (cosa > 0.0): return 2.0*math.asin(abs(v - u)/2.0) else: return math.pi - 2.0*math.asin(abs(-v - u)/2.0) def __repr__(self): return '(' + str(self.x) + ', ' + str(self.y) + \ ', ' + str(self.z) + ')' def __nonzero__(self): return int(self.x != 0.0 or self.y != 0.0 or self.z != 0.0) def __neg__(self): return V3(-self.x, -self.y, -self.z) def __pos__(self): # This is useful if one wants to get a copy of the object return V3(self.x, self.y, self.z) def __abs__(self): return self.length() def __eq__(self, other): return self.x == other.x and \ self.y == other.y and \ self.z == other.z def __ne__(self, other): return not (self.__eq__(other)) def __add__(self, other): return V3(self.x+other.x, self.y+other.y, self.z+other.z) def __sub__(self, other): return V3(self.x-other.x, self.y-other.y, self.z-other.z) def __mul__(self, other): return V3(self.x*other, self.y*other, self.z*other) def __rmul__(self, other): return self*other def __truediv__(self, other): if (other == 0.0): raise ZeroDivisionError("3-d vector divided by zero") return V3(self.x/other, self.y/other, self.z/other) # Mutators def __iadd__(self, other): self.x += other.x self.y += other.y self.z += other.z return self def __imul__(self, other): self.x *= other self.y *= other self.z *= other return self def __isub__(self, other): self.x -= other.x self.y -= other.y self.z -= other.z return self def __idiv__(self, other): if (other == 0.0): raise ZeroDivisionError("3-d vector divided by zero") self.x /= other self.y /= other self.z /= other return self
#!/usr/bin/env python3 # Created by: Jacob Bonner # Created on: September 2021 # This program draws a circle with a radius of 75 pixels import pygame # Importing the pygame library def main(): # This function will create a circle with a radius of 75 pixels # Initializing a surface object for the shapes to appear on (100 x 100) screen = pygame.display.set_mode((150, 150)) screen.fill((255, 255, 255, 255)) # Creating the circle pygame.draw.circle(screen, pygame.Color(0, 0, 0), (75, 75), 75) # Displaying the circle for a brief time pygame.display.update() pygame.time.delay(10000) if __name__ == "__main__": main()
class ListNode: def __init__(self, data=None, next=None, prev=None): """ A node in a doubly-linked list. """ self.data = data self.next = next self.prev = prev def __repr__(self): # 'toString' Impl return repr(self.data) class DoublyLinkedList: def __init__(self): """ Create a new doubly linked list. Takes O(1) time. """ self.head = None def __repr__(self): """ Return a string representation of the list. Takes O(n) time. """ result = [] curr = self.head while curr: result.append(repr(curr)) # using ListNode 'repr' curr = curr.next return '[' + ', '.join(result) + ']' def prepend(self, data=None): """ Insert a new element at the beginning of the list. Takes O(1) time. """ new_head = ListNode(data, next=self.head, prev=None) if self.head: self.head.prev = new_head self.head = new_head def append(self, data): """ Insert a new element at the end of the list. Takes O(n) time. """ if not self.head: self.head = ListNode(data, next=None) return curr = self.head while curr.next: curr = curr.next curr.next = ListNode(data, next=None, prev=curr) def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ curr = self.head while curr and curr.data != key: curr = curr.next return curr def remove(self, key): """ Unlink an element contains `key` from the list. Takes O(n) time. """ curr = self.head while curr and curr.data != key: curr = curr.next if curr and curr.prev: curr.prev.next = curr.next if curr and curr.next: curr.next.prev = curr.prev if curr and curr is self.head: self.head = curr.next if curr: curr.next = None curr.prev = None def remove2(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ elem = self.find(key) if not elem: return self.remove_item(elem) def remove_item(self, node: ListNode): """ Unlink an element from the list. Takes O(1) time. """ if node.prev: node.prev.next = node.next if node.next: node.next.prev = node.prev if node is self.head: self.head = node.next node.prev = None node.next = None def reverse(self): """ Reverse the list in-place. Takes O(n) time. """ if self.head is None or self.head.next is None: return curr_node = self.head prev_node = self.head.prev next_node = self.head.next while curr_node: next_node = curr_node.next curr_node.next = prev_node curr_node.prev = next_node prev_node = curr_node curr_node = next_node self.head = prev_node
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def __repr__(self): return str(self.value) class Queue: def __init__(self): self.first = None self.last = None self.length = 0 def __repr__(self): curr = self.first result = [] while curr: result.append(curr.value) curr = curr.next return str(result) def enqueue(self, value): new_node = Node(value) if self.first: self.last.next = new_node self.last = new_node self.length += 1 else: self.first = new_node self.last = new_node self.length = 1 def dequeue(self): if self.first: temp = self.first self.first = self.first.next self.length -= 1 return temp else: return None def peek(self): return self.first def isEmpty(self): return self.length == 0
from collections import deque from itertools import chain import numpy as np def windowed(seq, n, fillvalue=None, step=1): """Return a sliding window of width *n* over the given iterable. >>> all_windows = windowed([1, 2, 3, 4, 5], 3) >>> list(all_windows) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] When the window is larger than the iterable, *fillvalue* is used in place of missing values:: >>> list(windowed([1, 2, 3], 4)) [(1, 2, 3, None)] Each window will advance in increments of *step*: >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2)) [(1, 2, 3), (3, 4, 5), (5, 6, '!')] To slide into the iterable's items, use :func:`chain` to add filler items to the left: >>> iterable = [1, 2, 3, 4] >>> n = 3 >>> padding = [None] * (n - 1) >>> list(windowed(chain(padding, iterable), 3)) [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)] """ retlist = [] if n < 0: raise ValueError('n must be >= 0') if n == 0: # yield tuple() # return return retlist if step < 1: raise ValueError('step must be >= 1') it = iter(seq) window = deque([], n) append = window.append # Initial deque fill for _ in range(n): append(next(it, fillvalue)) # yield tuple(window) retlist.append(np.array(window)) # Appending new items to the right causes old items to fall off the left i = 0 for item in it: append(item) i = (i + 1) % step if i % step == 0: # yield tuple(window) retlist.append(np.array(window)) # If there are items from the iterable in the window, pad with the given # value and emit them. if (i % step) and (step - i < n): for _ in range(step - i): append(fillvalue) # yield tuple(window) retlist.append(np.array(window)) return np.array(retlist)
# Name:Javier Villalba # Date:9/26/19 # Period: # Lab: PythonLogic.py # Description: Write the 4 functions described below in comments # # Style - Code format, whitespace and PEP-8 style is followed making code easy to read. # Comments - Blocks of code are well commented, every function has a descriptive comment. # Tests - The program runs as described in the specifications without errors(passes all tests). # # The number 6 is great number. # Given two int values, a and b, return True if either one is 6. # Or if their sum or difference is 6. # Note: the function abs(num) computes the absolute value of a number. '''Your code below here''' def love_six(a: int, b: int): # Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a # boolean indicating if we are on vacation, return a string of the form "7:00" # indicating when the alarm clock should ring. Weekdays, the alarm should # be "7:00" and on the weekend it should be "10:00". # Unless we are on vacation -- then on weekdays it should be "10:00" and # weekend'''Your code below here'''s it should be "off" def alarm_clock(day: int, vacation: bool): return 1,2,3,4,5;7 0,6;10 bool;1,2,3,4,5;10 bool;0,6;"OFF" # For this problem, we'll round an int value up to the next multiple of 10 # if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, # round down to the previous multiple of 10 if its rightmost digit is less # than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of # their rounded values. # # To avoid code repetition, write a separate helper "def round10(num):" # and call it 3 times. Write the helper entirely below and at the same # indent level as round_sum(). def round_sum(a: int, b: int, c: int): '''Your code below here''' return # Given 3 int values, a b c, return their sum. However, if one of the values # is the same as another of the values, it does not count towards the sum. '''Your code below here''' def lone_sum(a: int, b:int, c: int): if lone_sum(): return # def main(): # '''Write some testing / debugging code here comment it out before submitting''' #main() #print(love_six (6,6)"should be true"
import numpy import os import random import movement def check_row(board): for row in board: size = len(row) for j in range(0,size-1): if row[j] == row[j+1]: return True return False def check_col(board): size = len(board[0]) for j in range(0,size-1): col = board[:,j] for k in range(0,size-1): if col[k] == col[k+1]: return True return False def init_board(size): board = numpy.zeros((size+1,size+1)) return board def select_size(): while True: try: os.system("clear") print "1.2x2 2.3x3 3.4x4, select any of the above board sizes" size = int(raw_input("Enter your option: ")) if (size < 4 and size >0): break else: continue except: print "Error!!!!!!!!!!!!" return size def spawn_num(board,size): empty_list = [] size = size +1 for j in range(size): for i in range(size): if board[j][i] == 0: empty_list.append((j,i)) length = len(empty_list) # print length # print empty_list if length < 1: if check_if_game_over(board): print board print "Game Over" quit() else: None elif length ==1: s = random.randint(1,3) element = empty_list[0] if s ==1: board[element[0]][element[1]] = 2 else: board[element[0]][element[1]] = 2 if check_if_game_over(board): print board print "Game Over" quit() else: None else: k = random.randint(1,length-1) print k s = random.randint(1,3) element = empty_list[k] if s ==1: board[element[0]][element[1]] = 2 else: board[element[0]][element[1]] = 2 def Movement(board,a): if a == 'w' or a == 'W': movement.board_up(board) elif a == 'S' or a == 's': movement.board_down(board) elif a == 'a' or a == 'A': movement.board_left(board) elif a == 'd' or a == 'D': movement.board_right(board) else: quit() def board_update(board): while True: try: os.system("clear") print board valids = ['w','s','a','d','W','S','D','A','q','Q'] a = raw_input(" Enter w (or) a (or) s (or) d:--> ") if a in valids: break else: continue except: pass Movement(board,a) print board def check_if_game_over(board): empty_list = [] size = len(board[0]) for j in range(size): for i in range(size): if board[j][i] == 0: empty_list.append((j,i)) length = len(empty_list) if length != 0: pass elif length == 0: if check_row(board) or check_col(board): pass else: os.system("clear") print board print "Game Over !!!!!!!!!!!!!!" quit() def main(): size = select_size() board = init_board(size) spawn_num(board,size) while True: board_update(board) spawn_num(board,size) check_if_game_over(board) print board if __name__ == "__main__": main()
""" para un juego que va a tener 20.000 planetas necesitamos formar nombres para cada uno de los planetas.Cres una lista con todos los posibles nombres de 3 silavas que se pueden formar con 10 consonantes y 5 vocales, de tal forma que cada letra sea seguida de una vocal y no se repita ninguna letra en cada uno de los nombres al final se mostrara 10 nombres de la lista a la zar y la cantidad de nombres que resultaron de este ejercicio """ import random consonantes = "cdbfljgtrkzq" vocales = "aeiou" nombres = [] for c1 in consonantes: for v1 in vocales: for c2 in consonantes: for v2 in vocales: for c3 in consonantes: for v3 in vocales: if c1 != c2 and c1 != c3 and c2 != c3 and \ v1 != v2 and v1 != v3 and v2 != v3: nombre = c1+v1+c2+v2+c3+v3 nombres.append(nombre) print("cantidad de nombres: {}".format(len(nombres))) for i in range(1,11): planeta = random.choice(nombres) print("nombre de el planeta: {} : {} ".format(i,planeta))
import time inicio = time.time() for i in range(11): for j in range(10): for f in range(10): print("{} {} {} ".format(i,j,f)) final = time.time() print("el adgoritmo tardo: ",final-inicio)
amigos = [["clara", 25], [ "sebastian", 19],["sergio", 32],["juan",27]] amigos.append(["sonia"]) amigos[4].append(1) for amigo in amigos: print("{} edad: {}".format(amigo[0],amigo[1])) print(amigos)
""" Cinco amigos van a hacer una carrera: Tomas, Maria, Laura, Miguel, Carlos Muestra todos los posibles resultados que se pueden dar en la carrera""" amigos = ["Tomas","Maria","Laura","Miguel","Carlos"] Contador = 0 for i in amigos: for j in amigos: for k in amigos: for m in amigos: for n in amigos: if i != j and i != k and i != m and i != n and \ j != k and j != m and j != n and \ k != m and k != n and m != n: resultado = [i,j,k,m,n] Contador += 1 print("{} : {}".format(Contador,resultado))
import urllib.parse import json import urllib.request #Consumer Key ZsamDKpuQn6SSr0BwKH4LkuTAKJfpCe2 #Consumer Secret Tdqlc6zcha6shcW1 def build_map_quest_url(list_of_locations: list)-> str: '''this function takes in the locations inputed in lets_begin and returns a URL the can be used in the API''' DIRECTIONS_MAPQUEST_URL = 'http://open.mapquestapi.com/directions/v2/route' API_KEY = 'ZsamDKpuQn6SSr0BwKH4LkuTAKJfpCe2' query_parameters = [] query_parameters.append(('key', API_KEY)) query_parameters.append(('from', list_of_locations[0])) for location in list_of_locations[1:]: query_parameters.append(('to', location)) #print(DIRECTIONS_MAPQUEST_URL + '?' + urllib.parse.urlencode(query_parameters)) return DIRECTIONS_MAPQUEST_URL + '?' + urllib.parse.urlencode(query_parameters) def read_url(url: str) ->dict: '''this function takes a url and returns a Python Dictionary representing the parsed Json response''' response = None try: response = urllib.request.urlopen(url) json_text = response.read().decode(encoding = 'utf-8') return json.loads(json_text) finally: if response != None: response.close() def build_elevation_url(route_info: dict)-> str: '''this function takes in LATLONG information from the mapquest api and builds elevation url''' ELEVATION_MAPQUEST_URL = 'http://open.mapquestapi.com/elevation/v1/profile' API_KEY = 'ZsamDKpuQn6SSr0BwKH4LkuTAKJfpCe2' query_parameters = [] key_parameters = [] key_parameters.append(('key', API_KEY)) key_parameters.append(('shapeFormat', 'raw')) for point in route_info['route']['locations']: latlng = (str(point['latLng']['lat']).split()) +(str(point['latLng']['lng']).split()) query_parameters += latlng location_string = (','.join(query_parameters)) key_parameters.append(('latLngCollection', location_string)) return ELEVATION_MAPQUEST_URL + '?' + urllib.parse.urlencode(key_parameters) class NoExistingRouteError(Exception): pass class MapQuestError(Exception): pass def check_error_type(route_info: dict): '''Determines error type by seeing the what status code appears in the mapquest api''' statuscode = route_info['info']['statuscode'] possible_errors = (601, 602, 604, 605, 606, 607, 608, 609, 610, 611, 612, 400, 401, 402, 403, 500) for codes in possible_errors: if codes == statuscode: raise NoExistingRouteError if statuscode != 0: raise MapQuestError
def exchange(x, y): y = x x = y return x, y a = 2 b = 3 a, b = exchange(a, b) print a, b
from gturtle import * def square(sidelength): repeat(4): forward(sidelength) right(90) makeTurtle() s = inputInt("Enter the side length") square(s)
from math import sin def sinc(x): y = sin(x) / x return y print sinc("python")
# Enter your code here. Read input from STDIN. Print output to STDOUT t = int(input()) for i in range(t): try: a,b = map(int, input().split()) print(a//b) except Exception as e: print("Error Code:", e)
def count_substring(string, sub_string): num = 0 check = True starting_index =0 while check: x = string.find(sub_string, starting_index) if x== -1: check = False else: num+=1 starting_index =x+1 return num if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
import re x = input() vowels = 'aeiouAEIOU' consonants = 'qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM ' ans = re.findall(r'(?<=[%s])([%s]{2,})[%s]'%(consonants,vowels,consonants),x) print('\n'.join(ans or ['-1']))
from searcher import Searcher from grid import Grid from math import sqrt class OrderedQueue(): def __init__(self, reverse : bool = False): self.reverse = reverse self._values = [] def __len__(self): return len(self._values) def append(self, item, value): try: self._values.remove((item, value)) except: pass self._values.append((item, value)) self._values.sort(key=lambda x: x[1], reverse=self.reverse) def pop(self): if len(self._values) == 0: return None value = self._values.pop(0) return value[0], value[1] def print(self): for index, value_score in enumerate(self._values): print(f"{index} - {value_score[1]} - {value_score[0]}") class AStar(Searcher): def __init__(self, grid : Grid): super().__init__(grid) self.queue = OrderedQueue() self.parents = {} self.queue.append(self.current_position, 0) # cost takes the base_cost (squares traveled) and then adds in # the estimated distance to the goal from the position def cost(self, location, base_cost): g_x, g_y = self.grid.goal x, y = location h_n = sqrt((g_x - x)**2 + (g_y - y)**2) return h_n def step(self): # If the queue is empty, there is no path if len(self.queue) == 0: raise Exception("Not path to the goal") current, cost = self.queue.pop() current_value = self.grid.get_value(current[0], current[1]) # If we reached the goal, we're done. Build the path if current_value == 'G': path = [current] while True: # If the cell is not the goal or robot, paint the path if current_value != 'G' and current_value != 'R': self.grid.set_value(current[0], current[1], 'P') # Set the "current" to the parent cell current = self.parents[current] current_value = self.grid.get_value(current[0], current[1]) path.append(current) # If we've reached the robot, escpae! if current_value == 'R': return path # current_cost is current_value with R being 0 if current_value is 'R': current_cost = 0 else: current_cost = current_value # Get each neighbor to this node and check their cost. # If they have a lower cost already associated we ignore the # neighbor. If the cost assigned is higher, we queue # the child and set the new parent to the current neighbors = self.grid.get_neighbors(current[0], current[1]) for neighbor in neighbors: value = self.grid.get_value(neighbor[0], neighbor[1]) if value in ['X', 'C', 'V', 'R']: continue # Since the goal is our target, if a neighbor is goal # we are just going to set that as the guaranteed next to # be processed and return here - we're almost done if value is 'G': self.queue.append(neighbor, -1) self.parents[neighbor] = current return # The cost to move to the next square is our # current_cost + 1. If the current_cost +1 is # equal to or more than the value already there if value is not 'O' and value < current_cost + 1: continue # estimated_cost is calculated by the cost function self.queue.append(neighbor, self.cost(neighbor, current_cost+1)) self.grid.set_value(neighbor[0], neighbor[1], current_cost+1) self.parents[neighbor] = current # We've added whatever children we could with updated # costs - return for now return
# class student: # def check_pass(self): # if self.marks>=40: # print("Passed") # elif self.marks<40: # print("Failed") # student1 = student() # student1.name="Hari" # student1.marks=80 # did_pass =student1.check_pass() # print(did_pass) # student2 = student() # student2.name="janet" # student2.marks = 30 # did_pass = student2.check_pass() # print(did_pass) # class Student(): # def __init__(self, name, marks): # self.name = name # self.marks = marks # # def check_pass(self): # if self.marks>=40: # return True # else: # return False # student1=Student("hary",80) # print(student1.name) # print(student1.marks) # did_pass = student1.check_pass() # print(did_pass) # student2=Student("Janet",39) # did_pass = student2.check_pass() # print(student2.name) # print(student2.marks) # print(did_pass)
from sys import argv script, user_name = argv #Notice though that we make a variable prompt that is set to the prompt we want, and we give #that to raw_input instead of typing it over and over. prompt = '$' print "HI I am %s, I'm the %s." % (user_name, script) print "I'd like to ask you afew questions." print "Do you like %s?" % (user_name) likes =raw_input(prompt) print "Where do you live %s?" % (user_name) lives = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print """ Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)
def is_leap(year): if year % 4 == 0 and (year % 400 == 0 or year % 100 != 0): return True else: return False def run(): leap_year = int(input('Ingrese un año: ')) if is_leap(leap_year): print('Año Bisciesto') else: print('Año no Bisciesto') if __name__ == "__main__": run()
def run(): numero = int(input('Ingrese el limite del conteo: ')) for i in range(numero,0,-1): print(i) if __name__ == "__main__": run()
def run(): numero = int(input('Ingrese el tamano del cuadrado: ')) for i in range(numero): for j in range(numero): print('#', end="") print() if __name__ == "__main__": run()
def run(): numero = int(input('Ingrese el tamano del trinagulo: ')) for i in range(numero): print('#'*i) for i in range(numero,0,-1): print('#'*i) if __name__ == "__main__": run()
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: 模块1 # Purpose: # # Author: Panywa # # Created: 29/12/2016 # Copyright: (c) Panywa 2016 # Licence: <your licence> #------------------------------------------------------------------------------- lista=[12,3,21,6,4,15] listb=[] print lista ##a = raw_input('Enter one integer') if 6 in lista: index = lista.index(6) print index lista.pop(index) lista.sort() for i in lista: if i>6: listb.append(i-1) else: listb.append(i) lista=listb print lista
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: 模块1 # Purpose: # # Author: 潘先生 # # Created: 26/12/2016 # Copyright: (c) 潘先生 2016 # Licence: <your licence> #------------------------------------------------------------------------------- def make_repeater(n): return lambda s:s*2 twice = make_repeater(2) print twice('word') print twice(5)
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: 模块1 # Purpose: # # Author: 潘先生 # # Created: 26/12/2016 # Copyright: (c) 潘先生 2016 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): lis1 = [2,6,3] lis2 = [2*i for i in lis1 if i>2] print lis2 #list for i in lis2: print i #int if __name__ == '__main__': main()
''' ====================== User inputs in Python ====================== We will use this file to write a simple program that let's user feed data to program ''' # print("Hello user,") # name = input("What can I call you?\n") # age = int(input("How old are you?\n")) # print("Hi %s, you are going to be %s next year" % (name, age+1)) # print("You just earned stars!") # print('*'*age) """ Well you can go creative with this function, and do many things from calculating how long the name is to building a biodata for the user. It is all upto you, but to do those we need to learn more. So once you have learnt the basics of python, you can come back to this file and add up features to the small program, go crazy. """ """ Let us see what happens if the user gave a wrong input for age. Like the user said 'Twenty One'. This ofcourse is a valid age when seen as and English statement. But we told python to interpret the input as an integer, but 'Twenty One' is not a valid integer. """ """ Python lets us hanlde unexpected/expected error without letting the program die. try: . . . except TheUnwantedExpectionClass: . . . Let know user if needed, gracefully handle the error Here the place where the error can occur is while python interprets the line No. 11 Let's wrap it inside a try/except. """ # print("Hello user,") # name = input("What can I call you?\n") # try: # age = int(input("How old are you?\n")) # except ValueError: # try: # age = int(input("How old are you (in numerics)?\n")) # except ValueError: # age = int(input("How old are you (in numerics, eg. 21)?\n")) # print("Hi %s, you are going to be %s next year" % (name, age+1)) # print("You just earned stars!") # print('*'*age)
# -*- coding: utf-8 -*- """ Created on Thu Nov 29 21:57:46 2018 #inspirado em: https://dev.to/mxl/dijkstras-algorithm-in-python-algorithms-for-beginners-dkc Referências: Caderno A first Look at Graphs Theory Python para Zumbis https://docs.python.org/3/tutorial/datastructures.html @CORMEN @author: MartManHunter """ def dijkstra(vertex, edges, pombal, vila_prado): #Edsger, not Sigismund. " black = set() #Conjunto ""visitado"" vazio" , black means visitei xparent = dict() #dicionário vazio" white = set({pombal}) #white means nao visitei distances = {pombal:0} while len(white) > 0: #enquanto houver alguem não visitado current = min([(distances[node],node) for node in white])[1] #relax, baby" if current == vila_prado: # menor caminho encontrado break #dance black.add(current) #senao achou, visita o node current e retira ele da lista de não visitados (obvio) white.remove(current) current_edges = edges[current] neighbors = [] #conjunto vazio de vizinhos. Seria meu sonho? for x in range(len(current_edges)): if not current_edges[x][0] in black: neighbors.append(current_edges[x]) for neighbor in neighbors: distance = distances[current] + neighbor[1] v = 10 if v > 110: mlt = (v-110) * 5 if distance < distances.get(neighbor[0], float('inf')): distances[neighbor[0]] = distance xparent[neighbor[0]] = current white.add(neighbor[0]) return distances[vila_prado] def main(): ### ### ### color_list = ["Red","Green","White" ,"Black"] xinput = input() (qtd_vertex,qtd_edges) = map(int,xinput.split()) vertex = list(range(qtd_vertex)) edges = {} color_list2 = ["Red","White" ,"Green","Black"] color_list3 = ["Red","White" ,"Black","Green"] color_list.remove("Red") color_list.remove("Black") color_list.remove("White") for i in range(qtd_edges): xinput = input() (origem,destino,peso) = map(int, xinput.split()) if origem in edges: edges[origem].append((destino,peso)) else: edges[origem] = [(destino,peso)] color_list3 = ["Red","Green","White" ,"Black"] color_list.remove("Green") color_list2.remove("Red") awnser = dijkstra(vertex,edges,0,len(vertex)-1) print(awnser) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # exemplo de uma função bastante simples def soma(a, b): return a + b; # exemplo de uma função um pouco mais complexa def fib(n): """ Descrição --------- Algoritmo iterativo para a sequência de Fibonacci. Entradas -------- n : um número inteiro positivo. """ i = 1 j = 0 for k in range(n): t = i + j i = j j = t return j
class Animal: #constructor def __init__(self, tipo): self.tipo = tipo def __setSangue__(self, s): self.sangue = s #quente ou frio def getSangue(self): print(self.sangue) def getTipo(self): print(self.tipo) class Pet(Animal): #constructor def __init__(self, nome, qtdPatas, somEleEmite): Animal.__init__(self,'Mamifero') Animal.__setSangue__(self,'quente') self.patas = qtdPatas self.som = somEleEmite self.name = nome def getName(): print(self.name) def getPatas(self): print(self.patas) def emitirSom(self): print(self.som) class Cao(Pet): def __init__(self, nome): Pet.__init__(self, nome, 4,'auau') class Gato(Pet): def __init__(self, nome): Pet.__init__(self, nome , 4,'meaw') Marie = Gato('Marie') Marie.emitirSom()
x = 6 #bad practice def example3(): global x x += 1 print(x) print(example3()) def example(): z = 5 print(z) print(example()) #best practice def example2(): z = 7 print(z) y = x + 1 print(y) print(example2()) x = example2() print(x)
from proof_stuff.source.data import cases from proof_stuff.source.proof_loops import prove_target_set, prove_1_to_1 for case in cases: case['upper'].substitute(n=case['n'], inplace=True) case['lower'].substitute(n=case['n'], inplace=True) big_sep = "\n" + 79*"#" + "\n" small_sep = 49*"*" print(big_sep) print(( "Checking the status of the statement " + "\n\t0 <= f(t,i) <= 2n for all f, t, i, in all cases" )) print(big_sep) for case in cases: print(small_sep) for k_form in case['k_forms']: print(30*'-') print(f"case n == {case['n']}, k == {k_form}") prove_target_set(case, k_form) print(big_sep) print(( "Checking the status of the statement " + "\n\tf1(t,i) == f2(t, j) for all f1, f2, t, i, j, in all cases" )) print(big_sep) for case in cases[:]: print(small_sep) for k_form in case['k_forms']: print(30 * '-') print(f"case n == {case['n']}, k == {k_form}") prove_1_to_1(case, k_form) print("Press Enter to exit.") input()
''' -find how many digits are in a given number -find a digit --raise number to the power -Find some of the powered digits -Compare final number to input number ''' def is_armstrong(number): print(number) strnumber = str(number) numberofdigits = len(strnumber) sum = 0 for strdigit in strnumber: digit = int(strdigit) sum = sum + (digit**numberofdigits) if(sum == (int(strnumber))): return True else: return False def generate_armstrong_numbers(highend): for x in range(highend): armstrong = is_armstrong(x) if(armstrong == True): print(str(x) + " Armstrong number. ") generate_armstrong_numbers(1000000000000000)
students=["Engel","Slosar","Boas","Spice" ] students.append(input("enter student")) print(students) students.append(input("enter student")) print(students) gpas = [4,5.4,5.4,4.5,4.7] print (gpas[3]) message = "The Quick Brown Fox Jumped Over The Fence" print(message) words = message.split() print(words) lines = "-".join(words) print(lines)
import random number = input("Enter Number:") number = int(number) answer = random.randint(0,25) while(number > answer): print("Too High") number = input("enter a number:") number = int(number) if(number > answer): print("Too High") elif(number < answer): print("Too Low") else: print("You got it") if(number < answer): print("Too low") number = input("Enter a number") number = int(number) if(number > answer): print("Too High") elif(number < answer): print("Too low") else: print("That's it") else: print("That's it") print(answer)
import sys import urllib.request import os #First Exercise 1 argList = sys.stdin.readline() print(argList) count = 1 def download(url, counter): print ("\n") print ("Downloading Item Number: ", (counter)) urlSplit = os.path.basename(url) urlSplit = urlSplit[:-1] print ("File will be named: ",urlSplit) print("Download Path: ", os.path.abspath(urlSplit)) urllib.request.urlretrieve(url, urlSplit) print ("Item number",counter, "finished\n") counter += 1 download(argList, count) # python download_script.py http://www.gutenberg.org/files/2701/2701-0.txt http://www.gutenberg.org/cache/epub/27525/pg27525.txt
#!/bin/python3 S = input() for x in ['isalnum', 'isalpha', 'isdigit', 'islower', 'isupper']: print(any(getattr(y,x)() for y in S))
#!/usr/local/bin/python3 import xml.etree.ElementTree as etree n = int(input()) lis = '' count = 0 for i in range(n): lis += input() tree = etree.fromstring(lis) for i in tree.iter(): count += len(i.attrib) print(count)
#!/bin/usr/python3 import datetime testcase = int(input()) for i in range(testcase): time1 = input().strip() time2 = input().strip() timeformat = "%a %d %b %Y %H:%M:%S %z" t1 = datetime.datetime.strptime(time1, timeformat) t2 = datetime.datetime.strptime(time2, timeformat) print(int(abs(t1 - t2).total_seconds()))
#!/usr/bin/python a = int(input()) b = int(input()) c = int(input()) d = int(input()) result = 0 power1 = 1 power2 = 1 for i in range(0,b): power1 = long(power1 * a) for i in range(0,d): power2 = long(power2 * c) result = long(power1 + power2) print (result)
# Enter your code here. Read input from STDIN. Print output to STDOUT from math import sqrt, acos, degrees AB = int(raw_input()) BC = int(raw_input()) AC = sqrt((AB * AB) + (BC * BC)) AM = AC / 2.0 print str(int(round(degrees(acos((BC/2.0)/AM))))) + "°"
class Car: def __init__(self, make, model, year, color): self.make = make self.model = model self.year = year self.color = color def carFacts(self): facts = "\nMake: {}\nModel: {}\nColor: {}\nYear: {}\n".format(self.make,self.model,self.color,self.year) return facts class Truck(Car): def __init__(self, make, model, year, color, bed_length, cab): super().__init__(make, model, year, color) self.bed_length = bed_length self.cab = cab def carFacts(self): facts = "\nMake: {}\nModel: {}\nColor: {}\nYear: {}\nBed Length: {}\nCab Type: {}\n".format(self.make,self.model,self.color,self.year,self.bed_length,self.cab) return facts class Bus(Car): def __init__(self, make, model, year, color, length, capacity): super().__init__(make, model, year, color) self.length = length self.capacity = capacity def carFacts(self): facts = "\nMake: {}\nModel: {}\nColor: {}\nYear: {}\nLength: {}\nCapacity: {}\n".format(self.make,self.model,self.color,self.year,self.length,self.capacity) return facts if __name__ == "__main__": car = Car('toyota','prius',2010,'silver') print(car.carFacts()) truck = Truck('toyota','tacoma',2015,'grey','6 foot','access cab') print(truck.carFacts()) bus = Bus('bluebird','all american',2013,'yellow','35 feet',90) print(bus.carFacts())
""" Simple genetic algorithm class in Python TODO: - INSTRUCTIONS (note that genemax is INCLUSIVE) - Multithread fitness evaluation - Errors shouldn't call exit - use exceptions - Parameterise everything (max age, individuals to keep on reset) - Variable length chromosomes - More crossover, mutation and selection methods - Parallel fitness evaluations - Reinsert best into population when resetting? - Save progress and current configuration in a different file (not log) that can be loaded directly from the class to continue the search (pickle?) """ from sys import exit import copy import numpy as np class GA: def __init__(self, max_population, chromlength, mutation_probability=0.01, mutation_strength=0.1, selection_percentage=0.2, genemin=-1.0, genemax=1.0, init_pop=None, genetype=float, logfile="quickga.log"): self.max_population = max_population self.mutation_probability = mutation_probability self.mutation_strength = mutation_strength self.selection_percentage = selection_percentage self.chromlength = chromlength self.genebounds = (genemin, genemax) self.population = init_pop self.genetype = genetype self.logfile = open(logfile, 'w') if issubclass(self.genetype, bool): exit("NOT IMPLEMENTED: Boolean gene types not implemented yet") if self.population is None: self.population = [] self.init_population() def init_population(self): del(self.population) self.population = [] low, high = self.genebounds if issubclass(self.genetype, float): randfunc = lambda size: np.random.random(size)*(high-low)+low elif issubclass(self.genetype, int): randfunc = lambda size: np.random.randint(low, high+1, size) elif issubclass(self.genetype, bool): exit("NOT IMPLEMENTED: Boolean gene types not implemented yet") for p in range(self.max_population): randchrom = randfunc(self.chromlength) newind = self.Individual(randchrom, 0) self.population.append(newind) def fitnessfunc(self): """ Calculates the fitness value of an individual, stores it in the individual's `fitness` member and returns it. This function is the target function to be optimised by the GA. This function should be overwritten by any implementation of the class. TODO: This could be done better. Have the storing and returning parts coded in the function and have another function, `evaluate` the fitness of an arbitrary chromosome, with no connection to the classes in this file. """ def evaluate_population(self, optargs): """ Updates the fitness values of the population, for all individuals flagged as unevaluated. """ for ind in self.population: if ind.fitness is None: self.fitnessfunc(ind, *optargs) def sort_population(self, optargs): """ Sorts the population based on fitness values such that the first individual is the best in the population. This method first calls the `evaluate_population` method to calculate the fitness values of any unevaluated individuals """ self.evaluate_population(optargs) self.population.sort(key=lambda individual: individual.fitness) def crossover(self, parent_one, parent_two): """ Two-point crossover. """ parchrom_one = copy.deepcopy(parent_one.chromosome) parchrom_two = copy.deepcopy(parent_two.chromosome) if parent_one.chromlength != parent_two.chromlength: exit("ERROR: Chromosome lengths don't match. " "Skipping crossover.") cutpoint_one = cutpoint_two = 0 chromlength = parent_one.chromlength cutpoints = np.random.choice(range(chromlength), 2, replace=False) cutpoint_one = min(cutpoints) cutpoint_two = max(cutpoints) childchrom_one = np.append(parchrom_one[0:cutpoint_one], parchrom_two[cutpoint_one:cutpoint_two]) childchrom_one = np.append(childchrom_one, parchrom_one[cutpoint_two:]) childchrom_two = np.append(parchrom_two[0:cutpoint_one], parchrom_one[cutpoint_one:cutpoint_two]) childchrom_two = np.append(childchrom_two, parchrom_two[cutpoint_two:]) if childchrom_one.size != childchrom_two.size: exit("ERROR: Child chromosome lengths don't match." " This shouldn't happen") if not (childchrom_one.size == parchrom_one.size == childchrom_two.size == parchrom_two.size): exit("ERROR: Chromosome lengths changed during crossover") # Turn childchroms into individuals # Childrens' generation will be youngest parent's gen+1 child_gen = max(parent_one.generation, parent_two.generation)+1 newind_one = self.Individual(childchrom_one, child_gen) newind_two = self.Individual(childchrom_two, child_gen) return newind_one, newind_two def mutate(self, individual): """ Mutates each gene of an individual's chromosome in place, based on the `mutation_probability`. Mutation applies a Gaussian random value drawn from distribution with mean 0 and `stdev = mutation_strength` Integer genes get rounded to the nearest int. """ try: genetype = self.genetype randvars = np.random.random_sample(self.chromlength) mutation_value = np.random.normal(0, self.mutation_strength, self.chromlength) newchrom = individual.chromosome +\ mutation_value*(randvars < self.mutation_probability) newchrom = np.clip(newchrom, *self.genebounds) if issubclass(individual.chromosome.dtype.type, int): newchrom = np.round(newchrom) individual.chromosome = newchrom.astype(genetype) individual.fitness = None # mark fitness as 'unevaluated' except (TypeError, AttributeError): exit("ERROR: (Mutation) Invalid chromosome type. " "Must be numpy float or int array.") def insert(self, *newinds): """ Inserts the new individuals into the population. If the population exceeds the max_population limit, the worst individuals from the original population is discarded. Assumes the population is evaluated and sorted. """ newpopsize = len(newinds)+len(self.population) overflow = newpopsize - self.max_population if overflow > 0: self.population = self.population[:-overflow] self.population.extend(newinds) def select(self, method): """ Currently selects individuals randomly for recombination. Later it will implement several methods for other selection methods. """ if method == 'rand': r1 = r2 = 0 popsize = len(self.population) while r1 == r2: r1 = int(round(np.random.random()*(popsize-1))) r2 = int(round(np.random.random()*(popsize-1))) return self.population[r1], self.population[r2] elif method == 'best': return self.population[0], self.population[1] elif method == 'roulette': # TODO: Print to stderr print("WARNING: Roulette-wheel selection not yet implemented. " "Falling back to random selection.") return self.select('rand') else: exit("ERROR: Invalid selection method") def printprogress(self, gen, bestind, alltime_bestind): self.logfile.write( "Generation %i\n" "Best individual of cur gen:\n" "%s\n" "Best individual so far:\n" "%s\n" "---\n" % (gen, bestind, alltime_bestind)) def optimise(self, num_generations, *optargs): """ Starts the optimisation, i.e., runs the GA loop. Stops after `num_generations`. Any subsequent arguments after `num_generations` will be passed on to the fitness function as supplied. """ self.sort_population(optargs) # copy 0 to initialise the variables bestind = copy.deepcopy(self.population[0]) bestind_age = 0 # alltime_bestind holds the best individual for when the population is # reset self.alltime_bestind = copy.deepcopy(self.population[0]) for gen in range(num_generations): p1, p2 = self.select('rand') c1, c2 = self.crossover(p1, p2) self.mutate(c1) self.mutate(c2) self.fitnessfunc(c1, *optargs) self.fitnessfunc(c2, *optargs) self.insert(c1, c2) self.sort_population(optargs) curbest = copy.deepcopy(self.population[0]) if curbest.fitness < self.alltime_bestind.fitness: self.alltime_bestind = copy.deepcopy(curbest) if curbest.fitness == bestind.fitness: # could use the actual chromosome instead of just fitness bestind_age += 1 else: bestind_age = 0 bestind = copy.deepcopy(curbest) if gen % 100 == 0: # TODO: Parameterise reporting interval self.printprogress(gen, bestind, self.alltime_bestind) print("Generation %i\nBest fitness: %f (all time best: %f)\n" % ( gen, bestind.fitness, self.alltime_bestind.fitness)) if bestind_age > 4000: # arbitrary age limit (TODO: Parameterise) # Recreate entire population, except best individual # TODO: Also parameterise number of individuals to keep when # resetting print("Age limit reached. Re-initializing population\n") self.logfile.write("Age limit reached. " "Re-initializing population.\n\n") self.init_population(self.max_population, self.chromlength) self.printprogress(gen, bestind, self.alltime_bestind) print("Final generation\nBest individual fitness:\n%f\n" % bestind.fitness) self.logfile.close() class Individual: def __init__(self, chrom, gen): self.chromosome = chrom self.generation = gen self.chromlength = chrom.size self.fitness = None # marks fitness as 'unevaluated' def __len__(self): """Length of Individual is simply length of chromosome""" return len(self.chromosome) def __repr__(self): stringrep = "Chromosome: " stringrep += ", ".join(str(c) for c in self.chromosome) if self.fitness is not None: stringrep += " Fitness: %f" % self.fitness else: stringrep += " <Unevaluated>" return stringrep def __eq__(self, other): """ Equality operator checks chromosomes for all() equality. """ return np.all(self.chromosome == other.chromosome)
#!/usr/bin/env python # -*- coding: utf-8 -*- for i in range(1, 101): result = "" if i % 3 == 0: result += "Fizz" if i % 5 == 0: result += "Buzz" print(result or i)
# -*- coding: utf-8 -*- """ Created on Sun Jan 1 11:53:43 2017 @author: Robert """ import random count= 0 checklist = ['heads','heads','heads','heads','heads','heads','heads','heads','heads','heads'] result = [] def addtolist(dict): dict.append(random.choice(['heads','tails'])) global count count += 1 return count for i in range(10): addtolist(result) while result != checklist: del result[:] for i in range(10): addtolist(result) if result == checklist: break print(result) print('Number of attempts to get 10 heads in sequence: '+(str(count))) lottonumbers = [] for i in range(52): lottonumbers.append(random.randint(1,53)) print('For lotto numbers:') userinput = [int(x) for x in input('Enter 6 random digits between 1 and 52 to see how many you got right: ').split()] #userinput=input('Enter 6 random digits between 1 and 52 to see how many you got right: ') lottocount=0 def check_for_matches(input): global lottocount for k in input: #print(k) if k in lottonumbers: lottocount+=1 check_for_matches(userinput) print(lottocount) lottoattempts=0 def new_lottonumbers(list): for i in range(53): global lottoattempts list.append(random.randint(1,53)) lottoattempts+=1 return lottoattempts if set(userinput)<set(lottonumbers): del lottonumbers[:] print('lottonumber should now be empty') print(lottonumbers) new_lottonumbers(lottonumbers) print('lottonumbers should now be full'+(str(lottonumbers))) print('Number of times played to get a 6 number match: '+ (str(lottoattempts)))
inventory = {'rope': 1, 'torch': 4, 'gold coin': 9, 'dagger': 2, 'arrow': 12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin' 'ruby'] print('Inventory:') def addToInventory(): for k, v in inventory.items(): for i in range(len(dragonLoot)): # findCount = 0 #i = dragonLoot if i in inventory.keys(): print ('True') #inventory.update(dragonLoot) else: print ("false") #inventory.update(dragonLoot) # inventory.values = inventory.values + (int(1)) # findCount += 1 #if findCount == 0: #inventory.values = 1 #inventoryUpdated = dict(inventory.items() + dragonLoot.item()) #if dragonLoot.items not in inventory.items(): # print ('inventory needs to be updated') #addToInventory() for k,v in inventory.items(): print (str(v)+' ' +k) sum = sum(inventory.values()) print (('Total number of items:')+' '+(str(sum))) answer = input('Add Dragon Loot to inventory? Yes or no? ') if answer == 'yes' or 'Yes': addToInventory() print ('Updated Inventory:') for k,v in inventory.items(): print (str(v)+' ' +k) else: print ('failed for some reason') #print ('this should launch the function')
# lettercount.py # A Python script that counts every letter in a given text. # http://www.meganspeir.com # # Copyright (C) 2013 Megan Speir. All rights reserved. # # Licensed under The BSD 3-Clause License. You may not use this file except # in compliance with the License. You may obtain a copy of the License at # http://opensource.org/licenses/BSD-3-Clause from sys import argv script, inputfile = argv #opens file from input f = open(inputfile) filetext = f.read() f.close() #initializes list with default value 0 alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] lettercount = [0] * 26 #loop through filetext to count char for char in filetext.lower(): if char in alphabet: index = alphabet.index(char) lettercount[index] += 1 for count in lettercount: print count
stack = 5*[float("inf")] n = int(input('Введите число N: ')) lst = list(map(int, input('Введите N чисел: ').split())) for i in range(len(lst)): #adding elements if max(stack) > lst[i]: stack += [lst[i]] stack.sort() if len(stack) > 5: stack.pop() #print for j in range(len(stack)-1, -1, -1): if stack[j] != float("inf"): print(stack[j], end=' ') print()
def euclides_mdc(dividendo, divisor): #maximo divisor comum pelo metodo de euclides while divisor != 0: temp = divisor divisor = dividendo % divisor dividendo = temp return dividendo def euclides_recursivo_mdc(dividendo, divisor): if divisor == 0: return dividendo else: return euclides_recursivo_mdc(divisor, dividendo % divisor) n = int(input()) for i in range(n): entrada = input() num = entrada.split(" ") a = euclides_recursivo_mdc(int(num[0]),int(num[1])) for i in range(int(num[0])+1,int(num[1])): if(i<int(num[0])+10): a = euclides_recursivo_mdc(a,i) else: break print(a)
import os import csv budget_csv = os.path.join('Resources', 'budget_data.csv') #budget_csv = os.path.join('..', '..', '..', '..', 'columbia', 'myWork', 'homework', '03-Python', 'Instructions', 'PyBank', 'Resources', 'budget_data.csv') with open(budget_csv, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # Skip header. next(csvreader) # Variables to calculate. num_months = 0 total_amount = 0 total_delta = 0 max_delta = 0 min_delta = 0 max_month = 'month' min_month = 'month' last_row_value = None # Loop through the data for row in csvreader: if last_row_value is None: last_row_value = int(row[1]) delta = int(row[1]) - last_row_value total_delta = total_delta + delta num_months = num_months + 1 total_amount = total_amount + int(row[1]) max_delta = max(max_delta, delta) if delta == max_delta: max_month = row[0] min_delta = min(min_delta, delta) if delta == min_delta: min_month = row[0] # Loop end print("Financial Analysis") print("-----------------------") print(f"Total Months: {num_months}") print(f"Total: ${total_amount}") print("Average change = ", total_delta / (num_months - 1)) print(f"Greatest Increase in Profits: {max_month} (${max_delta})") print(f"Greatest Decrease in Profits: {min_month} (${min_delta})")
words = "It's Thanksgiving day. It's my birthday, too!" print words.find("day") print words.replace("day", "month") x = [2, 54, -2, 7, 12, 98] max = 0; min = 0; for n in range(0, len(x)): if max < x[n]: max = x[n] if min > x[n]: min = x[n] print "max: ", max print "min: ", min y = ["hello", 2, 43, 4, 563465, "apex", ["grapes", "Zenith"]] print "first: ", y[0] print "second: ", y[-1] new = [y[0], y[-1]] print new x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x new1 = x[:len(x)/2] print new1 new2 = x[len(x)/2:] newArr = [new1] print newArr + new2 #**************************************# for i in range(1, 1001): if i%2 != 0: print i for j in range(5, 101): if j%5 == 0: print j a = [1, 2, 5, 10, 255, 3] add = 0 for i in range (0, len(a)): add += a[i] print add avg = add/len(a) print avg sI = 45 mI = 100 bI = 455 eI = 0 spI = -23 sS = "Rubber baby buggy bumpers" mS = "Experience is simply the name we give our mistakes" bS = "Tell me and I forget. Teach me and I remember. Involve me and I learn. Touch me, and I'll kill ya." eS = "" aL = [1,7,4,21] mL = [3,5,7,34,3,2,113,65,8,89] lL = [4,34,22,68,9,13,3,5,7,9,2,12,45,923] eL = [] spL = ['name','address','phone number','social security number'] def typeCast (x): if isinstance(x, int): if x >= 100: print "Why, that's huge!" else: print x, "is so small, sorry honey." elif isinstance(x, str): print x, "is a string, sweetheart" else: print x, "is a list, baby." typeCast(spI) typeCast(bS) typeCast(mL) #input # l = ['magical unicorns',19,'hello',98.98,'world'] l = [2,3,1,7,4,12] # l = ['magical','unicorns'] string = 0 integer = 0 sumOfIntegers = 0 sumOfString = 0 for i in range(0, len(l)): if isinstance(l[i], str): string += 1 if isinstance(l[i], int): integer += 1 sumOfIntegers += l[i] if isinstance(l[i], float): sumOfIntegers += float(l[i]) if string == len(l): print "YOUR INPUT IS ALL STRINGS, DARLIN'." print elif integer == len(l): print "YOUR INPUT IS ALL NUMBERS, BABY." print "The sum of which is: ", sumOfIntegers else: print l, "IS A MIXED BAG, HONEY." print "The sum of which is: ", sumOfIntegers # **************************************************# print 80*"*" list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] same = True for i in range(0, len(list_one)): if len(list_one) != len(list_two): same = False elif list_one[i] != list_two[i]: same = False print same print 80*"*" # **************************************************# word_list = ['hello','world','my','name','is','Anna'] new_list = [] char = 'o' # output # def find_char (list, char): for i in list: if char in i: new_list.append(i) print new_list find_char (word_list, char) for j in range (1, 11): if j%2 == 0: print " ****" else: print "****" print 80*"*" def mult_table(col): table = [] n = 1 for i in range (n, col+n): if i < 10: sp = " " elif i > 10: sp = " " table.append (sp + str(i)) print " x", table table = [] n = 1 for j in range (n, col+1): for i in range (1, col+1): if i*n < 10: sp = " " elif i*n > 9: sp = " " elif i*n > 99: sp = [] table.append(sp + str(i*n)) if n < 10: sp = " " print sp + str(n), table table = [] n += 1 mult_table(12) # def prime (num): for i in range (100, 10001): for k in range (2, i/2): if i%k == 0: yes = False
import datetime as d # classes class Business: def __init__(self, name, franchises): self.name = name self.franchises = franchises class Franchise: def __init__(self, address, menus): self.address = address self.menus = menus def __repr__(self): return "The address of the restaurant is " + self.address def available_menus(self, time): result = [] for menu in self.menus: if menu.start_time <= d.time(hour=time) <= menu.end_time: result.append(menu) return result class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = d.time(hour=start_time) self.end_time = d.time(hour=end_time) def __repr__(self): return self.name + " menu available from " + self.start_time.strftime("%I%p") + " to " + self.end_time.strftime("%I%p") def calculate_bill(self, purchased_items): total_price = 0 for item in purchased_items: total_price += self.items[item] return total_price # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # script # menus brunch = Menu("Brunch", { 'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50 }, 11, 16 ) early_bird = Menu("Early-bird", { 'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00, }, 15, 18 ) dinner = Menu("Dinner", { 'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00, }, 17, 23 ) kids = Menu("Kids", { 'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00 }, 11, 21 ) arepas_menu = ("Arepas menu", { 'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50 }, 10, 20 ) # testing representation # print(brunch) # testing .calculate_bill method our_breakfast = ['pancakes', 'home fries', 'coffee'] # print("Brunch bill:") # print(brunch.calculate_bill(our_breakfast)) # print() # testing .calculate_bill method last_guests_order = ['salumeria plate', 'mushroom ravioli (vegan)'] # print("Early_bird last guests' bill:") # print(early_bird.calculate_bill(last_guests_order)) # print() # # # # # # # # # # # # # # # # # # # # # # # # # # # # creating franchises flagship_store = Franchise("1232 West End Road", [brunch, early_bird, dinner, kids]) new_installment = Franchise("12 East Mulberry Street", [brunch, early_bird, dinner, kids]) arepas_place = Franchise("189 Fitzgerald Avenue", [arepas_menu]) # testing franchise representation # print(flagship_store) # print(flagship_store.menus) # print(flagship_store.available_menus(12)) # print() # print(new_installment.available_menus(12)) # print() # print() # print(flagship_store.available_menus(17)) # print() # print(new_installment.available_menus(17)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # testing business class first_business = Business("Basta Fazoolin' with my Heart", [flagship_store , new_installment]) arepas_business = Business("Take a' Arepa", [arepas_place])
# Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing. # # SJF works by, well, letting the shortest jobs take the CPU first. If the jobs are the same size then it is First In First Out (FIFO). The idea is that the shorter jobs will finish quicker, so theoretically jobs won't get frozen because of large jobs. (In practice they're frozen because of small jobs). # # Specification # # sjf(jobs, index) # # Returns the clock-cycles(cc) of when process will get executed for given index # # Parameters # jobs: Array (of Integerss) - A non-empty array of positive integers representing cc needed to finish a job. # index: Integer - A positive integer that respresents the job we're interested in # Return Value # Integer - A number representing the cc it takes to complete the job at index. # Examples # # jobs index Return Value # [3,10,20,1,2] 0 6 # [3,10,10,20,1,2] 2 26 import unittest def sjf(jobs, index): # sorted_list = sorted(jobs) sorted_indxs = [i[0] for i in sorted(enumerate(jobs), key=lambda x:x[1])] acum = 0 for idx in sorted_indxs: acum += jobs[idx] if index == idx: return acum # TESTS class Test(unittest.TestCase): def test_should_handle_the_example(self): self.assertEqual(sjf([3,10,20,1,2],0), 6) self.assertEqual(sjf([3,10,10,20,1,2],2), 26) self.assertEqual(sjf([10,10,10,10],3), 40)
# Your task is to create a function that will take an integer and return the result of the look-and-say function on that integer. This should be a general function that takes as input any positive integer, and returns an integer; inputs are not limited to the sequence which starts with "1". # # Conway's Look-and-say sequence goes like this: # # Start with a number. # Look at the number, and group consecutive digits together. # For each digit group, say the number of digits, then the digit itself. # Sample inputs and outputs: # # 1 is read as "one 1" => 11 # 11 is read as "two 1s" => 21 # 21 is read as "one 2, then one 1" => 1211 # 9000 is read as "one 9, then 3 0s" => 1930 # 222222222222 is read as "twelve 2s" => 122 import unittest def look_say(number): digits = [i for i in str(number)] prev_digit = digits[0] splits = 0 counts = [1] unique_digits = [prev_digit] if len(digits) == 1: out = "1" + str(prev_digit) else: for digit in digits[1:]: if digit == prev_digit: counts[splits] += 1 else: splits += 1 counts.append(1) unique_digits.append(digit) prev_digit = digit out = "" if splits == 0: out = str(counts[0])+str(unique_digits[0]) else: for i in range(splits+1): str_to_append = str(counts[i])+str(unique_digits[i]) out = out + str_to_append return int(out) # TESTS class Test(unittest.TestCase): def test_look_say_should_say_hello(self): self.assertEqual(look_say(0), 10) self.assertEqual(look_say(11), 21) self.assertEqual(look_say(12), 1112)
import random import time def getRandomNumber(low, high): return random.randrange(low, high) def getUserInput(message, expectedInput = ['Y', 'N']): user_input = input(message+ ' \n') if user_input.upper() in expectedInput: return user_input.upper() else: print('That was not expected, please type', expectedInput) getUserInput(message, expectedInput) def printList(scrollList, t = 1.25): for item in scrollList: print(item) time.sleep(t) def getGameStarted(difficulty, diffList, diffPrintList ): settingMessage = "What diffuculty do you choose?" userDiffuculty = getUserInput( settingMessage, diffList) pickedSetting = difficulty[userDiffuculty] continuePlaying = True playMessage = "Do you want to play again? [Y]/[N]" playGame(pickedSetting) while continuePlaying: resp = getUserInput(playMessage) if resp == 'N': continuePlaying = False else: printList(diffPrintList, 0.5) userDiffuculty = getUserInput( settingMessage, diffList) pickedSetting = difficulty[userDiffuculty] playGame(pickedSetting) def playGame(settings): guessAmt = settings[0] startRange = settings[1] endRange = settings[2] guessedRight = True rangeMessage = "Your range: " + str(startRange) + "-" + str(endRange) + '\n' guessMessage = "Make your guess, next number will be [E]qual, [H]igher or [L]ower than" hlInput = ['H', 'L', 'E'] initNum = getRandomNumber(startRange, endRange) guessedWrong = "You've guessed wrong and it should have been" while guessAmt > 0 and guessedRight: printMessage = rangeMessage + guessMessage + str(initNum) resp = getUserInput(printMessage, hlInput) genNum = getRandomNumber(startRange, endRange) if resp in ['H','E'] and initNum > genNum: guessedRight = 0 print(guessedWrong, "[L]ower, the number was", str(genNum)) break if resp in ['L','E'] and initNum < genNum: guessedRight = 0 print(guessedWrong, "[H]igher , the number was",str(genNum)) break if resp in ['H','L'] and initNum == genNum: guessedRight = 0 print(guessedWrong[:20], ",the number was equal to",str(genNum)) break print("You've guessed right!") initNum = genNum guessAmt -= 1 if guessedRight: print("You've won!") def printRules(difficulty, diffDef): lineOne = "This game will generate a number and you can guess if the next number is Higher or Lower." lineTwo = "If you guess correctly, you can guess again against that new number" lineThree = "When the game is over, you can start another game or end it." lines = [lineOne,lineTwo,lineThree] print() printList(lines) print() modeList = [] for mode,s in difficulty.items(): modeList.append("For " + diffDef[mode] + " [" + mode + "], you have to make " + str(s[0]) + " consecutive guesses for a random number between " + str(s[1]) + " and " + str(s[2]) ) printList(modeList) print() ## Dictionary 'Mode': [Number of Guess, Range Start, Range End] difficulty = { 'E': [3, 1, 100], 'M': [5, 1, 50], 'H': [7, 1, 20], 'V': [9, 1, 10] } diffDef = {'E': 'Easy', 'M':'Medium', 'H':'Hard', 'V':'Very Hard' } introMessage = 'Do you know how the High Low game works?[Y/N]' if getUserInput(introMessage) == 'N': printRules(difficulty, diffDef) else: print("Okay, hotshot let's do this!") diffList = [] diffPrintList = [] for key, value in diffDef.items(): diffPrintList.append(value + ' [' + key +']') print(value, '[' + key +']') time.sleep(.5) diffList.append(key) print() getGameStarted(difficulty, diffList, diffPrintList ) ##print(difficultyDef)
array = ["Sara" , "Ghada", "Afnan","Ghalia", "Abeer"] for x in array: if x == "Afnan" : continue elif x=="Ghalia": break print(x) for x in range(10): if x % 2 == 0: continue print(x)
#be om en mening och gör om till lista valdmening = (input("Skriv din mening: ")) #kons = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "W", "x", "z"] konssmall="bcdfghjklmnpqrstywxz" konsbig = konssmall.capitalize() kons = konssmall + konsbig nymening = "" for i in range(len(valdmening)): if valdmening[i] in kons: nymening += (valdmening[i] + "o" + valdmening[i]) if valdmening[i] not in kons: nymening += (valdmening[i]) print("Rövarspråk: " + nymening)
score = 0 #Set score to zero print("''**Welcome To The Magical Game!**''") #printing gamename name = input("Please insert your magical name: ") ans = int(input("What is 2*3? ")) #question 1 if ans == 6: print("Good job! you got one point!") score = score+1 #add 1 point else: print ("Too bad, wrong answer") print("Your score is: {}. " "" "Here comes another question!".format(score)) ans2 = input("What is your favourite animal? ") #question 2 if ans2 == "cat" or ans2 == "Cat": print("Good job! you got one point!") score = score + 1 # add 1 point elif ans2 == "dog" or ans2 == "Dog": print("Cats are better than dogs, you lost one point...") score = score - 1 # remove one point else: print("Too bad, wrong answer") print("Your score is: {}. Here comes another question!".format(score)) ans3 = input("What is the meaning with life? ") #question 3 if ans3 == "Love" or ans3 == "love": print("Loooove is all you neeeed <3. Congratulations, you got 32 points") score = score + 32 elif ans3 == "There is no meaning" or ans3 == "there is no meaning": print("That's depressing, you lost 42 points") score = score - 42 else: print("That's an interesting answer, you are probably right! You got one point!") score = score + 1 print("That was all the questions, good job on finishing the game. Lets see what score {} got:".format(name)) if score <=2 and score >=0: print("Your score is: {}. That was a mediocre score, better luck next time, {}!".format(score, name)) elif score >2: print("Your score is {}. Good job! You are very talented, {}!".format(score, name)) elif score <0: print("Your score is {}. That was really bad, hopefully you got other talents... {}".format(score, name))
list = [2, 6, 3, 0, 4, 13] nylista = [] lenghtlist = len(list) for i in range(len(list)): minsta = min(list) list.remove(minsta) nylista.append(minsta) print(nylista)
# Be om siffror numbers = (input("insert your numbers: ")) # gör om numbers till lista num = [] for x in range(len(numbers)): num.append(int(numbers[x])) #lägg till första siffran igen på slutet num.append(num[0]) print(num) #gör ny lista nynum=[] for i in range(len(num) -1): if num[i] == num[i +1]: nynum.append(num[i]) summa = sum(nynum) print(nynum) print(summa)
from eldar import Query import pandas as pd # build dataframe df = pd.DataFrame([ "Gandalf is a fictional character in Tolkien's The Lord of the Rings", "Frodo is the main character in The Lord of the Rings", "Ian McKellen interpreted Gandalf in Peter Jackson's movies", "Elijah Wood was cast as Frodo Baggins in Jackson's adaptation", "The Lord of the Rings is an epic fantasy novel by J. R. R. Tolkien"], columns=['content']) # build query object query = Query( '("gandalf" OR "frodo") AND NOT ("movies" OR "adaptation")', ignore_case=True, ignore_accent=True, match_word=True) # calling the object returns True if the text matches the query. # You can filter a dataframe using pandas mask syntax: df = df[df.content.apply(query)] print(df)
list_1 = [1, 2, 3, 4, 5] # O(1) - Constant def constant(n: list): return n[0] # O(N) - Linear def linear(n: list): for i in range(len(n)): print(i) # O(N^c) - Exponential def exponential(n: list): for i in range(len(n)): for j in range(len(n)): print(i, j) # Combination - # O(3) + O(10) + O(N) + O(N) + O(1) = O(14) + O(2N) = O(N), # constant and multiplication in N we desconsider because N could be # a number a lot more bigger def combination(n: list): # O(3) print(n[0]) print(n[1]) print(n[2]) # O(10) for i in range(10): print(i) # O(N) for j in range(len(n)): print(j) # O(N) for k in range(len(n)): print(k) # O(1) print('test')
from List import List from copy import deepcopy class LinkedList(List): def __init__(self): self.head = None self.tail = None def set_head(self, h): self.head = h def set_tail(self, t): self.tail = t def is_empty(self): return self.head is None and self.tail is None def prepend(self, item): if self.is_empty(): self.head = item else: self.set_tail(deepcopy(self)) self.set_head(item) def append(self, item): if self.is_empty(): self.head = item else: tmp = LinkedList() tmp.head = item cur = self while cur.tail is not None: cur = cur.tail cur.tail = tmp def head(self): return self.head def tail(self): return self.tail def iter(self, option): return range(option) def __str__(self): if self.is_empty(): return '' else: res = [] res.append(str(self.head)) if self.tail is not None: res.append(str(self.tail)) return '->'.join(res) if __name__ == '__main__': a = LinkedList() ''' print(a) a = a.prepend(1) print(a) a = a.prepend(2) print(a) a = a.prepend(3) print(a) ''' a.prepend(1) a.prepend(2) a.prepend(3) print(a.head) print(a.tail.head) print(a) print(a) a.append(4) a.append(5) print(a) b = LinkedList() b.append(1) print(b) b.append(2) print(b) b.prepend(1) b.prepend(2) b.prepend(3) print(b) for elem in a.iter(2): print(elem)
class Test: def __init__(self, a): self.a = a def seta(self, b): self.a = b def f(self, b): #self = Test(b) self.seta(b) t = Test(1) t.f(2) print(t.a)
class Solution: def isBalanced(self, root): #recursive """ :type root: TreeNode :rtype: bool """ if not root: return True def depth(node): if not node: return 0 # leaves has no length left=depth(node.left) right=depth(node.right) if abs(left-right) > 1: raise Exception return max(left,right)+1 try: return abs(depth(root.left)-depth(root.right))<=1 except: return False
import functools x=[1, -2, 3, -50, 40, -90] result = filter(lambda x: x>0, x) # возвести все положительные элементы последовательности в квадрат def positive_in_square(el): if el>0: return el**2 else: return el print(list(map(positive_in_square, x))) # map принимает 2 параметра: func и *iterables. # map makes an iterator that computes the function using arguments from each of the iterables. def make_p(func): functools.wraps(func) def wrapper(*args): result = '{0} {1} {2}'.format('<p>', func(*args), '</p>') return result return wrapper def make_strong(func): functools.wraps(func) def wrapper(*args): result = '{0} {1} {2}'.format('<strong>', func(*args), '</strong>') return result return wrapper #декоратор инициалиируется один раз для каждой новой переданой ему функции. После того как он инициализирован вызывается только wrapper def check_count(func): functools.wraps(func) def wrapper(*args, **kwargs): wrapper.calls += 1 print(wrapper.calls) return func(*args, **kwargs) wrapper.calls = 0 return wrapper @check_count @make_strong @make_p def create_text(text): return text # print(create_text('Hello world!')) # print(create_text('Hello world!')) # print(create_text('Hello world!')) # Генераторы numbers = [1, 2, 3, 4, 5, 6, 7, 8] # for num in numbers: # print(num) [num for num in numbers] [num for num in numbers if num>0] divide_by_two = [str(num) for num in numbers if num%2==0] for num in divide_by_two: print(num) #Генератор инициализирует по одному элементу, а не все элементы списка сразу #Генератор может быть и dictionary {}
""" Algorithm Design and Applications: An Example of Pseudo-Code """ # Algorithm arrayMax(A, n): # Input: An array A storing n >= 1 integers. # Output: The maximum element in A. # currentMax <- A[0] ............2 # for i <- 1 to n - 1 do.........1 + n - 1 # if currentMax < A[i] then....4(n - 1) # currentMax <- A[i]........and 6(n - 1) # return currentMax..............1 # --------------------------------------------- # best case: 2 + 1 + n + 4(n - 1) + 1 = 5n # worst case: 2 + 1 + n + 6(n - 1) + 1 = 7n - 1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] def arrayMax(n): currentMax = a[0] for i in n: if currentMax < a[i]: currentMax = a[i] return currentMax print arrayMax(a)
def fibonacci_series_r(present_term, next_term, term_count): # Using Recursion if term_count > 0: print(present_term, " ", end="") fibonacci_series_r(next_term, (present_term + next_term), (term_count - 1)) else: print("") def fibonacci_series(term_count): present_term = 0 next_term = 1 while term_count > 0: print(present_term, " ", end="") temp = present_term + next_term present_term = next_term next_term = temp term_count -= 1 print("") def fibonacci_term_r(present_term, next_term, term_count): # Using Recursion if term_count > 1: return fibonacci_term_r(next_term, (present_term + next_term), (term_count - 1)) else: return present_term def fibonacci_term(term_count): present_term = 0 next_term = 1 while term_count > 1: temp = present_term + next_term present_term = next_term next_term = temp term_count -= 1 return present_term def is_fibonacci(term_checked): present_term = 0 next_term = 1 while term_checked >= next_term: temp = present_term + next_term present_term = next_term next_term = temp if present_term == term_checked: return True else: return False def main(): # Driver Method t = int(input("Enter Number of terms: ")) fibonacci_series(t) f = fibonacci_term(t) print(f"The '{t}'th term is {f}") ch = int(input("Enter number to be checked: ")) print(is_fibonacci(ch)) if __name__ == "__main__": main()
def is_armstrong(num): temp, s = num, 0 while temp > 0: s += (temp % 10) ** 3 temp = temp // 10 if s == num: return True else: return False n = int(input("Enter number: ")) if is_armstrong(n): print("Armstrong!!") else: print("Not Armstrong")
#!/usr/bin/python # -*- coding: UTF-8 -*- #check whether user input is num import re import time number_str = input("請輸入一個數字,將列出可整除這個數字的integer:") num_pattern = r'^[0-9]+$' match = re.match(num_pattern, number_str.strip()) number_int = int(number_str) """first failure debug long time finding num%number_int -> number_int%num""" result_list = [x for x in range(1,number_int+1) if number_int%x==0] print(result_list)
willing_tocontinue = input(" Would you like to start the game type 'y' if you would like to or 'n' if you want to exit: ") if willing_tocontinue == "y": print ("great let's get started") else: exit(print("well thank you for stopping by see you next time")) user_name = input(" Ok now it's time to get to know you , please enter your name: ") while user_name.isdigit() == True: print("Sorry we only accept valid names") user_name = input(" Ok now it's time to get to know you , please enter your name: ") print("welcome" , user_name, "its nice to have you here") user_age = input ("how old are you "+user_name+ ": ") user_gender = input(" Are you a boy or a girl "+ user_name+" ?"+"(answer with boy or girl)" ": ") while (user_gender != "girl") and (user_gender != "boy") == True: print("Sorry we only accept boy or girl") user_gender = input(" Are you a boy or a girl "+ user_name+" ?"+"(answer with boy or girl)" ": ") print("Hum you are a", user_gender, "let me think about some options for you") if int(user_age) <= 12 and user_gender == "boy": user_continue = input( user_age+" years old that's a great age "+user_name+ " ready for some fun ?(type 'y' or 'n'): ") if user_continue == "y": print("great let's get started") else: print("well thank you for stopping by see you next time") print("Allright " +user_name+" since you are " +user_age+" years old, those are the things we suggest you to do") things_todo = ["going to the movies" , "going to the restaurant"] print(things_todo) user_choice = input(" The choice is tough you can only pick one choice, are you ready "+user_name+" ? if not just press something else to exit"+ " you can either write one of the options or exit: ") if user_choice.lower() == "going to the movies": print("Ok you choose to go to the movies ", user_name, " let's go to the movies then") print("here we go ",user_name, " we arived to the movies") elif user_choice.lower() == "going to the restaurant": print("Ok you choose to go to the restaurant ", user_name, " let's go to the restaurant then") else: print("It was nice meeting you ", user_name, "see you next time") elif int(user_age) <= 12 and user_gender == "girl": user_continue = input( user_age+" years old that's a great age "+user_name+ " ready for some fun ?(type 'y' or 'n'): ") if user_continue == "y": print("great let's get started") else: print("well thank you for stopping by see you next time") print("Allright " +user_name+" since you are " +user_age+" years old, those are the things we suggest you to do") things_todo = ["going to the zoo" , "going to the library"] print(things_todo) user_choice = input(" The choice is tough you can only pick one choice, are you ready "+user_name+" ? if not just press something else to exit"+ " you can either write one of the options or exit: ") if user_choice.lower() == "going to the zoo": print("Ok you choose going to the zoo ", user_name, " let's go to the zoo then") print("here we go ",user_name, " we arived to zoo") elif user_choice.lower() == "going to the library": print("Ok you choose to go to the library ", user_name, " let's go to the library then") else: print("It was nice meeting you ", user_name, "see you next time")
import requests, sys base_url = 'https://api.trello.com/1/{}' """ Enter Key and ID of your Trello account. Then create or choose the board on the Trello and copy the board ID. """ board_id = 'Write the board id here' auth_params = { 'key': 'Write your Trello key here', 'token': 'Write your Trello id here' } """ commands in console: PATH > python TrelloClient.py // Show all the lists and all the tasks in those lists PATH > python TrelloClient.py create_list "name-of-list" // Create new list PATH > python TrelloClient.py create_task "name-of-task" "name-of-list" // Create a new task in a list that you have choose PATH > python TrelloClient.py move "name-of-task" "name-of-list" // Move your task in a list that you have choose """ def read(): """ Get all columns and column data from the board 'board_id'. """ column_data = requests.get(base_url.format('boards') + '/' + board_id + '/lists', params = auth_params).json() for column in column_data: task_data = requests.get(base_url.format('lists') + '/' + column['id'] + '/cards', params=auth_params).json() print(f'"{column["name"]}". Number of tasks - {len(task_data)}') tasks_counter = 0 if not task_data: print(f'\tTasks is absent') continue for task in task_data: tasks_counter += 1 print(f'\t{tasks_counter}. "{task["name"]}" with ID: "{task["id"]}"') def create_list(name): """ Creating a new column in a board with a name = name. """ name = name_handler(name) board = requests.get(base_url.format('boards') + '/' + board_id, params=auth_params).json() our_board_id = board['id'] requests.post(base_url.format('lists'), data={'name': name, 'idBoard': our_board_id, **auth_params}) print('The list has been created.') def create_task(name, column_name): """ Creating a new task with a name = name in to a column = column_name. """ name = name_handler(name, component='task') column_data = requests.get(base_url.format('boards') + '/' + board_id + '/lists', params=auth_params).json() column_list = [] for column in column_data: if column['name'] == column_name: column_list.append({ 'name': column['name'], 'id': column['id'] }) if len(column_list) == 1: requests.post(base_url.format('cards'), data={'name': name, 'idList': column_list[0]['id'], **auth_params}) print('Task has been added.') elif len(column_list) > 1: counter = 0 print('All lists with the same name:') for column in column_list: counter += 1 print(f'{counter} - List: "{column["name"]}" with ID: "{column["id"]}"') answer_number = int(input('Choose number of list, where do you want add the new task:\n')) while answer_number not in range(1, len(column_list) + 1): answer_number = int(input('The list with this number is not exist, choose a correct number:\n')) requests.post(base_url.format('cards'), data={'name': name, 'idList': column_list[answer_number - 1]['id'], **auth_params}) print('Task has been added.') else: create_list(column_name) column_data = requests.get(base_url.format('boards') + '/' + board_id + '/lists', params=auth_params).json() for column in column_data: if column['name'] == column_name: requests.post(base_url.format('cards'), data={'name': name, 'idList': column['id'], **auth_params}) print('The task has been added.') def name_handler(name, component = 'list'): """ Check: is a task or list with same name is in a board? If yeas - offer choose do you want to create a task or list with this name, or to make new name. param: default = 'list', or can be 'task'. Choose what a name you want to find. """ column_data = requests.get(base_url.format('boards') + '/' + board_id + '/lists', params=auth_params).json() lists = [] tasks = [] for column in column_data: if column['name'] == name: lists.append({ 'name': column['name'], 'id': column['id'] }) task_data = requests.get(base_url.format('lists') + '/' + column['id'] + '/cards', params=auth_params).json() for task in task_data: if task['name'] == name: tasks.append({ 'name': task['name'], 'id': task['id'], 'list': column['name'] }) if (component == 'list') and len(lists) >= 1: print('Lists with the same name already is:') counter = 0 for list in lists: counter += 1 print(f'\t{counter} - Name: "{list["name"]}". ID: "{list["id"]}"') answer_number = int(input('Enter number:\n1 - If you want create list with the same name.\n2 - If you want enter enother name.\n')) while answer_number not in range(1, 3): answer_number = int(input('Incorrect number:\nTry again.\n')) if answer_number == 1: return name elif answer_number == 2: name = input('Enter new name:\n') return name elif (component == 'task') and len(tasks) >= 1: print('Tasks with the same name already is:') counter = 0 for task in tasks: counter += 1 print(f'\t{counter} - Name: "{task["name"]}". List: "{task["list"]}". ID: "{task["id"]}".') answer_number = int(input('Enter number:\n1 - If you want create task with the same name.\n2 - If you want enter enother name.\n')) while answer_number not in range(1, 3): answer_number = int(input('Incorrect number:\nTry again.\n')) if answer_number == 1: return name elif answer_number == 2: name = input('Enter new name:\n') return name return name def move(name, column_name): """ Move a task with a name = name in to a column = column_name. """ column_data = requests.get(base_url.format('boards') + '/' + board_id + '/lists', params=auth_params).json() tasks_list = [] for column in column_data: column_tasks = requests.get(base_url.format('lists') + '/' + column['id'] + '/cards', params=auth_params).json() for task in column_tasks: if task['name'] == name: tasks_list.append({ 'id': task['id'], 'name': task['name'], 'list_name': column['name'] }) if len(tasks_list) > 1: task_id = choose_task(tasks_list) else: task_id = tasks_list[0]['id'] column_list = [] for column in column_data: if column['name'] == column_name: column_list.append({ 'name': column['name'], 'id': column['id'] }) if len(column_list) > 1: print('The lists with the same name:') counter = 0 for column in column_list: counter += 1 print(f'{counter} - Name: "{column["name"]}". ID: "{column["id"]}".') answer_number = int(input('Choose number of list, where do you want move the task:\n')) while answer_number not in range(1, len(column_list) + 1): answer_number = int(input('Number of list is incorrect. Try again:\n')) requests.put(base_url.format('cards') + '/' + task_id + '/idList', data={'value': column_list[answer_number - 1]['id'], **auth_params}) print('The task has been moved.') elif len(column_list) == 1: requests.put(base_url.format('cards') + '/' + task_id + '/idList', data={'value': column_list[0]['id'], **auth_params}) print('The task has been moved.') else: print('List with those name is not exist') def choose_task(dict): """ Show in console all the tasks names from the dictionary and offers to choose one of it . Then return id of this task. """ counter = 0 for task in dict: counter += 1 print(f'{counter} - Task "{task["name"]}"\n from the "{task["list_name"]}" list\n with "id" - {task["id"]}') number_of_task = int(input('Choose the number of tusk, that you want to move:\n ')) return dict[number_of_task - 1]['id'] if __name__ == '__main__': if len(sys.argv) <= 2: read() elif sys.argv[1] == 'create_list': create_list(sys.argv[2]) elif sys.argv[1] == 'create_task': create_task(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'move': move(sys.argv[2], sys.argv[3])
import unittest from lexer import LexicalAnalyzer from parser import RegExParser class MyTestCase(unittest.TestCase): def test_primitive_parser(self): re = "a" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) def test_concatenation_parser(self): re = "abc" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) def test_or_parser(self): re = "a|b|c" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) def test_star_parser(self): re = "a**" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) def test_combination_parser(self): re = "a|b*|(cd)*e" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) def test_combination1_parser(self): re = "(0|1)*010" l = LexicalAnalyzer() l.run(re) parser = RegExParser(l) tree = parser.regex() print(tree) self.assertEqual(tree.__repr__() == re, True) if __name__ == '__main__': unittest.main()
import datetime """ Person class with name attribute. Real life anaglous: Library customers """ class Person(): '''Initialize person ''' def __init__(self,name,timeobj):#,userlist): self.name = name self.timeobj = timeobj def PrintName(self): return ("Customer name : %s "% self._name) def SetTime(self,dateime): self.timeobj = datetime.datetime def GetTime(self): return self.timeobj
""" list_node.py Contains a simple ListNode class, which simply has 'val' and 'next' fields. """ class ListNode: """ Models a single node in a singly-linked list. Has no methods, other than the constructor. """ def __init__(self, val): """ Constructs the object; caller must pass a value, which will be stored in the 'val' field. """ self.val = val self.next = None def __str__(self): out_list = [] curr = self while curr is not None: out_list.append(str(curr.val)) curr = curr.next return " -> ".join(out_list)
''' File: letter_swaps.py Author: Kevin Falconett Purpose: swaps every possible character in a string ''' def swap(i1,i2,string): ''' Swaps the letters at string[i1] and string[i2] Parameters: i1 (int): first index i2 (int): second index string (str): string to perform swap Returned: (str) with characters swapped ''' letter1 = string[i1] letter2 = string[i2] returned = '' # reconstructs string, swaps # when index is i1 or i2 for i in range(len(string)): if i == i1: returned += letter2 elif i == i2: returned += letter1 else: returned += string[i] return returned def letter_swaps(text): ''' gets all possible swaps of a string and returns them in a list Parameters: text (str): string to swap Returns: list[str] containing all possible swaps ''' returned = [] for i1 in range(len(text)): for i2 in range(len(text)): letter1 = text[i1] letter2 = text[i2] if letter1 == letter2: continue swapped = swap(i1,i2,text) if swapped in returned: continue else: returned.append(swapped) return sorted(returned) def main(): result = letter_swaps(input("Text: ")) print(result) if __name__ == '__main__': main()
""" File: puzzle_match Author: Kevin Falconett Purpose: check if puzzle pieces can be joined left to right or top to bottom """ def puzzle_match_LR(left, right): """ Checks to see if the right side of left can be matched to the left side of right Parameters: left (list[str]): List of strings right (list[str]): List of strings Preconditions: left and right are in the "puzzle" format (length 4) Returns: True if left's right side matches right's left side. False otherwise. """ leftR_Side = left[1] rightL_Side = right[3] rightL_Side = rightL_Side[::-1] return leftR_Side == rightL_Side def puzzle_match_TB(a, b): """ Checks to see if the bottom of a can be matched to the top of bottom Parameters: a (list[str]): List of strings b (list[str]): List of strings Preconditions: a and b are in the "puzzle" format (length 4) Returns: True if a's bottom matches b's top. False otherwise. """ # gets the bottom of a # and inverts it bottom = a[2] bottom = a[::-1] # gets the top of b top = b[0] return top == bottom def main(): pass if __name__ == "__main__": main()
""" File: classify.py Author: Kevin Falconett Function: determines whether the first letter of a word is a vowel, consonant, or neither """ if __name__ == "__main__": string = input("input: ") # retrieve input vowels = ["A", "E", "I", "O", "U"] # list of vowels consonants = [ "B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "X", "Z", "W", "Y", ] # list of consonants first = string[0].upper() # first character made uppercase # conditionals if first in vowels: # character is a vowel print("vowel") elif first in consonants: # character is a consonant print("consonant") else: # character is neither print("neither")
""" File: swap.py Author: Kevin Falconett Function: If string input is even, swap first and second halves of string. if the length of the string is odd, then the first part of the string will be the portion of the string from the beginning to to the middle, but not including the middle character. The second part of the odd string contains everything after the middle character of the input string. """ if __name__ == "__main__": # varables inputString = input("input: ") fHalf = "" sHalf = "" returned = "" length = len(inputString) mid = length // 2 if length % 2 == 0: # String inputted is even fHalf = inputString[0:mid] # gets first half of inputted string and assigns it sHalf = inputString[mid:length] # gets second half returned = sHalf + fHalf else: # string is odd midChar = inputString[mid] fHalf = inputString[0:mid] sHalf = inputString[mid + 1 : length] returned = sHalf + midChar + fHalf print(returned)
class YuChen: 'yuchen的测试类' def __int__(self): pass def test_list(self): '列表函数' list1 = ['go','to','school','by','bus']; list2 = ['1','2','3','4','5','6']; print(list1[0]); del list1[0]; #删除列表元素 remove()方法 print(list1[0]); list2[0]= 99; #更新列表元素 append()方法 print(list2[0]) def test_tup(self): '元组函数' tup0 = (); #空元组 tup1 = ('My','name','is','yuchen'); tup2 = (10.11,12,13,14,15,16); tup3 = (99999999,); #只有一个元素的元组,在元素后面添加逗号 print("访问tuop1元组的第一个元素:",tup1[0]); print("访问tuop1元组:", tup1); print("访问tup0空元组:",tup0); print("计算元素个数打印出来结果为:",len((tup3))); del tup2;#删除tup2元组,只能删除元组,不能删除元组的元素 def test_for(self): 'for循环函数' for aa in range(20,-20,-2): #print("aa",aa); for bb in range(-30,30,1): #//print("bb",bb); a=aa/10; b=bb/10; if(a*a+b*b-1)*(a*a+b*b-1)*(a*a+b*b-1)<=b*b*a*a*a: print("*",end=" ") else: print(' ',end=" "); print(); def test_for2(self): 'for循环函数' for aa in range(20,-20,-2): #print("aa",aa); for bb in range(-30,30,1): #//print("bb",bb); a=aa/10; b=bb/10; c=aa*a+b*b-1; print("aa*a+b*b-1=",c*c*c); def test_dict(self): '字典函数' dict1 = {'key1':12345,'key2':678910,'key':'zyc'}; dict2 = {'name':'yuchen','age':23,'birth':19940401,'dress':'重庆市'}; #访问字典的值 print("访问dict1的key1键:",dict1['key1']); #修改字典 dict2['age'] = 99; print("访问dict2的age键:",dict2['age']); #添加 dict2['School'] = '重庆邮电大学'; print("访问dict2新添加的键:",dict2['School']); #删除字典 del dict2['dress'];#删除字段的某一键值 dict2.clear();#清空字典 del dict2;#直接删除字典 def test_datetime(self): '日期函数' import time; #引入time模块 ticks = time.time(); #函数time.time()用于获取当前时间戳 print("当前的时间:",ticks); #获取当前时间(从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。) localtime1 = time.localtime(time.time()); print("本地时间为:", localtime1); localtime2 = time.localtime(ticks); print("本地时间为:",localtime2); #获取格式化的时间(最简单的获取可读的时间模式的函数是asctime()) localtime3 = time.asctime(time.localtime(time.time())); print("这种模式的时间为:",localtime3); #格式化日期(利用strftime方法) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())); # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y",time.localtime())); #获取某月日历(利用calendar模块) import calendar; cal = calendar.month(2017,9); print("输出2017年9月的日历:",cal); #匿名函数 # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2; # 调用sum函数 print("相加后的值为 : ", sum(10, 20)); print("相加后的值为 : ", sum(20, 20)); YuChen().test_datetime(); #YuChen().test_dict(); #YuChen().test_tup() #YuChen().test_list(); #YuChen().test_for2(); #YuChen().test_for2(); '''YuChen().test_for() YuChen().test_list(); A=YuChen(); A.test_list(); 测试但是大家都把时间可是大家思考的 7777 8888 9999 '''
''' Tetris Project Creators: Paul Vetter, Seth Webb, Sarah Rosinbaum, & Anna Woodruff Engr 102 final project The game will consist of 4 different files: JTetris - present the GUI for tetris in a window and do animation Piece class within Brain - simple heuristic logic that knows how to play the tetris JBrainTetris - Similar to JTetris except that it uses a brain to play the game w/ out a human player BrainTester - Possibly include this class to test our brain and implement machine learning Using Tetris-Architecture.html for guidance but was designed for java so just the basic idea ''' """ Instructions left arrow or "a" key moves piece left right arrow or "d" key moves piece right up arrow or "w" key rotates piece holding down the down arrow or "s" key will cause the piece to fall twice as fast Press Space to store a piece once per turn. Press p to toggle pause. When inputing New Highscore Name, DO NOT USE CONSOLE, just type it normally, backspace works, enter to submit. DO NOT put in names longer than four characters! PLay Long Enough and discover the hidden musical easteregg! """ """ Things still left to do: Add a Menu Before the Game Starts Add an AI to play and get better at the game. """ import pygame import random import turtle as t from turtle import bgcolor #Intialize pygame.init() clock = pygame.time.Clock() #Global Variables score = 0 #Initialized to be 0 for new game. windowWidth = 800 windowHeight = 600 playWidth = 300 # meaning 300 // 10 = 30 width per block playHeight = 600 # meaning 600 // 20 = 20 height per blo ck cellSize = 30 topLeftOfPlayX = (windowWidth - playWidth) // 2 isPieceStored = False #Create font Object fontObj = pygame.font.Font('8-BIT WONDER.ttf', 30) fontObjSmall = pygame.font.Font('8-BIT WONDER.ttf', 20) fontObjSmallest = pygame.font.Font('8-BIT WONDER.ttf', 15) high = open('High Score.txt', 'r') player1Name = high.readline().strip() player1Score = high.readline().strip() player2Name = high.readline().strip() player2Score = high.readline().strip() player3Name = high.readline().strip() player3Score = high.readline().strip() player4Name = high.readline().strip() player4Score = high.readline() newName = '' high.close() pygame.mixer.music.load("Chip Tone Aggie War Hymn.mp3") pygame.mixer.music.set_volume(0.1) """ Lists currently empty unitl Paul creates the shape grids, need to make sure the order is correct, and that we match the order of the shapes with the order of the colors. This will be passed into the piece class, also need his variable names. Shape grids now created in a new fromat to be better used, don't worry about it anymore. """ smashBoy = [['00000', '00000', '01100', '01100', '00000']] rhodeIslandZ = [['00000', '00000', '00110', '01100', '00000'], ['00000', '00100', '00110', '00010', '00000']] clevelandZ = [['00000', '00000', '01100', '00110', '00000'], ['00000', '00100', '01100', '01000', '00000']] hero = [['00100', '00100', '00100', '00100', '00000'], ['00000', '11110', '00000', '00000', '00000']] blueRicky = [['00000', '01000', '01110', '00000', '00000'], ['00000', '00110', '00100', '00100', '00000'], ['00000', '00000', '01110', '00010', '00000'], ['00000', '00100', '00100', '01100', '00000']] orangeRicky = [['00000', '00010', '01110', '00000', '00000'], ['00000', '00100', '00100', '00110', '00000'], ['00000', '00000', '01110', '01000', '00000'], ['00000', '01100', '00100', '00100', '00000']] teeWee = [['00000', '00100', '01110', '00000', '00000'], ['00000', '00100', '00110', '00100', '00000'], ['00000', '00000', '01110', '00100', '00000'], ['00000', '00100', '01100', '00100', '00000']] shapes = [smashBoy, rhodeIslandZ, clevelandZ, hero, blueRicky, orangeRicky, teeWee] colors = [(255, 255, 0), (0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 165, 0), (0, 0, 255), (130, 0, 130)] class Piece(object): """ Takes in a spawn position, x and y, and takes in what shape the piece will be. Used to create elements of pieces to be used by other of functions. Refrenced mainly by position, and color. Shape used when displaying next and stored pieces. """ # x = 20 #y = 10 def __init__(self, x, y, shape): #self is like this from java, funny enough turns out you can do other words not self, but to keep it easy for Dr. Ritchey to Grade I say we keep it as self. self.x = x self.y = y self.shape = shape self.color = colors[shapes.index(shape)] # Returns the color of the shape being passed self.rotation = 0 #Defaulted to 0, will incremint when up arrow is pressed, number will refrence which list to display. def main(screen): """ Takes in a window, named screen. Initializes a blank dictionary locked positions and then creates a grid based off of the dictionary, storing it in the varibale grid. initializes variables to fit the start conditions of the game. The game loop is initiated. The music manager is the first thing evaluated in the game loop. Next, the falling of the pieces is managed by set fall times and the clock rawtime, whenever the current clock time is greater than the set fall check time, the piece is moved down one posistion. We also recreate the grid variable based on the dictionary of locked positions. If the user exits out of the window it will exit out of the gameloop. We have specialized inputs to the state of the piece based on keyboard inputs given. we have the calls for next piece and stored piece when applicable. We then call the rendering near the bottem to ensure it displays the most current information. At the end of the game loop we check to see if the player has lost based on if there are pieces above the allowed play area. After the game loop we check to see if we need to update the score. """ lockedPositions = {} #Initialize Locked Postitions as a blank dictionary grid = createGrid(lockedPositions) #Passes the dictionary into our method isStored = False storedThisTurn = False storedPiece = 0 holdPiece = 0 changePiece = False #default this false or else itll constantly change pieces, will use this as a check later to know when to change piece. run = True #Initialize run for our while loop later, game will run while thise is true, stop when false. clock = pygame.time.Clock()# Sarahs clock that actually ended up being needed for controlling the falling piece fallTime = 0 #Will be refrenced later to controll when the piece drops. currentPiece = getShape() #Literally the only remaining part of the original code other than the window, changed to fit the getShape Method. nextPiece = getShape() #A benifit of this I just noticed is we only have to keep track of two sets of self. keeps memory relatively free. Only two objectives of the shape Class. fastFall = 1 musicCount = 1 #THE GAME LOOP, AS FROM THE ORIGINAL BUILD, BEFORE EVERYTHING WENT BAD while run: #This is a little easteregg left in be the development team, whats a game without eggs :) if not pygame.mixer.music.get_busy(): if musicCount % 3 == 0: pygame.mixer.music.load("Video Game medley.mp3") pygame.mixer.music.set_volume(0.4) else: pygame.mixer.music.load("Chip Tone Aggie War Hymn short.mp3") pygame.mixer.music.set_volume(0.1) pygame.mixer.music.play() musicCount += 1 fallCheck = 0.30/fastFall #should divide by fast fall, speed * fastFall during fast fall grid = createGrid(lockedPositions) #Called because we need to update the grid BEFORE ANYTHING ELSE fallTime += clock.get_rawtime() #Adds how much time has passed since last tick clock.tick() # Resets the raw time for next fall time update. if fallTime / 1000 > fallCheck: # in ms so divide by 1000 fallTime = 0 #reset this for next interval currentPiece.y += 1 #In squares not pixels, Remember Y goes down so plus not minus. if not(valid(currentPiece, grid)) and currentPiece.y > 0: #Checks if touching invalid spot, so long as not above screen currentPiece.y += -1 #move it back up to valid, gonna just go ahead and slide that bad boy back up there changePiece = True #I knew this would come in handy, *pats self on back* storedThisTurn = False for event in pygame.event.get(): #Pygame makes this so so sweet if event.type == pygame.QUIT: run = False #this breaks out of the while Loop if event.type == pygame.KEYDOWN: #means if key is being pressed, not down key #there will be or's to check for wasd and arrow key control :) if event.key == pygame.K_LEFT or event.key == pygame.K_a: currentPiece.x += -1 #Moves Left One Square if not ( valid(currentPiece, grid) ): currentPiece.x += 1 #Oppisite of the movement from key if event.key == pygame.K_RIGHT or event.key == pygame.K_d: currentPiece.x += 1 #Moves Right One Square if not ( valid(currentPiece, grid) ): currentPiece.x += -1 #Oppisite of the movement from key if event.key == pygame.K_DOWN or event.key == pygame.K_s: fastFall = 7 #The higher this number the faster the fall if event.key == pygame.K_p: run = pause(screen) if event.key == pygame.K_SPACE: if not isStored: storedPiece = currentPiece currentPiece = nextPiece nextPiece = getShape() storedThisTurn = True isStored = True elif not storedThisTurn: holdPiece = storedPiece storedPiece = currentPiece currentPiece = Piece(5,0, holdPiece.shape) storedThisTurn = True if event.key == pygame.K_UP or event.key == pygame.K_w: currentPiece.rotation += 1 #Changes the rotation cycles the layouts of shape. if not (valid(currentPiece, grid)): currentPiece.rotation += -1 if event.type == pygame.KEYUP: #When Key Is let go, used to reset fast fall if event.key == pygame.K_DOWN or event.key == pygame.K_s: fastFall = 1 #Should return drop to normal speed shapePosition = convertShape(currentPiece) for i in range(len(shapePosition)): x, y = shapePosition[i] if y > -1: grid[y][x] = currentPiece.color #y,x not x,y. We are about learning from our mistakes. if changePiece: #time for foresite to pay off, note only do this if automatic next,not user store will need other method for that. for pos in shapePosition: # SO MANY POS VARIABLES TO KEEP TRACK OF AHHAHAHHAHAHAH p = (pos[0], pos[1]) lockedPositions[p] = currentPiece.color #updates the tuple dictionary, note can be equal because the piece colors have already been passed #Enable the game to display next piece like in Real Tetris currentPiece = nextPiece nextPiece = getShape() changePiece = False #because we don't want to rapid change, have to reset this to default. #Call Clear Rows here because this is when piece stops. clearRows(grid, lockedPositions) #Our Draw Method Calls drawWindow(screen, grid) drawStoredShape(screen, storedPiece, isStored) drawNextShape(nextPiece, screen) drawScore(screen) drawHighScore(screen) pygame.display.update() if checkLost(lockedPositions): #We pass locked positions because they will contain all positions. run = False #Will exit the game Loop, the While Loop. pygame.mixer.music.stop() if int(score) >= int(player4Score): newHighScore(screen) newHigh = open('High Score.txt', 'w') if int(score) >= int(player1Score): #New First Place newHigh.write(newName+"\n") newHigh.write(str(score)+"\n") newHigh.write(player1Name+"\n") newHigh.write(player1Score+"\n") newHigh.write(player2Name+"\n") newHigh.write(player2Score+"\n") newHigh.write(player3Name+"\n") newHigh.write(player3Score) elif int(score) >= int(player2Score): newHigh.write(player1Name+"\n") newHigh.write(player1Score+"\n") newHigh.write(newName+"\n") newHigh.write(str(score)+"\n") newHigh.write(player2Name+"\n") newHigh.write(player2Score+"\n") newHigh.write(player3Name+"\n") newHigh.write(player3Score) elif int(score) >= int(player3Score): newHigh.write(player1Name+"\n") newHigh.write(player1Score+"\n") newHigh.write(player2Name+"\n") newHigh.write(player2Score+"\n") newHigh.write(newName+"\n") newHigh.write(str(score)+"\n") newHigh.write(player3Name+"\n") newHigh.write(player3Score) else: newHigh.write(player1Name+"\n") newHigh.write(player1Score+"\n") newHigh.write(player2Name+"\n") newHigh.write(player2Score+"\n") newHigh.write(player3Name+"\n") newHigh.write(player3Score+"\n") newHigh.write(newName+"\n") newHigh.write(str(score)) newHigh.close() #End of Main Functon. def createGrid(lockedPositions = {}): """ Creates a 2d matrix of values 0,0,0. Representing the color black. Then it checks for every possible position stored in the dictionary locked positions and return a color value if there exists a key corisponding to that position, updating and returning a grid, 2d matrix, filled with the color values needed. """ grid = [[(0,0,0,) for x in range(10)] for y in range(20)] #Draws a 20 X 10 Black-(0,0,0) Grid #Checks the grid for already played pieces for i in range(20): for j in range(10): if (j, i) in lockedPositions: pointColor = lockedPositions[(j,i)] #pointColor refferring to the color of the piece at that point grid[i][j] = pointColor return grid #returns the black grid with all the played pieces on it. def getShape(): """ Passes an object into the piece class and return the corrisponding set of values. Object values passed are x, y, shape is 5 and 0 because we are refferencing squares on the board not pixels The shape that is passed is chosen via random.choice form the list of shapes. """ global shapes, colors return Piece(5, 0, random.choice(shapes)) def convertShape(currentShape): """ Takes in a shape argument. creates an empty list called positions that will be added to during the conversion. The roation is a cycle of the different sets of values possible for the shapes, since it loops a modulus is used. posistions is appeneded based on whether or not the value of the set of shapes is a 0 or a 1, 1's get apended. """ positions = [] #new empty list form = currentShape.shape[currentShape.rotation % len(currentShape.shape)] #Modulus allows us to cycle through rotations :) hope that helps you in your design, Pual for i, line in enumerate(form): #had a lot of fun with this one. Sarcasm = True row = list(line) for j, column in enumerate(row): if column == '1': # 1 being where block is, based on Pauls form. Note This *********IMPORTANT********* positions.append((currentShape.x + j, currentShape.y + i)) for i, pos in enumerate(positions): positions[i] = (pos[0]-2 , pos[1] -4) #may or may not need offsets, will check when Paul passes his shapes return positions def valid(shape, grid): """ Passes in the shape of the current piece and the 2d list of color values grid. makes a list of accepted positions based on whether or not that postion in grid is black or not, black is accepted. Then gets a converted form of the shape by passing shape into convert shape. If the any of the positions of the piece is in a position not shared by accepted positions list, it will return False Otherwise, if all positions are shared by acceptedPositions it will return true. """ #The ifgrid[i][j] == black checks if empty space, we only want to add empty spaces to our valid list, for obvious reasons. acceptedPositions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0) ] for i in range(20)] #A tuple of all accepted positions allowed in the grid. Did it this way was tired of nested for loops, sue me. acceptedPositions = [j for sub in acceptedPositions for j in sub] #Had to look up how to do this, turns matrix into a list, 2D to 1D Emailed Ritchey to ask about will see when she responds """ [[1,2] , [3,4]] becomes [1,2,3,4] for refrence of before and after structure. """ converted = convertShape(shape) #Makes the info Usable for position in converted: if position not in acceptedPositions: #Checks list of accepted positions if position[1] > -1: #Incase Piece starts above the screen, otherwise the game would end before it started and thats no good. Would help with potentially needed offsets return False #I KEEP WANTING TO PUT SEMI COLONS AFTER RETURN AHHHHHHHHHHHHHHHHHHH return True #Because that means all must be true, all passed. def checkLost(positions): """ Is given the dictionary locked positions as positions. Checks to see if any of the key positions y values exists outside the play area, if so returns True and makes main exit the game loop, otherwise; if none postions are outside the play are it returns False and the game loop continues. """ for position in positions: #Note Singular versus Plural, this is important !!!!!!! x, y = position if y < 1: #Checks to see if above screen return True #Uh OH Thats A Game Over, Once we code that part... return False #you may live, for now -_- def clearRows(grid, lockedPositions ): """ Is given both the 2d list grid and the dictionary lockedPositions. Checks to see if a row(s) contain no black spaces, and makes count equal to the number of rows not containing a black space. I also stores the value of that row as remember. Next we clear the row set as remember. Now based on the count of rows cleared we incriment the scroe and downshift the dictionary of locked positions so we dont have floating incomplete row. """ #ALot harder than I though because of gravity, but I think I found a useful method, need to Test with Puals Shapes. count = 0 for i in range(19, -1, -1): #Counting Backwards, check to see if I did the math right Please. Count backwards to not overwrite rows. if (0,0,0,) not in grid[i]: # If there are no blank black spaces count += 1 remember = i for j in range(10): try: del lockedPositions[(j,i)] #the current position except: continue #Im pretty sure we needed a try as part of our grade, this was the best spot I could think of """ To Paul, If you dont understand how python handles Global variable refrence and how we keep the function from creating its own local variable, these two links might help give insight. - Seth https://www.python-course.eu/python3_global_vs_local_variables.php https://stackoverflow.com/questions/10506973/can-not-increment-global-variable-from-function-in-python """ global score#DO NOT REMOVE, This is needed or else it keeps trying to create a local variable score and the whole things crashes when you clear a line if count > 0: #Meaning we cleared at least one line #Score increase from clearing lines if count == 1: score += 100 if count == 2: score += 250 if count == 3: score += 400 if count == 4: score += 600 """" This next line basically sorts elements of the list be their Y values, it's a bit trippy and weird to explain but it works like this unsorted (1,2) , (5,3) (9,1) sorted (9,1) , (1,2) , (5,3) I didn't Use i and j because it needs to be key for that lamda sort. Hopefully it is easier to follow than write. For information on the sorts check these two websites, they had useful info, especially the first one. https://docs.python.org/3/howto/sorting.html https://stackoverflow.com/questions/3766633/how-to-sort-with-lambda-in-python """ for key in sorted(list(lockedPositions), key = lambda x: x[1])[::-1]: #Definitely had to look this up, converted it to work with our variables and matrix based data, that lambda stuff is funky. Probably best to not touch, convert things to work with this not vise verse x,y = key #Because key is a touple because of our 2D Matrix if y < remember: newkey = (x, y + count) lockedPositions[newkey] = lockedPositions.pop(key) #DO NOT DO THE FOLLOWING LINE, CRASHES CODE. THE ERROR IS RARE AND NON GAME BREAKING, LEAVE IT FOR NOW AND IF WE HAVE TIME TRY TO FIX IT. #clearRows(grid, lockedPositions)#Testing out this reccursion, theres a weird glitch where sometimes when multiple line clears occour than are unconcurerent lines. Reccurive calls on succesful clears should help. def drawGrid(screen, grid): """ Draws grid lines to split up the cells of play arean making it easier to line up pieces. """ #Draws A Grid Of Lines for i in range(20): pygame.draw.line(screen, (255, 255, 255), (topLeftOfPlayX, i * cellSize), (topLeftOfPlayX + playWidth, i * cellSize)) #Horizontal Line for j in range(10): pygame.draw.line(screen, (255, 255, 255), (topLeftOfPlayX + j * cellSize, 0), (topLeftOfPlayX + j * cellSize, playHeight)) #vert lines def drawNextShape(shape, screen): """ Takes in a shape and the window. Renders the word next. Then renders the piece corrisponding to the shape value passed, which should be the same is the shape value stored as next in the game loop, making the graphic and the gameplay corrispond. It draws the piece be seeing the shape and going through a 2d list evaluation of where it is defined, similar to convert shape. 0 means not exist, 1 means exist. Like a boolean. """ textscreenObj = fontObj.render('Next', True, (255, 255, 255))#Next Shape wouldn't fit, changed to Next nextPieceX = topLeftOfPlayX + playWidth + 50 nextPieceY = playHeight // 2 - 270 screen.blit(textscreenObj, (nextPieceX +20, nextPieceY))#Prints out Next Shape in white 8-bit letter form = shape.shape[shape.rotation % len(shape.shape)] #Same line as in convert shape, See that for Documentation for i, line in enumerate(form): row = list(line) for j, column in enumerate(row): if column == "1": #Rather than add postion, which we care not for, we will draw it, simmilar to the line in the drawWindow method below. wave at it, its a friend. pygame.draw.rect(screen, shape.color, (nextPieceX + j * cellSize, nextPieceY + i*cellSize + 45, cellSize, cellSize), 0) def drawStoredShape(screen, shape, check): """ Takes in the weindow, the shape of the stroed piece, and a boolean check which tells if a piece is stored. Draws the word stroed, It evaluates check, if true meaning there is a piece it will the render the piece based on the shape value given. For rendering details, see function drawNextShape. """ textscreenObj = fontObj.render('Stored', True, (255, 255, 255)) storedPieceX = topLeftOfPlayX + playWidth + 50 storedPieceY = playHeight // 2 + 30 screen.blit(textscreenObj, (storedPieceX - 10, storedPieceY))#Prints out stored in white 8-bit letter if check: form = shape.shape[shape.rotation % len(shape.shape)] #Same line as in convert shape, See that for Documentation for i, line in enumerate(form): row = list(line) for j, column in enumerate(row): if column == "1": #Rather than add postion, which we care not for, we will draw it, simmilar to the line in the drawWindow method below. wave at it, its a friend. pygame.draw.rect(screen, shape.color, (storedPieceX + j * cellSize, storedPieceY + i*cellSize + 45, cellSize, cellSize), 0) def drawWindow(screen, grid): """ Takes in a window, screen. Takes in a 2d list, grid. makes the window a solid maroon to be used as a background. cellSize is presdetirmed and is used to make more than one pixel be drawn. It then calls the funciton drawGrid, passing in the Screen and grid. """ screen.fill((67,0,48)) #Draws the maroon background. for i in range(20): for j in range(10): #Draws onto screen the color of grid[i][j], at the correct position, height and width of the draw, and the 0 at the end to make sure it filles the draw, without it it only draws borders pygame.draw.rect(screen, grid[i][j], (topLeftOfPlayX + j * cellSize, i * cellSize, cellSize, cellSize), 0) drawGrid(screen, grid) #Calls the draw grid method, to draw the grid def drawScore(screen): """ Evaluates the number of digits in the global variable score and then renders it in a location based on its length, the longer the score the more leftward it is rendered. y value is unnaffected. """ textscreenObj = fontObj.render('Score', True, (255, 255, 255) ) screen.blit(textscreenObj,( 40,330))#Prints out Score in white 8-bit letters #Format where the score is drawn based on its length digits = 0 holder = score while holder >= 10: holder = holder // 10 digits += 1 textscreenObj = fontObj.render(str(score), True, (255, 255, 255) ) screen.blit(textscreenObj,( 100 - digits * 12.5 ,380)) def drawHighScore(screen): """ Takes in the previously defined player names and scores and renders them accordingly in the top left corner of the screen. """ textscreenObj = fontObjSmall.render('Leaderboard', True, (255, 255, 255) ) screen.blit(textscreenObj,(15,30))#Prints out Score in white 8-bit letters #Format where the score is drawn based on its length textscreenObj = fontObjSmallest.render(player1Name, True, (255, 255, 255) ) screen.blit(textscreenObj,(15,80)) textscreenObj = fontObjSmallest.render(player1Score, True, (255, 255, 255) ) screen.blit(textscreenObj,(95,80)) textscreenObj = fontObjSmallest.render(player2Name, True, (255, 255, 255) ) screen.blit(textscreenObj,(15,100)) textscreenObj = fontObjSmallest.render(player2Score, True, (255, 255, 255) ) screen.blit(textscreenObj,(95,100)) textscreenObj = fontObjSmallest.render(player3Name, True, (255, 255, 255) ) screen.blit(textscreenObj,(15,120)) textscreenObj = fontObjSmallest.render(player3Score, True, (255, 255, 255) ) screen.blit(textscreenObj,(95,120)) textscreenObj = fontObjSmallest.render(player4Name, True, (255, 255, 255) ) screen.blit(textscreenObj,(15,140)) textscreenObj = fontObjSmallest.render(player4Score, True, (255, 255, 255) ) screen.blit(textscreenObj,(95,140)) def newHighScore(screen): """ Draws a black screen and looks for keyboard inputs, based on inputs it concatinates to a string and then renders the string into the middle of the screen. The string of the name is made global so it can be refrenced in the Main function when creating the new txt file. """ global newName run = True screen.fill((0,0,0)) while run: textScreenObj = fontObjSmall.render('Enter Your Initials', True, (255, 255, 255) ) screen.blit(textScreenObj,(225,30))#Prints out Score in white 8-bit letters for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: #Oh Boy THis will be fun if event.key == pygame.K_a: newName += "A" if event.key == pygame.K_b: newName += "B" if event.key == pygame.K_c: newName += "C" if event.key == pygame.K_d: newName += "D" if event.key == pygame.K_e: newName += "E" if event.key == pygame.K_f: newName += "F" if event.key == pygame.K_g: newName += "G" if event.key == pygame.K_h: newName += "H" if event.key == pygame.K_i: newName += "I" if event.key == pygame.K_j: newName += "J" if event.key == pygame.K_k: newName += "K" if event.key == pygame.K_l: newName += "L" if event.key == pygame.K_m: newName += "M" if event.key == pygame.K_n: newName += "N" if event.key == pygame.K_o: newName += "O" if event.key == pygame.K_p: newName += "P" if event.key == pygame.K_q: newName += "Q" if event.key == pygame.K_r: newName += "R" if event.key == pygame.K_s: newName += "S" if event.key == pygame.K_t: newName += "T" if event.key == pygame.K_u: newName += "U" if event.key == pygame.K_v: newName += "V" if event.key == pygame.K_w: newName += "W" if event.key == pygame.K_x: newName += "X" if event.key == pygame.K_y: newName += "Y" if event.key == pygame.K_z: newName += "Z" if event.key == pygame.K_BACKSPACE: newName = newName[0:-1] screen.fill((0,0,0)) textScreenObj = fontObjSmall.render('Enter Your Initials', True, (255, 255, 255) ) screen.blit(textScreenObj,(225,30))#Prints out Score in white 8-bit letters if event.key == pygame.K_RETURN: run = False textscreenObj = fontObjSmallest.render(newName, True, (255, 255, 255) ) screen.blit(textscreenObj, (300,300)) pygame.display.update() pygame.display.update() def pause(screen): """ Pauses the game, displays the pause message, unpauses when p is pressed again. Also pauses the music when pressed, resumes the music if the funciton is about to go back. Has a boolean return incase the user closes the window while paused, will stop music and exit game loop if returned false. """ pygame.mixer.music.pause() pause = True while pause: for event in pygame.event.get(): #Pygame makes this so so sweet if event.type == pygame.QUIT: pause = False pygame.mixer.music.stop() return False textScreenObj = fontObjSmall.render('Paused', True, (255, 255, 255) ) screen.blit(textScreenObj,(350,300)) if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: pause = False pygame.display.update() pygame.mixer.music.unpause() return True def MenuDisplay(): """ A simple collection of turtle graphic instructions that draws out welecome to aggieland tetris. Starts by initializing speed and color and mode. Next is all the movement instructions. """ #Welcome to Aggieland Tetris #Welcome to #Setting place t.speed(0) t.pensize(4) bgcolor('black') t.colormode(255) t.pencolor(67,0,48) t.penup() t.left(90) t.forward(100) t.left(90) t.forward(140) #W t.pendown() t.right(90) t.forward(34) t.right(180) t.forward(34) t.left(90) t.forward(15) t.left(90) t.forward(15) t.right(180) t.forward(15) t.left(90) t.forward(15) t.left(90) t.forward(34) t.penup() t.right(180) t.forward(34) t.left(90) t.forward(13) #e t.pendown() t.left(90) t.forward(18) t.right(90) t.forward(12) t.right(90) t.forward(5) t.right(90) t.forward(12) t.left(90) t.forward(13) t.left(90) t.forward(12) t.penup() #l t.forward(14) t.pendown() t.left(90) t.forward(35) t.penup() #c t.left(180) t.forward(35) t.left(90) t.forward(12) t.pendown() t.forward(15) t.right(180) t.forward(15) t.right(90) t.forward(18) t.right(90) t.forward(15) t.penup() t.right(90) t.forward(18) t.left(90) t.forward(10) #o t.left(90) t.pendown() t.forward(18) t.right(90) t.forward(18) t.right(90) t.forward(18) t.right(90) t.forward(18) t.penup() t.right(180) t.forward(27) #m t.pendown() t.left(90) t.forward(21) t.right(180) t.forward(3) t.left(90) t.forward(13) t.right(90) t.forward(18) t.left(180) t.forward(18) t.right(90) t.forward(13) t.right(90) t.forward(18) t.penup() #e t.left(90) t.forward(10) t.pendown() t.left(90) t.forward(18) t.right(90) t.forward(12) t.right(90) t.forward(5) t.right(90) t.forward(12) t.left(90) t.forward(13) t.left(90) t.forward(12) t.penup() #t t.forward(38) t.pendown() t.forward(10) t.right(180) t.forward(10) t.right(90) t.forward(27) t.right(180) t.forward(7) t.left(90) t.forward(8) t.left(180) t.forward(16) t.left(180) t.forward(8) t.right(90) t.forward(20) t.left(90) t.forward(10) t.left(90) t.forward(6) t.penup() #o t.right(180) t.forward(6) t.left(90) t.forward(10) t.left(90) t.pendown() t.forward(18) t.right(90) t.forward(18) t.right(90) t.forward(18) t.right(90) t.forward(18) t.penup() t.right(180) t.forward(27) #A t.pensize(3) t.home() t.left(180) t.penup() t.forward(250) t.pendown() t.forward(5) t.left(90) t.pendown() t.forward(10) t.left(90) t.forward(20) t.left(90) t.forward(10) t.left(90) t.forward(5) t.right(115) t.forward(13) t.right(65) t.forward(15) t.right(65) t.forward(13) t.right(115) t.forward(5) t.left(90) t.forward(10) t.left(90) t.forward(20) t.left(90) t.forward(10) t.left(90) t.forward(5) t.right(65) t.forward(40) t.right(115) t.forward(6) t.left(90) t.forward(10) t.left(90) t.forward(25) t.left(90) t.forward(10) t.left(90) t.forward(6) t.right(115) t.forward(40) t.left(115) t.penup() t.forward(18) t.left(90) t.forward(20) t.right(90) t.pendown() t.forward(10) t.left(115) t.forward(13) t.left(135) t.forward(13) t.left(110) t.penup() t.forward(45) t.right(90) t.forward(30) t.left(205) t.pendown() #G t.forward(12) t.right(25) t.forward(35) t.right(25) t.forward(12) t.right(65) t.forward(35) t.right(65) t.forward(12) t.right(25) t.forward(8) t.right(90) t.forward(12) t.right(90) t.forward(6) t.left(90) t.forward(22) t.left(90) t.forward(30) t.left(90) t.forward(20) t.left(90) t.forward(8) t.left(90) t.forward(5) t.right(90) t.forward(8) t.right(90) t.forward(18) t.right(90) t.forward(17) t.right(25) t.forward(15) t.right(65) t.forward(32) t.penup() #G t.right(180) t.forward(53) t.left(115) t.pendown() t.forward(12) t.right(25) t.forward(35) t.right(25) t.forward(12) t.right(65) t.forward(35) t.right(65) t.forward(12) t.right(25) t.forward(8) t.right(90) t.forward(12) t.right(90) t.forward(6) t.left(90) t.forward(22) t.left(90) t.forward(30) t.left(90) t.forward(20) t.left(90) t.forward(8) t.left(90) t.forward(5) t.right(90) t.forward(8) t.right(90) t.forward(18) t.right(90) t.forward(17) t.right(25) t.forward(15) t.right(65) t.forward(32) #I t.right(180) t.penup() t.forward(47) t.left(90) t.pendown() t.forward(13) t.right(90) t.forward(13) t.left(90) t.forward(30) t.left(90) t.forward(13) t.right(90) t.forward(13) t.right(90) t.forward(35) t.right(90) t.forward(13) t.right(90) t.forward(13) t.left(90) t.forward(30) t.left(90) t.forward(13) t.right(90) t.forward(13) t.right(90) t.forward(35) t.right(180) t.penup() t.forward(50) #E t.pendown() t.left(180) t.forward(8) t.right(90) t.forward(13) t.right(90) t.forward(7) t.left(90) t.forward(30) t.left(90) t.forward(7) t.right(90) t.forward(13) t.right(90) t.forward(50) t.right(90) t.forward(20) t.right(90) t.forward(13) t.right(90) t.forward(8) t.left(90) t.forward(20) t.left(90) t.forward(9) t.left(90) t.forward(12) t.right(90) t.forward(12) t.right(90) t.forward(13) t.left(90) t.forward(9) t.left(90) t.forward(20) t.left(90) t.forward(12) t.right(90) t.forward(13) t.right(90) t.forward(26) t.right(90) t.forward(45) t.right(180) t.penup() t.forward(60) #L t.left(180) t.pendown() t.forward(6) t.right(90) t.forward(14) t.right(90) t.forward(6) t.left(90) t.forward(32) t.left(90) t.forward(6) t.right(90) t.forward(10) t.right(90) t.forward(18) t.right(90) t.forward(42) t.left(90) t.forward(21) t.left(90) t.forward(6) t.right(90) t.forward(10) t.right(90) t.forward(20) t.right(90) t.forward(44) t.right(180) t.penup() t.forward(56) t.left(90) t.forward(10) t.left(90) t.pendown() #A t.forward(5) t.left(90) t.forward(10) t.left(90) t.pendown() t.forward(20) t.left(90) t.forward(10) t.left(90) t.forward(5) t.right(115) t.forward(13) t.right(65) t.forward(15) t.right(65) t.forward(13) t.right(115) t.forward(5) t.left(90) t.forward(10) t.left(90) t.forward(20) t.left(90) t.forward(10) t.left(90) t.forward(5) t.right(65) t.forward(40) t.right(115) t.forward(6) t.left(90) t.forward(10) t.left(90) t.forward(25) t.left(90) t.forward(10) t.left(90) t.forward(6) t.right(115) t.forward(40) t.left(115) t.penup() t.forward(18) t.left(90) t.forward(20) t.right(90) t.pendown() t.forward(10) t.left(115) t.forward(13) t.left(135) t.forward(13) t.left(110) t.penup() t.forward(45) t.right(90) t.forward(30) t.left(205) t.right(115) t.forward(7) t.left(180) #N t.pendown() t.forward(8) t.right(90) t.forward(10) t.right(90) t.forward(8) t.left(90) t.forward(36) t.left(90) t.forward(8) t.right(90) t.forward(10) t.right(90) t.forward(20) t.right(65) t.forward(50) t.left(155) t.forward(38) t.left(90) t.forward(8) t.right(90) t.forward(8) t.right(90) t.forward(25) t.right(90) t.forward(8) t.right(90) t.forward(6) t.left(90) t.forward(39) t.left(90) t.forward(6) t.right(90) t.forward(10) t.right(90) t.forward(24) t.right(65) t.forward(36) t.left(155) t.forward(22) t.left(90) t.forward(6) t.right(90) t.forward(10) t.right(90) t.forward(20) #D t.penup() t.right(180) t.forward(68) t.left(180) t.pendown() t.forward(8) t.right(90) t.forward(10) t.right(90) t.forward(8) t.left(90) t.forward(37) t.left(90) t.forward(8) t.right(90) t.forward(10) t.right(90) t.forward(48) t.right(65) t.forward(13) t.right(25) t.forward(33) t.right(25) t.forward(13) t.right(65) t.forward(40) t.right(180) t.penup() t.forward(10) t.left(90) t.forward(12) t.pendown() t.forward(33) t.right(90) t.forward(20) t.right(65) t.forward(8) t.right(25) t.forward(20) t.right(25) t.forward(8) t.right(65) t.forward(21) #T t.pensize(2.5) t.penup() t.home() t.right(90) t.forward(120) t.right(90) t.forward(110) t.right(90) t.pendown() t.forward(50) t.left(90) t.forward(10) t.right(90) t.forward(10) t.right(90) t.forward(35) t.right(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(50) t.right(90) t.forward(15) t.right(180) t.penup() t.forward(30) #E t.pendown() t.left(90) t.forward(60) t.right(90) t.forward(35) t.right(115) t.forward(13) t.right(65) t.forward(17) t.left(90) t.forward(8) t.left(90) t.forward(14) t.right(115) t.forward(9) t.right(65) t.forward(8) t.left(90) t.forward(20) t.left(90) t.forward(22) t.right(65) t.forward(13) t.right(115) t.forward(42) #T t.penup() t.right(180) t.forward(49) t.left(90) t.pendown() t.forward(50) t.left(90) t.forward(10) t.right(90) t.forward(10) t.right(90) t.forward(35) t.right(90) t.forward(10) t.right(90) t.forward(10) t.left(90) t.forward(50) t.right(90) t.forward(15) t.right(180) t.penup() t.forward(30) #R t.pendown() t.left(90) t.forward(60) t.right(90) t.forward(37) t.right(130) t.forward(25) t.left(130) t.forward(8) t.right(65) t.forward(46) t.right(115) t.forward(20) t.right(65) t.forward(41) t.right(55) t.forward(18) t.left(120) t.forward(10) t.left(90) t.forward(53) t.right(90) t.forward(10) t.left(180) t.penup() t.forward(48) #I t.pendown() t.forward(10) t.left(90) t.forward(45) t.left(90) t.forward(15) t.left(90) t.forward(32) t.right(180) t.forward(33) t.penup() t.forward(4) t.right(90) t.pendown() t.forward(15) t.left(90) t.forward(12) t.left(90) t.forward(15) t.left(90) t.forward(12) t.penup() t.forward(50) t.left(90) t.forward(20) #S t.pendown() t.left(90) t.forward(16.5) t.right(90) t.forward(20) t.left(125) t.forward(35) t.right(35) t.forward(16.5) t.right(90) t.forward(35) t.right(115) t.forward(16.5) t.right(65) t.forward(9) t.left(125) t.forward(35) t.right(35) t.forward(18) t.right(90) t.forward(39) t.right(180) t.penup() t.forward(46) #shape t.pensize(2) t.pendown() t.left(90) t.forward(68) t.left(90) t.forward(236) t.left(90) t.forward(76) t.left(90) t.forward(80) t.right(90) t.forward(76) t.left(90) t.forward(76) t.left(90) t.forward(76) t.right(90) t.forward(80) t.left(90) t.forward(10) t.left(180) t.forward(10) t.left(90) #hideturtle t.penup() t.forward(20) t.bye() def mainMenu(): """ Starts the music Calls the function MenuDisplay Creates a window named screen of dimensions windowWidth and windowHeight, global variables, and assigns different attributes to the window such as caption and icon. Passes the window into the main function. Closes the window, we do it here because this function is the bookend of the whole program so it ensures that happens everytime and that it happens last. """ pygame.mixer.music.play() MenuDisplay() #Creates the window, moved down here so it does show till after the animation. screen = pygame.display.set_mode((windowWidth, windowHeight)) #Named it screen as nostalgia from the Java Days. pygame.display.set_caption("Aggie Land Tetris!") windowIcon = pygame.image.load("Texas A&M Logo.png") pygame.display.set_icon(windowIcon) main(screen)#Passes from the window that was created and passed to main menu """ Need this or the kernel will die when the window closes, or game over. Really whenever we exit the game loop. But ITS IMPORTANT SO REMEMBER KEEP THIS AS LAST LINE AFTER THE GAME LOOP Put it here in the end so I didn't have to keep moving it when adding new functions and screens' """ pygame.display.quit() mainMenu() # Runs to start the game
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 模块字符串 ''' 学习使用seaborn中的分布图distribution plot及其参数 ''' # 模块导入 # 第三方模块导入 import numpy as np import seaborn as sns import matplotlib.pyplot as plt # seaborn的全局配置 sns.set(style="white", palette="muted", color_codes=True) # 伪随机数生成器 rs = np.random.RandomState(10) # Set up the matplotlib figure f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True) # 除去左坐标轴 sns.despine(left=True) # Generate a random univariate(单变量的) dataset d = rs.normal(size=100) # Plot a simple histogram with binsize(分箱大小) determined automatically sns.distplot(d, kde=False, color="b", ax=axes[0, 0]) # Plot a kernel density estimate(内部密度估计) and rug plot(地毯图) sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0, 1]) # Plot a filled kernel density estimate(填充的内部密度估计) sns.distplot(d, hist=False, color="g", kde_kws={"shade": True}, ax=axes[1, 0]) # Plot a histogram and kernel density estimate sns.distplot(d, color="m", ax=axes[1, 1]) plt.setp(axes, yticks=[]) plt.tight_layout() plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 模块字符串 ''' 学习使用seaborn分组盒图Group boxplots。 ''' # 模块导入 # 标准库导入 import ssl # 第三方库导入 import seaborn as sns import matplotlib.pyplot as plt # seaborn global configuration sns.set(style="ticks", palette="pastel") # urllib's ssl cert configuratioon ssl._create_default_https_context = ssl._create_unverified_context # Load the example tips dataset tips = sns.load_dataset("tips") # Draw a nested boxplot to show bills by day and time sns.boxplot(x="day", y="total_bill", hue="smoker", palette=["m", "g"], data=tips) sns.despine(offset=10, trim=True) plt.show()
tabela = [' '] * 10 rodada = 1 n1 = 0 n2 = 0 # função para imprimir a tabela a cada movimento; def imprimeTabela(): print(tabela[1], '|', tabela[2], '|', tabela[3]) print("----------") print(tabela[4], '|', tabela[5], '|', tabela[6]) print("----------") print(tabela[7], '|', tabela[8], '|', tabela[9]) print() # função para verificar se um dos jogadores é o vencedor. def vencedor(jogador): if (((tabela[1] == tabela[2] == tabela[3] == "X") or (tabela[1] == tabela[2] == tabela[3] == "O")) or ((tabela[4] == tabela[5] == tabela[6] == "X") or (tabela[4] == tabela[5] == tabela[6] == "O")) or ((tabela[7] == tabela[8] == tabela[9] == "X") or (tabela[7] == tabela[8] == tabela[9] == "O")) or ((tabela[1] == tabela[4] == tabela[7] == "X") or (tabela[1] == tabela[4] == tabela[7] == "O")) or ((tabela[2] == tabela[5] == tabela[8] == "X") or (tabela[2] == tabela[5] == tabela[8] == "O")) or ((tabela[3] == tabela[6] == tabela[9] == "X") or (tabela[3] == tabela[6] == tabela[9] == "O")) or ((tabela[1] == tabela[5] == tabela[9] == "X") or (tabela[1] == tabela[5] == tabela[9] == "O")) or ((tabela[3] == tabela[5] == tabela[9] == "X") or (tabela[3] == tabela[5] == tabela[9] == "O"))): print("-------------------------------------") print("Jogador %d é o vencedor!!!" % jogador) print("-------------------------------------") return 1 # # faz a jogada do jogador 1 e imprime a tabela. def jogador_1(): print("Jogador 1") n1 = int(input("Informe o numero correspondente ao espaço da tabela: ")) while ((1 > n1) or (n1 > 9) or (n1 == n2) or (tabela[n1] != ' ')): # o "and tabeça[n1] == '' " evita que o mesmo jogador digite uma posição já informada por ele. # Ex: o jogador 1 digita 5 na primeira rodada e novamente 5 na quarta rodada. n1 = int(input("Informe o numero correspondente ao espaço da tabela: ")) tabela[n1] = "X" imprimeTabela() # faz a jogada do jogador 2 e imprime a tabela. def jogador_2(): print("Jogador 2") n2 = int(input("Informe o numero correspondente ao espaço da tabela: ")) while ((1 > n2) or (n2 > 9) or (n2 == n1) or (tabela[n2] != ' ')): n2 = int(input("Informe o numero correspondente ao espaço da tabela: ")) tabela[n2] = "O" imprimeTabela() print("----------------------------------------------------------") print("\t\t\t\t\t JOGO DA VELHA") print("----------------------------------------------------------\n") while rodada <= 5: print() print("\t\t\t\t\t\tRODADA %d\n" % rodada) jogador_1() if vencedor(1) == 1: break # o programa é interrompido após a ultima jogada do jogador 1 na rodada 5 # ja que o jogador 1 jogará mais vezes que o jogador 2, pelo fato da tabela possuir um numero impar de casas, # o jogo será interrompido após a 9ª jogada. if (rodada == 5): if vencedor(1) != 1 and vencedor(2) != 1: print("-------------------------------------") print("\t\t\tEmpatado!!!") print("-------------------------------------") break # caso contrário... else: jogador_2() if vencedor(2) == 1: break rodada = rodada + 1
print("PLAYER 1 IS ASSIGNED X and PLAYER 2 IS ASSIGNED O BY DEFAULT") main = [] #list for x in range(0, 9, 1): main.append(str(x + 1)) # assigning values in the matrix playerOneTurn = True # initialization winner = False # initialization def printBoard(): for i in range(7,0,-3) : # got right by trial and error :) print(main[i-1]+main[i]+main[i+1]) #displaying count = 0 while not winner: printBoard() if (count >= 9): print("Draw") break if playerOneTurn: #When it is Player One it is changed in the end of the while loop print("Player 1 Move(X):") else: # When it is NOT Player One ie. Player Two it was changed in the end of the existing while loop print("Player 2 Move(O) :") choice = int(input(">> ")) if (choice > 9): print("DRAW") if main[choice - 1] == 'X' or main[choice - 1] == 'O': print("You cannot place your move where someone or you has already done NO NO \n PENALTY") break if playerOneTurn: #When it is Player One count += 1 main[choice - 1] = 'X' else: # When it is NOT Player One ie. Player Two count += 1 main[choice - 1] = 'O' playerOneTurn = not playerOneTurn # changing the state of the variable # the winner case checkings #diagonal if ((main[0] == main[4] == main[8]) or (main[2] == main[4] == main[6])): winner = True printBoard() # rows and columns if ((main[6] == main[7] == main[8]) or (main[3] == main[4] == main[5]) or (main[0] == main[1] == main[2]) or (main[6] == main[3] == main[0]) or (main[7] == main[4] == main[1]) or (main[2] == main[5] == main[8]) ): winner = True printBoard() print("Player " + str((int(playerOneTurn + 1))) + " wins!\n")
x = float(input("Enter a number: ")) n = int(input("Enter the degree of accuracy: ")) def fact(i): if(i==1): return 1 else: x = i*fact(i-1) return x ex = 1 print(fact(n)) for i in range(1,n): ex = ex + ((x**i)/fact(i)) print(ex)
banyak_data = int(input("Masukkan jumlah data: ")) a = [] jumlah = 0 for i in range(0 ,banyak_data): nilai = int(input("Masukkan data ke-%d: " % (i + 1))) a.append(nilai) jumlah = jumlah + nilai rata_rata = jumlah/banyak_data print("Rata rata: ", format(rata_rata, '.2f'))
""" Q3.Write a menu driven program that shows the working of a library. The menu option should be --ADD BOOK INFORMATION --DISPLAY BOOK INFORMATION --LIST ALL BOOKS OF GIVEN AUTHOR --LIST THE COUNT OF BOOKS IN THE LIBRARY --EXIT """ database = {} z=True while(z): class Library: print("------MENU-----") print("1.ADD BOOK INFORMATION\n2.DISPLAY BOOK INFORMATION\n3.LIST ALL BOOKS OF GIVEN AUTHOR \n4.LIST THE COUNT OF BOOKS IN THE LIBRARY \n5.EXIT") def inputdata(self,author,book): database[book]=author print("add complete") def display(self): print(*database,*database.values()) def liststep(self,author): def fill(n): if database[n]==author: return True else: return False res=filter(fill,database) for i in res: print(i) def countbook(self): print("total number of book present in library is ",len(database.keys())) l=Library() ch=input("Enter your choice:\n") if ch=='1': a=input("Enter the name of autnhor:\n") b=input("Enter the book name:\n") l.inputdata(a,b) elif ch=='2': l.display() elif ch=='3': aut=input("Enter the name of author to list books:\n") l.liststep(aut) elif ch=='4': l.countbook() else: print("Extited") k=input("do want to enter a number(y/n):\n") if k!="y": z=False
#Q6.Write a program to accept 5 names from user and store these names into an array sort these array element in alphabetical order. list1=[] z=True while(z): n=input("Enter a name:\n") list1.append(n) a=input("do want to enter a name(y/n):\n") if a!="y": z=False print("your list is:\n") print(list1) print("your sorted list is:\n") for i in list1: list1.sort() print(*list1)
""" Write a program to accept three sides of a triangle as input and print whether the Trangle is valid or Not. (The trangle is valid, if sum of each of the two sides is greater then the third side.) """ class Triangle: def check(self,a,b,c): if (a+b>c): print("triangle is valid") elif (b+c>a): print("triangle is valid") elif (c+a>b): print("triangle is valid") else: print("triangle is not valid") t=Triangle() a=int(input("enter the first side of a triangle")) b=int(input("enter the second side of the triangle")) c=int(input("enter the third side of the triangle")) t.check(a,b,c)
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': N = int(input()) arr=[] for N_itr in range(N): firstNameEmailID = input().split() firstName = firstNameEmailID[0] emailID = firstNameEmailID[1] if re.search(".+@gmail\.com$", emailID): arr.append(firstName) arr.sort() for firstName in arr: print(firstName)
class NextSequence: # operation = ["*", "+","-","/","^"] sequence = [] 2, 4, 6, 8 def __init__(self): print("Start") def ask_sequence(self): temp = input("Input your sequence, make sure your numbers are split by ',' with no spaces\n") self.sequence = temp.split(",") self.sequence = list(map(int, self.sequence)) def is_multiplication(self, c): multiplyer = c[1] / c[0] for a in range(1, len(c) - 1): if multiplyer != c[a + 1] / c[a]: return [False, False] return [True,multiplyer] def is_addition(self, a): factor = a[1] - a[0] for b in range(len(a) -1): if a[b]+factor != a[b+1]: return [False,False] return [True , factor] def pattern_differenceM(self, b): dif_array = [] for a in range(len(b)-1): dif_array.append(b[a+1]-b[a]) if self.is_multiplication(dif_array)[0]: return self.is_multiplication(dif_array) return False def addition_prev(self,array): last_number = 1 current_sum = 0 lastElement = array[len(array)-1] for i in range(len(array)-2, 0, -1): current_sum = current_sum + array[i] if current_sum == lastElement: second = len(array)-2 temp_sum = 1 for j in range(1,last_number+1): temp_sum = temp_sum + (array[len(array)-2-j]) if(array[len(array)-2] == temp_sum): return [True, last_number] last_number = last_number+1 return[False, False] def fucked_up_sequence_1(self): last = self.sequence[len(self.sequence)-1] second_last = self.sequence[len(self.sequence)-2] if self.sequence[len(self.sequence)-3] == last / second_last: if self.sequence[len(self.sequence)-4] == self.sequence[len(self.sequence)-2] / self.sequence[len(self.sequence)-3]: return True return False def pattern_differenceA(self, b): dif_array = [] for a in range(len(b) - 1): dif_array.append(b[a + 1] - b[a]) if self.is_addition(dif_array)[0]: return self.is_addition(dif_array) return False def findPattern(self): half = len(self.sequence) number = self.sequence[half] temp1 = self.sequence temp1.remove(number) def next_value(self): if (self.is_multiplication(self.sequence)[0]): return int(self.sequence[1] / self.sequence[0] * self.sequence[len(self.sequence)-1]) if (self.is_addition(self.sequence)[0]): return int(self.sequence[1]-self.sequence[0]+ self.sequence[len(self.sequence)-1]) if self.pattern_differenceA(self.sequence): return int(self.sequence[len(self.sequence)-1] - self.sequence[len(self.sequence)-2])+self.pattern_differenceA(self.sequence)[1] + self.sequence[len(self.sequence) -1 ] if self.fucked_up_sequence_1(): return int(self.sequence[len(self.sequence)-12]*self.sequence[len(self.sequence)-2]) if self.addition_prev(self.sequence)[0]: sum = 1; for i in range (self.addition_prev(self.sequence)[1]): sum = sum + self.sequence[self.sequence[len(self.sequence)]-i] return sum a = NextSequence() while True: a.ask_sequence() print ("The Next Number is : " + str(a.next_value()))