text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- #Gerar a informação de BUY, a compra realizada para o par SESSION, ITEM. #INPUT ##SESSION, DAY, MONTH, YEAR, TIME, ITEM, CATEGORY #14679, 03, 04, 2014, 04.73, 214645087, 0 #14672, 02, 04, 2014, 07.61, 214664919, 0 #14672, 02, 04, 2014, 07.61, 214826625, 0 #14673, 06, 04, 2014, 15.85, 214696625, 0 #14673, 06, 04, 2014, 15.96, 214696740, 0 #INPUT 2 #SESSION, DAY, MONTH, YEAR, TIME, ITEM, PRICE QUANTITY #11, 3, 4, 2014, 11.07, 214821371, 1046, 1 #11, 3, 4, 2014, 11.07, 214821371, 1046, 1 #12, 2, 4, 2014, 10.7, 214717867, 1778, 4 #489758, 6, 4, 2014, 9.98, 214826955, 1360, 2 #OUTPUT - column-buys.dat #0 #1 #0 #0 def read_file_parts(path, pattern_filename, match_numeric, list_index): list_temp = [] for i in list_index: print "Reading file:", pattern_filename.replace(match_numeric, str(i)) arq = open(path + pattern_filename.replace(match_numeric, str(i)), "r") list_temp = list_temp + arq.readlines() arq.close() return list_temp def read_single_file(filename): lines = "" print "Reading file:", filename arq = open(filename, "r") lines = arq.readlines() return lines def busca_binaria(lista, busca): inicio, fim = 0, len(lista)-1 while inicio <= fim: meio = (inicio + fim)/2 if busca == lista[meio]: return lista.index(lista[meio]) else: if lista[meio] < busca: inicio = meio + 1 else: fim = meio - 1 return None def sort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) # Don't forget to return something! return sort(less)+equal+sort(greater) # Just use the + operator to join lists # Note that you want equal ^^^^^ not pivot else: # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array. return array import os import sys sys.setrecursionlimit(1000000000) path = "/".join(os.path.dirname(os.path.realpath(__file__)).split("/")[0:-2]) + "/Data/" print "Loading CLICKS data" clicks_lines = read_file_parts(path, "clicks-proc-basico/clicks-proc-basico-parteX.dat", "X", [1,2,3,4,5,6]) print len(clicks_lines), "lines loaded\n" print "Loading BUYS data" buys_lines = read_file_parts(path, "buys-proc-basico/buys-proc-basico-parteX.dat", "X", [1,2]) print len(buys_lines), "lines loaded\n" print "Sorting buys data" buys_lines = sort(buys_lines) print "Buys data sorted\n" #monta uma lista ordenada das sessions em que houve compra buys_sessions_list = [] buys_items_list = [] arq_logs = open(path + "logs/log_buy_column.txt", "w") count = 0 for linha in buys_lines: count = count + 1 linha_split = linha.replace("\n","").split(",") session = linha_split[0] item = linha_split[5] if(not busca_binaria(buys_sessions_list, session)): buys_sessions_list.append(session) list_temp = [item] buys_items_list.append(list_temp) else: last_index = len(buys_items_list) - 1 buys_items_list[last_index].append(item) if(count % 100000 == 0): print "Processing Buys ", str(((count+0.0)/len(buys_lines)) * 100)[0:7] + "%" + " done!" arq_logs.write("Processing Buys " + str(((count+0.0)/len(buys_lines)) * 100)[0:7] + "%" + " done!\n") conta_linhas = 0 #gera array que representa a info de buy da linha info_buy = [] for linha in clicks_lines: conta_linhas = conta_linhas + 1 linha_split = linha.replace("\n","").split(",") session = linha_split[0] item = linha_split[5] buy_index = busca_binaria(buys_sessions_list, session) if (not buy_index == None): #print session, item, buys_items_list[buy_index] if (item in buys_items_list[buy_index]): info_buy.append(1) #print session, item else: info_buy.append(0) else: info_buy.append(0) if(conta_linhas % 5000000 == 0): print "Processing Clicks ", str(((conta_linhas+0.0)/len(clicks_lines)) * 100)[0:7] + "%" + " done!" arq_logs.write("Processing Clicks " + str(((conta_linhas+0.0)/len(clicks_lines)) * 100)[0:7] + "%" + " done!\n") print "Processing Clicks 100% done!" #salvando coluna de info de buy arq_w = open(path + "columns/clicks-column-buy.dat", "w") i = 0 for i in info_buy: arq_w.write(str(i)) arq_w.write("\n") arq_w.close()
files = ("HarkTheHerald.txt", "JoyToTheWorld.txt","AngelsWeHaveHeard.txt") new_file = "" def get_fixed_filename(files_new): new_file = "" for filename in files_new: for i, letter in enumerate(filename): new_file += letter print(new_file) try: if letter.islower() and filename[i + 1].isupper(): new_file += "_" except IndexError: continue return new_file for filenames in files: print(get_fixed_filename(filenames))
import pymysql from pymysql.cursors import DictCursor connection = pymysql.connect( host='localhost', user='root', password='123456', db='sys', charset='utf8mb4', cursorclass=DictCursor) try: with connection.cursor() as cursor: answer = input("Would you like to add new guest to DB? (y/n) ") if answer == 'y' or answer == 'Y': first_name = input('Input guest First Name: ') last_name = input('Input guest Last Name: ') email = input('Input guest Email: ') phones = input('Input guest Phones: (use space to separate them) ').split() sql = "INSERT INTO guests (first_name, last_name, email) VALUES (%s, %s, %s)" cursor.execute(sql, (first_name, last_name, email)) connection.commit() sql = "INSERT INTO phones (guest_id, phone_number) VALUES " for phone in phones: if phone == phones[-1]: sql += '(LAST_INSERT_ID(), {})'.format(phone) else: sql += '(LAST_INSERT_ID(), {}), '.format(phone) cursor.execute(sql) connection.commit() else: print('Ok. here what you have in DB: ') with connection.cursor() as cursor: sql = "SELECT * FROM guests LEFT JOIN phones USING (guest_id)" cursor.execute(sql) result = cursor.fetchall() print(*result, sep='\n') finally: connection.close()
# Convolutional Neural Network # Part 1 - Building the CNN # Importing the keras libraries and packages from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense #Initialising the CNN classifier=Sequential() #Step 1-Convolution classifier.add(Convolution2D(32,3,3,input_shape=(64,64,3),activation='relu')) #Step 2-Pooling classifier.add(MaxPooling2D(pool_size=(2,2))) #Adding a second convolutional layer classifier.add(Convolution2D(32,3,3,activation='relu')) classifier.add(MaxPooling2D(pool_size=(2,2))) #Step 3- Flattening classifier.add(Flatten()) #Step 4-Full Connection classifier.add(Dense(units=128,activation='relu')) classifier.add(Dense(units=1,activation='sigmoid')) # Part 3 - Training the CNN # Compiling the CNN classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy']) #Fitting the CNN to images from keras.preprocessing.image import ImageDataGenerator # Generating images for the Training set train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) # Generating images for the Test set test_datagen = ImageDataGenerator(rescale = 1./255) # Creating the Training set training_set = train_datagen.flow_from_directory('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') # Creating the Test set test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, samples_per_epoch=8000, nb_epoch=25, validation_data=test_set, nb_val_samples=2000) #4. Making new prediction import numpy as np from keras.preprocessing import image test_image=image.load_image('samples.jpg',target_size=(160,160)) test_image=image.img_to_array(test_image) test_image=np.expand_dims(test_image,axis=0) result=classifier.predict(test_image) if(result[0][0]==1): print("Yes") else: print("NO")
""" https://adventofcode.com/2016/day/1 Note: Implemented for speed in terms of solving the solution, not for efficiency or scalability """ import unittest def process_directions(start_position, directions, stop_on_same_location=False): north = 0 east = 1 south = 2 west = 3 x_pos = start_position[0] y_pos = start_position[1] locations_visited = set() heading = north steps = directions.split(',') for step in steps: direction = step.strip()[0] distance = step.strip()[1:] heading = get_heading(heading, direction) for i in range(int(distance)): if heading == north: y_pos += 1 elif heading == south: y_pos -= 1 elif heading == east: x_pos += 1 elif heading == west: x_pos -= 1 loc = (x_pos, y_pos) if stop_on_same_location and loc in locations_visited: return loc locations_visited.add(loc) return x_pos, y_pos def get_heading(heading, direction): new_heading = heading if direction == 'R': new_heading = heading + 1 elif direction == 'L': new_heading = heading - 1 if new_heading > 3: new_heading = 0 elif new_heading < 0: new_heading = 3 return abs(new_heading) def calculate_distance_travelled(start_pos, end_pos): x = end_pos[0] - start_pos[0] y = end_pos[1] - start_pos[1] return abs(x) + abs(y) class TestDay01(unittest.TestCase): def test_part_1_distance_travelled(self): position = (0, 0) input = 'L5, R1, L5, L1, R5, R1, R1, L4, L1, L3, R2, R4, L4, L1, L1, R2, R4, R3, L1, R4, L4, L5, L4, R4, L5, R1, R5, L2, R1, R3, L2, L4, L4, R1, L192, R5, R1, R4, L5, L4, R5, L1, L1, R48, R5, R5, L2, R4, R4, R1, R3, L1, L4, L5, R1, L4, L2, L5, R5, L2, R74, R4, L1, R188, R5, L4, L2, R5, R2, L4, R4, R3, R3, R2, R1, L3, L2, L5, L5, L2, L1, R1, R5, R4, L3, R5, L1, L3, R4, L1, L3, L2, R1, R3, R2, R5, L3, L1, L1, R5, L4, L5, R5, R2, L5, R2, L1, L5, L3, L5, L5, L1, R1, L4, L3, L1, R2, R5, L1, L3, R4, R5, L4, L1, R5, L1, R5, R5, R5, R2, R1, R2, L5, L5, L5, R4, L5, L4, L4, R5, L2, R1, R5, L1, L5, R4, L3, R4, L2, R3, R3, R3, L2, L2, L2, L1, L4, R3, L4, L2, R2, R5, L1, R2' end_position = process_directions(position, input) distance = calculate_distance_travelled(position, end_position) print('Part 1. Distance Travelled:', distance) self.assertEqual(226, distance) def test_part_2_distance_travelled_at_first_location_visited_twice(self): position = (0, 0) input = 'L5, R1, L5, L1, R5, R1, R1, L4, L1, L3, R2, R4, L4, L1, L1, R2, R4, R3, L1, R4, L4, L5, L4, R4, L5, R1, R5, L2, R1, R3, L2, L4, L4, R1, L192, R5, R1, R4, L5, L4, R5, L1, L1, R48, R5, R5, L2, R4, R4, R1, R3, L1, L4, L5, R1, L4, L2, L5, R5, L2, R74, R4, L1, R188, R5, L4, L2, R5, R2, L4, R4, R3, R3, R2, R1, L3, L2, L5, L5, L2, L1, R1, R5, R4, L3, R5, L1, L3, R4, L1, L3, L2, R1, R3, R2, R5, L3, L1, L1, R5, L4, L5, R5, R2, L5, R2, L1, L5, L3, L5, L5, L1, R1, L4, L3, L1, R2, R5, L1, L3, R4, R5, L4, L1, R5, L1, R5, R5, R5, R2, R1, R2, L5, L5, L5, R4, L5, L4, L4, R5, L2, R1, R5, L1, L5, R4, L3, R4, L2, R3, R3, R3, L2, L2, L2, L1, L4, R3, L4, L2, R2, R5, L1, R2' end_position = process_directions(position, input, True) distance = calculate_distance_travelled(position, end_position) print('Part 2. Distance Travelled:', distance) self.assertEqual(79, distance) def test_part_2_distance_travelled_at_first_location_visited_twice_example_data(self): position = (0, 0) input = 'R8, R4, R4, R8' end_position = process_directions(position, input, True) distance = calculate_distance_travelled(position, end_position) print('Distance Travelled:', distance) self.assertEqual(4, distance) if __name__ == '__main__': unittest.main()
""" https://adventofcode.com/2020/day/6 Note: Implemented for speed in terms of solving the solution, not for efficiency or scalability """ import unittest input_file = r'resources/day7_input.txt' def part_1(data): for line in data: print(line) return -1 def read_input_data(filename): with open(filename) as file: data = [line.strip() for line in file.readlines()] return data class TestDay7(unittest.TestCase): def test_part_1(self): result = part_1(read_input_data(input_file)) print('Part1:', result) self.assertEqual(0, result) if __name__ == '__main__': unittest.main()
# OSM Points and Streets # Build from nodes and ways # For each node, add it to node-ids with lat and lng # For each way, add them to Streets ## If Street has a node with a previous street, build a connectsto relation between the two # 0) Opening the file import urllib, urllib2 osmfile = open('macon.osm', 'r') allnodes = { } nodes = { } inway = False wayname = "" waynodes = [] addedways = [] wayids = {} isHighway = False firstToAdd = "wetherlyln" for line in osmfile: # 1) Becoming aware of nodes #if(line.find('<node id=') > -1): # node_id = line[ line.find('id=') + 4 : len(line) ] # node_id = node_id[ 0 : node_id.find('"') ] # lat = line[ line.find('lat=') + 5 : len(line) ] # lat = lat[ 0 : lat.find('"') ] # lng = line[ line.find('lon=') + 5 : len(line) ] # lng = lng[ 0 : lng.find('"') ] # allnodes[ node_id ] = lat + "," + lng # 2) Add Streets if(line.find('<way') > -1): inway = True elif(inway == True): if(line.find('<nd ref') > -1): # add this node id id = line[ line.find('ref="') + 5 : len(line) ] id = id[ 0 : id.find('"') ] waynodes.append( id ) elif(line.find('k="highway"') > -1): isHighway = True elif(line.find('k="name"') > -1): # found the road name wayname = line[ line.find('v="') + 3 : len(line) ] wayname = wayname[ 0 : wayname.find('"') ] # use database's preferred parsing of street names wayname = wayname.lower().replace(' ','') elif(line.find('</way>') > -1): # only care about roads with names if(wayname != "" and isHighway == True): # check if way needs to be added to the database if(not (wayname in addedways)): print wayname addedways.append( wayname ) values = { "name": wayname } data = urllib.urlencode(values) # store final url: /streets/ID if((firstToAdd == None) or (firstToAdd == wayname)): wayids[ wayname ] = urllib2.urlopen(urllib2.Request('http://houseplot.herokuapp.com/streets', data)).geturl().split('streets/')[1] print wayids[ wayname ] firstToAdd = None else: # retrieve this way ID by name wayids[ wayname ] = urllib2.urlopen('http://houseplot.herokuapp.com/streetname/' + wayname).read() # now add relationships to nodes in the way for node in waynodes: if(nodes.has_key(node)): for streetid in nodes[node]: # bidirectional if(streetid == wayids[wayname]): continue if(firstToAdd is None): #print "attempting connection at " #print allnodes[node] values = { "streetid": wayids[wayname] #, #"latlng": allnodes[node] } data = urllib.urlencode(values) urllib2.urlopen(urllib2.Request('http://houseplot.herokuapp.com/streets/' + streetid + '/follow', data)).read() values = { "streetid": streetid #, #"latlng": allnodes[node] } data = urllib.urlencode(values) urllib2.urlopen(urllib2.Request('http://houseplot.herokuapp.com/streets/' + wayids[wayname] + '/follow', data)).read() print "connection made" nodes[node].append( wayids[ wayname ] ) else: nodes[node] = [ wayids[wayname] ] # reset way defaults wayname = "" waynodes = [] isHighway = False
import numpy as np import time import random """ neuralnet.py ~~~~~~~~~~ The functions in this module will allow for the creation of a feed-forward neural network with standard sigmoidal units. The weights for each node will be optimized with a stochastic gradient descent function (the derivatives will be calculated with backpropagation) and the network will be trained with cross-validation on a training set. The inputs will be the network architechure (number of input nodes, hidden layer nodes, and output nodes), learning rate, and training data. Note: This code is based off of the nerual network code provided at: http://neuralnetworksanddeeplearning.com/chap1.html and https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6 """ def sigmoid(z): """The sigmoid function.""" return 1.0/(1.0+np.exp(-z)) def sigmoid_prime(z): """Derivative of the sigmoid function.""" return np.exp(-z)/((1+np.exp(-z))**2) class Network: def __init__(self, sizes): """The list ``sizes`` contains the number of neurons in each layer of the network. Since I am creating a three layer network, the list should be three layers specifying the size of the input, hidden, and output layer, respectively. The biases and weights for the network are initialized randomly, using a Gaussian distribution with mean 0, and variance 1 for the biases and mean 0, and variance 1/(# inputs)**0.5 for the weights. Note that the first layer is assumed to be an input layer. """ #self.input = x self.num_layers = len(sizes) self.sizes = sizes self.default_weight_initializer() self.cost = [] # will record the cost for all inputs in training data self.cost_overall = [] #self.y = y #self.output = np.zeros(y.shape) def default_weight_initializer(self): #Initialize the bias for all the hidden layers and output layer #as a y x 1 array where y = # neurons in the layer self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]] #Initialize the weights for all the hidden layers and output layer #as a y x n array where y = # neurons in the layer n = # input nodes self.weights = [np.random.randn(y, n)/np.sqrt(n) for y, n in zip(self.sizes[1:], self.sizes[:-1])] def feedforward(self, a): """Return the output of the network if ``a`` is input by feeding it through each layer. """ for b, w in zip(self.biases,self.weights): a = sigmoid(np.dot(w, a)+b) return a def cost_fn(self, a, y): """Return the cost associated with an output ``a`` and desired output ``y``. Note that np.nan_to_num is used to ensure numerical stability. In particular, if both ``a`` and ``y`` have a 1.0 in the same slot, then the expression (1-y)*np.log(1-a) returns nan. The np.nan_to_num ensures that that is converted to the correct value (0.0). """ #return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a))) return np.sum(np.nan_to_num(y*np.log(a)+(1-y)*np.log(1-a))) def cost_derivative(self, a, y): return np.nan_to_num((a-y)/(a*(1-a))) def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``. """ #Intialize the gradient values as zero nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x #input activations = [] # list to store all the activations, layer by layer activations.append(activation) zs = [] # list to store all the z vectors (weighted inputs), layer by layer for i in range(len(self.biases)): #print(activation) #Go through each layer and store the activations and weighted inputs (z) z = np.dot(self.weights[i], activation) + np.array(self.biases[i]) #Calculate weighted input zs.append(z) activation = sigmoid(z) #Calculate output activations.append(activation) # backward pass self.cost.append(self.cost_fn(self.feedforward(activations[0]), y)) #-1 delta = self.cost_derivative(activations[-1], y) * \ sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) for l in range(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) def update_mini_batch(self, mini_batch, eta, train_len): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)`` and ``eta`` is the learning rate, """ #Initialize update matrices nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] #cost_mini_holder = [] for pair in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(pair[0], pair[1]) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] #cost_mini_holder.append(cost) self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] #return np.mean(cost_mini_holder) def SGD(self, training_data, epochs, mini_batch_size, eta): #test_data=None """ Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. Epochs designates how many times you will pass through the training set. Mini_batch_size designates the size of the sample of the training data that the model will iterate through before updating the weights and biases. Eta is the learning rate If ``test_data`` is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out. This is useful for tracking progress, but slows things down substantially. """ start = time.time() n = len(training_data) #cost_avg = [] for j in range(epochs): #for each epoch self.cost = [] random.shuffle(training_data) #shuffle the training data mini_batches = [training_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] #partition data into mini-batches for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta, n) #update weights self.cost_overall.append(-1/n * np.sum(self.cost)) if j > 2 and abs(self.cost_overall[-1] - self.cost_overall[-2]) < 0.00001: end = time.time() print("Epochs complete in:", (end-start)/60, " min") return end = time.time() print("Epochs complete in:", (end-start)/60, " min") #This was written specifically to use for the Rap1 training data def cross_val(self, pos_data, neg_data, epochs, mini_batch_size, eta, k): self.accuracy = [] random.shuffle(pos_data) pos_batch_size = len(pos_data) // k pos_chunks = [pos_data[j:j+pos_batch_size] for j in range(0, len(pos_data), k)] random.shuffle(neg_data) neg_batch_size = len(neg_data) // k neg_chunks = [neg_data[j:j+neg_batch_size] for j in range(0, len(neg_data), k)] for i in range(k): pos_data_holder = [] neg_data_holder = [] self.default_weight_initializer() pos_test = pos_chunks[i] neg_test = neg_chunks[i] for x in list(set(list(range(k))) - set([i])): pos_data_holder = pos_data_holder + pos_chunks[x] neg_data_holder = neg_data_holder + neg_chunks[x] train_data = pos_data_holder + neg_data_holder self.SGD(train_data, epochs, mini_batch_size, eta) self.accuracy.append(self.evaluate(pos_test+neg_test)) def evaluate(self, test_data): """Return the % of test inputs for which the neural network outputs the correct result. """ test_results = [([round(i[0]) for i in self.feedforward(x)][0], y) for (x, y) in test_data] accuracy = [(x,y) for (x,y) in test_results if x == y] return len(accuracy)/len(test_data) def evaluate_8_3_8(self, test_data): """Return the otuput for the 8x3x8 encoder""" test_results = [([round(i[0]) for i in self.feedforward(x)], y) for (x, y) in test_data] return test_results def output(self, test_data): """ Return the original sequence and the probability of it being a Rap1 sequence """ vec_2_base = {tuple([1,0,0,0]):"A",tuple([0,1,0,0]):"T", tuple([0,0,1,0]):"C", tuple([0,0,0,1]):"G"} test_results = [(self.feedforward(x), y) for (x, y) in test_data] sequences = [] output = [] for pair in test_data: sequence = '' for i in range(0,68,4): index = pair[0][i:i+4] test = [] for j in index: test = test + list(j) sequence = sequence + vec_2_base[tuple(test)] sequences.append(sequence) for k in range(len(test_data)): output.append([sequences[k],test_results[k][0][0][0]]) return output
class HTMLNode: def __init__(self, tag="", attributes=(), content="", inline=False): self.tag = tag self.attributes = attributes self.children = [] self.content = content self.parent = None self.inline = inline def addChild(self, child): self.children.append(child) self.children[-1].setParent(self) def setParent(self, parent): self.parent = parent def getFirstChild(self): if len(self.children) > 0: return self.children[0] return None def getLastChild(self): if len(self.children) > 0: return self.children[-1] return None def getChildren(self): return self.children def getParent(self): return self.parent def isInline(self): return self.inline class HTMLTree: def __init__(self): self.root = HTMLNode() self.currentNode = self.root self.html = "" def add(self, node : HTMLNode): self.currentNode.addChild(node) def goDown(self): self.currentNode = self.currentNode.getLastChild() def goUp(self): self.currentNode = self.currentNode.getParent() def createHtml(self): """ Creates HTML based on the content of the tree Returns str object with the html code """ self.hmtl = "" self._traverseTree(self.root.getFirstChild()) # not self.root, because self.root is an empty HTMLNode return self.html def _traverseTree(self, node, depth=0): self._createOpeningTag(node, depth) self._handleChildren(node.getChildren(), depth) self._addClosingTag(node, depth) def _createOpeningTag(self, node, depth): self._appendOpeningTag(node, depth) self._addAttributesToOpeningTag(node) self._closeOpeningTag(node) def _appendOpeningTag(self, node, depth): tab = "\t" self.html += f"{depth*tab if not node.getParent().isInline() else ''}<{node.tag}{' ' if len(node.attributes) > 0 else ''}" def _closeOpeningTag(self, node): newLine = "\n" self.html += f">{newLine if not node.isInline() else ''}" def _addAttributesToOpeningTag(self, node): for attribute in node.attributes: if attribute[0] == ".": self.html += f'class="{attribute[1:]}" ' elif attribute[0] == "#": self.html += f'id="{attribute[1:]}" ' else: self.html += attribute + " " def _addClosingTag(self, node, depth): tab = "\t" newLine = "\n" self.html += f"{depth*tab if not node.isInline() else ''}</{node.tag}>{newLine if not node.getParent().isInline() else ''}" def _handleChildren(self, children, depth): tab = "\t" newLine = "\n" for child in children: if child.tag == "": self.html += f"{(depth+1)*tab if (not child.getParent().isInline()) and (not child.isInline()) else ''}{child.content} {newLine if not child.getParent().isInline() else ''}" else: self._traverseTree(child, depth+1)
student = {'first_name':'robin','last_name': 'islam', 'gender': 'male', 'age': 22, 'martal status': 'single', 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'country':'Bangladesh', 'city': 'dhaka', 'address': 'gulshan'} key = student.keys() print(key)
from tkinter import * from tkinter import messagebox window = Tk() #function conver Kg to G def ConvertKgtoG(): tmp = float(txtIn.get())*1000; messagebox.showinfo('Kilograms To Grams',str(tmp) + ' Grams') #function conver Kg to Metric Tons def ConvertKgtoMT(): tmp = float(txtIn.get())/1000; messagebox.showinfo('Kilograms to Metric Tons',str(tmp) + ' Metric Tons') #function conver Kg to Pounds def ConvertKgtoP(): tmp = float(txtIn.get())*2.20462262; messagebox.showinfo('Kilograms to Pounds',str(tmp) + ' Pounds') #Create input txtIn = Entry(window,width = 20) txtIn.grid(column = 0,row = 0) window.title("Convert Kilogram") #add Convert Gram Button btnG = Button(window,bg ="darkblue",fg = "white", text="To Grams", command = ConvertKgtoG) btnG.grid(column=1, row=0) #add Convert miliGram Button btnMG = Button(window,bg ="green",fg = "red", text="To Metric Tons", command = ConvertKgtoMT) btnMG.grid(column=2, row=0) #add COnver pounds Button btnP = Button(window, bg ="Black",fg = "white" , text="To Pounds", command = ConvertKgtoP) btnP.grid(column=3, row=0) window.mainloop()
#!/usr/bin/python3 """This module contain a function that add two integers Args: a (int): first parameter b (int): second parameter """ def add_integer(a, b=98): """add_integer function that add two integers Returns: int: Addition between a + b.""" if type(a) is not int and type(a) is not float: raise TypeError("a must be an integer") if type(b) is not int and type(b) is not float: raise TypeError("b must be an integer") if type(a) == float: a = int(a) if type(b) == float: b = int(b) return a + b
#!/usr/bin/python3 """This module contains a function called write_file""" def write_file(filename="", text=""): """write_file function that overwrite a file or create new file Args: filename (str, optional): file name. Defaults to "". text (str, optional): string to write inside the file. Defaults to "". """ with open(filename, "w", encoding="utf-8") as a_file: num_chars = a_file.write(text) return num_chars
#!/usr/bin/python3 """This module contain a function that prints a square""" def print_square(size): """print_square function prints a square Args: size (int): size of the square """ if type(size) != int or (type(size) != int and size < 0): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for i in range(0, size): j = 0 for j in range(0, size): print("#", end="") print()
#!/usr/bin/python3 from sys import argv len_args = len(argv) - 1 if __name__ == "__main__": print("{:d} {}{}".format(len_args, "argument\ " if len_args == 1 else "arguments", ".\ " if len_args == 0 else ":")) i = 1 while i <= len_args: print("{:d}: {}".format(i, argv[i])) i += 1
#!/usr/bin/python3 """This module contains a class that defines a square. In the Square class we initialize each object by the __init__ method with a private instance variable called __size that takes the size variable's value passed as argument. Also checks if the size arg has a valid value. area method returns the area of the square. """ class Square: """Class that defines a square Attributes: __size (int): size of the square. """ def __init__(self, size=0): """__init__ method that initialize the __size attribute Args: size (int): Size to initialize the square. """ self.size = size @property def size(self): return self.__size @size.setter def size(self, value): """size method that set size attribute to value Args: value (int): Size to set size attribute to. """ if type(value) is not int: raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value def __call__(self): """__call__ method return the value of the square's area""" return (self.__size ** 2) def __lt__(self, other): """__lt__ method compare the instance value with other instance""" return self.__size < other.__size def ___le__(self, other): """__le__ method compare the instance value with other instance""" return self.__size <= other.__size def __eq__(self, other): """__eq__ method compare the instance value with other instance""" return self.__size == other.__size def __ne__(self, other): """__ne__ method compare the instance value with other instance""" return self.__size != other.__size def __gt__(self, other): """__gt__ method compare the instance value with other instance""" return self.__size > other.__size def __ge__(self, other): """__ge__ method compare the instance value with other instance""" return self.__size >= other.__size
#!/usr/bin/python3 """This module contain a function that divides all elements of a matrix""" def matrix_divided(matrix, div): """matrix_divided function divides all elements of a matrix Args: matrix (list of lists): two dimension matrix div (int, float): divisor Returns: list of lists: new matrix with all elements divided""" if type(matrix) != list or matrix == []: raise TypeError("matrix must be a matrix\ (list of lists) of integers/floats") # capture the first row len len_row = len(matrix[0]) # validate div conditions if type(div) != int and type(div) != float: raise TypeError("div must be a number") elif div == 0: raise ZeroDivisionError("division by zero") # validate rows len in matrix and values inside each list for i in matrix: if type(i) != list or i == []: raise TypeError("matrix must be a matrix\ (list of lists) of integers/floats") if len(i) == len_row: for j in i: if type(j) != int and type(j) != float: raise TypeError("matrix must be a matrix\ (list of lists) of integers/floats") else: raise TypeError("Each row of the matrix must have the same size") return list(map(lambda x: list(map(lambda y: round(y/div, 2), x)), matrix))
#!/usr/bin/python3 """This module contain a class that inherits list class""" class MyList(list): """Mylist class that inherits list class Args: list (class): list class """ def print_sorted(self): """print_sorted function that prints a list in sorted way""" print(sorted(self))
# -*- coding: utf-8 -*- """ Created on Wed Jun 12 12:55:08 2019 @author: jai """ x = 10 y = 3 print("10 divided by 3 is", x/y) print("remainder after 10 divided by 3 is", x%y)
#Justin Mitchell #2/22/2021 #Problem 1 Area of a Circle import math def areaOfCircle(radius): return math.pi * radius ** 2 r = float(input(" Please enter the radius of a circle: ")) area = areaOfCircle(r) print(" Area Of a Circle = %.2f" %area) #Program asks the user to enter the radius of the circle, then the area of the circle is provided to user.
import cs50 from sys import argv, exit if len(argv) != 2: # if not correct display message for correct usage and exit program with code (1) print("Usage: python roster.py house") exit(1) # call database as SQL function db = cs50.SQL("sqlite:///students.db") # SELECT from the table where house = command line argument myline = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", argv[1]) # print values per row[key] per line for row in myline: # if there's a middle name if row["middle"] == None: print(row["first"] + " " + row["last"] + ", born " + str(row["birth"])) else: print(row["first"] + " " + row["middle"] + " " + row["last"] + ", born " + str(row["birth"]))
from itertools import zip_longest DAY = 'day' HOUR = 'hour' NAME = 'name' class Formatter: def __init__(self, indent=5 * ' '): self.indent = indent def append(self, text, tag=None): raise NotImplementedError('Must override append() in derived class') def println(self, *args): sep = None for a in args: if sep: self.append(sep) else: sep = ' ' if isinstance(a, str): self.append(a) else: self.append(*a) self.append('\n') def show(self, previous, day, hour, name, text): if day: if previous: self.println() self.println((day, DAY)) if name: if not day: self.println() self.println((hour, HOUR), (name, NAME)) self.show_multiline(None, text) else: self.show_multiline(hour, text) def show_multiline(self, hour, text): hh = [(hour, HOUR)] if hour else [] for h, line in zip_longest(hh, text.split('\n'), fillvalue=self.indent): self.println(h, line)
# 1. 交換值 from xml.etree.ElementTree import Element import sys x, y = 1, 2 print(x, y) x, y = y, x print(x, y) # 2. 字符串列表合併為一個字符串 sentence_list = ["my", "name", "is", "George"] sentence_string = " ".join(sentence_list) print(sentence_string) # 3. 將字符串拆分為子字符串列表 sentence_string = "my name is George" sentence_string.split() print(sentence_string) # 4. 通過數字填充初始化列表 [0]*1000 # List of 1000 zeros [8.2]*1000 # List of 1000 8.2's # 5. 字典合併 x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y} print(x) print(y) print(z) # 6. 反轉字符串 name = "George" name[::-1] print(name[::-1]) # 7. 從函數返回多個值 def get_a_string(): a = "George" b = "is" c = "cool" return a, b, c sentence = get_a_string() (a, b, c) = sentence # 8. 列表解析式 a = [1, 2, 3] # Create a new list by multiplying each element in a by 2 b = [num*2 for num in a] # 9. 遍歷字典 m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value)) # 10. 同時遍歷列表的索引和值 m = ['a', 'b', 'c', 'd'] for index, value in enumerate(m): print('{0}: {1}'.format(index, value)) # 11. 初始化空容器 a_list = list() a_dict = dict() a_map = map() a_set = set() # 12. 刪除字符串兩端的無用字符 name = " George " name_2 = "George///" name.strip() # prints "George" name_2.strip("/") # prints "George" # 13. 列表中出現最多的元素 test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key=test.count)) # 14. 檢查對象的記憶體使用情況 x = 1 print(sys.getsizeof(x)) # 15. 將 dict 轉換為 XML def dict_to_xml(tag, d): ''' Turn a simple dict of key/value pairs into XML ''' elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) elem.append(child) return elem
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) xtrain, ytrain = mnist.train.next_batch(5000) xtest, ytest = mnist.test.next_batch(200) xtr = tf.placeholder("float", [None, 784]) xte = tf.placeholder("float", [784]) # reduce_sum takes the sum of all elements across an axis in a tensor distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1) pred = tf.arg_min(distance, 0) accuracy = 0. init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(len(xtest)): nearest_neighbour_index = sess.run(pred, feed_dict={xtr: xtrain, xte: xtest[i, :]}) print "Test: %d " % i, "Prediction: %d" % (np.argmax(ytrain[nearest_neighbour_index])), "Actual class: %d" % ( np.argmax(ytest[i])) if np.argmax(ytrain[nearest_neighbour_index]) == np.argmax(ytest[i]): accuracy += 1. / len(xtest) print "Completed.." print "The accuracy of the algorithm is: %.3f" % accuracy
#!/usr/bin/env python import unittest from acme import Product from acme_report import inventory_report, ADJECTIVES, NOUNS from random import randint class AcmeProductTests(unittest.TestCase): """Making sure Acme products are the tops!""" def test_default_product_price(self): """Test default product price being 10.""" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): """Test default product weight being 20.""" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_product_explode_set_value(self): """Test product explode value.""" prod2 = Product('Test2', weight=50, flammability=0.8) self.assertEqual(prod2.explode(), '...boom!') class AcmeReportTests(unittest.TestCase): """Making sure Acme report are the correct""" def test_default_num_products(self): """Test default number of product report is 30.""" report = inventory_report() self.assertEqual(self.report.number_of_products, 30) def test_legal_names(self): """Test product naming convention.""" report = inventory_report() product_names = report.combinednamelist adj_list = ADJECTIVES() noun_list = NOUNS() random_prod_selection = random.choice(product_names) self.assertIN(adj_list, random_prod_selection) self.assertIN(noun_list, random_prod_selection) self.assertIN(" ", random_prod_selection) if __name__ == '__main__': unittest.main()
s=input() buff=[] for x in s: if x == "0" or x == "1": buff.append(x) else: if len(buff) > 0: buff.pop() print("".join(buff))
s=input() vowel=["a","e","i","o","u"] if s in vowel: print("vowel") else: print("consonant")
A,a=input().split() if A.lower()==a: print("Yes") else: print("No")
#!/usr/bin/env python # -*- coding: utf-8 -*- input = raw_input() num_input = int(input) if num_input < 1000: input = '%03d' % num_input output = "ABC" else: input ='%03d' % (num_input - 999) output = "ABD" print output
S = list(input().split()) d = set() for x in S: tmp = "" for y in x.split("@")[1:]: if y: d.add(y) d = list(d) d.sort() print(*d, sep=" ")
import math N = int(input()) n = math.sqrt(N) if n == math.floor(n): print(N) else: print(pow(math.floor(n), 2))
N=int(input()) k=0 while(2**k <= N): k+=1 print(2**(k-1))
X = int(input()) y = X % 105 z = X // 105 if y >= max(0, 100 - 5*z) or y == 0: print(1) else: print(0)
import collections N=int(input()) table=collections.defaultdict(int) for i in range(N): table[input()]+=1 vote=0 ans="" for x in table: if vote < table[x]: ans=x vote=table[x] print(ans)
c1=input() c2=input() for i in range(3): if c1[i]==c2[-1-i]: continue else: print("NO") exit(0) print("YES")
import collections N = int(input()) table = collections.defaultdict(list) for i in range(N): table[int(input())].append(i) table = list(table.keys()) table.sort() print(table[-2])
N=int(input()) if N == 3 or N == 5 or N == 7: print("YES") else: print("NO")
# To use this program, create a .txt file that contains your HTML source code and name it 'htmlfile.txt' # Date Created: 10/18/2015 # Date Last Modified: 10/19/2015 import re class Stack: # List implementation of Stack def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def __str__(self): return '[' + ', '.join(self.items) + ']' class Tag(): def __init__ (self, data_file, tag_list): self.data_file = data_file self.tag_list = tag_list def getTag(self): line = self.data_file.readlines() exception = '' EXCEPTIONS = ['meta', 'br', 'hr', 'ul'] for i in line: matches = re.findall('<.*?>', i) # regular html tags for tag in matches: for char in tag: if char == '<' or char == '>': tag = tag.replace(char,'') self.tag_list.append(tag) # Find exception cases and add it to the list for special_tag in EXCEPTIONS: for tag in self.tag_list: if special_tag in tag: # get location of the exception tag to be replaced loc = self.tag_list.index(tag) # remove the original form of the special tag self.tag_list.remove(tag) # insert the special tag self.tag_list.insert(loc, special_tag) return self.tag_list def processTag(self): tagStack = Stack() EXCEPTIONS = ['meta', 'br', 'hr', 'ul'] for tag in self.tag_list: if tag[0] != '/' and tag not in EXCEPTIONS: tagStack.push(tag) print('Tag is ', tag, ': pushed: stack is now ',tagStack) elif tag[0] == '/' and tag not in EXCEPTIONS: if tagStack.peek() == tag[1:]: tagStack.pop() print('Tag is ', tag, ': matches: stack is now ', tagStack) else: print('Error: tag is', tag, 'but top of stack is', tagStack.peek()) break if tagStack.isEmpty(): print('Processing complete. No mismatches found.') else: print('Processing complete. Unmatched tags remain on stack: ', tagStack) def main(): tag = [] num = [] # read data file htmlfile.txt data_file = open('htmlfile.txt', 'r') # create html object html = Tag(data_file, tag) # Print out the list of tags from the data file print(html.getTag()) # Print out the process of the tags and whether they are valid html.processTag() main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 17 15:58:04 2020 @author: Mack """ # Rocket.py import math import numpy as np import matplotlib.pyplot as plt import pprint DT = 0.01 # set our delta t (s) gravity = -9.81 # set gravity (m/s^2) simulation_time = 600 # length of simulation (s) burnout_time = 60 # period over which fuel burns numIterations = int(simulation_time/DT) + 1 # How many iterations we have of loop rocket_mass = 1000 # Mass of rocket without fuel initial_mass = 5000 # Mass of rocket with fuel fuel_mass = initial_mass-rocket_mass # Mass of fuel mass = initial_mass # Variable that is tracked in loop change_in_mass = fuel_mass/burnout_time # How quickly our mass changes (assuming constant change) t = 0 # Initial time time = [t] # Initializing our time list v = 0 # Initial velocity velocity = [v] # Initializing our velocity list p = .0001 # Initial position position = [p] # Initializing our position list isp = 200 # Initializing special impulse to 200 (from book) coefficient_drag = 0.6 # Intializing drag coefficient to 0.6 (online) area_rocket = 10.75 # The area of the top our rocket (from online) # thrust_list = [0] # Initializing our thrust list # grav_list = [-gravity] # Initializing our gravity list # air_resistance_list = [0] # Initializing our air resistance list # mass_l = [mass] # Initializing mass list RADIUS_OF_EARTH = 6378100 # This is the radius of earth # Function to find next iteration of values def find_next_v(DT, mass, change_in_mass, v, p): if(mass > rocket_mass): # This section checks to make sure mass -= (change_in_mass) * DT # that our rocket's mass doesn't if(mass < rocket_mass): # drop below the mass of its frame mass = rocket_mass # as that would be impossible. (lost mass is lost fuel-mass) # Before it reaches the base mass # of the rocket, it subtracts the # change_in_mass from mass each iteration p += (v) * DT # Change position based on what velocity previously was if(p < 0): # Rockets can't go underground, so we check if our position is below 0 p = 0 # if it is, we set it equal to 0 grav_a = -9.81 # back at an altitude of 0, so grav_a = -9.81 thrust_a = 0 # no fuel so thrust is 0 v = 0 # can't move as can't go through earth air_resistance_a = 0 # no air resistance if we're not moving return(mass, change_in_mass, p, v, thrust_a, grav_a, air_resistance_a) density_air = math.exp(-0.1385 * p/1000) # calculate the density of air at our new position if(mass == rocket_mass): # This if-statement makes sure that if our mass change_in_mass = 0 # = base rocket mass, we stop having a change in mass # and therefore, thrust becomes 0, as no more fuel is used # Calculate acceleration due to gravity grav_a = gravity * ((RADIUS_OF_EARTH)**2)/((RADIUS_OF_EARTH+p)**2) # Calculate acceleration due to thrust thrust_a = (isp * grav_a * (-change_in_mass)) / mass # Calculate acceleration due to air resistance air_resistance_a = ((1/2) * density_air * (v) * abs(v) * coefficient_drag * area_rocket)/mass # Calculate new velocity based on acceleration due to thrust, gravity, and air resistance v = v + (thrust_a + grav_a - air_resistance_a) * DT # Return our new values! return(mass, change_in_mass, p, v, thrust_a, grav_a, air_resistance_a) # loop the desired numebr of times for i in range(1, numIterations): t = i * DT # Our time for each iteration time.append(t) # Add to time list # Call function and assign new values to variables # Only call function if we are still at p != 0. Position is initalized # to slightly above 0 so that we enter this if statement the first loop through if(p != 0): mass, change_in_mass, p, v, thrust_a, grav_a, air_resistance_a = find_next_v(DT, mass, change_in_mass, v, p) # thrust_list.append(thrust_a) # add new thrust to thrust list # mass_l.append(mass) # add new mast to mass list # grav_list.append(-grav_a) # add new gravity to gravity list # air_resistance_list.append(air_resistance_a)# add new air resistance to air resistance list velocity.append(v) # add new velocity to velocity list position.append(p) # add new position to position list # Plot in five separate graphs: # Position vs time plt.figure(1) plt.plot(time, position, label="Position", color="red") plt.legend(loc = 2) # Velocity vs time plt.figure(2) plt.plot(time, velocity, label = "Velocity") plt.legend(loc = 2) # If you wanted to plot others # # Mass vs time # plt.figure(3) # plt.plot(time, mass_l, label="Mass") # plt.legend() # # Air Resistance vs time # plt.figure(4) # plt.plot(time, air_resistance_list, label = "Air Resistance") # plt.legend() # # Gravity vs time # plt.figure(5) # plt.plot(time, grav_list, label = "Gravity") # axes = plt.gca() # axes.set_ylim([0,10]) # plt.legend()
# -*- coding: utf-8 -*- """ Created on Sat Sep 26 19:00:14 2020 @author: ntruo """ #%% Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #%% Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:,1:-1].values y = dataset.iloc[:,-1].values #%% Training the Linear Regression model on the whole dataset from sklearn.linear_model import LinearRegression linear_reg = LinearRegression() linear_reg.fit(X,y) #%% Training the Polynomial Regression model on the whole dataset from sklearn.preprocessing import PolynomialFeatures polynomial_reg = PolynomialFeatures(degree=4) X_poly = polynomial_reg.fit_transform(X) linear_regressor2 = LinearRegression() linear_regressor2.fit(X_poly,y) #%% Visualising the Linear Regression results plt.scatter(X,y,color = 'red') plt.plot(X,linear_reg.predict(X),color='blue') plt.xlabel('Position') plt.ylabel('Salary') plt.title('Truth or Bluff (Linear Regression)') plt.show() #%% Visualising the Polynomial Regression results plt.scatter(X, y, color = 'red') plt.plot(X, linear_regressor2.predict(X_poly), color = 'blue') plt.title('Truth or Bluff (Polynomial Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() #%% predict linear print(linear_reg.predict([[6.5]])) #%% poly prediction print(linear_regressor2.predict(polynomial_reg.fit_transform([[6.5]])))
import math import bisect def SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 primes = [] for i in range(2, n+1): if(prime[i] == 1): primes.append(i) return primes primes = SieveOfEratosthenes(50000000) print(primes[-1]) print("DONE") answer = 0 for prime in primes: if(prime > 10000): break else: answer += bisect.bisect(primes, 10**8//prime) + 1 print(answer)
import math def issquare(D): return (math.floor(math.sqrt(D))**2 == D or math.ceil(math.sqrt(D))**2 == D ) def evaluate_continued_fraction(denom): frac_num = 0 frac_denom = 1 for i in range(len(denom)-1, -1, -1): frac_num += denom[i]*frac_denom if(i != 0): temp = frac_denom frac_denom = frac_num frac_num = temp return frac_num, frac_denom def construct_continued_fraction(D): # compute continued fraction of sqrt(D) continued_fraction_coeff = [] x = math.sqrt(D) d = 1 m = 0 a0 = math.floor(x) continued_fraction_coeff.append(a0) a = a0 while(a != 2*a0): m = d*a - m d = (D - m*m)/(d) a = math.floor((a0 + m)/d) continued_fraction_coeff.append(a) return continued_fraction_coeff maxD = 1 maxX = 0 for D in range(1,1001): if(not issquare(D)): x = 0 y = 0 coeff = construct_continued_fraction(D) k = len(coeff) - 1 if(k % 2 == 0): coeff.pop() x,y = evaluate_continued_fraction(coeff) if(k % 2 == 1): coeff += coeff[1:k] x,y = evaluate_continued_fraction(coeff) # print(coeff) # print(x,y) if(x > maxX): maxD = D maxX = x print(maxD)
def credit_range(credit): #def for credit range check = False for i in range (0,130,+20): #Range of Credits if(credit==i): check = True break return check count=0 progress=0 trailing=0 retriever=0 excluded=0 Pass_credit=0 print("This Programme Allow Staff To Predict student's Progression Outcome At The End Of Each Academic Year") pass_credit=input("Please Press Enter To Start ") #Press enter to start print("Welcome To The Staff Version of Student Progression Predictor Please Follow The Given Instructions") print("If you want to creat the Histrogram of taken data Please Enter q in the enter number of credits at pass input") while(pass_credit!="q"): try: pass_credit=input("Enter Number of Credits at Pass: ") #enter pass credits pass_credit=int(pass_credit) if(credit_range(pass_credit)==True): defer_credit=input("Enter Number of Credits at Defer: ") #enter defer credits try: defer_credit=int(defer_credit) if(credit_range(defer_credit)==True): fail_credit=input("Enter Number of Credits at Fail: ") #enter fail credits try: fail_credit=int(fail_credit) if(credit_range(fail_credit)==True): total=pass_credit+defer_credit+fail_credit #check the total if(total==120): count+=1 if(pass_credit==120): print("Progress") progress+=1 elif(pass_credit==100): print("Progress-module trailer") trailing+=1 elif(pass_credit==80): print("Do not Progress-module retriever") retriever+=1 elif(pass_credit==60): print("Do not progress-module retriever") retriever+=1 elif(pass_credit==40): if(fail_credit==80): print("Exclude") excluded+=1 else: print("Do not Progress-module retriever") retriever+=1 elif(pass_credit==20): if(fail_credit<80): print("Do not progress-module retriever") retriever+=1 else: print("Exclude") excluded+=1 elif(pass_credit==0): if(fail_credit<80): print("Do not progress-module retriever") retriever+=1 else: print("Exclude") excluded+=1 else: print("Total incorrect") print("Make Sure the Total of credits is equal to 120") print("prograamme is running Please Try Again") else: print("Range error") print("Make Sure the inputs are in range") print("prograamme is running Please Try Again") except: print("Integers required") print("Make Sure to use only integers as inputs") print("prograamme is running Please Try Again") else: print("Range error") print("Make Sure the inputs are in range") print("prograamme is running Please Try Again") except: print("Integers required") print("Make Sure to use only integers as inputs") print("prograamme is running Please Try Again") else: print("Range error") print("Make Sure the inputs are in range") print("prograamme is running Please Try Again") except: if(pass_credit!="q"): print("Integers required") print("Make Sure to use only integers as inputs") print("prograamme is running Please Try Again") else: print("Histrogram is Generating.....") print() print() print() print("Progress \t{}: {} ". format(progress,( "*"*progress))) print("Trailing \t{}: {} ". format(trailing,( "*"*trailing))) print("Retriever \t{}: {} ". format(retriever,( "*"*retriever))) print("Exclude \t{}: {} ". format(excluded,( "*"*excluded))) print() print(count,"outcomes in total") print() print("Programme is Exiting\tThankyou....")
import Variables import Functions import pygame import Snake import Levels def pause(snake): """ Displays Pause Screen. Args: snake (obj): Object of class Snake. """ while True: for event in pygame.event.get(): if event.type == pygame.QUIT: Functions.end_game() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: snake.direction = Variables.resume_dir Variables.Main.game_loop() text_surface, text_rect = Functions.text_objects('||', Variables.large_text, Variables.black) text_surface2, text_rect2 = \ Functions.text_objects('Press space to resume', Variables.small_text, Variables.black) text_rect.center = ((Variables.game_width / 2), (Variables.game_height / 3)) text_rect2.center = ((Variables.game_width / 2), (Variables.game_height / 2)) Variables.screen.blit(text_surface, text_rect) Variables.screen.blit(text_surface2, text_rect2) Variables.resume_dir = snake.direction pygame.display.update() Variables.clock.tick(30) def lost(): """ Displays the screen when the snake died. Waits for input from the user what to do next. """ while Variables.is_dead: for event in pygame.event.get(): if event.type == pygame.QUIT: Functions.end_game() Variables.screen.blit(Variables.lost, (Variables.block_size * 3, Variables.block_size * 4.5)) text_surface, text_rect = Functions.text_objects('Best scores: ', Variables.small_text, Variables.orange) text_rect.center = (Variables.block_size * 6, int(Variables.block_size * 6.3)) Variables.screen.blit(text_surface, text_rect) scores = 0 for score in Variables.high_score: scores += 1 if scores < 6: text_surface, text_rect = Functions.text_objects("{} points".format(score), Variables.small_text, Variables.orange) text_rect = (Variables.block_size * 3.6, int(Variables.block_size * 6.2) + scores * Variables.block_size * 0.5) Variables.screen.blit(text_surface, text_rect) Functions.button('Start', Variables.block_size * 3.4, Variables.block_size * 9.2, Variables.block_size * 1.6, Variables.block_size * .8, Variables.dark_gray, Variables.orange, Snake.Snake().reset_snake) Functions.button('Exit', Variables.block_size * 5.3, Variables.block_size * 9.2, Variables.block_size * 1.6, Variables.block_size * .8, Variables.dark_gray, Variables.orange, Functions.end_game) Functions.button('Level', Variables.block_size * 7, Variables.block_size * 9.2, Variables.block_size * 1.6, Variables.block_size * .8, Variables.dark_gray, Variables.orange, Levels.re_level) pygame.display.update() Variables.clock.tick(30) def starting(): """ Displays the welcome screen. Waits for the user input about chosen level. """ while Variables.starting: for event in pygame.event.get(): if event.type == pygame.QUIT: Functions.end_game() Variables.screen.blit(Variables.welcome, (Variables.block_size * 3, Variables.block_size * 4.5)) text_surface, text_rect = Functions.text_objects('Choose level: ', Variables.small_text, Variables.orange) text_rect.center = (Variables.block_size * 6, int(Variables.block_size * 6.6)) Variables.screen.blit(text_surface, text_rect) Functions.button('Easy', Variables.block_size * 5, Variables.block_size * 6.9, Variables.block_size * 2, Variables.block_size * 1, Variables.dark_gray, Variables.orange, Levels.easy) Functions.button('Medium', Variables.block_size * 5, Variables.block_size * 7.9, Variables.block_size * 2, Variables.block_size * 1, Variables.dark_gray, Variables.orange, Levels.medium) Functions.button('Hard', Variables.block_size * 5, Variables.block_size * 8.9, Variables.block_size * 2, Variables.block_size * 1, Variables.dark_gray, Variables.orange, Levels.hard) pygame.display.update() Variables.clock.tick(30)
word = input("Enter word :") word=word.split(',') word=sorted(word) ans='' for x in word: if x != word[len(word)-1]: ans=ans+x+',' else: ans=ans+x print(ans)
a=input() check=['YES','yes','Yes'] if a in check: print('Yes') else: print('No')
string=input() alpha=0 numeric=0 for s in string: if ord(s) in range(65,91) or ord(s) in range(97,123): alpha+=1 if ord(s) in range(48,58): numeric+=1 print('LETTERS ',alpha) print('DIGITS ',numeric)
#Function Exercises #make sure you add code to each to check for good input before using the input #also add comments with each line explaining what its doing #Exercise 1 x = input('Input: ') def is_two(x): if x == '2' or x == 2: return True else: return False #Exercise 2 vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} def is_vowel(char): if char in vowels: return True else: return False #Exercise 3 def is_consonant(char): vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} if char not in vowels: return True else: return False #Exercise 4 def str_cap(word): assert type(word) == str, "Invalid input - must be string." if is_consonant(word[0]) and (' ' not in word): str[0].upper() return word else: return word #Exercise 5 def calculate_tip(tip_per, bill_total): assert type(tip_per) == float, "Please use a float" assert type(bill_total) == float, "Please use a float" tip_amount = (tip_per * bill_total) return tip_amount #Exercise 6 def apply_discount(orig_price, discount): return (orig_price - (orig_price * discount)) #Exercise 7 def handle_commas(str): assert type(string) == str new_num = int(str.replace(',', '')) return new_num #Exercise 8 def get_letter_grade(num_grade): num_grade = int(num_grade) if num_grade >= 88: return "A" elif 80 <= num_grade < 88: return "B" elif 67 <= num_grade < 80: return "C" elif 60 <= num_grade < 67: return "D" else: return "F" #Exercise 9 def remove_vowels(str): vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} for char in str: if char not in vowels: char.pop() return str #Gabbys def remove_vowels(str): vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} chars = [] for i in string: if i not in vow: chars.append(i) return joinchars #didnt catch the rest #Exercise 10 def normalize_name(any_str): newstr = any_str.lower() space = ' ' char = '!@#$%^&*' for string in any_str: if string in space: newstr = newstr.replace(space, '_') for string in any_string: if string in char: newstr = newstr.replace(string, '') return newstr #Exercise 11 def cumulative_sum(list[]): for num in list: sum = list[num - 1] + list[num] def cumulative_sum(nums_list): return [sum(nums_list[:i+1])] for i in range(len(nums_list))]
def hex_to_dec(hexa): hexa_table = ['0','1', '2','3','4','5','6','7','8','9','10','a','b','c','d','e'] for num in range(len(hexa_table)): if hexa == hexa_table[num]: return num
from csv import reader from csv import DictReader warning_data = 'p_483_2020.csv' def main(): print('*** Read csv file line by line using csv module reader object ***') print('*** Iterate over each row of a csv file as list using reader object ***') # open file in read mode with open(warning_data, 'r') as read_obj: # pass the file object to reader() to get the reader object csv_reader = reader(read_obj) # Iterate over each row in the csv using reader object for row in csv_reader: # row variable is a list that represents a row in csv print(row) print('*** Read csv line by line without header ***') # skip first line i.e. read header first and then iterate over each row od csv as a list with open('students.csv', 'r') as read_obj: csv_reader = reader(read_obj) header = next(csv_reader) # Check file as empty if header != None: # Iterate over each row after the header in the csv for row in csv_reader: # row variable is a list that represents a row in csv print(row) print('Header was: ') print(header) print('*** Read csv file line by line using csv module DictReader object ***') # open file in read mode with open('students.csv', 'r') as read_obj: # pass the file object to DictReader() to get the DictReader object csv_dict_reader = DictReader(read_obj) # iterate over each line as a ordered dictionary for row in csv_dict_reader: # row variable is a dictionary that represents a row in csv print(row) print('*** select elements by column name while reading csv file line by line ***') # open file in read mode with open('students.csv', 'r') as read_obj: # pass the file object to DictReader() to get the DictReader object csv_dict_reader = DictReader(read_obj) # iterate over each line as a ordered dictionary for row in csv_dict_reader: # row variable is a dictionary that represents a row in csv print(row['Name'], ' is from ' , row['City'] , ' and he is studying ', row['Course']) print('*** Get column names from header in csv file ***') # open file in read mode with open('students.csv', 'r') as read_obj: # pass the file object to DictReader() to get the DictReader object csv_dict_reader = DictReader(read_obj) # get column names from a csv file column_names = csv_dict_reader.fieldnames print(column_names) print('*** Read specific columns from a csv file while iterating line by line ***') print('*** Read specific columns (by column name) in a csv file while iterating row by row ***') # iterate over each line as a ordered dictionary and print only few column by column name with open('students.csv', 'r') as read_obj: csv_dict_reader = DictReader(read_obj) for row in csv_dict_reader: print(row['Id'], row['Name']) print('*** Read specific columns (by column Number) in a csv file while iterating row by row ***') # iterate over each line as a ordered dictionary and print only few column by column Number with open('students.csv', 'r') as read_obj: csv_reader = reader(read_obj) for row in csv_reader: print(row[1], row[2]) if __name__ == '__main__': main()
import wikipedia from wikipedia.wikipedia import search search = input("Enter a search topic:") result = wikipedia.summary({search}, sentences = 2) print(result)
#Feature 1 #create a csv file of different customer orders where each row contains a # customer order along with customer name address and phone number #after you have built that out you will create a function to change the name, and for extra credit (because some customers change the phone numbers) add in a way to modify the phone number #you are writing this from scratch so no outside libraries import csv import os mydict = [{'Sales Order ID': '0001','Product':'Tree Tea Oil','Customer ID':'35', 'Company Name':'Young Living ', 'Contact Name':'Aaron', 'Company Address': '', 'Phone Number':''}] fields = ['Sales Order ID','Product','Customer ID', 'Company Name', 'Contact Name', 'Company Address', 'Phone Number'] filename = 'company_sales_order2021.csv' with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = fields) writer.writeheader() writer.writerows(mydict) def clear_console(): # Clear the console if os.name == 'nt': os.system('cls') else: os.system('clear') def open_list(filename, list): try: with open(filename) as file: data = file.read().splitlines() list.extend(data) except FileNotFoundError: pass def show_option(): clear_console() # Print out instructions on how to use the app print('') print('='*30) print('Customer Orders') print('='*30) print('') print(""" You have {} items in your list. \n Enter O to show options. Enter P to see your list. Enter S to save your list Enter R to remove an item. Enter C to clear your list. Enter QUIT to exit without saving.""".format(len(list))) while True: new_item = input("\nAdd an item: ") if new_item == "q": show_list(sl) print("\nHave a nice day!\n") break elif new_item == "o": show_help(sl) continue elif new_item == "p": show_list(sl) continue elif new_item == "s": show_list(sl) save_list(saved_file, sl) break elif new_item == "c": delete_list(saved_file, sl) continue elif new_item == "REMOVE": remove_from_list(sl) continue else: add_to_list(new_item, sl)
bin_str = input('Enter in a binary: ') def bin_to_dec(bin_str): answer = int(bin_str, 2) print('Binary value has the decimal value of:', answer) bin_to_dec(bin_str)
km = float(input('Qual a distância da sua viagem em Km? ')) if km <= 200: pr1 = km*0.50 print('Você vai pagar na sua viagem: {:.2f}'.format(pr1)) else: pr2 = km*0.45 print('Você irá gasta na sua viagem: {:.2f}'.format(pr2)) print('Boa Viagem!')
d1 = int(input('Quanto de dinheiro você tem na carteira?')) d2 = d1/3.27 print('Você tem {} na carteira e pode comprar {:.2f} de dólares'.format(d1, d2))
n1 = int(input('Digite qualquer número inteiro:')) if n1 % 2 == 0: print('Esse numero é par!') else: print('Esse numero é ímpar!')
s1 = int(input('Qual o salario atual: ')) s2 = s1*(15/100) s3 = s1+s2 print(' O salário atual é: {}\n Com aumento de 15% passa a ser de {:.0f}'.format(s1, s3))
#while loop i = 1 while i<=7: print(i) i = i + 1 print("Finished!") print() #break i = 0 while 1==1: #infinite loop print(i) i = i + 1 if i >= 5: print("Breaking") break print("Finished") print() #Continue i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished")
#check the 3 sections one by one using the comments. we cant compile the 3 types at a time bcs after giving an exception the program exits. """ An assertion is a sanity-check that you can turn on or turn off when you have finished testing the program. An expression is tested, and if the result comes up false, an exception is raised. Assertions are carried out through use of the assert statement. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output. """ #(i) ''' print(1) assert (2 + 2 == 4), "error spooted" print(2) assert 1 + 1 == 3 print(3) ''' #(ii) def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print (KelvinToFahrenheit(273)) print (int(KelvinToFahrenheit(505.78))) print (KelvinToFahrenheit(-5)) #(iii) - assert inside the try except block ''' try: temp = -10 assert (temp >= 0), "Colder than absolute zero!" except AssertionError: print ("Error Bypassed") '''
#simple operations print(2+2) print(2 + 5 * 10) print(5 * 10 + 2) print(2*(3+4)) print(10/2) print(10//2) print(-7) print(-5+5) print(-7-7) print((-7+2)*(-4)) # print(11/0) -> it produces ZeroByDivisionError print(6*7.0) #exponention print(2**5) print(2**1/2) print(3**(3**3)) print(3**3**3) print(8**(1/3)) print(9**0.5) print(9**(1/2)) #quotient & remainder print(20//6) print(1.25 % 0.5)
import os def percent(num1, num2): return (num1 / num2) # Take input from the user num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) with open(os.path.expanduser("~/Ansible_numa/results/percentage.txt"), 'w') as f: print("The packetdrop percentage is", percent(num1, num2)*100, file=f)
class Dog: def __del__(self): print('-----英雄over----') dog1 = Dog() dog2 = dog1 del dog1 #不会调用__del__方法,因为这个对象还有其他的变量指向它,即引用计算不是0 print('============') del dog2 #此时会调用__del__方法,以为没有变量指向它 print('============') #如果在程序结束时,有些对象还存在,那么python解释器会自动调用他们的__del__方法来完成清理工作
class Dog: def __init__(self, new_name): self.name = new_name self.__age = 0 #定义了一个私有的属性,属性的名字是__age #同过内部定义的方法设置私有属性 def set_age(self, new_age): if new_age > 0 and new_age <= 100: self.__age = new_age else: self.__age = 0 #通过内部定义的方法调用返回私有属性 def get_age(self): return self.__age dog = Dog('小白') #dog.age = -10 #dog.name = '小黑' #print(dog.age) #print(dog.name) dog.set_age(10)#通过内部方法设置私有属性 #age = dog.get_age() #dog.__age = -10 print(dog.get_age())#通过内部方法调用私有属性 print(dog.__age)#直接调用报错,对象不存在调用属性
from prac_08.unreliable_car import UnreliableCar def main(): """Test some unreliable cars""" # create cars with different reliabilities car_one = UnreliableCar("Car 1", 100, 90) car_two = UnreliableCar("Car 2", 100, 10) # attempt to drive the cars 10 times # output what distance they drove for i in range(1, 11): print("Attempting to drive {}km:".format(i)) print("{:12} drove {:2}km".format(car_one.name, car_one.drive(i))) print("{:12} drove {:2}km".format(car_two.name, car_two.drive(i))) # print the final states of the cars print(car_one) print(car_two) if __name__ == '__main__': main()
def intersection(arrays): """ YOUR CODE HERE """ result = [] store = {} # store each number from each array as {number: count} in a dictionary for arr in arrays: for num in arr: if num not in store: store[num] = 1 else: store[num] += 1 # check for numbers with value == length of arrays (meaning the num is in each sub array) # if so, add the number to the result (this won't work if numbers appear more than once in the sub arrays) for key, value in store.items(): if value == len(arrays): result.append(key) return result if __name__ == "__main__": arrays = [] arrays.append(list(range(1000000, 2000000)) + [1, 2, 3]) arrays.append(list(range(2000000, 3000000)) + [1, 2, 3]) arrays.append(list(range(3000000, 4000000)) + [1, 2, 3]) print(intersection(arrays))
import random lst = [] n = int(input("Довжина списку: ")) for i in range(n): lst.append(random.randint(0, 10)) print(lst) def func(lst): for i in range(len(lst)): if lst[i]>lst[i+1]: return True else: return False print(func(lst))
import random # a = [] # b=[] # for i in range(1,10): # a.append(random.randint(0, 100)) # for i in range(1,10): # b.append(random.randint(0,100)) # print(a) # a.sort() # print(b) # b.sort() # print(a) # print(b) lst_1 = [] lst_2 = [] n = int(input("Довжина першого списку: ")) m = int(input("Довжина другого списку: ")) for i in range(n): lst_1.append(random.randint(-100, 10)) lst_1 = sorted(lst_1) print(lst_1) for i in range(m): lst_2.append(random.randint(-100, 10)) lst_2 = sorted(lst_2) print(lst_2) lst_3 = lst_1 + lst_2 lst_3 = sorted(lst_3) print(lst_3)
print(12 > 44) # False, т.к 12 меньше 44 print(12 == 44) # False, т.к 12 не равно 44 print(12 < 44) # True, т.к 12 меньше 44 print("*" * 50) print(bool("Hi!")) print(bool(1)) # Функция bool( ) возвращает True в случае если аргумент не равен нулю или если аргумент не пустая последовательность # и если аргумент содержит текст, и возвращает False если аргумент равен нулю или если аргумент пустая # последовательность. print("*" * 50) print(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool([])) print(bool({})) print("*" * 50) def func(): return 0 if func(): print("Yes") else: print("No") # эта строка будет выполнена, т.к func() возвращает 0
import random n = int(input("Введіть кількість чисел: ")) i = 1 avg = 0 while n >= i: num = random.randrange(1, n + 1) print(num) avg = avg + num i += 1 print(f'Середнє арифметичне чисел = {avg / n}') def func(n): i = 1 fct = 1 while n >= i: fct = fct * i i += 1 return f"Факторіал {n} = {fct}" print(func(4))
# Конкатенація списків a = [1, 2, 3, 4] b = [5, 6, 7, 8] c = a + b print(c) # Конкатенація через extend a.extend(b) print(a) # Функція len() d = [1, 2, 3, 4] e = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} print(len(d)) print(len(e)) # Конструкція if variable in collection f = [3, 1, 9, 0] print(f) # 0 есть в списке f if 0 in f: print("Існує") else: print("Не існує")
n = int(input()) for i in range(n): s = input() k = 0 odd = "" even = "" for j in s: if k % 2 is 0: odd += j else: even += j k += 1 print("%s %s" % (odd, even))
# f = open("../data/readme.txt",'r') # string = f.read() # print(string) # strline = f.readline() # print(strline) # f.close() # f=open('../data/readme.txt','r') # strline = f.readline() # print(strline) # f.close() # f = open('../data/readme.txt','w') # f.write('hello world \nhello') # f.close() ''' 方法的重写 ''' # class People: # def speak(self): # print("people is speaking") # class Student(People): # #方法重写,重写父类的speak方法 # def speak(self): # print('student is speaking') # class Teacher(People): # pass # #Student类的实例 # s = Student() # s.speak() # t = Teacher() # t.speak() #多态特性 # class Animal: # def eat(self): # print("animal is eating") # class Dog(Animal): # def eat(self): # print("dog is eating") # class Cat(Animal): # def eat(self): # print('cat is eating') # def eatting_double(animal): # animal.eat() # animal.eat() # animal = Animal() # dog = Dog() # cat = Cat() # eatting_double(animal) # eatting_double(dog) # eatting_double(cat) '''列表生成式''' #列表生成式通常是结合range函数一起使用的,所以先了解range函数的使用方法 # r = range(0,4) # print('r:',r) # for x in r: # print(x,end="") # b = list(range(0,6,2)) # print('b:',b) # c = tuple(range(2,9,3)) # print('c:',c) # #列表生成式 # data = [1,2,3,4] # def func(x): # return x**2 # d = [func(x) for x in data] # print('d:',d) # h = ['HD','FASFSA','SDAGSG'] # M = [x.lower() for x in h] # print(M) # filter()用于过滤序列,接受两个参数;一个函数和一个序列,将函数作用在序列的每个元素上,根据函数的返回值是true还是false, # 来决定是否舍弃该元素,最终返回一个迭代器 def is_even(x): return x%2 == 0 l = filter(is_even,[0,1,2,3,4,5]) print(l) for val in l: print(val) #使用匿名函数的形式来使用filter函数 str_tuple = ('hiasfasda','asfsda','sagdsgfds','rtyhfb','asfdaspython') result = filter((lambda x:x.find('python')!=-1),str_tuple) for string in result: print('result:',string)
import pandas as pd import requests import json # !Elements of the Get Request api_url = "https://api.data.gov/sam/v3/registrations" api_key = 'VpTi8pF59uRnH9TY5djWg8YUWVNgeOut39RiEL1G' status = 'registrationStatus:A' zipcode = 'samAddress.zip:22201' # ? Instead of using params, you can also build the full URL and run the following: # ? api_url = https://api.data.gov/sam/v3/registrations?qterms=registrationStatus:A+AND+samAddress.zip:22201&length=5&api_key=VpTi8pF59uRnH9TY5djWg8YUWVNgeOut39RiEL1G # ? response = requests.get(api_url) # *Can build the parameters dictionary by concatenating the strings params = {'qterms': status + '+AND+' + zipcode, 'api_key': api_key, 'length': 5} print(params) #!Calling the API response = requests.get(api_url, params=params) print(response) # in this case, status code 200 means the request was successful print(response.status_code) # Print this to see the possible headers print(response.headers) # This tells you that this particular API will return a JSON object print(response.headers['Content-Type']) # This will tell you how many more calls you can make with this api-key and IP address on this day print(response.headers['X-RateLimit-Remaining']) # !Parsing JSON # * read response as JSON object data = response.json() print(data) # *print a more JSON object print(json.dumps(data, indent=4)) # If indent is a non-negative integer or string, then JSON will be printed with that indent level # * Write data to a JSON file to examine with open('data.json', 'w') as outfile: outfile.write(json.dumps(data, indent=4)) # define results because we dont care about the 'links' part of the JSON results = data['results'] with open('results.json', 'w') as outfile: outfile.write(json.dumps(results, indent=4)) # TODO Use a JSON path to yield result (key, value pairs) # get the cage number from the second result cage_number_2 = results[2]['cage'] print(cage_number_2) # ? With deeply nested JSON objects can have a path that looks like # ? value_n = JSON_object[index_1]['key_1']['key_2'][index_2][key_3]...['key_n'] # TODO Create a list of values # Use for loop to list all of the cage numbers results_list = [] for i in list(range(0, len(results))): results_list.append(results[i]['cage']) print(results_list) # TODO Create a list of two values as key-value pairs # use a for loop to create a dictionary that assigns the value cage number to the corresponding key legalBusinessName # Can extend this such that values are a list of values results_dict = {} for i in list(range(0, len(results))): var_name = results[i]['legalBusinessName'] results_dict[var_name] = results[i]['cage'] print(results_dict) # turn dictionary into a data frame, where the indexes are numbers and the columns are the keys and the values # just using pd.DataFrame(results_dict) will create a column of the values that has the keys as indexes results_df = pd.DataFrame(list(results_dict.items()), columns=[ 'legalBusinessName', 'cage']) print(results_df) # ! Flatten whole response # TODO use pd.json_normalize to flatten # Note that json_normalize is a pandas function. Use this turn a JSON object into tabular data. # Python deals with dictionaries and arrays better than data frames, unlike excel and R, but this can still be a very useful tool for viewing and displaying information df_normalized = pd.json_normalize(results, sep="_") print(df_normalized) print(df_normalized['links']) # *using parameters record_path and meta links_flatten = pd.json_normalize(results, record_path='links') print(links_flatten) # print(results['cage'], results['samAddress']['zip']) # TypeError: list indices must be integers or slices, not str # this means that there are multiple ['samAddress'], and thus we need to include and index to tell python which to choose # * meta print(results[0]['cage'], results[0]['samAddress']['zip']) # * record_path print(results[0]['links']) # This is one row of data row_0 = pd.json_normalize(results[0], record_path='links', meta=['cage', 'hasKnownExclusion', 'legalBusinessName', 'duns', 'debtSubjectToOffset', 'duns_plus4', 'status', 'expirationDate', [ 'samAddress', 'zip'], ['samAddress', 'stateOrProvince'], ['samAddress', 'city'], ['samAddress', 'countryCode'], ['samAddress', 'zip4'], ['samAddress', 'line1']], sep="_") print(row_0) # Because an index is needed, if there are a lot of results it is more efficient to use a loop df_normalized2 = pd.DataFrame([]) for i in range(0, len(results)): row = pd.json_normalize(results[i], record_path='links', meta=['cage', 'hasKnownExclusion', 'legalBusinessName', 'duns', 'debtSubjectToOffset', 'duns_plus4', 'status', 'expirationDate', [ 'samAddress', 'zip'], ['samAddress', 'stateOrProvince'], ['samAddress', 'city'], ['samAddress', 'countryCode'], ['samAddress', 'zip4'], ['samAddress', 'line1']]) df_normalized2 = df_normalized2.append(row) print(df_normalized2) # 1 to 1 series # This will create an entirely flat series where there is a unique name for each value. def flatten_nested_json_recursive(nested_json): flattened_result = {} def flatten_json(data, key=''): if type(data) is dict: for i in data: flatten_json(data[i], key + i + '_') elif type(data) is list: f = 0 for i in data: flatten_json(i, key + str(f) + '_') f += 1 else: flattened_result[key[:-1]] = data flatten_json(nested_json) return flattened_result flattened_result = pd.Series(flatten_nested_json_recursive(results)) print(flattened_result) #! Error Handling # # TODO Method 1: if/then # print(response.status_code) # api_key_error is missing a character and thus will throw a 403 error api_url = "https://api.data.gov/sam/v3/registrations" api_key_error = 'VpTi8pF59uRnH9TY5djWg8YUWVNgeOut39RiEL1' params = {'qterms': status + '+AND+' + zipcode, 'api_key': api_key_error, 'length': 5} response = requests.get(api_url, params=params) if response.status_code != 200: print("error: " + str(response.status_code)) else: print("success!") # This one is the same query but uses the correct api_key params = {'qterms': status + '+AND+' + zipcode, 'api_key': api_key, 'length': 5} response = requests.get(api_url, params=params) if response.status_code != 200: print("error: " + str(response.status_code)) else: print("success!") # * for a looped request duns4 = ['0230433700000', '1240234040000', '8588887610000', '858887610000', '1280234040000' ] # Because some of these duns throw errors, when the loop will stop at the first error and not continue looping for i in duns4: api_url = "https://api.data.gov/sam/v8/registrations/" + str(i) params = {'return_values': 'full', 'api_key': 'pZRf3NHMazUCn8CxibYQWC9qttnh7EHmFPkSYoTO'} response = requests.get(api_url, params=params) data = response.json() # print(str(i) + " success!") x = data['sam_data']['registration']['businessStartDate'] print(x) # This loop will print the required data from the requests with a 200 response and print the type of error for the errors for i in duns4: api_url = "https://api.data.gov/sam/v8/registrations/" + str(i) params = {'return_values': 'full', 'api_key': 'pZRf3NHMazUCn8CxibYQWC9qttnh7EHmFPkSYoTO'} response = requests.get(api_url, params=params) data = response.json() if response.status_code != 200: print(str(i) + " error: " + str(response.status_code)) else: # print(str(i) + " success!") x = data['sam_data']['registration']['businessStartDate'] print(x) # TODO Method 2: Try/Except # Look into try/except statements, especially notes on else: and finally: # Also look into using commands like continue and break # Read about the different Python exceptions you can use to specify what to do given a specific error # using "except:" without a term after except sends all errors to the except phrase for i in duns4: api_url = "https://api.data.gov/sam/v8/registrations/" + str(i) params = {'return_values': 'full', 'api_key': 'VpTi8pF59uRnH9TY5djWg8YUWVNgeOut39RiEL1G'} response = requests.get(api_url, params=params) data = response.json() try: x = data['sam_data']['registration']['businessStartDate'] print(x) except: print(str(i) + " error: " + str(response.status_code)) continue # TODO including a timeout option # You can add a timeout exception so the query will stop a request that is taking too long getting a response try: response = requests.get('https://api.github.com', timeout=1) except Timeout: print('The request timed out') else: print('The request did not time out') # TODO using rate limit with a while loop # The following assigns the rate limit of your api-key to x and subtracts one from x after each call # This is useful since even if you run out of calls, your loop withh continue running adn just throw a series of 429 errors, indicating too many requests have been made print(response.headers['X-RateLimit-Remaining']) x_response = requests.get( 'https://api.data.gov/sam/v8/registrations/1240234040000?return_values=full&api_key=pZRf3NHMazUCn8CxibYQWC9qttnh7EHmFPkSYoTO') x = int(x_response.headers['X-RateLimit-Remaining']) print(x) while x != 0: for i in duns4: api_url = "https://api.data.gov/sam/v8/registrations/" + str(i) params = {'return_values': 'full', 'api_key': 'pZRf3NHMazUCn8CxibYQWC9qttnh7EHmFPkSYoTO'} response = requests.get(api_url, params=params) x = x-1 break # x=response.headers['X-RateLimit-Remaining'] print(x) # TODO a method for collecting errors # This loop will enable you to collect the successful results in one dictionary and the failed results seperately # This can be useful for checking on errors and for re-running errors duns4 = ['0230433700000', '8487079310000', '1240234040000', '8588887610000', '8487079310000', '0802394200000', '5061655360000'] sam_results_dict = {} except_dict = {} for i in duns4: api_url = "https://api.data.gov/sam/v8/registrations/" + str(i) params = {'return_values': 'full', 'api_key': api_key} response = requests.get(api_url, params=params) try: data = response.json() y = data['sam_data']['registration']['businessStartDate'] sam_results_dict[str(i)] = y except: except_dict[str(i)] = response.status_code continue print(sam_results_dict) print(except_dict)
import math class Point: __x: float __y: float def __init__(self, x: float, y: float): self.set_x(x) self.set_y(y) def set_x(self, x): if not isinstance(x, float): raise Exception self.__x = x def get_x(self): return self.__x def set_y(self, y): if not isinstance(y, float): raise Exception self.__y = y def get_y(self): return self.__y class Points: __points: list = [] def add_point(self, p: Point): self.__points.append(p) def get_distance(self, point_a: Point, point_b: Point): side_x = abs(point_a.get_x() - point_b.get_x()) side_y = abs(point_a.get_y() - point_b.get_y()) side_z = math.sqrt(pow(side_x, 2) + side_y ** 2) return side_z def get_closest_distance(self): distances = {} for r1 in self.__points: for r2 in self.__points: if r1 != r2: distance = self.get_distance(r1, r2) if distance not in distances: distances[distance] = [r1, r2] short = sorted(distances.keys())[0] print(f'{short:.3f}') p1, p2 = distances[short] print(f'({p1.get_x():.3g}, {p1.get_y():.3g})') print(f'({p2.get_x():.3g}, {p2.get_y():.3g})') num_points = int(input()) points = Points() while num_points > 0: num_points -= 1 x, y = list(map(float, input().split())) points.add_point(Point(x, y)) points.get_closest_distance()
class Book: __title: str __author: str __price: float __chapters: list def __init__(self, title, author, price, chapters): self.__title = title self.__author = author self.__price = float(price) self.__chapters = chapters def get_title(self): return self.__title def get_author(self): return self.__author def get_price(self): return self.__price def get_chapters_num(self): return len(self.__chapters) on_work = False books = {} sold_books = [] while True: data = input() if data == 'end work': if len(sold_books): sold_sum = 0.00 for book in sold_books: print(f'SOLD: {book.get_title()} with author {book.get_author()}. Chapters in the book {book.get_chapters_num()}') sold_sum += book.get_price() print(f'Money: {sold_sum:.2f}') else: print('Bad day :(') break if data == 'on work': on_work = True continue if on_work: title = data.split()[0] if title in books: sold_books.append(books[title]) else: print("No such book here") else: try: f_part, s_part = data.split(' -> ') title = f_part.split(' ')[0] author = f_part.split(' ')[1] price = f_part.split(' ')[2] chapters = s_part.split(',') if title and author and float(price) >= 0.01: if title not in books: books[title] = Book(title, author, price, chapters) except: pass
def print_head(num): for row in range(1, num + 1): for col in range(1, row + 1): print(f"{col} ", end='') print() def print_foot(num): for row in range(num, 0, -1): for col in range(1, row): print(f"{col} ", end='') print() def print_triangle(num): print_head(num) print_foot(num) num = int(input()) print_triangle(num)
numbers_list = list(map(int, input().split())) numbers_list.sort(reverse=True) square_numbers = [] for num in numbers_list: if num > 0 and num**0.5 == int(num**0.5): square_numbers.append(num) print(" ".join(map(str, square_numbers)))
dict = {} while True: asdf = input() if asdf == 'Over': break (key, val) = asdf.split(' : ') if val.isdigit(): dict[key] = str(val).strip() else: dict[val] = str(key).strip() for key in sorted(dict): print(f"{key} -> {dict[key]}")
string = input() string_list = [x for x in string] counts = {} for letter in string_list: cnt = string_list.count(letter) counts[letter] = cnt for key, val in counts.items(): print(f"{key} -> {val}")
list_strings = input().split() list_strings = [str.lower() for str in list_strings] counts = {} for string in list_strings: cnt = list_strings.count(string) counts[string] = cnt print(", ".join([key for key, val in counts.items() if val%2 != 0]))
#!/usr/bin/env python """ Takes in a base test file as the first argument using the -f flag Parses through the base tests, and replaces values preceding with < and proceeded with > with all possible named values of that kind. The types must be defined before they can be replaced i.e. running test_generator.py on the following test file: "prince" ||| stereotype "princess" ||| stereotype "noble" ||| stereotype {"ran into a stereotype" : [<stereotype>]} ||| event returns: "prince" ||| stereotype "princess" ||| stereotype "noble" ||| stereotype {"ran into a stereotype" : ["prince"]} ||| event {"ran into a stereotype" : ["princess"]} ||| event {"ran into a stereotype" : ["noble"]} ||| event """ from optparse import OptionParser def generate_tests(tests_iter): raw_lines = [] test_types = dict() results = [] # Store lines and generate dict for line in tests_iter: try: test, type = [x.strip() for x in line.split("|||")] except ValueError: raise Exception("Line %s not formatted correctly" % (line)) if type in test_types: # if already exists, append to list test_types[type].append(test) else: # otherwise, make list test_types[type] = [test] raw_lines.append(line) # Go through raw lines, and replace words in < > with corresponding value # from dict strings_to_look_for = ['<' + x + '>' for x in test_types.keys()] for raw_line in raw_lines: found_replacement = False for string_to_look_for in strings_to_look_for: # For every stirng to find if raw_line.find(string_to_look_for) != -1: # Found one of the strings found_replacement = True # Type is the text within <> type = string_to_look_for.replace('<','').replace('>','') # For keeping track of strings to replace it with replacements = [] # Parse through the list of type for replace_with in test_types[type]: # Replace the <type_name> with the value replacements.append(raw_line.replace(string_to_look_for,replace_with)) # Add replacements to results results.extend(replacements) if not found_replacement: # We didn't find any <>s so just add raw line results.append(raw_line) return results if __name__ == "__main__": opt = OptionParser() opt.add_option("-f", "--file", type="string", dest="tests_file", help="File to generate tests from") options, args = opt.parse_args() tests = generate_tests(open(options.tests_file)) print "".join(tests)
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 21:07:02 2021 @author: slb """ #The next two lines clears the workspace from IPython import get_ipython get_ipython().magic('reset -sf') import os file_path = os.path.join(os.path.curdir, "Dec6.txt") with open(file_path) as f: data = f.readlines() groups = [] item = [] for i in range(len(data)): data1 = data[i] data1 = data1.split() if len(data1) == 0: groups.append(item) groups[-1] = [j for i in groups[-1] for j in i] #Flattens the list of lists to one list (of strings) item = [] continue item.append(data1) groups.append(item) #In order to not loose the last passport in the list groups[-1] = [j for i in groups[-1] for j in i] yes = 0 yes2 = 0 for item in groups: t = len(item) #I.e. t is the number of people in each group liste = [j for i in item for j in i] #Splits the list of strings into a list of characters yes += len(set(liste)) #set(liste)) gives the number of unique elements in liste how_many = {} #Creates an empty dictionary for n in liste: how_many[n] = how_many.get(n, 0) + 1 #Calculates the occurence of each element and stors it in the dictionary yes2 += sum(x == t for x in how_many.values()) #Counts how many elements of the dictionary occurred t times and adds it to the counter print(yes) print(yes2)
# Author: Shao Zhang and Phil Saltzman # Last Updated: 4/18/2005 # # textureMovie.py shows how to set up a texture movie effect. This tutorial # shows how to use that effect in a different context. Instead of setting the # texture based on time, this tutorial has an elevator that sets a texture on # its floor based on its height so that shadows cast by nearby lights line up # correctly. # # The elevator, shaft, and shadow movie were created by T.J. Jackson # for the Entertainment Technology Center class Building Virtual Worlds import direct.directbase.DirectStart from panda3d.core import Texture from direct.interval.LerpInterval import LerpFunc from direct.gui.OnscreenText import OnscreenText from direct.showbase.DirectObject import DirectObject from direct.task.Task import Task import sys #Our specialized function to load texture movies and output them as lists #From textureMovie.py. Look there for a full explanation on how it works def loadTextureMovie(frames, name, suffix, padding = 1): return [loader.loadTexture((name+"%0"+str(padding)+"d."+suffix) % i) for i in range(frames)] class World(DirectObject): def __init__(self): #Standard initialization stuff #Standard title that's on screen in every tutorial self.title = OnscreenText(text='Panda3D: Tutorial - Texture "Movies" (Elevator)', style=1, fg=(1,1,1,1), pos=(0.6,-0.95), scale = .07) #Load the elevator and attach it to render self.elevator = loader.loadModel('models/elevator') self.elevator.reparentTo(render) #Load the plane that will be animated and attach it to the elevator iteslf self.shadowPlane = loader.loadModel('models/shadowPlane') self.shadowPlane.reparentTo(self.elevator) self.shadowPlane.setPos(0,0,.01) #Load the textures that will be applied to the polygon self.shadowTexs = loadTextureMovie(60, 'shadow/barShadows.', 'jpg') #Add the task that will animate the plane taskMgr.add(self.elevatorShadows, 'elevatorTask') #Builds the shaft, which is a 30ft repeatable segment self.shaft = [] for i in range(-1,2): sh = loader.loadModel('models/shaft') sh.reparentTo(render) sh.setPos(-6.977, 0, 30*i) self.shaft.append(sh) #Linearly move the elevator's height using an interval. #If you replaced this with some other way of moving the elevator, the #texture would compensate since it's based on height and not time LerpFunc(self.elevator.setZ, fromData = 30, toData = -30, duration = 5).loop() #Puts the camera relative to the elevator in a position that #shows off the texture movie base.disableMouse() camera.reparentTo(self.elevator) camera.setPosHpr(-9, 0, 20, -90, -60, 0) #The task that runs the elevator. This is nearly the same as the one in #textureMovie.py with a few differences: #1) This task is only used once so the parameters were placed with hard-coded # Values #2) Intead of basing the current frame on task.time, # it's based on elevator.getZ() def elevatorShadows(self, task): texFrame = (int((self.elevator.getZ()%30)/.5)+26)%60 self.shadowPlane.setTexture(self.shadowTexs[texFrame], 1) return Task.cont w = World() run()
# Author: Shao Zhang and Phil Saltzman # Last Updated: 4/18/2005 # # This tutorial will cover fog and how it can be used to make a finite length # tunnel seem endless by hiding its endpoint in darkness. Fog in panda works by # coloring objects based on their distance from the camera. Fog is not a 3D # volume object like real world fog. # With the right settings, Fog in panda can mimic the appearence of real world # fog. # # The tunnel and texture was originally created by Vamsi Bandaru and Victoria # Webb for the Entertainment Technology Center class Building Virtual Worlds import direct.directbase.DirectStart from panda3d.core import Fog from panda3d.core import TextNode from direct.gui.OnscreenText import OnscreenText from direct.showbase.DirectObject import DirectObject from direct.interval.MetaInterval import Sequence from direct.interval.LerpInterval import LerpFunc from direct.interval.FunctionInterval import Func import sys #Global variables for the tunnel dimensions and speed of travel TUNNEL_SEGMENT_LENGTH = 50 TUNNEL_TIME = 2 #Amount of time for one segment to travel the #distance of TUNNEL_SEGMENT_LENGTH class World(DirectObject): #Macro-like function used to reduce the amount to code needed to create the #on screen instructions def genLabelText(self, text, i): return OnscreenText(text = text, pos = (-1.3, .95-.06*i), fg=(1,1,1,1), align = TextNode.ALeft, scale = .05) def __init__(self): ###Standard initialization stuff #Standard title that's on screen in every tutorial self.title = OnscreenText( text="Panda3D: Tutorial - Fog", style=1, fg=(1,1,1,1), pos=(0.9,-0.95), scale = .07) #Code to generate the on screen instructions self.escapeEventText = self.genLabelText("ESC: Quit", 0) self.pkeyEventText = self.genLabelText("[P]: Pause", 1) self.tkeyEventText = self.genLabelText("[T]: Toggle Fog", 2) self.dkeyEventText = self.genLabelText("[D]: Make fog color black", 3) self.sdkeyEventText = self.genLabelText( "[SHIFT+D]: Make background color black", 4) self.rkeyEventText = self.genLabelText("[R]: Make fog color red", 5) self.srkeyEventText = self.genLabelText( "[SHIFT+R]: Make background color red", 6) self.bkeyEventText = self.genLabelText("[B]: Make fog color blue", 7) self.sbkeyEventText = self.genLabelText( "[SHIFT+B]: Make background color blue", 8) self.gkeyEventText = self.genLabelText("[G]: Make fog color green", 9) self.sgkeyEventText = self.genLabelText( "[SHIFT+G]: Make background color green", 10) self.lkeyEventText = self.genLabelText( "[L]: Make fog color light grey", 11) self.slkeyEventText = self.genLabelText( "[SHIFT+L]: Make background color light grey", 12) self.pluskeyEventText = self.genLabelText("[+]: Increase fog density", 13) self.minuskeyEventText = self.genLabelText("[-]: Decrease fog density", 14) base.disableMouse() #disable mouse control so that we can place the camera camera.setPosHpr(0,0,10, 0, -90, 0) base.setBackgroundColor(0,0,0) #set the background color to black ###World specific-code #Create an instance of fog called 'distanceFog'. #'distanceFog' is just a name for our fog, not a specific type of fog. self.fog = Fog('distanceFog') #Set the initial color of our fog to black. self.fog.setColor(0, 0, 0) #Set the density/falloff of the fog. The range is 0-1. #The higher the numer, the "bigger" the fog effect. self.fog.setExpDensity(.08) #We will set fog on render which means that everything in our scene will #be affected by fog. Alternatively, you could only set fog on a specific #object/node and only it and the nodes below it would be affected by #the fog. render.setFog(self.fog) #Define the keyboard input #Escape closes the demo self.accept('escape', sys.exit) #Handle pausing the tunnel self.accept('p', self.handlePause) #Handle turning the fog on and off self.accept('t', ToggleFog, [render, self.fog]) #Sets keys to set the fog to various colors self.accept('r', self.fog.setColor, [1,0,0]) self.accept('g', self.fog.setColor, [0,1,0]) self.accept('b', self.fog.setColor, [0,0,1]) self.accept('l', self.fog.setColor, [.7,.7,.7]) self.accept('d', self.fog.setColor, [0,0,0]) #Sets keys to change the background colors self.accept('shift-r', base.setBackgroundColor, [1,0,0]) self.accept('shift-g', base.setBackgroundColor, [0,1,0]) self.accept('shift-b', base.setBackgroundColor, [0,0,1]) self.accept('shift-l', base.setBackgroundColor, [.7,.7,.7]) self.accept('shift-d', base.setBackgroundColor, [0,0,0]) #Increases the fog density when "+" key is pressed self.accept('+', self.addFogDensity, [.01]) #This is to handle the other "+" key (it's over = on the keyboard) self.accept('=', self.addFogDensity, [.01]) self.accept('shift-=', self.addFogDensity, [.01]) #Decreases the fog density when the "-" key is pressed self.accept('-', self.addFogDensity, [-.01]) #Load the tunel and start the tunnel self.initTunnel() self.contTunnel() #This function will change the fog density by the amount passed into it #This function is needed so that it can look up the current value and #change it when the key is pressed. If you wanted to bind a key to set it #at a given value you could call self.fog.setExpDensity directly def addFogDensity(self, change): #The min() statement makes sure the density is never over 1 #The max() statement makes sure the density is never below 0 self.fog.setExpDensity( min(1, max(0, self.fog.getExpDensity() + change))) #Code to initialize the tunnel def initTunnel(self): #Creates the list [None, None, None, None] self.tunnel = [None for i in range(4)] for x in range(4): #Load a copy of the tunnel self.tunnel[x] = loader.loadModel('models/tunnel') #The front segment needs to be attached to render if x == 0: self.tunnel[x].reparentTo(render) #The rest of the segments parent to the previous one, so that by moving #the front segement, the entire tunnel is moved else: self.tunnel[x].reparentTo(self.tunnel[x-1]) #We have to offset each segment by its length so that they stack onto #each other. Otherwise, they would all occupy the same space. self.tunnel[x].setPos(0, 0, -TUNNEL_SEGMENT_LENGTH) #Now we have a tunnel consisting of 4 repeating segments with a #hierarchy like this: #render<-tunnel[0]<-tunnel[1]<-tunnel[2]<-tunnel[3] #This function is called to snap the front of the tunnel to the back #to simulate traveling through it def contTunnel(self): #This line uses slices to take the front of the list and put it on the #back. For more information on slices check the Python manual self.tunnel = self.tunnel[1:]+ self.tunnel[0:1] #Set the front segment (which was at TUNNEL_SEGMENT_LENGTH) to 0, which #is where the previous segment started self.tunnel[0].setZ(0) #Reparent the front to render to preserve the hierarchy outlined above self.tunnel[0].reparentTo(render) #Set the scale to be apropriate (since attributes like scale are #inherited, the rest of the segments have a scale of 1) self.tunnel[0].setScale(.155, .155, .305) #Set the new back to the values that the rest of teh segments have self.tunnel[3].reparentTo(self.tunnel[2]) self.tunnel[3].setZ(-TUNNEL_SEGMENT_LENGTH) self.tunnel[3].setScale(1) #Set up the tunnel to move one segment and then call contTunnel again #to make the tunnel move infinitely self.tunnelMove = Sequence( LerpFunc(self.tunnel[0].setZ, duration = TUNNEL_TIME, fromData = 0, toData = TUNNEL_SEGMENT_LENGTH*.305), Func(self.contTunnel) ) self.tunnelMove.start() #This function calls toggle interval to pause or unpause the tunnel. #Like addFogDensity, ToggleInterval could not be passed directly in the #accept command since the value of self.tunnelMove changes whenever #self.contTunnel is called def handlePause(self): ToggleInterval(self.tunnelMove) #End Class World #This function will toggle any interval passed to it between playing and paused def ToggleInterval(interval): if interval.isPlaying(): interval.pause() else: interval.resume() #This function will toggle fog on a node def ToggleFog(node, fog): #If the fog attached to the node is equal to the one we passed in, then #fog is on and we should clear it if node.getFog() == fog: node.clearFog() #Otherwise fog is not set so we should set it else: node.setFog(fog) w = World() run()
empty = {} #Creates a dictionary of an empty key-value my_dict = {"book":1, "Boys":3, "Girls":4} #Creates a my_dict dictionary of 3 Key_values winning_lottery_numbers = dict([("class", True),("School", False)]) #Creates a dictionary from a tupule using the dict function
class SymbolTable: def __init__(self): self.labelTable = {} def addEntry(self, symbol, address): self.labelTable[symbol] = address def contains(self, symbol): return True if symbol in self.labelTable else False def getAddress(self, symbol): return self.labelTable[symbol]
""" Your goal is to define a `Queue` class that uses two stacks. Your `Queue` class should have an `enqueue()` method and a `dequeue()` method that ensures a "first in first out" (FIFO) order. As you write your methods, you should optimize for time on the `enqueue()` and `dequeue()` method calls. The Stack class that you will use has been provided to you. init- create 2 stacks; in stack and out stack enqueue push a item to the in stack dequeue check if the out stack is empty while the in stack is not empty push the items from the in stack on to the out stack ?? check for no items and deal with it ?? return the item from the top of the out stack to the caller """ class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): if len(self.data) > 0: return self.data.pop() return "The stack is empty" def __len__(self): return len(self.data) class QueueTwoStacks: def __init__(self): self.in_stack = Stack() self.out_stack = Stack() def enqueue(self, item): self.in_stack.push(item) def dequeue(self): if len(self.out_stack) == 0: while len(self.in_stack) > 0: stack_item = self.in_stack.pop() self.out_stack.push(stack_item) # if len(self.out_stack) == 0: # raise IndexError("The Queue is Empty, you can not dequeue at this time") return self.out_stack.pop() q = QueueTwoStacks() q.enqueue(1) q.enqueue(2) q.enqueue(3) a = q.dequeue() # 1 b = q.dequeue() # 2 c = q.dequeue() # 3 print(a, b, c, d)
#4. Faça um programa que peça dois números, base e expoente, calcule # e mostre o primeiro número elevado ao segundo número. # Não utilize a função de potência da linguagem. n1 = int(input("Informe um número para a base: ")) n2 = int(input("Informe o segundo número para o expoente: ")) bas = 1 for x in range(n2): bas = n1*bas x += 1 print("A base é: %d"%n1) print("O expoente é: %d"%n2) print("Resultado de "+str(n1)+" elevado a "+str(n2)+" é: "+str(bas))
#7. Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), # se digitar outro valor deve aparecer valor inválido n1 = int(input('Escreva um numero: ')) semana = ['sla', 'Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'] if n1 <= 7 and n1 > 0: print('O número '+str(n1)+' representa '+ semana[n1]) else: print('Número inválido')
s1 = input() s2 = input() ctr,s=len(s1),'' vowels=['a','e','i','o','u','A','E','I','O','U'] while ctr>=0: if s1[ctr] in vowels and s2[ctr] in vowels or s1[ctr] not in vowels and s2[ctr] not in vowels: s+=s1[ctr]+s2[ctr] s1,s2=s2,s1 else: s+=s1[ctr] ctr-=1 print(s)
# mcountInversions.py # input: an array of integers # output: number of inversions that were in the array # # inversions count how many moves are needed to move out-of-place elements into an ordered list # for example, in the list [3, 2, 1], 3 is two places out of place so that's two inversions; once 3 is in place, 1 is one out of place # so the total is 3 inversions def countInversions(arr): """Leverage merge sort to find number of inversions in a list""" if len(arr) == 1: #print('BASE CASE REACHED') return 0, arr midpoint = len(arr)//2 leftCount, leftArray = countInversions(arr[:midpoint]) rightCount, rightArray = countInversions(arr[midpoint:]) #print('--- DIVIDE AND CONQUER ---') #print('len: ' + str(len(arr)) + ' midpoint: ' + str(midpoint) + ' leftArray: ' + str(leftArray) + ' leftCount: ' + str(leftCount) + ' rightArray: ' + str(rightArray) + ' rightCount: ' + str(rightCount)) leftIndex = 0 rightIndex = 0 sortedArray = [] inversionCount = leftCount + rightCount #print('--- MERGE SOLUTIONS ---') for i in range(len(arr)): #print('i: ' + str(i) + ' leftIndex: ' + str(leftIndex) + ' rightIndex: ' + str(rightIndex) + ' inversionCount: ' + str(inversionCount)) if leftArray[leftIndex] <= rightArray[rightIndex]: sortedArray.append(leftArray[leftIndex]) leftIndex += 1 #print('left index incremented, now: ' + str(leftIndex) + ' inversionCount: ' + str(inversionCount)) else: sortedArray.append(rightArray[rightIndex]) rightIndex += 1 inversionCount += len(leftArray) - leftIndex #print('right index incremented, now: ' + str(rightIndex) + ' inversionCount: ' + str(inversionCount)) #print('sortedArray: ' + str(sortedArray)) if leftIndex == len(leftArray): #print('left array used up! just append rest of right array to result. inversionCount: ' + str(inversionCount)) sortedArray += rightArray[rightIndex:] break if rightIndex == len(rightArray): #print('right array used up! just append rest of left array to result. inversionCount: ' + str(inversionCount)) sortedArray += leftArray[leftIndex:] break return inversionCount, sortedArray #print(countInversions([3,2,1])) #print(countInversions([1,3,5,2,4,6])) # Algorithms Week 2 Assignment # Attempt 1: 2397819672 (Issue: array of strings had to be converted to array of ints first) # Attempt 2: 2407905288 CORRECT Answer with open('TestData-CountInversions.txt') as f: data = f.read() strArray = data.strip().split('\n') intArray = [int(numStr) for numStr in strArray] count, sortedArray = (countInversions(intArray)) print(str(count)) #print(sortedArray)
"""Calendar class to wrap list of Appointments for Paxos Log Entries.""" from Appointment import Appointment import datetime class Calendar(object): """ Calendar object to function as container of Appointment objects, which enforces logical rules of a calendar. appointments: unordered set of Appointment objects; order of addition of appointment objects are tracked however for indexing, i.e., Calendar[0] == [first appointment added] """ def __init__(self, *appointments): """ Initialize a Calendar object with any number of Appointment objects. Raise TypeError if some provided arg is not of type Appointment. Raise ValueError if any two Appointment objects provided are conflicting. """ #Enforce positional arguments as only consisting of Appointment objects for appt in appointments: if not hasattr(appt, "_is_Appointment"): raise TypeError( "Positional arguments must Appointment objects") #Enforce no two conflicting Appointment objects for i, appt1 in enumerate(list(appointments)): for j, appt2 in enumerate(list(appointments)): if i != j: if Appointment._is_conflicting(appt1, appt2): raise ValueError( "Appointments \n" + str(appt1) + "\n and \n" + str(appt2) + "\n are conflicting.") #remove duplicates and set l_appointments = list(appointments) self._appointments = [] #loop through with list instead of set to keep order for appointment in l_appointments: if appointment not in self._appointments: self._appointments.append(appointment) self._is_Calendar = True def __eq__(self, other): """Implement == operator for Calendar objects; unordered equality.""" if other == None: return False if not hasattr(other, "_is_Calendar"): raise TypeError("both == operands must be Calendar objects") intersection_length = len( set(self._appointments) & set(other._appointments)) union_length = len(set(self._appointments) | set(other._appointments)) #if count of intersection is same as count of both lists they're the #same list if intersection_length == union_length: return True else: return False def __iadd__(self, other): """ Implement + operator for Calendar. Add an Appointment provided it isn't conflicting. """ appointment_cond = hasattr(other, "_is_Appointment") calendar_cond = hasattr(other, "_is_Calendar") if not appointment_cond and not calendar_cond: raise TypeError( "Only Appointment or Calendar objects may be added to a " "Calendar object.") #handle addition of Appointment if appointment_cond: if self._is_appointment_conflicting(other): raise ValueError( other._name + " is in conflict with Calendar") if other not in self: self._appointments.append(other) #handle addition of Calendar if calendar_cond: if self._is_calendar_conflicting(other): raise ValueError("Cannot add conflicting Calendars") for appointment in other: if appointment not in self: self._appointments.append(appointment) return self def __ne__(self, other): """Implement != operator for Calendar objects; unordered equality.""" return not self.__eq__(other) def __len__(self): """Implement len(Calendar).""" return len(self._appointments) def __getitem__(self, key): """Implement indexing for Calendar object.""" try: return self._appointments[key] except TypeError: raise TypeError("Index must be an int") except IndexError: raise IndexError("invalid index: " + str(key)) def __setitem__(self, key, value): """ Implement Calendar[key] = value; needed to ensure no conflicts added. """ if not hasattr(value, "_is_Appointment"): raise TypeError("value parameter must be an Appointment object") #Ensure valid key while setting try: self._appointments[key] except TypeError: raise TypeError("Index must be an int") except IndexError: raise IndexError("invalid index: " + str(key)) non_key_appts = [] for i, appt in enumerate(self._appointments): if i != key: non_key_appts.append(appt) for appt in non_key_appts: if Appointment._is_conflicting(value, appt): raise ValueError( str(value) + "\n conflicts with \n" + str(appt) + "\n already in Calendar") for appt in non_key_appts: if value == appt: raise ValueError( "Cannot add duplicate Appointment to Calendar") self._appointments[key] = value def __iter__(self): """Implement iterator for Calendar.""" for appointment in self._appointments: yield appointment def __contains__(self, item): """Implement "in" operator for Calendar object.""" for appointment in self: if appointment == item: return True return False def __deepcopy__(self, memo): """Implement copy.deepcopy for Calendar object.""" from copy import deepcopy new_calendar = Calendar() for appointment in self: new_calendar += deepcopy(appointment) return new_calendar def _is_appointment_conflicting(self, appointment): """ Determine if Appointment object appointment conflicts with any Appointment in Calendar object calendar. NOTE: if a copy of appointment is in this Calendar, appointment param will not conflict with the copy. """ #Type checking first if not hasattr(appointment, "_is_Appointment"): raise TypeError( "appointment parameter must be an Appointment object") #if appointment conflicts with anything in this Calendar for calendar_appointment in self: if Appointment._is_conflicting(calendar_appointment, appointment): return True return False def _is_calendar_conflicting(self, other): """Determine if self and other are conflicting.""" if not hasattr(other, "_is_Calendar"): raise TypeError("both parameters must be Calendar objects.") #if any pair of appointments is conflicting, calendars conflict for appt1 in self: for appt2 in other: if Appointment._is_conflicting(appt1, appt2): return True return False def get_appointment_names(self): """Return sorted list of Appointment names in this Calendar object.""" return sorted([appt._name for appt in self._appointments]) @staticmethod def serialize(calendar): """Return a string representation of the calendar with appointments seperated by a hash delimiter""" if calendar: return "#".join([str(appt) for appt in calendar._appointments]) else: return None @staticmethod def deserialize(serial_msg): """Return a Calendar object parsed from a serialized string""" if not serial_msg: return serial_msg if type(serial_msg) != str: return serial_msg appt_list = serial_msg.split("#") appt_for_calendar = [] for appt_str in appt_list: first_str = appt_str.split(" on ") appt_name = first_str[0].split("Appointment ")[1][1:-1] second_str = first_str[1].split(" with ") user_list = second_str[1].split(" and ") users_final = [] for part in user_list: users = part.split(" ") for part in users: if len(part) == 2: users_final.append(int(part[:-1])) else: users_final.append(int(part)) dates_part_1 = first_str[1].split(" from ") times = dates_part_1[1].split(" to ") start_time = times[0] end_time = times[1].split(" with ")[0] appointment_day = dates_part_1[0] start_time_hour, start_time_minute = [ int(comp_time) for comp_time in start_time.split(":") ] end_time_hour, end_time_minute = [ int(comp_time) for comp_time in end_time.split(":")] start_time_final = datetime.time(start_time_hour, start_time_minute) end_time_final = datetime.time(end_time_hour, end_time_minute) appointment = Appointment(appt_name, appointment_day, start_time_final, end_time_final, users_final) appt_for_calendar.append(appointment) return Calendar(*appt_for_calendar) def __str__(self): """Implement str(Calendar) ofr Calendar object.""" ret_str = "Calendar:\n" for appointment in sorted(self, key=lambda x: x._name): ret_str += '\t' + str(appointment) + '\n' return ret_str def __repr__(self): """Implement repr(Calendar).""" return self.__str__() def main(): """Quick tests.""" a1 = Appointment("yo","saturday","12:30pm","1:30pm", [1, 2, 3]) a3 = Appointment("yo1","saturday","1:30am","12:30pm", [1]) a4 = Appointment("yo2","sunday","2:30am","12:30pm", [1]) a5 = Appointment("yo3","monday","12:30am","3:30am", [1]) a6 = Appointment("yo4","tuesday","4:30am","12:30pm", [1]) a7 = Appointment("yo5","wednesday","5:30am","12:30pm", [1]) a8 = Appointment("yo6","thursday","6:30am","12:30pm", [1]) a9 = Appointment("yo7","friday","7:30am","12:30pm", [1]) a10 = Appointment("yo8","monday","8:30am","9:30am", [1]) a11= Appointment("yo9","tuesday","12:30pm","2:30pm", [1]) c3 = Calendar(a1, a3, a4, a5, a6, a7, a8, a9, a10, a11) serial_calendar = Calendar.serialize(c3) import pickle import sys msg = pickle.dumps(serial_calendar) size = sys.getsizeof(msg) print "size", size uC = Calendar.deserialize(serial_calendar) print c3 == uC pass if __name__ == "__main__": main()
''' Summary: RSA Key Generation Principle Author: [email protected] Version: 0.2 Date: 18 Sep 2018 Platform: Ubuntu Server 18.04 LTS python version: 3.6 RSA Key Generation Principle ---------------------------- 1. Generate two large random primes, p and q, of approximately equal size such that their product n = pq is of the required bit length, e.g. 1024 bits. 2. Compute n = pq and (φ) phi = (p-1)(q-1). 3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1. 4. Compute the secret exponent d, 1 < d < phi, such that ed ≡ 1 (mod phi). -modular arithmetics or congruences theorem- 5. The public key is (n, e) and the private key is (n, d). Keep all the values d, p, q and phi secret. * n is known as the modulus. * e is known as the public exponent or encryption exponent or just the exponent. * d is known as the secret exponent or decryption exponent. ''' from random import randrange from math import gcd def print_title(): ''' Prints the program title. ''' print() print('Simple RSA encryption example') print('-' * 29) print() def input_primes(): ''' Function that asks the user for input of primes(p,q). 1) Returns primes(p,q) ''' p = int(input('Select prime p: ')) q = int(input('Select prime q: ')) print() return (p, q) def calc_modulus(primes): ''' 1) Modulus calculation with prime variables (p,q). 2) Checks if variables contain primes. 3) Returns the value of modulus ''' p, q = primes[0], primes[1] n = p * q print('modulus n = p * q = {}'.format(n)) return n def calc_phi(primes): ''' 1) Phi calculation with the given prime variables (p,q). 2) Checks if variables contain primes. 3) Returns the value of Phi. ''' p, q = primes[0], primes[1] phi = (p - 1) * (q - 1) print('phi = (p - 1) * (q - 1) = {}'.format(phi)) print() return phi def pick_public_key(phi): ''' Public key generator (Random). 1) Checks if random and Phi integer have no common factors except 1. 2) Returns Public key ''' gcd_is_one = False while not gcd_is_one: e = randrange(2, phi) if gcd(e, phi) == 1: gcd_is_one = True print('Choose Public key e: {}'.format(e)) print('[*] {} and {} have no common factors except 1'.format(e, phi)) print() return e def calc_private_key(e, phi, n): ''' Private key generator 1) Mod inversion of public key and Phi. 2) Returns Private key ''' for d in range(1, n - 1): if (e * d - 1) % phi == 0: break print('Computed Private key d: {}'.format(d)) print('[*] {} * {} mod {} = 1'.format(e, d, phi)) print() return d def input_message(): ''' Function that asks the user for input message(m) to encrypt. 1) Returns message (m) ''' m = int(input('Select message m: ')) print() return m def encrypt_message(e, n, m): ''' Function for encryption 1) Encrypted(c) = Message(m) ^ PublicKey(e) % Modulus(n) 2) Returns encrypted message(c) ''' # c = m ** e % n c = pow(m, e, n) print('Encrypted message c = m ** e % n = {}'.format(c)) return c def decrypt_message(d, n, c): ''' Function for Decryption 1) Decrypted(mm) = Encrypted(c) ^ PrivateKey(d) % Modulus(n) 2) Returns decrypted message(mm) ''' # mm = c ** d % n mm = pow(c, d, n) print('Decrypted message mm = c ** d % n = {}'.format(mm)) print() return mm def verify_message(m, mm): ''' Function that verifies encrypted message(m) equals the decrypted message (mm) 1) Prints message if equals or not-equals ''' print('[*] Is m == mm ? ... ', end="") msg = 'OK WORKING EXAMPLE' if m == mm else 'NOT OK -- CHECK FOR ANY ERROR' print(msg) print() def main(): ''' Main function executes Functions/Methodes/Code inside it accordingly. Without the main, the code would be executed even if the script were imported as a module. ''' print_title() my_primes = input_primes() n = calc_modulus(my_primes) phi = calc_phi(my_primes) e = pick_public_key(phi) d = calc_private_key(e, phi, n) m = input_message() c = encrypt_message(e, n, m) mm = decrypt_message(d, n, c) verify_message(m, mm) if __name__ == '__main__': main()
#!/usr/bin/env python3 from collections import namedtuple import aoc DistLoc = namedtuple('DistLoc', ['distance', 'location']) Slope = namedtuple('DistLoc', ['relation', 'slope']) def parse_input(input_list): """ Parse input to a set of coordinate locations. Only locations with an asteroid will be put in the map. """ asteroid_map = set() for y_loc, row in enumerate(input_list): for x_loc, value in enumerate(row): if value == '#': asteroid_map.add(aoc.Coord(x_loc, y_loc)) return asteroid_map def calculate_slopes(base_location, asteroid_map): """ Calculate the slopes of all asteroids in the map referenced to base_location. If two asteroids have the same slope then the closest one will block the view of the further ones. """ slopes = {} for location in asteroid_map: relation = aoc.coord_relation_negy(base_location, location) if relation != 0: distance = aoc.distance_manhattan_coords(location, base_location) location_list = slopes.setdefault((relation, aoc.slope_negy(base_location, location)), []) # Add a tuple containing the distance. Since distance will be unique we can then # sort the list to get a closest to furthest list. location_list += [DistLoc(distance, location)] location_list.sort() return slopes def find_best_location(asteroid_map): """ Find the asteroid that is situated such that it can see the most other asteroids. """ best_num_asteroids = 0 best_location = None for base_location in asteroid_map: slope_set = calculate_slopes(base_location, asteroid_map) num_asteroids_seen = len(slope_set) if num_asteroids_seen > best_num_asteroids: best_num_asteroids = num_asteroids_seen best_location = base_location return best_location, best_num_asteroids def simulate_destroying_asteroids(asteroid_map): num_asteroids_destroyed = 0 best_location, _ = find_best_location(asteroid_map) slope_set = calculate_slopes(best_location, asteroid_map) clockwise_ordered_list = sorted(slope_set, reverse=True) for slope in clockwise_ordered_list: location_list = slope_set[slope] location = location_list.pop(0) if not location_list: # All locations on this slope are used so drop it. slope_set.pop(slope) num_asteroids_destroyed += 1 if num_asteroids_destroyed == 200: break return location.location.x_val * 100 + location.location.y_val def part1(input_list): asteroid_map = parse_input(input_list) _, best_num_asteroids = find_best_location(asteroid_map) return best_num_asteroids def part2(input_list): asteroid_map = parse_input(input_list) return simulate_destroying_asteroids(asteroid_map) if __name__ == "__main__": aoc.main(part1, part2)
#len() - dlugosc - length #.append - dodac #.extend - rozszerzyc #.inset(index, co) - wstawic #.index - indeks danego elementu #sort(reverse=False) - sortuj rosnaco #max() #min() #.count - ile razy cos wystapi #.pop - usun ostatni element #.remove - usun pierwsze wystapienie #.clear - wyczysc liste #.reverse - zamien kolejnosc lista1 = [54, 1, -2, 20, 1] lista2 = ["Arkadiusz", "Wioletta"] print(len(lista1))
import sys # wyrazenie lisowne evenNumbers = [element for element in range(400) if (element % 2 == 0) ] # wyrazenie generujace - wypisujemy dane i o nich zapominamy evenNumbersGenerator = (element for element in range(400) if (element % 2 == 0) ) print(sys.getsizeof(evenNumbersGenerator)) for item in evenNumbersGenerator: print(item) potega2generator = (item**2 for item in range (100) ) print(sum(potega2generator))
import math print("1: Oblicz Pole prostokąta") print("2: Oblicz pole kwadratu") print("3: Oblicz pole trojkata") print("4: Oblicz pole trapezu") print("5: Oblicz pole koła") wybor = input("Pole jakiej figury chcesz policzyc? ") def pole_prostokata(a, b): return a * b def pole_kwadratu(a): return a * a def pole_trojkata(a, h): return 0.5 * a * h def pole_trapezu(a, b, h): return (a + b) / 2 * h def pole_trapezu2(a, b, h): print((a + b) / 2 * h) def pole_kola(r): return math.pi * r ** 2 if (wybor == "1"): a = int(input("Podaj wartosc a:")) b = int(input("Podaj wartosc b: ")) print(pole_prostokata(a, b)) elif (wybor == "2"): a = int(input("Podaj wartosc a:")) print (pole_kwadratu(a)) elif (wybor == "3"): a = int(input("Podaj wartosc a:")) h = int(input("Podaj wartosc h: ")) print(pole_trojkata(a, h)) elif (wybor == "4"): a = int(input("Podaj wartosc a:")) b = int(input("Podaj wartosc b: ")) h = int(input("Podaj wartosc h: ")) print(pole_trapezu(a, b, h)) elif (wybor == "5"): r = int(input("Podaj wartosc r:")) print(pole_kola(r)) else: print("Nie wpisales liczby z zakresu od 1 do 5")
import random cardList = ["9", "9", "9", "9", "10", "10", "10", "10", "Jack", "Jack", "Jack", "Jack", "Queen", "Queen", "Queen", "Queen", "King", "King", "King", "King", "Ace", "Ace", "Ace", "Ace", "Joker", "Joker"] random.shuffle(cardList) for CardsPlayer in range (2): CardsPlayer = [] def rozdanie(CardsPlayer): for i in range(5): CardsPlayer.append(cardList.pop()) return CardsPlayer print(rozdanie(CardsPlayer))
""" OOP - Object Oriented Programming Programowanie zorientowane wokół obiektów OBIEKT OBIEKTY - to pojemniki do przechowywania zmiennych i funkcji tematycznie ze sobą powiązanych do dalszego łatwiejszego ponownego użycia Klasy - foremki (szablony) do tworzenia egzemplarzy obiektów Atrybut - cecha opisująca obiekt Metoda - funkcja, która operuje na obiekcie Instacja klasy - instance z ang. egzemplarz to obiekt, który wyszedł z formy (klasy) """ class User: age = 0 seba = User() mirek = User() arek = User() mirek.age = 24 age = 40 print(seba.age) print(mirek.age) print(age) x = 5
#petla """ suma = 0 x = int(input("Podaj kolejna liczbe") suma += x x = int(input("Podaj kolejna liczbe") suma += x x = int(input("Podaj kolejna liczbe") suma += x """ #suma = 0 #x = int(input("Podaj kolejna liczbe") """ while - podczas gdy """ liczba = 100 while liczba >=0: print (liczba) liczba -= 1