text
stringlengths
37
1.41M
from collections import namedtuple filename = "input.txt" #filename = "example_input.txt" with open(filename, "r") as f: data = f.readlines() data = [line.strip() for line in data] Instruction = namedtuple('Instruction', ['op', 'has_run']) instructions = {} for i, line in enumerate(data): instructions[i] = Instruction(op=line, has_run=False) i = 0 acc = 0 for instruction in instructions.values(): print(instruction) while True: print("Current op index", i) op, _ = instructions[i] instructions[i] = instructions[i]._replace(has_run=True) if "nop" in op: print("Nop detected.") print("Moving to next instruction") if "acc" in op: amount = int(op.split(" ")[1]) acc += amount print("Acc detected", amount) print("Accumulator set to", acc) if "jmp" in op: amount = int(op.split(" ")[1]) next_instruction = (i + amount) % (len(instructions) - 1) print("Jump detected:", amount) print("Jumping from", i, "to", next_instruction) i = next_instruction - 1 i += 1 op, has_run = instructions[i] if has_run: print("Loop detected @", op) break print("Accumulator before loop:", acc)
with open('input.txt', 'r') as f: data = f.readlines() data = [line.strip() for line in data] def convert_char(char): """ Convert input to binary so that we can reuse the same function for both rows and columns """ if char == 'F' or char == 'L': return 0 return 1 def bsp(line, current, max): """ Binary Space Partitioning algorithm """ char = convert_char(line[0]) #print("Character is: ", char) #print("Difference between max-min:", max - current) if len(line) == 1: #print("Last character is:", char) #print("Range is:", (current, max)) if char == 0: return current return max difference = max - current half = difference // 2 upper_half = max - half lower_half = current + half #print("Lower half:", (current, lower_half)) #print("Upper half:", (upper_half, max)) if char == 0: #print("Taking the lower half.") #print("New range is:", (current, lower_half)) #print("") return bsp(line[1:], current, lower_half) #print("Taking the upper half.") #print("New range is:", (upper_half, max)) #print("") return bsp(line[1:], upper_half, max) seats = [] for line in data: row = bsp(line[0:7], 0, 127) column = bsp(line[7:], 0, 7) seat_id = row * 8 + column seats.append((row, column, seat_id)) #print("Seats: ") highest_seating_id = 0 for seat in seats: x, y, seating_id = seat #print("Seat:", seat) if seating_id > highest_seating_id: highest_seating_id = seating_id print("Highest seating ID:", highest_seating_id)
#Compound Interest = P(1 + R/100)**t #Where, #P is principle amount #R is the rate and #T is the time span p = float(input("principle amount: \n--->> ")) r = float(input("rate: \n--->>")) t = float(input("time: \n--->>")) result = p * (1 + (r / 100)) ** t print("compound is: ", int(result))
num1 = int(input("Enter a Number: ")) num2 = int(input("Enter another Number: ")) sum = num1 + num2 print(f"The sum of {num1} and {num2} is {sum}")
import sys ''' Converts a string of ints into a list of ints and finds the product ''' def getProd(numStr): return reduce(lambda x, y: x * y, [int(i) for i in numStr]) ''' Main execution ''' try: inNumber = sys.argv[1] numAdj = int(sys.argv[2]) except: sys.exit("Script execution must follow the following format: python problem5.py <inNumber> <numAdj>") result = 0 if numAdj >= len(inNumber): result = getProd(inNumber) else: for x in range(0, len(inNumber) - numAdj + 1): if getProd(inNumber[x : x + numAdj]) > result: result = getProd(inNumber[x : x + numAdj]) sys.exit(str(result))
import json from collections import Counter wordlist = open("minidic-WORDLIST.txt") wordlist = [x[:-2] for x in wordlist] # first thousand print wordlist rawlog = open("lesswrong_logs.json") print "Loading JSON..." logdict = json.load(rawlog) logs = [] users = set() for day in logdict.keys(): for line in logdict[day]: if line[3] == u'olivia': logs.append(line) users.add(line[3]) print "Removing common words..." uncommons = [] for line in logs: clean = line[4].split() # Naive, will miss stuff for elem in clean: if elem not in wordlist: uncommons.append(elem) print Counter(uncommons).most_common(1000)
print "Bucket List Time!" print "Let's create an awesome Bucket List of the things you've always dreamed of doing!" responses = {} question1="What's the most dangerous thing you want to do? " question2="What's the scariest thing you want to do? " question3="What languages do you want to learn? " question4="What countries do you want to visit? " question5="What animals do you want to come face to face with? " question6="Where do you want to volunteer? " question7="Who have you always wanted to meet? " question8="When you're all finished, write exit! " #I used the while loop to get each users answer and then store the input in a dictionary which is then written to a file while True: user_input = raw_input("What's the most dangerous thing you want to do? ") responses[question1]=user_input user_input = raw_input("What's the scariest thing you want to do? ") responses[question2]=user_input user_input = raw_input("What languages do you want to learn? ") responses[question3]=user_input user_input = raw_input("What countries do you want to visit? ") responses[question4]=user_input user_input = raw_input("What animals do you want to come face to face with? ") responses[question5]=user_input user_input = raw_input("Where do you want to volunteer? ") responses[question6]=user_input user_input = raw_input("Who have you always wanted to meet? ") responses[question7]=user_input user_input = raw_input("When you're all finished, write exit! ") if user_input == "exit!": break bucket_list_file = open("bucket_list_file.txt", 'w+') bucket_list_file.write("WELCOME TO YOUR BUCKET LIST!\n\n") print "WELCOME TO YOUR BUCKET LIST!" count = 1 for question in responses: #for each key (question) the value (user input) will print print question, responses[question] bucket_list_file.write(str(count) + ". " + question + "\n" + responses[question] + "\n") count += 1 bucket_list_file.write("\nNOW GO MAKE YOUR DREAMS COME TRUE!\n") print "NOW GO MAKE YOUR DREAMS COME TRUE!" bucket_list_file.close()
def convert(s): try: x = int(s) print("Conversion succeeded! x = ", x) except ValueError: print("Conversion failed!") x = -1 except TypeError: print("Conversion failed!") x = -1 return x print(convert("6ddd")) def convert(s): try: x = int(s) print("Conversion succeeded! x = ", x) except (ValueError, TypeError): print("Conversion failed!") x = -1 return x
# Support Vector Machine from Scratch using SMO """Support Vector Machines are a type of supervised machine learning algorithm that provides analysis of data for classification and regression analysis. While they can be used for regression, SVM is mostly used for classification. We carry out plotting in the n-dimensional space. The value of each feature is also the value of the specified coordinate. Then, we find the ideal hyperplane that differentiates between the two classes. These support vectors are the coordinate representations of individual observation. It is a frontier method for segregating the two classes. This machine learning model is able to generalise between two different classes if the set of labelled data is provided in the training set to the algorithm. The main function of the SVM is to check for that hyperplane that is able to distinguish between the two classes. I use Sequential Minimal Optimization Algorithm for the fast result over SVM Model. John Platt from Microsoft gave this amazing technique to train the model in a fast way. In this SMO actually check some of the lambdas of data which is find by the SVM over KKT Conditions. If any of the lambdas fit all the conditions then it will be treated as Support Vector for the training and fixing the Hyperplane.""" # Importing libraries import pandas as pd import numpy as np # Theta Function """Funtion to return thetas after the SVM trains itself on training data.""" def thetas(lambdas,C_train,x): a=lambdas*C_train.T theta=np.matmul(x.T,a.T) neg_x=x[np.where(C_train==-1)[0]] pos_x=x[np.where(C_train==1)[0]] pos=np.min(1-np.matmul(theta.T,pos_x.T)) neg=np.max(-1-np.matmul(theta.T,neg_x.T)) theta0=(pos+neg)/2 return theta,theta0 # Error Function """Funtion to calculate Error between new lambdas and old lambdas.""" def E(i,b,C_train,lambdas,x): fx=np.sum((C_train*lambdas)*np.matmul(x,x[i].T))+b return fx-C_train[i] # L and H Bound Function """Funtion to find upper and lower bounds which don't voilate KKT condition. L is lower bound and H is upper bound.""" def LnH(i,j,regularize,C_train,lambdas): if C_train[i]!=C_train[j]: L=max(0, lambdas[j]-lambdas[i]) H=min(regularize,regularize+lambdas[j]-lambdas[i]) if C_train[i]==C_train[j]: L=max(0,lambdas[i]+lambdas[j]-regularize) H=min(regularize,lambdas[i]+lambdas[j]) return L,H # Compute Eta Function """Funtion to return inner product (or implement some kernel funtion K)""" def compute_eta(i,j,x): return (2*np.matmul(x[i],x[j].T)-np.matmul(x[i],x[i].T)-np.matmul(x[j],x[j].T)) # Compute B-Threshold Function """Funtion to compute threshold i.e. B which is compute after finding the lambdas so that it can satisfied the vectors.""" def compute_b(i,j,b,E1,E2,R,C_train,lambdas,lambdas_old,x): # Finding y*(alphai - aplhai_old) & y(alphaj - alphaj_old) I=C_train[i]*(lambdas[i]-lambdas_old[i]) J=C_train[j]*(lambdas[j]-lambdas_old[j]) # Finding b1 and b2 b1=b-E1-(I*np.matmul(x[i],x[i].T))-(J*np.matmul(x[i],x[j].T)) b2=b-E2-(I*np.matmul(x[i],x[j].T))-(J*np.matmul(x[j],x[j].T)) if lambdas[i]>0 and lambdas[i]<R: b=b1 elif lambdas[j]>0 and lambdas[j]<R: b=b2 else: b=(b1+b2)/2 return b # Cliping Function """Function to clip the value of 'Lagrange Multiplier' if they voilate KKT condition""" def clip(H,L,j,lambdas): if lambdas[j]>H: lambdas[j]=H elif lambdas[j]<L: lambdas[j]=L elif L<=lambdas[j]<=H: lambdas[j]=lambdas[j] # Calculate J Function """Funtion to pick second Lagrange multiplier which results the max value of Error with the first Lagrange Multiplier""" def second_lambda(i,x,b,C_train,lambdas): elist=[] for k in range(0,x.shape[0]): e=E(k,b,C_train,lambdas,x) elist.append(abs(e-E(i,b,C_train,lambdas,x))) new_j=np.argmax(elist) return new_j def main(): # Calling Data """Data is call for work. The Columns are selected here is according to the BREAST CANCER DATASET from WINCONSIN Hospital Easily find on Kaggle(www.kaggle.com). Creating Dataset from original columns from the dataset so that you won't face any trouble regarding the dataset. I use Breast Cancer Dataset to train model and predict whether the person is having cancer or not.""" data=pd.read_csv("./Dataset/Breast Cancer Dataset/Breast_Cancer_Data.csv") # Taking Out Labels C=(data['diagnosis']) C.replace(to_replace=['B','M'],value=[1,-1],inplace=True) C=np.array(C).reshape(569,1) # Data Preprocessing removing Unnecessory columns data.drop([data.columns[0],data.columns[1],data.columns[32]],axis = 1, inplace = True) data=(data-np.mean(data,axis=0))/np.std(data,axis=0) # Splitting training and testing data training_len=0.75*data.shape[0] train_data=data.iloc[-int(training_len):] test_data=data.iloc[:data.shape[0]-int(training_len)] x=np.array(train_data) C_train=C[:int(training_len)] C_test=C[int(training_len):] # Initializing parameters for Sequencial Minimal Optimization max_passes=4 passes=0 tol=10**(-1) R=x.shape[0] lambdas=np.zeros((C_train.shape[0])) #lambdas[np.where(lambdas<0)[0]]=0 lambdas_old=np.zeros((C_train.shape[0])) b=0 # Sequential Minimal Optimization (Refrenced from : CS229 Simplified SMO) while passes < max_passes: changed_alphas = 0 for i in range(0,x.shape[0]): E1=E(i,b,C_train,lambdas,x) if (C_train[i]*E1 < -tol and lambdas[i] < R) or (C_train[i]*E1 > tol and lambdas[i] > 0): j=second_lambda(i,x,b,C_train,lambdas) E2=E(j,b,C_train,lambdas,x) lambdas_old[i]=lambdas[i] lambdas_old[j]=lambdas[j] L,H=LnH(i,j,R,C_train,lambdas) if L == H: continue eta=compute_eta(i,j,x) if eta >= 0: continue lambdas[j]=lambdas[j]+(C_train[j]*(int(E2-E1)))/eta clip(H,L,j,lambdas) if (abs(lambdas[j] - lambdas_old[j]) < 10**(-5)): continue lambdas[i]=lambdas[i]-(C_train[i]*C_train[j]*(lambdas[j]-lambdas_old[j])) b=compute_b(i,j,b,E1,E2,R,C_train,lambdas,lambdas_old,x) changed_alphas = changed_alphas + 1 if changed_alphas == 0: passes=passes + 1 else: passes=0 print(passes) # Number of support vectors np.count_nonzero(lambdas) # Getting the parameters for Decision Boundary t,t0=thetas(lambdas,C_train,x) # Testing Accuracy y=np.array(test_data) predicted_labels=np.matmul(y,t)+t0 predicted_labels[np.where(predicted_labels>0)[0]]=1 predicted_labels[np.where(predicted_labels<=0)[0]]=-1 o=np.count_nonzero(np.equal(C_test,predicted_labels)) test_accuracy=(o/C_test.shape[0])*100 print("Testing accuracy : ",test_accuracy) # Training Accuracy training_label=np.matmul(x,t)+t0 training_label[np.where(training_label>0)[0]]=1 training_label[np.where(training_label<0)[0]]=-1 train_accuracy = np.count_nonzero(np.equal(C_train,training_label))/C_train.shape[0]*100 print("Training accuracy : ",train_accuracy) # Calling Main Function if __name__ == "__main__": # Calling Main Function main()
#====================================================================== # Logistic Regression from SKLearn over MNIST Dataset (Multi-Class Classification) """ Logistic regression is a statistical model that in its basic form uses a logistic function to model a multiple dependent variable, although many more complex extensions exist. In regression analysis, logistic regression (or logit regression) is estimating the parameters of a logistic model (a form of binary/multiple regression). It is a Discriminate Learning Algorithm which means that it try to find posterior probability over classes directly without the envolvement of likelihood probabilities.<br> In statistics, the logistic model is used to model the probability of a certain class or event existing such as pass/fail, win/lose, alive/dead, True/False or healthy/sick. <br> This can be extended to Classify several classes of events such as determining whether an image contains a cat, dog, lion, etc.<br> This code contains only about how we can fit a logistic model over user given dataset and also to get a good output result out of it. The code written keeping vision of object oriented programing which means that the code is fully moduler so that to keep in mind about the use of the functions in other programs also. """ #====================================================================== #====================================================================== #Importing Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix,plot_confusion_matrix #====================================================================== #====================================================================== #Prediction Function """ Prediction function is use to get the accuracy of the fitted model over training and testing data so that we can get to know how much accurate over model is trained over training data to predict right output. """ def accuracy_with_confusion_matrix(model,testing_data,testing_labels): predict = model.predict(testing_data) accuracy = model.score(testing_data,testing_labels) accuracy = accuracy*100 print('Accuracy : ',accuracy) cm = confusion_matrix(testing_labels,predict) print("\n\nThe Confusion Matrix is : \n\n",cm,"\n\nThe Graph Plot over Confusion Matrix : \n") plot_confusion_matrix(model,testing_data,testing_labels) #====================================================================== #====================================================================== #Main Function def main(): #====================================================================== #Calling Data """ Data is call for fitting of object classifer created here. The Columns are selected here is according to the DIGIT RECOGNISATION DATASET from Famous MNIST DATASET Easily find on Kaggle(https://www.kaggle.com/oddrationale/mnist-in-csv?select=mnist_train.csv). """ training_data = pd.read_csv('mnist_train.csv') testing_data = pd.read_csv('mnist_test.csv') #====================================================================== #====================================================================== #Preprocessing of training and testing data training_labels = training_data['label'] training_data.drop(['label'],axis=1,inplace=True) testing_labels = testing_data['label'] testing_data.drop(['label'],axis=1,inplace=True) #====================================================================== #====================================================================== #Normalising the data """ Scaling the features. The scaling is also know as standardisation/normalisation. Standardization is a process for making a dataset fit for the training of the model. In this prosess we make a dataset whose value lies between zero mean and one standard deviation. The Data Comming out from this process is smooth for the curves and fitting a model. """ sc=StandardScaler() training_data=sc.fit_transform(training_data) testing_data=sc.fit_transform(testing_data) #====================================================================== #====================================================================== #Logistic Regression Model """ Creating a Logistic regression model object and fitting it over training data.<br> The Model contain these three function for the fitting over the data.""" #-------------------------------------------------------------------------------------------------------------------------------------- #Softmax Function """ Defining the Softmax Function. Softmax function is use in the ml to get the probability value (i.e. between 0 to 1) for any feature. The function basically has the formula which make the value equal to probable value of the feature between 0 to 1. Funtion to return Posterior Probabilities """ #Formula : refer to python notebook #-------------------------------------------------------------------------------------------------------------------------------------- #Derivative Functions """ Derivative functions are define to find the derivative of the features to train the model and get the weights for the GDA. Funtions to return derivatives with respect to wieghts for GDA. """ #Formula del by del0s : refer to python notebook #Formula del by dels : refer to python notebook #-------------------------------------------------------------------------------------------------------------------------------------- #Cross Entropy Function """ Defining Function for Cross Entroy Loss calculation.In Convex Optimization we find the global minima to train the model so it get less error while prediction for the testing and training data. This error is called as loss. We introduce log and a negative sign in case to smoothing of and inverting the parabola to find the global minima.<br> """ #Here, Logrithm is use to smoothing out the curve so that it don't stucked in any local minima. #Here, Negative sign is introduce to invert the parabola of the function. #Formula : refer to python notebook #-------------------------------------------------------------------------------------------------------------------------------------- #Gradient Descent """ The Fit function is to fit the learning curve and reduce the loss of the model. The algorithm use here is the Stocastic Gradient Descent(SGD). The algorithm is containing the learning rate,epsilon for the stoping of under going algorithm to find global minima.Creating Classifier object and fitting to our training data """ logistic=LogisticRegression(verbose=1,multi_class='ovr',max_iter=10000) logistic.fit(training_data,training_labels) #====================================================================== #====================================================================== #Predicting result on both the datasets #Training Accuracy accuracy_with_confusion_matrix(logistic,training_data,training_labels) #Testing Accuracy accuracy_with_confusion_matrix(logistic,testing_data,testing_labels) #====================================================================== #====================================================================== #====================================================================== #Calling Main Function if __name__ == "__main__": #Calling Main Function main() #======================================================================
import random arr_card_types = ['red', 'blue', 'green', 'yellow'] arr_card_numbers = [x for x in range(1, 11)] class Card: def __init__(self, card_type=None, card_number=None): self.card_type = card_type self.card_number = card_number class Deck: def __init__(self, cards): self.deck_cards = cards self.number = 0 def __iter__(self): return self def __next__(self): if self.number > len(self.deck_cards): raise StopIteration return self.deal() def __bool__(self): return True if self.deck_cards else False def print_deck(self): for d_card in self.deck_cards: print(f"({d_card.card_type} {d_card.card_number})", end=" ") print("\n") def shuffle(self): random.shuffle(self.deck_cards) def deal(self): return self.deck_cards.pop(len(self.deck_cards) - 1) def build_array_cards(cards_type, cards_number): return [Card(c_number, c_type) for c_number in cards_number for c_type in cards_type] # array_cards = [] # for c_number in cards_number: # for c_type in cards_type: # new_card = Card(c_number, c_type) # array_cards.append(new_card) # return array_cards arr_cards = build_array_cards(arr_card_types, arr_card_numbers) deck_cards = Deck(arr_cards) deck_cards.print_deck() deck_cards.shuffle() deck_cards.print_deck() deal_card = deck_cards.deal() print(f"Card details: {deal_card.card_type}, {deal_card.card_number} ") deal_card = deck_cards.deal() deck_cards.print_deck() if deck_cards: card = deck_cards.deal() else: print("the deck is empty")
import pygame ,sys,random,math #general setup # snake class Snake(): def __init__(self,pixel_size): self.snake_color= pygame.Color(0,206,0) self.snake_head_color= pygame.Color(0,100,0) self.size=1 self.tail=[] self.history= [] self.state = [0,0,0,1] self.frame_itiration=0 self.head = pygame.Rect(1,1,pixel_size-2,pixel_size-2) def eat(self,food,pixel_size,screen_width): if abs(food.head.x-self.head.x)<5 and abs(food.head.y-self.head.y)<5: self.size+=1 self.history=[] food.reset(self,pixel_size,screen_width) self.frame_itiration=0 self.tail.append(pygame.Rect(-500,-500,pixel_size-2,pixel_size-2)) return 10 else: return 0 def move(self,action,pixel_size,screen_width,screen_height,food): if self.size>2: i = self.size-2 while i>0: self.tail[i].x=self.tail[i-1].x self.tail[i].y=self.tail[i-1].y i-=1 if self.size>1: self.tail[0].x=self.head.x self.tail[0].y=self.head.y if self.state==action: reward = 0 else: reward = -0.1 #test action if (action[0] and not (self.state[1])) or (action[1] and not (self.state[0]))or (action[2] and not (self.state[3]))or (action[3] and not (self.state[3])): self.state= action #move if self.state[0]: #upp self.head.y +=-1*pixel_size elif self.state[1]: #down self.head.y +=1*pixel_size elif self.state[2]: #left self.head.x +=-1*pixel_size elif self.state[3]: #right self.head.x +=1*pixel_size game_over = False score = self.size if self.is_lose(screen_width,screen_height): self.lose() reward = -10 game_over = True food.reset(self,pixel_size,screen_width) self.history.append([self.head.x,self.head.y]) reward += self.eat(food,pixel_size,screen_width) return reward , game_over , score def is_lose(self,screen_width,screen_height): return self.head.x<0 or self.head.y<0 or self.head.x>screen_width or self.head.y>screen_height or self.on_tail(self) or (self.history.count([self.head.x,self.head.y])>10)or self.frame_itiration>100*self.size def lose(self): self.history=[] self.size = 1 self.tail = [] self.state = [0,0,0,1] self.head.x = 1 self.head.y = 1 self.frame_itiration=0 def draw(self,screen): for i in range(self.size-1): x=100+(i+1)*10 if x<256: pygame.draw.rect(screen,pygame.Color(0,x,0),self.tail[i]) else: pygame.draw.rect(screen,pygame.Color(0,255,0),self.tail[i]) pygame.draw.rect(screen,self.snake_head_color,self.head) def on_tail(self,obj): f= False for i in self.tail: if abs(i.x - obj.head.x)<5 and abs(i.y - obj.head.y)<5: f= True return f # food class Food: def __init__(self,snake,pixel_size,screen_width): self.food_color= pygame.Color(206,0,0) self.head = pygame.Rect(0,0,pixel_size-2,pixel_size-2) self.reset(snake,pixel_size,screen_width) def reset(self,snake,pixel_size,screen_width): x = random.randint(0, (screen_width-pixel_size )//pixel_size ) y = random.randint(0, (screen_width-pixel_size )//pixel_size ) self.head.x = x*pixel_size self.head.y = y*pixel_size if (abs(snake.head.x - self.head.x)<5 and abs(snake.head.y - self.head.y)<5) or snake.on_tail(self): self.reset(snake,pixel_size,screen_width) # colors class Game: def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.fast = True self.visible = True # Setting up the main window self.screen_width = 1000 self.screen_height = 1000 self.pixel_size = 50 self.screen = pygame.display.set_mode((self.screen_width,self.screen_height)) pygame.display.set_caption('Snake') self.snake = Snake(self.pixel_size) self.food = Food(self.snake,self.pixel_size,self.screen_width) self.bg_color= pygame.Color(12,12,12) def play_round(self,action,number_of_games): #handling input for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: self.fast = not self.fast if event.key == pygame.K_v: self.visible = not self.visible self.snake.frame_itiration+=1 reward ,game_over , score = self.snake.move(action,self.pixel_size,self.screen_width,self.screen_height,self.food) # Draw if self.visible: self.screen.fill(self.bg_color) self.snake.draw(self.screen) pygame.draw.ellipse(self.screen,self.food.food_color,self.food.head) # Updating the window pygame.display.flip() if self.fast: self.clock.tick(10000) else: self.clock.tick(20) return reward,game_over , score-1 # game_1 =Game() # while True: # action =[0,0,1,0] # if game_1.snake.frame_itiration>10: # action =[0,1,0,0] # reward ,game_over , score = game_1.play_round(action)
#!/usr/bin/env python """ """ from unittest import TestCase, main from land import Land class TestLand(TestCase): """ """ def setUp(self): pass def tearDown(self): pass def test_init(self): """Test Land's init. Expect certain attributes can be used as kwargs while others raise an exception.""" land = Land(0, 'test-land', 10, area_perm=3) self.assertEqual(land.area_perm, 3) with self.assertRaises(AttributeError): land = Land(0, 'test-land', 10, random_attr=3) def test_calculations(self): """ """ pass if __name__ == '__main__': main()
from random import randint def is_valid(isbn): result = False isbn = validation(isbn) if isbn: if (isbn[0] * 10 + isbn[1] * 9 + isbn[2] * 8 + isbn[3] * 7 + isbn[4] * 6 + isbn[5] * 5 + \ isbn[6] * 4 + isbn[7] * 3 + isbn[8] * 2 + isbn[9] * 1) % 11 == 0: result = True print("ISBN-13 from the ISBN-10 original:", isbn_13_generator(isbn, "10 to 13")) return result def validation(isbn, operation = "normal"): isbn = isbn.replace("-", "") if operation == "normal" or (operation != "normal" and isbn): if operation == "normal": if len(isbn) != 10: return False if isbn[-1].isalpha() and isbn[-1].upper() != "X": return False for x in isbn: if x.isalpha() and x.upper() != "X": return False for x in isbn[:-1]: if x.upper() == "X": return False if isbn[-1].upper() == "X": isbn = list(map(int, isbn[:-1])) isbn.append(10) else: isbn = list(map(int, isbn)) else: isbn = [] return isbn def isbn_13_generator(isbn, isbn_type, has_X = False): if isbn_type == "10 to 13": val = 3 else: val = 13 - len(isbn) while True: for inserting in range(val): isbn.insert(0, randint(0,9)) if (isbn[0] * 13 + isbn[1] * 12 + isbn[2] * 11 + \ isbn[3] * 10 + isbn[4] * 9 + isbn[5] * 8 + isbn[6] * 7 + isbn[7] * 6 + isbn[8] * 5 + \ isbn[9] * 4 + isbn[10] * 3 + isbn[11] * 2 + isbn[12] * 1) % 11 == 0: tmp = f"{isbn[0]}-" for x in isbn[1:4]: tmp += str(x) tmp += "-" for x in isbn[4:12]: tmp += str(x) if has_X == True: tmp += "-X" else: tmp += f"-{isbn[-1]}" return tmp else: for deleting in range(val): del isbn[0] def generator(partial = ""): if partial: string = f"ISBN-13 from the partial ISBN {partial}:" else: string = "ISBN-13 fully generated:" has_X = False if partial and partial[-1].upper() == "X": has_X = True if len(partial.replace("-", "")) >= 13: raise ValueError("Partial ISBN already have 13 or more digits") isbn = validation(partial, "generator") if isbn or isbn == []: print(string, isbn_13_generator(isbn, "new", has_X)) else: raise ValueError("Partial ISBN must be composed only by numbers or 'X' as check character, separated or not by dashes")
def latest(scores): if not scores: return "There's no score in the ranking..." return scores[-1] ## I'm assuming that when you put a new score in the list, you will use append method def personal_best(scores): if not scores: return "There's no score in the ranking..." return max(scores) def personal_top_three(scores): if not scores: return "There's no score in the ranking..." if len(scores) <= 3: return sorted(scores, reverse=True)[:len(scores)] return sorted(scores, reverse=True)[:3]
import sqlite3 conn = sqlite3.connect('imdb.db') c = conn.cursor() c.execute("select * from name_basics limit 10") for row in c: print(row) conn.close() import sqlite3 class database: #https://docs.python.org/3/library/sqlite3.html def __init__(self, base): self.base = "" def connexion(self): self.con = .sqlite3.connect(self.base) self.cur = self.con.cursor() def deconnexion(self): self.con.close() def fetch(self, sql): self.connexion() self.cur.execute(sql) result = self.cur.fetchall() self.deconnexion() return result def execute(self, sql): self.connexion() self.cur.execute(sql) self.deconnexion() def chargersql(): pass def afficher_table(): pass def listedesrequetes(): pass def infotable(): pass def informations_base(): pass """ import sqlite3 def database_connexion(db_file): connexion = None try: connexion = sqlite3.connect(db_file) exept Error as e: return e return connexion conn = database_connexion("data/imb.db") def execute_sql(connexion,sql): cur = connexion.cursor() cur.execute(sql) raws = cur.fetchall() for row in rows: print(row) run_sql = execute_sql sql = "SELECT DISTINCT types FROM title_akas" run_sql(conn,sql) """
'''Use Queue for example Create two process in parent process, one write data to Queue, another one read data from Queue. But this time, not terminate the read process. What if I just leave the read process keep running? ''' from multiprocessing import Process, Queue import sys import os, time, random # write to queue process def write(q): for value in ['a', 'b', 'c']: print('Put %s to queue' % value) q.put(value) time.sleep(random.random()) # read to queue process def read(q): while True: value = q.get(True) print('Get %s from queue' % value) if __name__ == '__main__': # init a Queue instance q = Queue() # init the write process pw = Process(target=write, args=(q,)) # init the read process pr = Process(target=read, args=(q,)) # start the write process # the write process will terminate after all jobs done pw.start() # start read process # the read process will not terminate # because it's a infinity loop waiting for data from queue pr.start() # wait the write process done pw.join() # and then terminate the read process # what if I don't terminate the read process # pr.terminate() while True: i = input('To keep the parent process remaining.\n') if i == 'quit': pr.terminate() break # finally you will get just two python process of this file # one is the main parent process # anther one is the read process waiting to read data from queue
'''Difference between run() and start(): If you invoke run() directly, it's executed on the calling thread, just like any other method call. When you call Thread.start(), it starts a new thread, and calls the run() method of the runnable instance internally to execute it within that thread. ''' import time, threading, random def task(): current_thread_name = threading.currentThread().name print('Thread %s is running ...' % current_thread_name) for i in range(5): print('Thread %s is working on task %s' % (current_thread_name, i)) time.sleep(random.random()) print('Thread %s is done ...' % current_thread_name) if __name__ == '__main__': current_thread_name = threading.currentThread().name print('Thread %s is running ...' % current_thread_name) t = threading.Thread(target=task, name="jesse") r = threading.Thread(target=task, name="s3cret") # If you invoke run() dirctly, it's executing on the current thread, # which is 'MainThread' in this case, just like any other method call. #t.run() # here comes the method start() t.start() r.start() # running in the main thread, you cannot call join() # or it raise RuntimeError #t.join() r.join() print('Thread %s is done ...' % current_thread_name)
import os import urllib.request, urllib.parse, urllib.error print('Please enter a URL like http://data.pr4e.org/cover3.jpg') urlstr = input().strip() if len(urlstr) < 5: print('Using default url') urlstr = 'http://data.pr4e.org/cover3.jpg' img = urllib.request.urlopen(urlstr) # Get the last "word" of the url as filename words = urlstr.split('/') fname = words[-1] # Don't overwrite the file if os.path.exists(fname): if input('Replace ' + fname + ' (Y/n)?') != 'Y': print('Data not copied') exit() print('Replacing', fname) fhand = open(fname, 'wb') size = 0 while True: info = img.read(100000) if len(info) < 1: break size = size + len(info) fhand.write(info) #print(size, 'characters copied to', fname) # size is the number of characters downloaded # one character is 1 Byte (8 bit) already # transfer it to KB size = size/1024 print('%.2f KB copied to' % size, fname) fhand.close()
# Search for lines that start with 'F', followed by # any 2 characters, followed by 'm:' import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() # call re.search(regular_expression, from_which_sentence) # ^ stands for re starts, . stands for any character except \n, \r if re.search('^F..m:', line): print(line)
stuff = list() stuff.append('python') stuff.append('chuck') # this sort do some magic things for the stuff list stuff.sort() #print(stuff) # all the three sentence does exactly the same thing print (stuff[0]) # this will get the sorted `chunck` print (stuff.__getitem__(0)) print (list.__getitem__(stuff,0))
'''read data from json file ''' import json class student(): def __init__(self, name='default', score=0): self.name = name self.score = score def speak(self): print('My name is %s and my score is %d' % (self.name, self.score)) filename = 'students.json' with open(filename, 'r') as f: content = f.read() students_json = json.loads(content) students_list = [] for each in students_json: name = each['name'] score = each['score'] students_list.append(student(name, score)) for each in students_list: each.speak()
# with open as f # f.readline() with open('foo', 'r') as f: while True: r = f.readline() if len(r) < 1: break print(r, end='')
'''When call con.notify() the thread will just continue the last wait() line. ''' from threading import Condition, Thread con = Condition() count = 0 class wait_notify(Thread): def run(self): global count while True: if con.acquire(): print(self.name, 'acquired the lock') if count < 50: print(self.name, 'is going to con.wait()') con.wait() print('I want to wait again!') print(con) con.wait() print('Again I am wake up!') if __name__ == '__main__': w = wait_notify() w.start()
def compute_exponent_base_two(exp): return 2 ** exp def int_to_string(integer): return str(integer) def main(exp): exponent = compute_exponent_base_two(exp) string_int = int_to_string(exponent) result = 0 for i in string_int: result += int(i) return result if __name__ == "__main__": print(main(1000))
# make a while loop, printing out numbers user inputs for how many times. num = (int(input("Enter a number to start from: "))) MAX = (int(input("Enter ending number: "))) while (num <= MAX): print (num) num += 1
#imports #================================================================================================== import time from time import sleep import sys #defines #================================================================================================== def slowtype(text): for char in text: # this is to type out the characters in the game slowly, this is because the function is called slowtype sleep(0.045) sys.stdout.write(char) def fasttype(text): # this is t type out the characters in thr game faster, the function is called fasttype for char in text: sleep(0.005) sys.stdout.write(char) def _help(): print("test for help") #this is all the commands I want the player (you) to know def _map(): print("test for map") # a map of the region you play in, can be used to see the lay of the land, there are multiple maps for the smaller regions. def fasttravel(): slowtype("where do you want to go?\n") #the movement feature of the game, you can travel to some of the locations in the game after reaching a certain level. print("1") print("2") print("3") x = input ("> ") if x == "1": slowtype("you caught the train to 1") #this is the code for going to the first major location elif x == "2": slowtype("you caught the train to 2") # this is the code for fast travelling to the second location elif x == "3": slowtype("you caught the train to 3") # for travelling to the third major area def _gamelogo(): slowtype(" G E N E R I C G A M E T I T L E\n\n") # this is the game logo, I thought it looked cool so i used it. sleep(1) print(" |\ /)") # I was looking for a logo that was similar to a medieval styled fighting game. print(" /\_\\__ (_//") print(" | `>\-` _._ //`)") # then I came across this ascii art and thought it matched my criteria so i used it. print(" \ /` \\ _.-`:::`-._ //") print(" ` \|` ::: `|") # The creator of the art is Joan Stark, so thansk to them for this amazing ascii art. print(" | ::: |") print(" |.....:::.....|") print(" |:::::::::::::|") print(" | ::: |") print(" \ ::: /") print(" \ ::: /") print(" `-. ::: .-'") print(" //`:::`\\") print(" // ' \\") print(" |/ \\") sleep(1) def breaker(): fasttype("\n\n=================================================================================") #this is used to break up text to make the game easier on the eyes def immortal(): if _charselect =="dave": _damage = "0" def _charface(name): if name=="DAVE": print(" T H I S I S D A V E") print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") # this is my custom ascii art for thr character dave print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄.") print("⠄⠄⠄⠄⠄⠄⠄⠄⣀⣀⣤⣤⣀⣀⡤⠴⠒⠒⠶⣤⠖⠛⠛⠛⠳⠶⠚⠛⠛⠛⠲⣤⠄⠄⠄⠄⠄⠄⠄⠄") # please don't make fun of dave he is sensitive to insults AND constructive criticism print("⠄⠄⠄⠄⠄⠄⡴⠋⠉⠄⠄⠄⠄⠉⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⠉⠓⣦⠄⠄⠄⠄⠄") print("⠄⠄⢀⡴⠖⠛⠇⠄⠄⠄⠄⠄⠄⠄⠄⣀⣀⣤⠤⠤⠤⠤⠤⢤⣄⣀⣀⠄⠄⠄⠄⠄⠄⡴⠿⡄⠄⠄⠄⠄") # no really don't make fun of him D: print("⠄⠄⠘⠦⣤⣀⡀⠄⠄⠄⢀⣠⠴⠚⠋⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠉⠙⠲⢦⣄⠄⠄⠄⣠⠇⠄⠄⠄.") print("⠄⠄⠄⢸⣅⠄⠄⠄⣠⠶⠋⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣸⠟⢶⡋⠁⠄⠄⠄⠄⠄") #you asked for this... karen... A GREAT GAME (what else did you think I was implying... smh) print("⠄⠄⠄⠄⠈⠉⣻⢿⣥⣄⣀⣀⣀⣀⣴⣄⡀⠄⠄⠄⠄⠄⢀⣠⡜⠲⠶⠶⠒⠛⠁⠄⠄⠘⢷⡄⠄⠄⠄⠄") print("⠄⠄⠄⠄⢀⣴⣣⠿⣥⣤⡬⠿⠉⠄⠄⠈⠉⠙⠓⠒⠒⠛⠉⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠹⣆⠄⠄⠄") print("⠄⠄⠄⠄⡼⠛⠛⠉⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣀⣀⣀⠄⠄⠄⠄⠄⠘⣇⠄⠄") print("⠄⠄⠄⣸⠃⠄⠄⠄⠄⠄⠄⢀⡴⠛⠛⠳⣤⠄⠄⠄⠄⠄⠄⠄⠄⠄⡼⠋⠄⠄⠉⢳⠄⠄⠄⠄⠄⢸⡄⠄") # Dave was born in the year 1405 and is immortal but you wouldn't of picked dave because you saw print("⠄⠄⠄⡿⠄⠄⠄⠄⠄⠄⠄⢸⡀⠄⠄⠄⣸⠇⠄⠄⠄⠄⠄⠄⠄⠄⢳⣄⠄⠄⣀⡼⠄⠄⠄⠄⠄⠈⣇⠄") print("⠄⠄⠄⡇⠄⠄⠄⠄⠄⠄⠄⠄⠙⠶⠶⠞⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⠉⠉⠁⠄⠄⠄⠄⠄⠄⠄⣿⠄") # Karen as a playable character, you fool, you should've checked the notes before picking your print("⠄⠄⠄⣿⠄⠄⠄⠄⣀⣀⣤⠶⠒⠒⠒⠲⠶⠛⠛⠛⠒⠛⠛⠛⠛⠛⠛⠛⠛⠲⢶⣤⡀⠄⠄⠄⠄⢠⡏⠄") print("⠄⠄⠄⠸⡆⠄⠄⠈⠻⠿⢧⣤⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣤⣀⣀⣽⠿⠶⠖⠚⠃⠄⠄⠄⠄⣸⠁⠄") # character. You will suffer damage, dave will not, dave is a god, your character is not. print("⠄⠄⠄⠄⢻⡄⠄⠄⠄⠘⠛⠛⠛⠋⠉⠄⠄⠄⠉⠉⠉⠉⠉⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣰⠇⠄⠄") print("⠄⠄⠄⠄⠄⠹⣆⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⡴⠋⠄⠄⠄") # of course, no one knows dave is immortal, only you can find the hidden command to make dave print("⠄⠄⠄⠄⠄⠄⠈⠷⣀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣠⠞⠁⠄⠄⠄⠄") print("⠄⠄⠄⠄⠄⠄⠄⠄⠉⠳⣤⣀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣠⡴⠛⠁⠄⠄⠄⠄⠄⠄") #immortal print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠉⠓⠶⣤⣄⣀⠄⠄⠄⠄⠄⠄⠄⢀⣀⣠⡤⠖⠋⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄") print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⠉⠉⠛⠛⠛⠋⠉⠉⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") elif name=="KAREN": print(" T H I S I S K A R E N") print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") # this is karen they enjoy making string ( its the midde ages she desn't know code) print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") print("⠄⠄⠄⠄⠄⢀⣀⣀⣠⣤⣄⣀⣠⣤⣤⣤⣤⣤⣤⣴⣖⣒⠲⢦⠤⠶⠒⠒⠲⠦⢤⣀⡀⠄⠄⠄⠄⠄⠄⠄") # karen was born on 1400 being the oldest character, since the year you play in is print("⠄⣀⣠⣶⣶⣍⠉⠄⠄⣀⡤⠞⠛⠉⠉⠁⠄⠄⠄⠄⠉⠉⠙⠒⠦⣄⡀⠄⠄⠄⠄⣉⣯⣷⡄⠄⠄⠄⠄⠄") print("⢸⢿⣿⣿⡇⣿⢀⣴⠚⠉⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⠙⢶⣤⣤⣶⢻⢛⣻⡿⠄⠄⠄⠄⠄") # 1430. print("⣸⠈⠷⢤⣤⣽⣯⠁⠄⠄⠄⠄⠄⣀⠄⠄⠄⠄⠄⠄⠄⠄⠄⣠⣀⣀⣀⣀⣹⣾⠋⠉⠉⠉⡇⠄⠄⠄⠄⠄") print("⣷⠄⠄⣹⠋⢩⡏⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢀⣾⠈⣷⠄⠄⣿⠄⠄⠄⠄⠄") #this ascii art was not inpired by you ( i swear) you also probably picked this character print("⠇⠄⢰⡏⠄⠸⡇⡰⠖⠋⠉⠛⠶⡄⠄⠄⢀⡆⠄⠄⠄⢀⡴⠶⠶⠶⢦⡀⢸⡇⠄⠈⡇⠄⣿⠄⠄⠄⠄⠄") print("⠄⠄⢸⡇⢀⠄⡟⢧⣀⣀⣀⣀⣤⠇⠄⠄⡿⠄⠄⠄⠄⣇⡀⠄⠄⠄⢀⡿⢸⡇⠄⠄⡇⣄⣿⠄⠄⠄⠄⠄") # because it shares the same name as you, you also probably had a rather big panic attack from seeing print("⡇⠄⢸⡇⠘⣆⡇⠄⠉⠉⠉⠉⠄⠄⠄⣸⠁⠄⠄⠄⠄⠈⠑⠒⠒⠒⠋⠁⢈⡧⠄⠄⡇⢹⡿⠄⠄⠄⠄⠄") print("⡇⠄⠘⡇⠄⣿⠁⠄⠄⠄⠄⠄⠄⠄⠐⠋⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢸⡇⠄⢠⡇⢸⠃⠄⠄⠄⠄⠄") # my bad ascii art, but it is the best I can do. print("⡇⠄⠄⢹⡆⡿⠄⠄⠄⠄⠄⠄⠄⠄⢀⣰⠶⣄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⣇⠄⡾⢀⢸⠄⠄⠄⠄⠄⠄") print("⢧⠄⠄⢰⣿⣇⠄⠄⠄⠄⠄⠄⠄⢴⡛⠁⠄⠈⢳⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢸⡾⡅⢸⠟⠄⠄⠄⠄⠄⠄") # Karen Doesn't do much in her spare time, but since you chose karen as your adventurer, she is now print("⢸⢀⡇⢸⡟⠙⣆⠄⠄⠄⠄⠄⠄⠈⠑⢦⣠⡖⠋⠄⠄⠄⠄⠄⠄⠄⠄⠄⣠⣾⣾⣧⡟⠄⠄⠄⠄⠄⠄⠄") print("⢸⣿⢧⡼⠁⠄⠈⠱⣤⡀⠄⠄⠄⠄⠄⠄⠉⠄⠄⠄⠄⠄⠄⠄⠄⢀⣠⠾⠁⢸⣿⠉⠁⠄⠄⠄⠄⠄⠄⠄") # thrown into battle, of course it doesn't matter that she hasn't ever battled before only you can print("⣼⡿⠄⠄⠄⠄⠄⠄⠄⠙⠳⠤⣄⣀⡀⠄⠄⠄⠄⠄⠄⣀⣀⡤⠞⠋⠁⠄⠄⣼⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄") print("⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠉⠉⠛⠒⠒⠒⠛⠉⠉⠁⠄⠄⠄⠄⠄⠄⠉⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") # decide if she is bad at fighting or not. print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") # Overall karen is a pretty chill character. print("⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄") #actual game code #==================================================================================================== _gamelogo() fasttype("\n\n================================= INTRO ========================================") slowtype("\n\nwelcome, pick a character...\n\n Dave\n Karen\n\n") while True: _charselect = input("> ").upper() # input for selection of character _charface(_charselect) if _charselect == "KAREN": slowtype("epic\n") elif _charselect == "HELP": print(" select a character by typing out their name, must be the full name.") elif _charselect =="DAVE": slowtype("dave hides a secret... find it\n\n")
'''Unit4 Lesson4: K-Nearest Neighbors''' import pandas as pd import matplotlib.pyplot as plt import numpy as np import random df = pd.read_csv('iris/iris.data.csv') df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'iris'] features = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid'] # print(df.info()) # print(df['iris'].unique()) # print(df.iris.value_counts()) def plot_scatter(): fig = plt.figure('Iris') (alpha, size) = (.7, 50) plt.scatter(df[df.iris=='Iris-setosa'].sepal_len, df[df.iris=='Iris-setosa'].sepal_wid, s=size, c='r', alpha=alpha, label='Setosa') plt.scatter(df[df.iris=='Iris-versicolor'].sepal_len, df[df.iris=='Iris-versicolor'].sepal_wid, s=size, c='b', alpha=alpha, label='Versicolor') plt.scatter(df[df.iris=='Iris-virginica'].sepal_len, df[df.iris=='Iris-virginica'].sepal_wid, s=size, c='g', alpha=alpha, label='Virginica') plt.xlabel('Sepal length (cm)') plt.ylabel('Sepal width (cm)') plt.legend(loc='upper right') plt.show() # plot_scatter() def k_nn(point, k=3, df_pred=0, df_classes=0): '''get the k-closest neighbors from the point and outputs the majority class df_pred = predictor(s); df_classes = classes (len(df_pred) = len(df_classes)) point is a dictionary whose keys are the same as column names of df_pred''' temp = df_pred.copy() for feat in df_pred.columns: temp[feat] = (temp[feat] - point[feat])**2 distance = np.sqrt(temp.sum(axis=1)) distance.sort_values(inplace=True, ascending=True) return df_classes.iloc[distance[:k].index].value_counts().index[0] # Note: value_counts counts the number of occurence of each value in df_classes and sort them in descending order test_idx = np.random.uniform(0, 1, len(df)) <= 0.3 df_train = df[test_idx==False] df_train.index = range(len(df_train)) df_test = df[test_idx==True] df_test.index = range(len(df_test)) # df_test['prediction'] = df_test[features].apply(k_nn, axis=1, k=7, df_pred=df_train[features], df_classes=df_train.iris) # df_test['good_prediction'] = df_test.iris == df_test.prediction # accuracy = float(len(df_test[df_test.good_prediction==True])) / len(df_test) def test_accuracy_with_k(): accuracy = [] k = [] for i in xrange(1, 11): k.append(i) df_test['prediction'] = df_test[features].apply(k_nn, axis=1, k=i, df_pred=df_train[features], df_classes=df_train.iris) df_test['good_prediction'] = df_test.iris == df_test.prediction accuracy.append(float(len(df_test[df_test.good_prediction==True])) / len(df_test)) fig = plt.figure('K-NN accuracy as a function of k') plt.plot(k, accuracy) plt.xlabel('k') plt.ylabel('accuracy') plt.xlim([min(k)-1, max(k)]) plt.ylim([0,1]) plt.show() test_accuracy_with_k()
#!/usr/bin/env python3 # coding: UTF-8 p = 'パトカー' t = 'タクシー' result = '' for (a, b) in zip(p, t): result += a + b print (result)
class MysteryString(str): def __new__(cls, word, guesses, delimiter='-'): result = [ (letter if (letter in guesses or word in guesses) else delimiter) for index, letter in enumerate(word)] match = ''.join(result) obj = str.__new__(cls, match) obj.word = word obj.guesses = guesses return obj @property def guessed_words(self): return {guess for guess in self.guesses if len(guess) == len(self.word)} @property def missed_words(self): return {guess for guess in self.guessed_words if guess != self.word} @property def guessed_letters(self): return self.guesses - self.guessed_words @property def known_letters(self): return {letter for letter in self.guessed_letters if letter in self.word} @property def missed_letters(self): return self.guessed_letters - self.known_letters
age = input("Enter your age: ") new_age = int(age) + 50 # int() converts to integer # str() converts to string print(new_age)
""" name: puzzle_generator.py language: python 3.7 description: generates a word search puzzle text from a given list of words author: awallien """ import random import sys EMPTY_FILL = " " class WordSearchPuzzle: """ The class that constructs the puzzle board and word list """ def __init__(self, wordlist): """ Constructor :param wordlist: list of words to insert into the puzzle """ self.layword = [self.__horizontal, self.__vertical, self.__diagonal] self.wordlist = wordlist self.max_len = 0 self.board = None self.__make_board() def __make_board(self): """ makes the word search puzzle board :return: """ def empty_board(): """ Create an empty, blank puzzle board :return: the board """ return [[EMPTY_FILL for i in range(self.max_len)] for j in range(self.max_len)] def fill_board(wordlist, stack): """ private function to DFS backtrack until we get a valid board with all words on it :return: the final config board if all words can fit on the board, None otherwise """ if not wordlist: return stack[-1] # for each word # get a layout: vertical, horizontal, or diagonal # get an x and y coordinate for word in wordlist: for layout in random.sample(range(len(self.layword)), len(self.layword)): for i in random.sample(range(self.max_len), self.max_len): for j in random.sample(range(self.max_len), self.max_len): new_config = self.layword[layout](word, stack[-1], i, j) if new_config: stack.append(new_config) if fill_board(wordlist[1:], stack): return stack[-1] return None # get dimension size of longest word and make board self.max_len = len(max(self.wordlist, key=len))*2 stack = list() stack.append(empty_board()) self.board = fill_board(self.wordlist, stack) # a board cannot be made for this word of list if not self.board: print("Unable to make board with given list", file=sys.stderr) exit(1) self.__random_filler() def __vertical(self, word, board, x, y): """ Place the word vertically on the board :param word: the word to put on board :param board: the instance of board :param x: the x coordinate :param y: the y coordinate :return: the new board if the word can fit; otherwise, None """ # print("vertical") length = len(word) if y + length > self.max_len: return None # check the slots on the board starting at board[x,y] # is there a letter already occupying a spot for k in range(length): if board[x][y + k] != EMPTY_FILL and board[x][y + k] != word[k]: return None # should the word be reversed? if random.randint(0, 1): word = word[::-1] # lay the word down for k in range(length): board[x][y + k] = word[k] return board def __horizontal(self, word, board, x, y): """ Put the word horizontally on the board :param word: the word to put on board :param board: the instance of board :param x: the x coordinate :param y: the y coordinate :return: the new board if word can fit; otherwise, None """ # print("horizontal") length = len(word) if x + length > self.max_len: return None for k in range(length): if board[x + k][y] != EMPTY_FILL and board[x + k][y] != word[k]: return None if random.randint(0, 1): word = word[::-1] for k in range(length): board[x + k][y] = word[k] return board def __diagonal(self, word, board, x, y): """ Put the word diagonally on the board :param word: the word :param board: the instance of board :param x: the x coordinate to insert word :param y: the y coordinate to insert word :return: the new board if the words fits; otherwise, None """ # print("diagonal") length = len(word) if x + length > self.max_len or y + length > self.max_len: return None for k in range(length): if board[x + k][y + k] != EMPTY_FILL and board[x + k][y + k] != word[k]: return None word = word[::-1] if random.randint(0, 1) else word for k in range(length): board[x + k][y + k] = word[k] return board def __random_filler(self): """ Fill the empty spots on the puzzle board with random letters :return: None """ for row in range(self.max_len): for col in range(self.max_len): if self.board[row][col] == EMPTY_FILL: self.board[row][col] = chr(random.randrange(ord('a'), ord('z'))) def output(self,fname=""): """ Writes the puzzle and list of words to a text file :return: None """ # will use later, right now, testing purposes # hashcode = hash(self)%(10**6) # out = open("puzzle"+str(hashcode), "w") out = "" if not fname: hashcode = hash(self)%(10**6) if hashcode < 0: hashcode *= -1 out = open("puzzle"+str(hashcode), "w") else: out = open(fname, "w") for row in range(self.max_len): for col in range(self.max_len): if col == self.max_len - 1: out.write(self.board[row][col] + "\n") else: out.write(self.board[row][col] + " ") out.write("\n") for idx in range(len(self.wordlist)): if idx == len(self.wordlist) - 1: out.write(self.wordlist[idx]) else: out.write(self.wordlist[idx] + "\n") if __name__ == '__main__': """ As a standalone program, used to make a text file that contains the puzzle board and the list of words :return: None """ # error check for number of arguments passed to command line if len(sys.argv) != 2: print("Usage: python3.7 puzzle_generator.py word_list", file=sys.stderr) else: # error check for valid file file = None try: file = open(sys.argv[1], "r") wordlist = file.read().split("\n") # check for empty file if not wordlist[0]: print("Reading empty file", file=sys.stderr) else: WordSearchPuzzle(wordlist).output("test") except IOError: print("Cannot open file:", sys.argv[1], file=sys.stderr) exit()
"""grid class""" import pygame from utils.tiles import Tile class Grid(): """class representing the gird of tiles""" tiles = [] start_node = None finish_node = None def __init__(self, number_of_nodes, block_size, screen): self._initialize_empty_list(number_of_nodes, block_size, screen) self.number_of_nodes = number_of_nodes def _initialize_empty_list(self, number_of_nodes, block_size, screen): """a helper method; returns an array of (size number of nodes)x(size number of nodes) of normal nodes""" self.tiles = [] for i in range(number_of_nodes): row = [] for j in range(number_of_nodes): block = Tile((j*(block_size+2)+1,i*(block_size+2)+1), (block_size, block_size), screen) row.append(block) pygame.draw.rect(screen, Tile.TILE_COLOUR, block) self.tiles.append(row) def drag_drawing(self, mouse_pos, previous): """handles drawing of tiles with mouse drag previous argument is where mouse has been before the current tile or null if just pressing mouse""" for row in self.tiles: # \ for current in row: # > this gets the element the mouse is on -> current element if current.collidepoint(mouse_pos) and current != previous: # / # case1: drawing a wall if ( ( previous is None or previous.state == "wall" ) and ( current.state == "normal" or current.state == "path" or current.state == "search" ) ): current.makeWall() return current # case2: ereasing walls elif ( ( ( previous is None or previous.state == "normal" or previous.state == "path" or previous.state == "search" ) and current.state == "wall" ) or (previous is not None and previous.state == "normal" and (current.state == "path" or current.state == "search")) ): current.makeNormal() return current # case3: moving the start and finish tiles elif (previous is None and (current.state == "start" or current.state == "finish")): return current elif (current.state == "path" or current.state == "search" or current.state == "normal"): if(previous.state == "start"): current.makeStart() self.set_start(current) previous.makeNormal() elif(previous.state == "finish"): current.makeFinish() self.set_finish(current) previous.makeNormal() return current # in all other cases "skip" else: return previous return previous def index_2d(self, element): for i, x in enumerate(self.tiles): if element in x: return (i, x.index(element)) return(None) def cleanup(self, v = 0): """cleans the grid of paths (and walls if v is anthing other than 0)""" for row in self.tiles: for element in row: if v != 0: if element.state == "wall": element.makeNormal() if element.state == "path" or element.state == "search": element.makeNormal() def set_start(self, node): if isinstance(node, Tile): self.start_node = node elif isinstance(node, tuple): self.start_node = self.tiles[node[0]][node[1]].makeStart() def set_finish(self, node): if isinstance(node, Tile): self.finish_node = node elif isinstance(node, tuple): self.finish_node = self.tiles[node[0]][node[1]].makeFinish() def draw_path(self, path): for element in path: self.tiles[element[0]][element[1]].makePath() def cellular(self): cells = [] for row in self.tiles: new_row = [] for cell in row: if cell.state == "wall": new_row.append(0) else: new_row.append(1) cells.append(new_row) return cells
ff=int(input()) if ff>1: for i in range(2,ff): if(ff%i==0): print("no") break; else: print("yes") else: print("no")
yy=int(input()) if(yy%4==0 or yy%400==0 and yy%100!=0): print("yes") else: print("no")
''' You are going to write a program that tests the compatibility between two people. To work out the love score between two people: Take both people's names and check for the number of times the letters in the word TRUE occurs. Then check for the number of times the letters in the word LOVE occurs. Then combine these numbers to make a 2 digit number. For Love Scores **less than 10** or **greater than 90**, the message should be: `"Your score is **x**, you go together like coke and mentos."` For Love Scores **between 40** and **50**, the message should be: `"Your score is **y**, you are alright together."` Otherwise, the message will just be their score. e.g.: `"Your score is **z**."` e.g. `name1 = "Angela Yu"` `name2 = "Jack Bauer"` T occurs 0 times R occurs 1 time U occurs 2 times E occurs 2 times Total = 5 L occurs 1 time O occurs 0 times V occurs 0 times E occurs 2 times Total = 3 Love Score = 53 Print: "Your score is 53." ''' print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") name=name1+name2.lower() true_count=sum(name.count(x) for x in ("t","r","u","e")) love_count=sum(name.count(x) for x in ("l","o","v","e")) love_score = int(str(true_count)+str(love_count)) if love_score < 10 or love_score>90: print(f"Your score is {love_score}, you go together like coke and mentos.") elif love_score > 40 and love_score<50: print(f"Your score is {love_score}, you are alright together.") else: print(f"You score is {love_score}")
# Filter Even numbers using list comprehension if __name__ == '__main__': numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] even_list = [num for num in numbers if num % 2 == 0] print(even_list) # OUTPUT :- [2, 8, 34]
class MoneyMachine: def __init__(self): self.total_money = 0 def make_payment(self, cost): print("Please enter Money.") quarters = float(input("How many Quarters:")) nickle = float(input("How many nickles:")) dimes = float(input("How many dimes:")) pennies = float(input("How many pennies:")) self.total_money = 0.25*quarters + 0.1*dimes + 0.05*nickle + 0.01*pennies if self.total_money >= cost: print(f"Your change is :- ${'{0:.2f}'.format(self.total_money-cost)}") return True else: return False
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, } def check_resources(coffee): if coffee not in "espresso": if MENU[coffee]["ingredients"]["milk"] > resources["milk"]: return False if MENU[coffee]["ingredients"]["water"] > resources["water"] and MENU[coffee]["ingredients"]["coffee"] > resources["coffee"]: return False else: return True def check_money(coffee): print("Please insert coins") quarters = float(input("How Many Quarters: ")) dimes = float(input("How Many Dimes: ")) nickles = float(input("How Many Nickles: ")) penny = float(input("How Many Pennies: ")) total_money = (0.25*quarters) + (0.1*dimes) + (0.05*nickles) + (0.01*penny) if total_money > MENU[coffee]["cost"]: print(f"Your change is ${'{0:.2f}'.format(total_money - MENU[coffee]['cost'])}") return True if total_money == MENU[coffee]["cost"]: return True return False def recalculate_resource(coffee): if coffee not in "espresso": resources["milk"] -= MENU[coffee]["ingredients"]["milk"] resources["water"] -= MENU[coffee]["ingredients"]["water"] resources["coffee"] -= MENU[coffee]["ingredients"]["coffee"] def generate_report(): print(f"Water: {resources['water']}\nMilk: {resources['milk']}\nCoffee: {resources['coffee']}") machine_running = True while machine_running: choice = input("What would you like? (espresso/latte/cappuccino): ").lower() if choice == "off": print("Coffee Machine is turned off") machine_running = False elif choice == "report": generate_report() elif choice in ["espresso", "latte", "cappuccino"]: if not check_resources(choice): print("Not Sufficient resources are available") machine_running = False else: if not check_money(choice): print("Not Sufficient money") machine_running = False else: print(f"Your {choice} is served , please Enjoy") recalculate_resource(choice) else: print("Invalid entry")
#issue was that type checking "int" was not there at the time of accepting input year = int(input("Which year do you want to check?")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year.") else: print("Not leap year.") else: print("Leap year.") else: print("Not leap year.")
n1= int(input('Digite um número: ')) resultado= n1 % 2 if resultado == 0: print('É par! ') else: print('É ímpar!!')
# Matrix Algebra import numpy # m * n = rows by columns # 1. matrix dimensions A = numpy.matrix([[1,2,3],[2,7,4]]) # 2 row by 3 columns B = numpy.matrix([[1,-1],[0,1]]) # 2 rows by 2 columns C = numpy.matrix([[5,-1],[9,1],[6,0]]) # 3 rows by 2 columns D = numpy.matrix([[3,-2,-1],[1,2,3]]) # 2 rows by 3 columns u = numpy.matrix([6,2,-3,5]) # 1 row by 4 columns v = numpy.matrix([3,4,-1,4]) # 1 row by 4 columns w = numpy.matrix([[1],[8],[0],[5]]) # 4 rows by 1 column #1: Matrix Dimensions # numpy.shape displays as (outerarraylength, innerarraylength), or rows/columns as I've coded them #1.1 print "1.1" print numpy.shape(A) #1.2 print "1.2" print numpy.shape(B) #1.3 print "1.3" print numpy.shape(C) #1.4 print "1.4" print numpy.shape(D) #1.5 print "1.5" print "below should probably display as (1,4) in these circumstances for rows, columns format:" print numpy.shape(u) #1.6 print "1.5" print "below should probably display as (1,4) in these circumstances for rows, columns format:" print numpy.shape(v) #1.7 print "1.7" print numpy.shape(w) # i may have coded w wrong, i can clearly see the column/row difference here but the code doesn't seem to # #2: Vector Operations alpha = 6 #2.1: u + v # addition print "2.1" print numpy.add(u,v) #2.2: u - v # subtraction print "2.2" print numpy.subtract(u,v) #2.3 alpha * u #scaling print "2.3" print numpy.multiply(alpha,u) #2.4 u * v #dotproduct print "2.4" # we use multiply here due to vector multiplication being slightly different than matrix multiplication per the linear algebra handout print numpy.multiply(u,v) #2.5 ||u|| # norm(length) print "2.5" print numpy.linalg.norm(u) #3: Matrix Operations # use numpy's .dot for matrices multiplying matrixes, for vector by vector or scalar by vector we can use .multiply # 3.1: A+C print "3.1" print "not defined, operation fails" #print numpy.add(A,C) # 3.2: A- C transpose print "3.2" CT = numpy.transpose(C) print numpy.subtract(A,CT) # 3.3: C transpose + 3 * D three_D = numpy.dot(3,D) print "3.3" print numpy.add(CT,three_D) # 3.4: B*A print "3.4" print numpy.dot(B,A) # 3.5: B * Atranspose AT = numpy.transpose(A) print "3.5" print "not defined" #print numpy.dot(B,AT) # fails print "Optional problems:" # 3.6: B*C print "3.6" print "not defined" #print numpy.dot(B,C) # fails # 3.7: C*B print "3.7" print numpy.dot(C,B) # # 3.8: B^4 # print "3.8" # # 3.9 A * A transpose # print "3.9" # # 3.10 D transpose * D # print "3.10" # def matrix_add(m1,m2): # result[a][b] == m1[a][b]+m2[a][b] # return "no" # result = [] # result[0][0]=A[0][0]+B[0][0] # print result # def check(m1,m2): # result = [] # for i in range(0,len(m1)): # if len(m1[i]) > 1: # for j in range(0,len(m1[i]): # result[i][j] = m1[i][j] + m2[i][j] # return result # print check(A,D) # # note this only works for MATRICES WITH 2x2 or greater sizes # def matrix_add(m1, m2): # # check to make sure matrices have same number of rows # if len(m1) != len(m2): # print 'matrices must be of the same dimensions to add them' # return False # # check to make sure matrices have same number of columns # # this checks literally every sub-item, we could probably do a simple 0 vs 0 check # for i in range(0,len(m1)): # if len(list(m1[i])) != len(list(m2[i])): # print 'matrices must be of the same dimensions to add them' # return False # result = [] # #iterate through rows # for a in range(len(m1)): # #iterate through columns # for b in range(len(m1[0])): # result[a][b] = m1[a][b] + m2[a][b] # return result
#string = "atgctaccatcattagctaccata" # validation def validate_nucleotide(string_new, state): for nucleotide in string_new: if nucleotide == "G" or nucleotide == "C" or nucleotide == "T" or nucleotide == "A": pass else: return ("bad") # nucleotidecounter def nucleotide_counter(string): dictionary = {"G": 0, "C": 0, "T": 0, "A": 0} state = "good" string_novel = (string.replace(" ", "")).upper() string_new = (((string_novel.replace("\n\r","")).replace("\r\n","")).replace("\r","")).replace("\n","") state = validate_nucleotide(string_new, state) if state == "good" or state == None: for nucleotide in string_new: if nucleotide == "G" or nucleotide == "C" or nucleotide == "A" or nucleotide == "T": dictionary[nucleotide] = dictionary[nucleotide] + 1 return(dictionary, string_new) else: return("Sorry Bad Sequence", string_new) # Test # nucleotide_counter(string)
""" CTEC 121 <your name> <Grant Parkinson> <assignment/lab description """ """ IPO template Input(s): list/description Process: description of what function does Output: return value and description """ def main(): ''' # definite loop example for i in range(0, 11, 2): print(i) print() # same behavior but codes as indefinite or while loop count = 0 while(count < 11): print(count) #count = count + 2 count += 2 print() ''' print(True and False) print(True and True) print(True and False or False) print(False or False or True) main()
#!/usr/bin/env python import string from collections import defaultdict from Queue import PriorityQueue from math import radians, cos, sin, asin, sqrt import sys # All the heuristic logics, and ways of handling the data inconsistency explained below. # Assuming the end_city given as input will have lat, lon values as mentioned in piazza.. otherwise this might fail ''' Logic used for A-Star: 1) Heuristic for Distance: -- Calculated heuristic as - Since the displacement is always <= to the road distance, calculated displacement between the current city to goal city using the latitudes, longitudes given in the city-gps.txt file and used it as heuristic value. -- Used haversine formula to calculate the displacement -- Mentioned the reference in the 'calDisplacement' function. Handling the data inconsistency: -- Problem with calculating the displacements was that the given data doesn't have lat, lon values of all cities. -- In that case, I considered the city which is nearest to it by road distance by iterating through it's succesors/predecessors. -- Again, one more problem here. If none of it's nearby cities have the lat, lon data; then I considered the lat, lon average of that state in which city is present and calculated distance using that. -- Yet again, faced few problems because of invalid state names like Jct_34&56. There are cases where the none of the cities in a particular state are mentioned in the city-gps.txt file. In that case, average can't be calculated. -- So, to tackle the above problem, while iterating, i'm storing the previous city in the route and using it's lat, lon values. 2) Heuristic for Time: -- Calculated heuristic as - Distance(heuristic value as caluculated above) / Average speed of all routes in the given data. -- Average speeds of all routes given in the data seemed to be the best option as the denominator, as we are neither aware of the upcoming route, nor can rely on the route followed till now, as the speeds keeps changing based on states and highways. Handling the data inconsistency: -- Problem here was that few routes were missing speed values or have the speed values as '0'. -- So to handle this problem, i've replaced 0s and missing speeds with average speed in that particular highway, rather than overall avergae. If that highway does not occur in any other route, then using the over all avergae speed instead. 3) Heuristic for Segments: -- Calculated the heuristic as - Distance(heuristic value as caluculated above) / Average distance of all routes -- Intuition behind this is that, by diving heuristic distance value with average distance, we get the estimated number of segments. -- Although the heuristics seems to be good enough and data inconsisties handled properly, but still was not able to get optimal answers as compared to UCS. -- After thorough investigation, I have identified that the latitudes, longitudes data given in the file itself are wrong or the road distance values in the road-segments.txt file are wrong. They give the displacement values higher than the road distances, thus making the heuristic inadmissible and not able to produce optimal results. ''' def solve_ids(start_city, end_city, algo, cost): for i in range(10000): fringe = [] distance_so_far = 0 time_so_far = 0 route_so_far = start_city fringe.append((start_city, route_so_far, 0, distance_so_far, time_so_far)) visited = defaultdict(list) while len(fringe): if fringe[len(fringe) - 1][2] <= i: (state, route_so_far, depth_so_far, distance_so_far, time_so_far) = fringe.pop() if state == end_city: if cost == "segments": return "yes " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far else: return "no " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far if not visited[state]: visited[state] = True if depth_so_far + 1 <= i: for city in succOfCity[state]: fringe.append((city[0], route_so_far + " " + city[0], depth_so_far + 1, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2]) )) return False def solve_dfs(start_city, end_city, algo, cost): fringe = [] route_so_far = start_city distance_so_far = 0 time_so_far = 0 fringe.append((start_city, route_so_far, distance_so_far, time_so_far)) visited = defaultdict(list) while len(fringe): (state, route_so_far, distance_so_far, time_so_far) = fringe.pop() if state == end_city: return "no " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far if not visited[state]: visited[state] = True for city in succOfCity[state]: fringe.append((city[0], route_so_far + " " + city[0], distance_so_far + city[1], time_so_far + float(city[1])/float(city[2]))) return False def solve_bfs(start_city, end_city, algo, cost): fringe = [] route_so_far = start_city distance_so_far = 0 time_so_far = 0 fringe.append((start_city, route_so_far, distance_so_far, time_so_far)) visited = defaultdict(list) while len(fringe): (state, route_so_far, distance_so_far, time_so_far) = fringe.pop(0) if state == end_city: if cost == "segments": return "yes " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far else: return "no " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far if not visited[state]: visited[state] = True for city in succOfCity[state]: fringe.append((city[0], route_so_far + " " + city[0], distance_so_far + city[1], time_so_far + float(city[1])/float(city[2]))) return False def solve_ucs(start_city, end_city, algo, cost): fringe = PriorityQueue() route_so_far = start_city cost_so_far = 0 distance_so_far = 0 time_so_far = 0 fringe.put((0, (start_city, route_so_far, cost_so_far, distance_so_far, time_so_far))) visited = defaultdict(list) visited[start_city] = True while fringe.qsize() > 0: (state, route_so_far, cost_so_far, distance_so_far, time_so_far) = fringe.get()[1] visited[state] = True if state == end_city: return "yes " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far else: for city in succOfCity[state]: if not visited[city[0]]: if cost == "distance": current_cost = city[1] fringe.put((current_cost + cost_so_far, (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) elif cost == "time": current_cost = float(city[1]) / float(city[2]) fringe.put((current_cost + cost_so_far, (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) elif cost == "segments": current_cost = 1 fringe.put((current_cost + cost_so_far, (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) return False def calcDisplacement(fromCity, toCity): """ Haversine method to Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # Referred from the below link. # https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points global prev_state if latlon[fromCity]: lon1 = latlon[fromCity][0] lat1 = latlon[fromCity][1] else: #If lat, lon fof cities missing if fromCity == "" or len(citiesInState[fromCity.split(",")[1]]) == 0: # If nearest city with lon, lat found in it's succesors and unable to calc state average because of invalid name or has no cities in the state with lat, lon data lon1 = LonsofState[prev_state] / len(citiesInState[prev_state]) lat1 = LatsofState[prev_state] / len(citiesInState[prev_state]) else: # If nearest city with lon, lat found in it's succesors, calclate state avg lon1 = LonsofState[fromCity.split(",")[1]] / len(citiesInState[fromCity.split(",")[1]]) lat1 = LatsofState[fromCity.split(",")[1]] / len(citiesInState[fromCity.split(",")[1]]) if latlon[toCity]: lon2 = latlon[toCity][0] lat2 = latlon[toCity][1] else: lon2 = LonsofState[toCity.split(",")[1]] / len(citiesInState[toCity.split(",")[1]]) lat2 = LatsofState[toCity.split(",")[1]] / len(citiesInState[toCity.split(",")[1]]) lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) #global prev_state if fromCity != "": prev_state = fromCity.split(",")[1] # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) r = 3956 # Radius of earth in kilometers. Use 3956 for miles return c * r def findClosestCity(city): min = 10000 nearestCity = "" roadDist = 0 for nearbyCities in succOfCity[city]: if latlon[nearbyCities[0]]: roadDist = nearbyCities[1] if roadDist < min: min = roadDist nearestCity = nearbyCities[0] else: continue return nearestCity def heuristic_astar(city): if latlon[city] and latlon[end_city]: return calcDisplacement(city, end_city) elif latlon[city] and not latlon[end_city]: return calcDisplacement(city, findClosestCity(end_city)) elif not latlon[city] and latlon[end_city]: return calcDisplacement(findClosestCity(city), end_city) else: return calcDisplacement(findClosestCity(city), findClosestCity(end_city)) def solve_astar(start_city, end_city, algo, cost): fringe = PriorityQueue() route_so_far = start_city cost_so_far = 0 distance_so_far = 0 time_so_far = 0 fringe.put((0, (start_city, route_so_far, cost_so_far, distance_so_far, time_so_far))) visited = defaultdict(list) visited[start_city] = True while fringe.qsize() > 0: (state, route_so_far, cost_so_far, distance_so_far, time_so_far) = fringe.get()[1] visited[state] = True if state == end_city: return "yes " + str(distance_so_far) + " " + str(time_so_far) + " " + route_so_far else: for city in succOfCity[state]: if not visited[city[0]]: if cost == "distance": current_cost = city[1] fringe.put((current_cost + cost_so_far + heuristic_astar(city[0]), (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) elif cost == "time": current_cost = float(city[1]) / float(city[2]) fringe.put((current_cost + cost_so_far + float(heuristic_astar(city[0]))/float(avg_speed), (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) elif cost == "segments": current_cost = 1 fringe.put((current_cost + cost_so_far + heuristic_astar(city[0])/float(avg_dist), (city[0], route_so_far + " " + city[0], current_cost + cost_so_far, distance_so_far + city[1], time_so_far + float(city[1])/float(city[2])))) return False succOfCity = defaultdict(list) speedsofHighway = defaultdict(list) sumOfSpeeds = 0 numOfRoutes = 0 sumOfDist = 0 with open('road-segments.txt', 'r') as file: for line in file: if not len(line.split()) == 4 and int(line.split()[3]) != 0: succOfCity[line.split()[0]].append((line.split()[1], int(line.split()[2]), int(line.split()[3]), line.split()[4])) succOfCity[line.split()[1]].append((line.split()[0], int(line.split()[2]), int(line.split()[3]), line.split()[4])) speedsofHighway[line.split()[4]].append(int(line.split()[3])) numOfRoutes = numOfRoutes + 1 with open('road-segments.txt', 'r') as file: for line in file: sumOfDist = sumOfDist + int(line.split()[2]) if len(line.split()) == 4 or int(line.split()[3]) == 0: if not speedsofHighway[line.split()[3]]: speedsofHighway[line.split()[3]].append(int(30)) sumOfSpeeds = sumOfSpeeds + 30 else: sumOfSpeeds = sumOfSpeeds + int(sum(speedsofHighway[line.split()[3]])/len(speedsofHighway[line.split()[3]])) succOfCity[line.split()[0]].append((line.split()[1], int(line.split()[2]), int(sum(speedsofHighway[line.split()[3]])/len(speedsofHighway[line.split()[3]])), line.split()[3])) succOfCity[line.split()[1]].append((line.split()[0], int(line.split()[2]), int(sum(speedsofHighway[line.split()[3]])/len(speedsofHighway[line.split()[3]])), line.split()[3])) else: sumOfSpeeds = sumOfSpeeds + int(line.split()[3]) avg_speed = float(sumOfSpeeds)/float(numOfRoutes) avg_dist = float(sumOfDist)/float(numOfRoutes) latlon = defaultdict(list) citiesInState = defaultdict(list) LonsofState = defaultdict(float) LatsofState = defaultdict(float) with open('city-gps.txt', 'r') as file: for line in file: citiesInState[(line.split()[0]).split(",")[1]].append(line.split()[0]) if not LonsofState[(line.split()[0]).split(",")[1]]: LonsofState[(line.split()[0]).split(",")[1]] = 0 if not LatsofState[(line.split()[0]).split(",")[1]]: LatsofState[(line.split()[0]).split(",")[1]] = 0 LonsofState[(line.split()[0]).split(",")[1]] = LonsofState[(line.split()[0]).split(",")[1]] + float(line.split()[1]) LatsofState[(line.split()[0]).split(",")[1]] = LatsofState[(line.split()[0]).split(",")[1]] + float(line.split()[2]) latlon[line.split()[0]].append((float(line.split()[1]))) latlon[line.split()[0]].append((float(line.split()[2]))) start_city = sys.argv[1] end_city = sys.argv[2] algo = sys.argv[3] cost = sys.argv[4] prev_state = start_city.split(",")[1] if algo == "bfs": print(solve_bfs(start_city, end_city, algo, cost)) if algo == "uniform": print(solve_ucs(start_city, end_city, algo, cost)) if algo == "dfs": print(solve_dfs(start_city, end_city, algo, cost)) if algo == "ids": print(solve_ids(start_city, end_city, algo, cost)) if algo == "astar": print(solve_astar(start_city, end_city, algo, cost))
# FIXME (1): Prompt for four weights. Add all weights to a list. Output list. users_weight = [] for i in range(0,1): x = input('Enter weight 1: \n') users_weight.append(float(x)) x = input('Enter weight 2: \n') users_weight.append(float(x)) x = input('Enter weight 3: \n') users_weight.append(float(x)) x = input('Enter weight 4: \n') users_weight.append(float(x)) print('') print('Weights:',users_weight) # FIXME (2): Output average of weights. average_weights = sum(users_weight) / float(len(users_weight)) print('Average weight:', average_weights) # FIXME (3): Output max weight from list. max_weight = max(users_weight) print('Max weight: %s\n' % max_weight) # FIXME (4): Prompt the user for a list index and output that weight in pounds and kilograms. index_value = (input('Enter a list index (1 - 4): \n')) if index_value == '1': index_value = users_weight[0] print('Weight in pounds:', index_value) index_value = users_weight[0] * 0.45359237 rounded_value = round(index_value) print('Weight in kilograms: %.1f\n' % rounded_value) elif index_value == '2': index_value = users_weight[1] print('Weight in pounds:', index_value) index_value = users_weight[1] * 0.45359237 rounded_value = round(index_value) print('Weight in kilograms: %.1f\n' % rounded_value) elif index_value == '3': index_value = users_weight[2] print('Weight in pounds:', index_value) index_value = users_weight[2] * 0.45359237 rounded_value = round(index_value) print('Weight in kilograms: %.1f\n' % rounded_value) else: index_value = users_weight[3] print('Weight in pounds:', index_value) index_value = users_weight[3] * 0.45359237 rounded_value = round(index_value) print('Weight in kilograms: %.1f\n' % rounded_value) # FIXME (5): Sort the list and output it. users_weight.sort() print('Sorted list:', users_weight)
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Arianna # # Created: 08/04/2014 # Copyright: (c) Arianna 2014 # Licence: <your licence> #------------------------------------------------------------------------------- def printBoard(board): #n=8 final=[] for c in range(len(board)): lis=['- ']*len(board) lis[board[c]]='Q' final.append(''.join(lis)) print('#######################') for n in final: print('#',n,'#') print('#######################') def cost(board): colsi=0 for q in range(len(board)): queenRow=q queenCol=board[q] for n in range(q+1,len(board)): if board[n]==queenCol: colsi+=1 elif abs(queenCol-board[n])==abs(queenRow-n): colsi+=1 return colsi from copy import* def parentSwap(board): print(board,'= parent') finalList=[] child=[]+board for n in range(len(board)): child=[]+board for q in range(n, len(board)-1): child[q],child[q+1]=child[q+1],child[q] finalList.append(child) child=[]+child for a in finalList: print(a) def main(): board=[0,1,2,3,4] printBoard(board) print(cost(board)) parentSwap(board) if __name__ == '__main__': main() #If it is at 2,2 #and is checking if one with coordinates 4,4
# # Author: Arianna # # Created: 12/12/2013 #------------------------------------------------------------------------------- def bogusFunction(stng): diCt={} for n in range(len(stng)): s=stng[n:n+1] #get the individual character if s not in diCt.keys(): diCt[s]=1 # insert character into dictionary if not already in else: diCt[s]+=1 #add to the number of times s appears in stng return len(diCt.keys()), diCt def main(): num,di=bogusFunction('SUPERCALIFRAGILISTICEXPIALIDOCIOUS') print('Number of Characters:',num) print('') print('----------Characters and Count----------') for letter in di.keys(): print('| Letter',letter,' Appears ', di[letter],'Time(s) |') print('----------------------------------------') Number of Characters: 15 ----------Characters and Count----------- | letter C appears 3 time(s) | | letter A appears 3 time(s) | | letter G appears 1 time(s) | | letter F appears 1 time(s) | | letter E appears 2 time(s) | | letter D appears 1 time(s) | | letter I appears 7 time(s) | | letter O appears 2 time(s) | | letter L appears 3 time(s) | | letter S appears 3 time(s) | | letter R appears 2 time(s) | | letter P appears 2 time(s) | | letter U appears 2 time(s) | | letter T appears 1 time(s) | | letter X appears 1 time(s) | ----------------------------------------- if __name__ == '__main__': main()
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Arianna # # Created: 24/04/2014 # Copyright: (c) Arianna 2014 # Licence: <your licence> #------------------------------------------------------------------------------- POPSIZE=8 from random import * def createRandChromosomes(): #each is 10 long chromList=[] for p in range(POPSIZE): currentChrom=[] for n in range(10): currentChrom.append(randint(0,1)) chromList.append(currentChrom) return chromList def sortChroms(chromList): chromList.sort(key=sum, reverse=True) def combine(p1,p2): number=randint(0,POPSIZE-1) c1,c2=p1[:number]+p2[number:],p2[:number]+p1[number:] return c1,c2 def main(): population=createRandChromosomes() # print(population) population.sort(key=sum,reverse=True) #print(population) for n in range(20): c1, c2=combine(population[0],population[1]) c3, c4=combine(population[0],population[2]) c5, c6=combine(population[0],population[3]) c7, c8=combine(population[0],population[POPSIZE//2]) population=[c1,c2,c3,c4,c5,c6,c7,c8] sortChroms(population) for n in population: print(n) #create a popultatoin of size POPSIZE #sort them so that the one wiht the highest collective value is in position 1 #and so on and so on #done up to here #then you combine that one with the four below it (chroms[1],chroms[2],chroms[POP//2] #each coupling should produce 2 chldren #children replace thier population #chrm[5],5,7 not allowed because least fit #then process is repeated #proceed for 20 #pass #each has 10 chrom, 100 chromosomes? #find sum of all 100 #then find the max? if __name__ == '__main__': main()
""" Helper functions to construct image pyramids """ import cv2 import numpy as np # Function to downsample an intensity (grayscale) image def downsampleGray(img): """ The downsampling strategy eventually chosen is a naive block averaging method. That is, for each pixel in the target image, we choose a block comprising 4 neighbors in the source image, and simply average their intensities. For each target image point (y, x), where x indexes the width and y indexes the height dimensions, we consider the following four neighbors: (2*y,2*x), (2*y+1,2*x), (2*y,2*x+1), (2*y+1,2*x+1). NOTE: The image must be float, to begin with. """ # Perform block-averaging img_new = (img[0::2,0::2] + img[0::2,1::2] + img[1::2,0::2] + img[1::2,1::2]) / 4. return img_new # Function to downsample a depth image def downsampleDepth(img): """ For depth images, the downsampling strategy is very similar to that for intensity images, with a minor mod: we do not average all pixels; rather, we average only pixels with non-zero depth values. """ # Perform block-averaging, but not across depth boundaries. (i.e., compute average only # over non-zero elements) img_ = np.stack([img[0::2,0::2], img[0::2,1::2], img[1::2,0::2], img[1::2,1::2]], axis=2) num_nonzero = np.count_nonzero(img_, axis=2) num_nonzero[np.where(num_nonzero == 0)] = 1 img_new = np.sum(img_, axis=2) / num_nonzero return img_new.astype(np.uint8) # Function to construct a pyramid of intensity and depth images with a specified number of levels def buildPyramid(gray, depth, num_levels, focal_length, cx, cy): # Lists to store each level of a pyramid pyramid_gray = [] pyramid_depth = [] pyramid_intrinsics = [] current_gray = gray current_depth = depth current_f = focal_length current_cx = cx current_cy = cy # Build levels of the pyramid for level in range(num_levels): pyramid_gray.append(current_gray) pyramid_depth.append(current_depth) K_cur = dict() K_cur['f'] = current_f K_cur['cx'] = current_cx K_cur['cy'] = current_cy pyramid_intrinsics.append(K_cur) if level < num_levels-1: current_gray = downsampleGray(current_gray) current_depth = downsampleDepth(current_depth) return pyramid_gray, pyramid_depth, pyramid_intrinsics
def check(i,j,matrix): isp=0 if(j==0): isp=1 if(matrix[i][j+1]>0): return(True) elif(j==len(matrix[i])-1): isp=1 if(matrix[i][j-1]>0): return(True) if(isp==1): if(i==0): if(matrix[i+1][j]>0): return(True) else: return(False) elif(i==len(matrix)-1): if(matrix[i-1][j]>0): return(True) else: return(False) else: if(matrix[i+1][j]>0 or matrix[i-1][j]>0): return(True) else: return(False) else: if((matrix[i][j+1])>0): return(True) elif((matrix[i][j-1])>0): return(True) if(i==0): if(matrix[i+1][j]>0): return(True) else: return(False) elif(i==len(matrix)-1): if(matrix[i-1][j]>0): return(True) else: return(False) else: if(matrix[i+1][j]>0 or matrix[i-1][j]>0 ): return(True) else: return(False) def minimumPassesOfMatrix(matrix): # Write your code here. if(len(matrix)==0): return(-1) if(len(matrix)==1): if((len(matrix[0])==1 and matrix[0][0]<0)or len(matrix[0])==0): return(-1) else: return(0) l=[] ct=0 for i in matrix: b=[] for j in i: b.append(j) if(j<0): ct+=1 l.append(b) count=0 while(1): if(ct==0): return(count) isp=0 for i in range(0,len(matrix)): for j in range(0,len(matrix[i])): if(matrix[i][j]<0): if(check(i,j,matrix)==True): isp=1 l[i][j]*=-1 ct-=1 if(isp==0): return(-1) print(l) matrix=[] for x in l: c=[] for j in x: c.append(j) matrix.append(c) count+=1
def moveElementToEnd(array, toMove): # Write your code here. k=[] l=[] for i in range(0,len(array)): if(array[i]==toMove): k.append(array[i]) else: l.append(array[i]) for j in k: l.append(j) return(l)
Do not edit the class below except for # the insert, contains, and remove methods. # Feel free to add new properties and methods # to the class. class BST: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): # Write your code here. # Do not edit the return statement of this method. isp=0 x=value p=BST(value=x) while(self!=None): if(value>=self.value): isp=1 prev=self self=self.right else: isp=2 prev=self self=self.left if(isp==1): prev.right=p elif(isp==2): prev.left=p print("done") return self def contains(self, value): # Write your code here. while(self!=None): if(self.value==value): return(True) elif(value>=self.value): self=self.right else: self=self.left return(False) def remove(self, value): # Write your code here. # Do not edit the return statement of this method. isp=0 if(self.right==None and self.left==None): return(self) while(self!=None): if(value==self.value): p=self if(self.right==None and self.left==None): if(isp==1): prev.right=None elif(isp==2): prev.left=None x=self self=p del(x) break prev=self self=self.right if(self==None): x=prev.left prev.value=x.value prev.left=x.left del(x) self=p else: ct=0 while(self.left!=None): ct+=1 prev=self self=self.left p.value=self.value if(ct==0): prev.right=self.right else: prev.left=None x=self self=p del(x) break elif(value>=self.value): isp=1 prev=self aa=self self=self.right else: isp=2 prev=self aa=self self=self.left return self
import requests # Safari Animals # Below are safari animals, however, each letter has been replaced by its position in the alphabet, # but the spaces between the resulting numbers have been removed. # e.g. DOG=4.15.7=4157 animals = [ '18891415', '3181531549125', '79181665', '38552018', '12515161184', '89161615', '512516811420', '2216611215', '1291514' ] def recursive_parse(numeric_word, parsed_word, current_index, max_index, parsed_list): while current_index < max_index: numeric_letter = numeric_word[current_index] # if the next number is 0 it must be part of this 'numeric letter' if current_index + 1 < max_index and numeric_word[current_index + 1] == '0': numeric_letter += '0' current_index += 1 # if the current 'numeric letter' is 1 or 2 AND there are more numbers # it _may_ be a 2 digit numeric letter if numeric_letter in ['1', '2'] and current_index + 1 < max_index: next_letter = numeric_word[current_index + 1] test_letter = int(numeric_letter + next_letter) save_word = parsed_word if test_letter < 27: parsed_word += chr(test_letter + 64) recursive_parse(numeric_word, parsed_word, current_index + 2, max_index, parsed_list) parsed_word = save_word parsed_word += chr(int(numeric_letter) + 64) current_index += 1 parsed_list.append(parsed_word[0] + parsed_word[1:].lower()) def parse(number_word): parsed_word = '' current_index = 0 parsed_list = [] max_index = len(number_word) recursive_parse(number_word, parsed_word, current_index, max_index, parsed_list) return parsed_list for animal in animals: parsed_animal_list = parse(animal) # print(parsed_animal_list) for parsed_animal in parsed_animal_list: # ask Wikipedia if it knows what the animal is r = requests.head('https://en.wikipedia.org/wiki/' + parsed_animal) if r.status_code == 301: # if wikipedia gives us a redirect, pick up the new location and try that r = requests.head(r.headers['Location']) if r.status_code == 200: print('{} = {}'.format(animal, parsed_animal)) break
import copy class Vertex(object): def __init__(self, node1, node2): self.node1 = node1 self.node2 = node2 def __lt__(self, other): return self.node1 < other.node1 and self.node2 < other.node2 def __repr__(self): return f'{self.node1},{self.node2}' class Node(object): edges = set() def __init__(self, letter): self.letter = letter def __repr__(self): return f'{self.letter}' def join_node(self, other): v = Vertex(self, other) self.edges.add(v) def get_joined_nodes(self): for vertex in self.edges: if vertex.node1 == self: yield vertex.node2 elif vertex.node2 == self: yield vertex.node1 if __name__ == '__main__': nodes=set() t = Node('t') nodes.add(t) h = Node('h') nodes.add(h) t.join_node(h) o = Node('o') nodes.add(o) n = Node('n') nodes.add(n) n.join_node(o) i = Node('i') nodes.add(i) e = Node('e') nodes.add(e) h.join_node(o) h.join_node(n) h.join_node(i) h.join_node(e) p = Node('p') nodes.add(p) o.join_node(p) n.join_node(p) o2 = Node('o2') nodes.add(o2) p.join_node(o2) n.join_node(o2) s = Node('s') nodes.add(s) o2.join_node(s) n.join_node(s) s2 = Node('s2') nodes.add(s2) n.join_node(s2) i.join_node(s2) b = Node('b') nodes.add(b) s.join_node(b) s2.join_node(b) s3 = Node('s3') nodes.add(s3) s.join_node(s3) b.join_node(s3) i2 = Node('i2') nodes.add(i2) s3.join_node(i2) b.join_node(i2) y = Node('y') nodes.add(y) b.join_node(y) i2.join_node(y) e2 = Node('e2') nodes.add(e2) i.join_node(e2) l1 = Node('l') nodes.add(l1) b.join_node(l1) e3 = Node('e3') nodes.add(e3) i.join_node(e3) l1.join_node(e3) r = Node('r') nodes.add(r) e.join_node(r) i.join_node(r) e2.join_node(r) w = Node('w') nodes.add(w) e3.join_node(w) e2.join_node(w) l1.join_node(w) a = Node('a') nodes.add(a) w.join_node(a) y.join_node(a) y.join_node(w) for edge in t.edges: print(edge) def traverse_nodes(current, end, letters, visited_nodes, possibles): my_letters = copy.copy(letters) my_letters.append(current.letter[0]) my_visited_nodes = copy.copy(visited_nodes) my_visited_nodes.add(current) if current != end: for node in current.get_joined_nodes(): if node not in my_visited_nodes: traverse_nodes(node, end, my_letters, my_visited_nodes, possibles) else: word_stream = ''.join(my_letters) if len(word_stream) == 20: possibles.append(word_stream) likely = list() traverse_nodes(t, y, [], set(), likely) print(likely)
from itertools import permutations # See oct_29_2020.jpg class Sweet(object): colour = None def __init__(self, colour): self.colour = colour def __repr__(self): return f'{self.colour}' def __eq__(self, other): return self.colour == other.colour def is_colour(self, colour): return self.colour == colour def __lt__(self, other): return self.colour < other.colour def __hash__(self): return hash(self.colour) class Child(object): name = None sweet1 = None sweet2 = None def __init__(self, name, sweet1, sweet2): self.name = name self.sweet1 = sweet1 self.sweet2 = sweet2 def has_colour(self, colour): return self.sweet1.is_colour(colour) or self.sweet2.is_colour(colour) def __repr__(self): return f'{self.name:8}: has - {self.sweet1},{self.sweet2}' def __hash__(self): return hash(self.name) ^ hash(self.sweet1) ^ hash(self.sweet2) def __eq__(self, other): return self.name == other.name and self.sweet1 == other.sweet1 and self.sweet2 == other.sweet2 class Solution(object): solution_children = [] def __init__(self, children): self.solution_children = [c for c in children] def __repr__(self): return f'{self.solution_children[0]}\n{self.solution_children[1]}\n{self.solution_children[2]}\n{self.solution_children[3]}' def __eq__(self, other): return self.solution_children[0] == other.solution_children[0] and self.solution_children[1] == \ other.solution_children[1] and self.solution_children[2] == \ other.solution_children[2] and self.solution_children[3] == other.solution_children[3] def __hash__(self): return self.solution_children[0].__hash__() ^ self.solution_children[1].__hash__() ^ self.solution_children[ 2].__hash__() ^ self.solution_children[ 3].__hash__() if __name__ == '__main__': sweets = [Sweet('blue'), Sweet('blue'), Sweet('red'), Sweet('red'), Sweet('green'), Sweet('green'), Sweet('orange'), Sweet('orange')] solutions = set() for s1, s2, s3, s4, s5, s6, s7, s8 in permutations(sweets, 8): if s1 < s2 and s3 < s4 and s5 < s6 and s7 < s8: jesse = Child('Jesse', s1, s2) jamie = Child('Jamie', s3, s4) jo = Child('Jo', s5, s6) jules = Child('Jules', s7, s8) if not jules.has_colour('orange') and not jesse.has_colour('blue') and not jamie.has_colour( 'red') and jo.has_colour('green') and jesse.has_colour('orange'): children = [jesse, jamie, jo, jules] x1 = set(filter(lambda child: (child.has_colour('red') and child.has_colour('green')), children)) x2 = set(filter(lambda child: (child.has_colour('red') and child.has_colour('blue')), children)) if len(x1) >= 1 and len(x2) == 1: solutions.add(Solution(children)) for s in solutions: print(s)
#Ikbel El Amri #CodeAcademy unit 8 Project #Command Line Calendar """In this project, we'll build a basic calendar that the user will be able to interact with from the command line. The user should be able to choose to: View the calendar Add an event to the calendar Update an existing event Delete an existing event The program should behave in the following way: Print a welcome message to the user Prompt the user to view, add, update, or delete an event on the calendar Depending on the user's input: view, add, update, or delete an event on the calendar The program should never terminate unless the user decides to exit""" from time import sleep, strftime from sys import stdout def loading(message): """display the loading aninmation""" stdout.write(message) sleep(0.4) for i in range(3): stdout.write('.') sleep(0.2) print('.\n') def get_user_name(): """prompt the user for their name and return it""" #prompt user for their first name USER_FIRST_NAME = raw_input("To start, please enter your first name: ") #in case entry is invalid (empty) prompt user for their name again while USER_FIRST_NAME=="": print "\nInvalid entry." USER_FIRST_NAME = raw_input("Please enter your first name: ") #return name return USER_FIRST_NAME def welcome(): """displays the initialization messages: welcome message with the user's name""" #print the start message loading("Starting calendar") #prompt user for their name NAME = get_user_name() #print welcome message using concatenation print "\nWelcome to the Calendar App, " + NAME + "!\n" sleep(0.75) #pause program #print current date and time using the imported strftime function #documentation: https://docs.python.org/2/library/time.html#time.strftime print "Today is: " + strftime("%A %B %d, %Y") + "\n" print "The time is: " + strftime("%X") + "\n" sleep(0.75) #pause program print "What would you like to do?" def start_calendar(calendar): """calendar functionality""" def view(): """view calendar""" loading("\nAccessing calendar") #print animation #if calendar is empty if len(calendar.keys())<1: print "Calendar is empty.\n" sleep(1) #sleep program for 1s else: print calendar def update(): """update calendar""" #prompt user for event to update calendar with date = raw_input("\nEnter date (MM/DD/YYYY): ") while len(date)!=10: #check entry and prompt user again until valid input is entered print "\nEntry is invalid." #error message date = raw_input("Enter date in this format MM/DD/YYYY (including the slashes): ") update = raw_input("Enter the update: ") while len(update)<1: print "\nEntry is invalid." #error message update = raw_input("Enter the update: ") #update calendar by adding the update to the date that the user specifies calendar[date] = update loading("\nUpdating calendar") #print animation print "Update successful!\n" #update confirmation print calendar sleep(1) #sleep program for 1s def add(): """add event to calendar""" #prompt user for event to add to calendar event = raw_input("\nEnter the event you would like to add: ") while len(event)<1: print "\nEntry is invalid." #error message event = raw_input("Enter the event you would like to add: ") date = raw_input("Enter date (MM/DD/YYYY): ") while len(date)!=10: #entry validity checker print "\nEntry is invalid." #error message date = raw_input("Enter date in this format MM/DD/YYYY (including the slashes): ") #add event to calendar calendar[date] = event loading("\nAccessing the calendar") #print animation print "Event added successfully!\n" #add confirmation print calendar print "\n" sleep(1) #sleep program for 1s def delete(): """delete event from calendar""" loading("\nAccessing calendar events") #print animation #if calendar is empty if len(calendar.keys())<1: print "Calendar is empty. There are no events to delete.\n" sleep(1) #sleep program for 1s #if events exist inside the calendar else: event = raw_input ("Which event would you like to delte? ") while len(event)<1: #check for errors in the input and prompt again if input is invalid print "\nEntry is invalid." #error message event = raw_input ("Which event would you like to delte? ") #iterate through the dates (keys) and find the matching event (value) for date in calendar.keys(): loading("\nFinding event") #animation #if event is found if event == calendar[date]: del calendar[date] #delete event from calendar loading("\nDeleting event") #animation print "Event deleted successfully.\n" #confirm delete sleep(1) #sleep program for 1s #print remaining events in calendar. indicate calendar is empty if no more events exist if len(calendar.keys())<1: print "Calendar is empty." sleep(1) #sleep program for 1s else: print calendar sleep(1) #sleep program for 1s break #skip rest of code in this function #if event to delete does not exist inside the calendar else: print "Could not find the event in the calendar." #ask if the user would like to continue with the program try_again = raw_input("Try Again? Press Y for Yes if you would like to perform another action, or press N for No to exit: ") try_again = try_again.upper() while try_again!="Y" and try_again!="N": #check entry and prompt again if invalid print "\nEntry is invalid." #error message try_again = raw_input("Try Again? Y for Yes, N for No: ") try_again = try_again.upper() if try_again == "Y": #if user would like to try another action print "\n" return #start loop from the beginning elif try_again == "N": #if user chooses to exit program return "Exit" #return exit command def leave(): """exit calendar program""" print "\nThank you for using the Calendar App!" loading("Exiting program") return False print "You can view the calendar, update it, add to it or delete from it.\n" #we need the project to terminate only when the user voluntarily exits the program run_calendar = True #prompt user for desired action while run_calendar: user_choice = raw_input("Please enter A to Add, U to Update, V to View, D to Delete or X to Exit: ") user_choice = user_choice.upper() #if user enters invalid input while user_choice!="A" and user_choice!="U" and user_choice!="V" and user_choice!="D" and user_choice!="X": print "\nInvalid entry." #error message #prompt user for desired action until entry is valid user_choice = raw_input("Please enter A to Add, U to Update, V to View, D to Delete or X to Exit: ") user_choice = user_choice.upper() #user asks to view the calendar if user_choice == "V": view() #user asks to update the calendar elif user_choice == "U": update() #user asks to add to the calendar elif user_choice == "A": add() #user asks to delete an event from the calendar elif user_choice == "D": command = delete() #if delete function returns an exit command if command == "Exit": run_calendar = leave() #exit program elif user_choice == "X": run_calendar = leave() def main(): #print welcome messages welcome() #a calendar allows users to at least associate an event with a date, as a pair #for this reason, we will use a dictionary as data structure for our calendar calendar = {} #run the calendar start_calendar(calendar) main() """if len(date)<1: print "\nEntry is invalid." #error message #ask if the user would like to continue with the program try_again = raw_input("Try Again? Y for Yes, N for No: ") try_again = try_again.upper() while try_again!="Y" and try_again!="N": #check entry and prompt again if invalid print "\nEntry is invalid." #error message try_again = raw_input("Try Again? Y for Yes, N for No: ") try_again = try_again.upper() if try_again == "Y": #if continue #start loop from the beginning else: #if user chooses to exit program run_calendar = False"""
import unittest class Node(object): def __init__(self, data, next=None): self.data, self.next = data, next def delete_middle(node): next = node.next node.data = next.data node.next = next.next class Test(unittest.TestCase): def test_delete_middle(self): head = Node(1, Node(2, Node(3, Node(4)))) delete_middle(head.next.next) self.assertEqual(head.data, 1) self.assertEqual(head.next.data, 2) self.assertEqual(head.next.next.data, 4) if __name__ == '__main__': unittest.main()
import unittest class NodeT(): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class NodeLL(): def __init__(self, data, next=None): self.data = data self.next = next def print(self): res = '' node = self while node: res += str(node.data) node = node.next print(res) def list_of_depths(root): res = [] q = [] q.append(root) res.append([NodeLL(root.data)]) while q: x = q.pop(0) sub_ll = NodeLL(None) temp = sub_ll if x.left: q.append(x.left) temp.next = NodeLL(x.left.data) temp = temp.next if x.right: q.append(x.right) temp.next = NodeLL(x.right.data) temp = temp.next sub_ll = sub_ll.next res.append([sub_ll]) return res class Test(unittest.TestCase): def test_list_of_depths(self): root = NodeT(3) root.left = NodeT(2) root.right = NodeT(5) root.left.left = NodeT(1) root.right.left = NodeT(4) list_of_ll = list_of_depths(root) for i in list_of_ll: print(i) self.assertEqual(len(list_of_ll), 3) return if __name__ == '__main__': unittest.main()
def RealZeros(equation): numerator,denominator, answer = [],[],[] firstcoe,lastcoe = equation[0],int(equation[-1]) for i in range(1,lastcoe/2 + 1): if lastcoe % i == 0: numerator.append(i) numerator.append(lastcoe) if firstcoe.isdigit() is False: denominator = [1, -1] else: firstcoe = int(firstcoe) for i in range(1,firstcoe +1): if firstcoe % i == 0: denominator.append(i) denominator.append(-i) options = Join(numerator, denominator) print 'The options are {}'.format(options) print for x in options: if eval(equation) == 0: answer.append(x) return answer def Join(list1,list2): list3 = [] for i in list1: for z in list2: list3.append(float(i)/float(z)) for item in list3: if list3.count(item) > 1: list3.remove(item) return list3 while True: question = raw_input('Enter Equation ') print RealZeros(question)
from random import * msg = "Mass bunk today" def encipher(): msg = input("\n\nGimme something to encrypt: ") key = keygen(msg) ct = "".join([ chr(ord('a') + (ord(msg[i].lower()) + key[i] - ord('a') )%26) if msg[i].isalpha() else msg[i] for i in range(len(msg))]) print( "\n=======Encrypting the data========") print( key ) print("Msg: " + msg + "\n" + "Secret Text: " + ct) return ct,key def decipher(ct, key): pt = "".join([chr( ord('a') + (ord(ct[i]) - key[i] - ord('a') )%26) if ct[i].isalpha() else ct[i] for i in range(len(ct))]) print("\n========Decrypting the data=========") print("Secret Text: " + ct + "\n" + "Message: " + pt) def keygen(msg): return [ randint(0, 100) for i in range(len(msg)) ] if __name__ == '__main__': (ct, key) = encipher() decipher(ct, key)
def minimumDays(rows, columns, grid): # WRITE YOUR CODE HERE n = 0 while (haszero(rows, columns, grid)): n+=1 new_grid = list(grid) # copy grid to new_grid for i in range(rows): for j in range(columns): if grid[i][j] == 0: if hasonearound(rows, columns, i, j, grid): new_grid[i][j]=1 grid = list(new_grid) #update grid return n def haszero(rows, columns, grid): for i in range(rows): if sum(grid[i])<columns: return True return False def hasonearound(rows, columns, irow, icol, grid): #up if irow>0: if (grid[irow-1][icol]==1): return True #down if irow<(rows-1): if (grid[irow+1][icol]==1): return True #left if icol>0: if (grid[irow][icol-1]==1): return True #right if icol<(columns-1): if (grid[irow][icol+1]==1): return True return False a = [[1,1,0], [0,0,0]] print(minimumDays(2, 3, a))
# # @lc app=leetcode id=168 lang=python # # [168] Excel Sheet Column Title # # https://leetcode.com/problems/excel-sheet-column-title/description/ # # algorithms # Easy (29.62%) # Likes: 886 # Dislikes: 184 # Total Accepted: 192.3K # Total Submissions: 643.3K # Testcase Example: '1' # # Given a positive integer, return its corresponding column title as appear in # an Excel sheet. # # For example: # # # ⁠ 1 -> A # ⁠ 2 -> B # ⁠ 3 -> C # ⁠ ... # ⁠ 26 -> Z # ⁠ 27 -> AA # ⁠ 28 -> AB # ⁠ ... # # # Example 1: # # # Input: 1 # Output: "A" # # # Example 2: # # # Input: 28 # Output: "AB" # # # Example 3: # # # Input: 701 # Output: "ZY" # # # @lc code=start class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str 26进制 但是是从1到26 不是0到25 所以如果余数等于0 要处理一哈 """ res ='' while n>0: r = n%26 if r == 0: r = 26 n = n-1 res = chr(ord('A')+r-1)+res n = n//26 return res # @lc code=end
# # @lc app=leetcode id=28 lang=python # # [28] Implement strStr() # # https://leetcode.com/problems/implement-strstr/description/ # # algorithms # Easy (32.66%) # Likes: 1043 # Dislikes: 1495 # Total Accepted: 493.8K # Total Submissions: 1.5M # Testcase Example: '"hello"\n"ll"' # # Implement strStr(). # # Return the index of the first occurrence of needle in haystack, or -1 if # needle is not part of haystack. # # Example 1: # # # Input: haystack = "hello", needle = "ll" # Output: 2 # # # Example 2: # # # Input: haystack = "aaaaa", needle = "bba" # Output: -1 # # # Clarification: # # What should we return when needle is an empty string? This is a great # question to ask during an interview. # # For the purpose of this problem, we will return 0 when needle is an empty # string. This is consistent to C's strstr() and Java's indexOf(). # # 0 1 2 3 4 5 class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ # in python str1.find(str2) can be used # but this is not allowed in the algorithm test # result = haystack.find(needle) # return result needleL = len(needle) if len(haystack) < needleL: return -1 for i in range(len(haystack)-needleL+1): if haystack[i:i+needleL] == needle: return i return -1
# # @lc app=leetcode id=229 lang=python # # [229] Majority Element II # # https://leetcode.com/problems/majority-element-ii/description/ # # algorithms # Medium (34.83%) # Likes: 1423 # Dislikes: 159 # Total Accepted: 135.3K # Total Submissions: 388.4K # Testcase Example: '[3,2,3]' # # Given an integer array of size n, find all elements that appear more than ⌊ # n/3 ⌋ times. # # Note: The algorithm should run in linear time and in O(1) space. # # Example 1: # # # Input: [3,2,3] # Output: [3] # # Example 2: # # # Input: [1,1,1,3,3,2,2,2] # Output: [1,2] # # # @lc code=start class Solution: def majorityElement(self, nums): group1 = 0 group2 = 1 count1 = 0 count2 = 0 if not nums: return [] for oneValue in nums: if oneValue == group1: count1+=1 elif oneValue == group2: count2+=1 elif count1 == 0: group1 = oneValue count1=1 elif count2 == 0: group2 = oneValue count2=1 else: count1-=1 count2-=1 count1, count2 = 0, 0 for oneValue in nums: if oneValue == group1: count1+=1 elif oneValue == group2: count2+=1 res = [] length = len(nums) if count1 > length//3: res.append(group1) if count2 > length//3: res.append(group2) return res # @lc code=end
# # @lc app=leetcode id=268 lang=python # # [268] Missing Number # # https://leetcode.com/problems/missing-number/description/ # # algorithms # Easy (50.92%) # Likes: 1581 # Dislikes: 1940 # Total Accepted: 423.9K # Total Submissions: 832.2K # Testcase Example: '[3,0,1]' # # Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find # the one that is missing from the array. # # Example 1: # # # Input: [3,0,1] # Output: 2 # # # Example 2: # # # Input: [9,6,4,2,3,5,7,0,1] # Output: 8 # # # Note: # Your algorithm should run in linear runtime complexity. Could you implement # it using only constant extra space complexity? # # @lc code=start class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # Solution 1 # since in the range(len(nums)) the largest one that is # len(nums) is not included # result = len(nums) # for i in range(len(nums)): # result = result ^ i ^ nums[i] # return result # return (len(nums)+1)*len(nums)/2 - sum(nums) res = len(nums) for i in range(len(nums)): res = res ^ i ^ nums[i] return res # @lc code=end
# # @lc app=leetcode id=29 lang=python # # [29] Divide Two Integers # # https://leetcode.com/problems/divide-two-integers/description/ # # algorithms # Medium (16.16%) # Likes: 783 # Dislikes: 3787 # Total Accepted: 217.4K # Total Submissions: 1.3M # Testcase Example: '10\n3' # # Given two integers dividend and divisor, divide two integers without using # multiplication, division and mod operator. # # Return the quotient after dividing dividend by divisor. # # The integer division should truncate toward zero. # # Example 1: # # # Input: dividend = 10, divisor = 3 # Output: 3 # # Example 2: # # # Input: dividend = 7, divisor = -3 # Output: -2 # # Note: # # # Both dividend and divisor will be 32-bit signed integers. # The divisor will never be 0. # Assume we are dealing with an environment which could only store integers # within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose # of this problem, assume that your function returns 2^31 − 1 when the division # result overflows. # # # class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ # every time multiply temporary divisor by two # if dividend < divisor, set temporary divisor to be the original one if dividend == 0: return 0 isNegative = not ( (dividend <0) == (divisor <0)) dividend, divisor = abs(dividend), abs(divisor) res = 0 while dividend >=divisor: temp = divisor i = 1 while dividend >= temp: res+=i dividend -= temp temp<<=1 i<<=1 if isNegative: res = -res limit = 2**31 return min(max(-limit, res), limit-1) # if dividend == 0: # return 0 # isPositive = (dividend < 0) == (divisor < 0) # dividend, divisor = abs(dividend), abs(divisor) # res = 0 # while dividend >= divisor: # temp = divisor # i = 1 # while dividend >= temp: # dividend -= temp # res+=i # i<<=1 # x <<=y : x = x*2^y zy: <<= update i # temp<<=1 # if not isPositive: # res = -res # return min(max(-2147483648,res), 2147483647)
# # @lc app=leetcode id=60 lang=python # # [60] Permutation Sequence # # https://leetcode.com/problems/permutation-sequence/description/ # # algorithms # Medium (34.20%) # Likes: 989 # Dislikes: 266 # Total Accepted: 151.8K # Total Submissions: 443.5K # Testcase Example: '3\n3' # # The set [1,2,3,...,n] contains a total of n! unique permutations. # # By listing and labeling all of the permutations in order, we get the # following sequence for n = 3: # # # "123" # "132" # "213" # "231" # "312" # "321" # # # Given n and k, return the k^th permutation sequence. # # Note: # # # Given n will be between 1 and 9 inclusive. # Given k will be between 1 and n! inclusive. # # # Example 1: # # # Input: n = 3, k = 3 # Output: "213" # # # Example 2: # # # Input: n = 4, k = 9 # Output: "2314" # # # # @lc code=start class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ if n == 1: return '1' fact_arr = [None for i in range(n-1)] fact_arr[0] = 1 for i in range(1, n-1): fact_arr[i] = (i+1)*fact_arr[i-1] nums = list(range(1,n+1)) res = [] self.getRes(nums, k, res, fact_arr) return ''.join(res) def getRes(self, nums, k, res, fact_arr): numsL = len(nums) if numsL == 1: res.append(str(nums[0])) return else: nGroup = (k-1)//fact_arr[numsL-2] res.append(str(nums.pop(nGroup))) k = (k-1) % fact_arr[numsL-2] + 1 # 1 needs to be added since k starts from 1 self.getRes(nums, k, res, fact_arr) # # if n == 1 then [0]*(n-1) bug; seperately consider it # if n==1: # return '1' # fact_arr = [0]*(n-1) # fact_arr[0]=1 # for i in range(1, n-1): # fact_arr[i]=(i+1)*fact_arr[i-1] # nums = list(range(1,n+1)) # res = [] # # int list to string: every time append a str(int) then at last ''.join(list) # self.getRes(nums, k, res,fact_arr) # return ''.join(res) # def getRes(self, nums, k, res,fact_arr): # numsL = len(nums) # if numsL==1: # res.append(str(nums[0])) # return # group = (k-1)//fact_arr[numsL-2] # the corresponding index numsL-2 # res.append(str(nums.pop(group))) # remain = (k-1) % fact_arr[numsL-2] # k = remain + 1 # self.getRes(nums, k, res, fact_arr) # @lc code=end
# # @lc app=leetcode id=56 lang=python # # [56] Merge Intervals # # https://leetcode.com/problems/merge-intervals/description/ # # algorithms # Medium (36.20%) # Likes: 2346 # Dislikes: 183 # Total Accepted: 380.2K # Total Submissions: 1.1M # Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]' # # Given a collection of intervals, merge all overlapping intervals. # # Example 1: # # # Input: [[1,3],[2,6],[8,10],[15,18]] # Output: [[1,6],[8,10],[15,18]] # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into # [1,6]. # # # Example 2: # # # Input: [[1,4],[4,5]] # Output: [[1,5]] # Explanation: Intervals [1,4] and [4,5] are considered overlapping. # # NOTE: input types have been changed on April 15, 2019. Please reset to # default code definition to get new method signature. # # # @lc code=start class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ # first sort and then merge if len(intervals)<=1: return intervals intervals.sort(key = lambda x:x[0]) result = [intervals[0]] for i in range(1, len(intervals)): if intervals[i][0] <= result[-1][1]: if result[-1][1]<=intervals[i][1]: result[-1][1] = intervals[i][1] else: result.append(intervals[i]) return result # if len(intervals)<=1: # return intervals # intervals.sort(key = lambda x:x[0]) # i = 1 # while 1: # if intervals[i][0] <= intervals[i-1][1]: # if intervals[i][1]>intervals[i-1][1]: # intervals[i-1][1] = intervals[i][1] # del intervals[i] # else: # i+=1 # if i == len(intervals): # return intervals # @lc code=end
# # @lc app=leetcode id=199 lang=python3 # # [199] Binary Tree Right Side View # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: TreeNode) -> List[int]: res = [] if not root: return res nodeQueue = [root] while nodeQueue: level_len = len(nodeQueue) for i in range(level_len): node = nodeQueue.pop(0) if i == level_len -1: res.append(node.val) if node.left: nodeQueue.append(node.left) if node.right: nodeQueue.append(node.right) return res # @lc code=end
# # @lc app=leetcode id=96 lang=python # # [96] Unique Binary Search Trees # # https://leetcode.com/problems/unique-binary-search-trees/description/ # # algorithms # Medium (47.90%) # Likes: 2101 # Dislikes: 82 # Total Accepted: 225K # Total Submissions: 468.1K # Testcase Example: '3' # # Given n, how many structurally unique BST's (binary search trees) that store # values 1 ... n? # # Example: # # # Input: 3 # Output: 5 # Explanation: # Given n = 3, there are a total of 5 unique BST's: # # ⁠ 1 3 3 2 1 # ⁠ \ / / / \ \ # ⁠ 3 2 1 1 3 2 # ⁠ / / \ \ # ⁠ 2 1 2 3 # # # # @lc code=start class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n== 0: return 0 dp = [0]*(n+1) dp[0]=1 for i in range(1,n+1): for root in range(1, i+1): n_left = root-1 n_right = i - root dp[i]+=dp[n_left]*dp[n_right] return dp[n] # @lc code=end
# # @lc app=leetcode id=213 lang=python # # [213] House Robber II # # https://leetcode.com/problems/house-robber-ii/description/ # # algorithms # Medium (36.13%) # Likes: 1533 # Dislikes: 47 # Total Accepted: 162.3K # Total Submissions: 449.3K # Testcase Example: '[2,3,2]' # # You are a professional robber planning to rob houses along a street. Each # house has a certain amount of money stashed. All houses at this place are # arranged in a circle. That means the first house is the neighbor of the last # one. Meanwhile, adjacent houses have security system connected and it will # automatically contact the police if two adjacent houses were broken into on # the same night. # # Given a list of non-negative integers representing the amount of money of # each house, determine the maximum amount of money you can rob tonight without # alerting the police. # # Example 1: # # # Input: [2,3,2] # Output: 3 # Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = # 2), # because they are adjacent houses. # # # Example 2: # # # Input: [1,2,3,1] # Output: 4 # Explanation: Rob house 1 (money = 1) and then rob house 3 (money = # 3). # Total amount you can rob = 1 + 3 = 4. # # # @lc code=start class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ # seperate the whole array into two arrays # array[0: len -1] array[1:len] if not nums: return 0 length = len(nums) if length == 1: return nums[0] return max(self.getMaxRobValue(0, length-2, nums), self.getMaxRobValue(1, length-1, nums)) def getMaxRobValue(self, start, end, nums): ## start end are both inclusive lag2 = 0 lag1 = res = nums[start] for i in range(start+1, end+1): res = max(lag2+nums[i], lag1) lag2, lag1 = lag1, res return res # @lc code=end
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param l1: the first list # @param l2: the second list # @return: the sum list of l1 and l2 def addLists(self, l1, l2): # write your code here dummy = ListNode(0) result = dummy carry = 0 while l1 or l2 or carry: if l1 == None and l2 == None: result.next = ListNode(carry) result = result.next carry = 0 elif l1 == None: result.next = ListNode(l2.val + carry) l2 = l2.next result = result.next carry = 0 elif l2 == None: result.next = ListNode(l1.val + carry) l1 = l1.next result = result.next carry = 0 else: result.next = ListNode((l1.val + l2.val + carry) % 10) carry = (l1.val + l2.val + carry)//10 l1 = l1.next l2 = l2.next result = result.next return dummy.next
import numpy as np __author__ = 'Otilia Stretcu' def normalize(data, axis, offset=None, scale=None, return_offset=False): """ Normalizes the data along the provided axis. If offset and scale are provided, we compute (data-offset) / scale, otherwise the offset is the mean, and the scale is the std (i.e. we z-score). Args: data(np.ndarray or list of embedded lists): Array-like data. axis(int): Axis along which to normalize. offset(np.ndarray or list of embedded lists): It matches the shape of the data along the provided axis. scale(np.ndarray or list of embedded lists): It matches the shape of the data along the provided axis. Returns: Normalized data, and optionally the offset and scale. """ if offset is None: offset = np.expand_dims(data.mean(axis=axis), axis=axis) if scale is None: scale = np.expand_dims(data.std(axis=axis), axis=axis) scale[scale == 0.0] = 1.0 if return_offset: return (data - offset) / scale, offset, scale return (data - offset) / scale
import ktanlib def solution1(S, P, Q): mapping = {'A':1, 'C':2, 'G':3, 'T':4} result = [0] * len(P) for i in range(len(P)): # print P[i],Q[i],S[P[i]:Q[i]+1] result[i] = mapping[min(S[P[i]:Q[i] + 1])] return result def solution2(S, P, Q): result = [] DNA_len = len(S) mapping = {"A":1, "C":2, "G":3, "T":4} # next_nucl is used to store the position information # next_nucl[0] is about the "A" nucleotides, [1] about "C" # [2] about "G", and [3] about "T" # next_nucl[i][j] = k means: for the corresponding nucleotides i, # at position j, the next corresponding nucleotides appears # at position k (including j) # k == -1 means: the next corresponding nucleotides does not exist next_nucl = [[-1] * DNA_len, [-1] * DNA_len, [-1] * DNA_len, [-1] * DNA_len] # Scan the whole DNA sequence, and retrieve the position information next_nucl[mapping[S[-1]] - 1][-1] = DNA_len - 1 for index in range(DNA_len - 2, -1, -1): next_nucl[0][index] = next_nucl[0][index + 1] next_nucl[1][index] = next_nucl[1][index + 1] next_nucl[2][index] = next_nucl[2][index + 1] next_nucl[3][index] = next_nucl[3][index + 1] next_nucl[mapping[S[index]] - 1][index] = index for index in range(0, len(P)): if next_nucl[0][P[index]] != -1 and next_nucl[0][P[index]] <= Q[index]: result.append(1) elif next_nucl[1][P[index]] != -1 and next_nucl[1][P[index]] <= Q[index]: result.append(2) elif next_nucl[2][P[index]] != -1 and next_nucl[2][P[index]] <= Q[index]: result.append(3) else: result.append(4) return result def solution3(S, P, Q): mapping = {'A':1, 'C':2, 'G':3, 'T':4} result = [0] * len(P) next_occurence = [[-1] * len(S), [-1] * len(S), [-1] * len(S), [-1] * len(S)] next_occurence[mapping[S[-1]] - 1][-1] = len(S) - 1 for i in range(len(S) - 2, -1, -1): next_occurence[0][i] = next_occurence[0][i + 1] next_occurence[1][i] = next_occurence[1][i + 1] next_occurence[2][i] = next_occurence[2][i + 1] next_occurence[3][i] = next_occurence[3][i + 1] next_occurence[mapping[S[i]] - 1][i] = i for j in range(len(P)): if next_occurence[0][P[j]] != -1 and next_occurence[0][P[j]] <= Q[j]: result[j] = 1 elif next_occurence[1][P[j]] != -1 and next_occurence[1][P[j]] <= Q[j]: result[j] = 2 elif next_occurence[2][P[j]] != -1 and next_occurence[2][P[j]] <= Q[j]: result[j] = 3 else: result[j] = 4 return result def main(): S = list("CAGCCTA") P = [2, 5, 0] Q = [4, 5, 6] # print solution1(S,P,Q) print solution2(S, P, Q) print solution3(S, P, Q) # print solution1(ktanlib.generate_random_array(0,1,1000000)) # print ktanlib.prefix_sum([0,1,0,1,0,1]) # 6 if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Sat Jan 23 12:41:13 2021 @author: Windows """ F = [[1,1],[1,0]] T = [[1,2],[3,4]] def copy(A, B): #copies matrix B into matrix A. Matrixes must be 2 by 2. A[0][0] = B[0][0] A[0][1] = B[0][1] A[1][0] = B[1][0] A[1][1] = B[1][1] pass def multiply(A, B): #Multiplies matrix A by matrix B. Matrixes must be 2 by 2. Result is stored in matrix A. R = [[0,0],[0,0]] R[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] R[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] R[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0] R[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1] copy(A,R) pass def power(A, n): #Fast exponentiation on the fibonacci matrix. copy(F, A) #time: 1 if (n == 1): #time: 1 return power(A, n//2) #time: T[n/2] multiply(A, A) #time: 1 if (n % 2 == 1): #time: 1 multiply(A, F) #time: 1 pass # T[n] = T[n/2] + 5 # 2^k = n => T[2^k] = T[2^k-1] + 5 # T[2^k] = 5k + 2 # T[n] = 5 log(n) + 2 def fib(n): #Gets the n-th term of the Fibonacci sequence in O(log(n)) time. if (n == 0): return 0 if (n == 1): return 1 F = [[1,1],[1,0]] power(F, n) return(F[0][1]) pass def fib2_fake(n): #slower if (n == 0): return 0 if (n == 1): return 1 i = 1; fn = 1 fnn = 1 while (i < n): aux = fnn fnn = fnn + fn fn = aux i = i + 1 return fn def main(): print("Olá, usuário. Esse é o solucionador de fibonacci. Seguem as instruções de uso:") print("Para usar a implementação rapida de fibonacci(n), digite: fib n e aperte enter.") print("Para usar a implementação lenta de fibonacci(n), digite: fake n e aperte enter.") print("O programa imprimirá na tela o resultado da sequência. Você pode pedir outras instruções.") print("Digite qualquer coisa diferente dos comandos acima e aperte enter para terminar o programa.") running = 1 while running: usinput = input() inputlist = usinput.split() if (inputlist[0] == "fib"): print(str(fib(int(inputlist[1])))) elif (inputlist[0] == "fake"): print(str(fib2_fake(int(inputlist[1])))) else: running = 0 pass pass if __name__ == "__main__": main()
print("Enter your name:") somebody = input() # 콘솔 창에서 입력한 값을 somebody에 저장 print("Hi", somebody, "How are you today?")
sexo = input('Informe seu sexo por gentileza: ') if sexo == 'F' or sexo == 'f': print('Voce é do sexo feminino') elif sexo == 'M' or sexo == 'm': print('Voce é do sexo masculino') else: print('Sexo invalido')
print('#################################### M E N U ####################################') print('File Duplo') print('Alcatra') print('Picanha') print('#################################################################################') file_duplo_ate_5kg = 4.90 file_duplo_acima_5kg = 5.80 alcatra_ate_5kg = 5.90 alcatra_acima_5kg = 6.80 picanha_ate_5kg = 6.90 picanha_acima_5kg = 7.80 tipo_carne = input('Qual tipo de carne o senhor deseja: ') if tipo_carne == 'file' or tipo_carne == 'File Duplo' or tipo_carne == 'file duplo' or tipo_carne == 'duplo': quantidade = int(input('Quantos kg voce deseja: ')) if quantidade > 5: preco_file_duplo = quantidade * file_duplo_acima_5kg print(tipo_carne,quantidade,'Valor: ',preco_file_duplo) else: preco_file_duplo = quantidade * file_duplo_ate_5kg print(tipo_carne, quantidade, 'Valor: ', preco_file_duplo) forma_pagamento = input('Qual a forma de pagamento: ') if forma_pagamento =='cartao' or forma_pagamento == 'Cartao': desconto = preco_file_duplo * ( 5 / 100) print('Voce ganhou um desconto de 5% por usar cartao o valor descontado foi de: ',desconto) preco_file_duplo = preco_file_duplo - desconto print('O valor total com desconto é: ',preco_file_duplo) else: print('Voce não teve direito ao desconto') print('Valor total: ',preco_file_duplo) if tipo_carne == 'alcatra' or tipo_carne == 'Alcatra': quantidade = int(input('Quantos kg voce deseja: ')) if quantidade > 5: preco_alcatra = quantidade * alcatra_acima_5kg print(tipo_carne,quantidade,'Valor: ',preco_alcatra) else: preco_alcatra = quantidade * alcatra_ate_5kg print(tipo_carne, quantidade, 'Valor: ', preco_alcatra) forma_pagamento = input('Qual a forma de pagamento: ') if forma_pagamento == 'cartao' or forma_pagamento == 'Cartao': desconto = preco_alcatra * ( 5 / 100) print('Voce ganhou um desconto de 5% por usar cartao o valor descontado foi de: ',desconto) preco_alcatra = preco_alcatra - desconto print('O valor total com desconto é: ',preco_alcatra) else : print('Voce não teve direito ao desconto') print('Valor total: ',preco_alcatra) if tipo_carne == 'Picanha' or tipo_carne == 'picanha': quantidade = int(input('Quantos kg voce deseja: ')) if quantidade > 5: preco_picanha = quantidade * picanha_acima_5kg print(tipo_carne,quantidade,'Valor: ',preco_picanha) elif quantidade < 5: preco_picanha = quantidade * picanha_ate_5kg print(tipo_carne, quantidade, 'Valor: ', preco_picanha) forma_pagamento = input('Qual a forma de pagamento: ') if forma_pagamento == 'Cartao' or forma_pagamento == 'cartao': desconto = preco_picanha * ( 5 / 100) print('Voce ganhou um desconto de 5% por usar cartao o valor descontado foi de: ',desconto) preco = preco_picanha - desconto print('O valor total com desconto é: ',preco) elif forma_pagamento == 'Dinheiro' or forma_pagamento == 'dinheiro': print('Voce não teve direito ao desconto') print('Valor total: ',preco_picanha)
pergunta1 = input('Telefonou para a vitima ?: ') pergunta2 = input('Esteve no local do crime ?: ') pergunta3 = input('Mora perto da vitima ?: ') pergunta4 = input('Devia para a vitima ?: ') pergunta5 = input('ja trabalhou com a vitima ?: ') total = 0 if pergunta1 == 'sim': total = total + 1 if pergunta2 == 'sim': total = total + 1 if pergunta3 == 'sim': total = total + 1 if pergunta4 == 'sim': total = total + 1 if pergunta5 == 'sim': total = total + 1 print(total) if total == 5: print("Assasino") elif total == 4 or total == 3: print('Cumplice') elif total == 2: print('Suspeito') else: print('inocente')
quantidade = 5 numeros = [] soma = 0 for n in range(quantidade): nota = float(input('nota: ')) numeros.append(nota) soma = soma + nota print('Notas: ',numeros) print('Soma das notas: ',soma) media = soma / 5 print('Media: ',media)
valor1 = int(input("Digite o primeiro valor: ")) valor2 = int(input('Digite o segundo valor: ')) soma = valor1 + valor2 print('A soma dos valores é: ',soma)
import math import fractions a = int(input('Digite o valor do a: ')) if a == 0: print('Não é uma equação do segundo grau') else: b = int(input('Digite o valor do b: ')) c = int(input('Digite o valor do c: ')) delta = (b**2) - (4*a*c) print('Delta: ',delta) if delta < 0: print('A equação não possui raizes reais.') elif delta == 0: print('A equação possui apenas uma raiz real') x = (-b + math.sqrt(delta)) / (2 * a) print('O valor de x1 é igual: ',fractions.Fraction(x)) elif delta > 0: print('A equação possui duas raizes reais') x = (-b + math.sqrt(delta)) / (2 * a) x2 = (-b - math.sqrt(delta)) / (2 * a) print('x1: ',x) print('x2: ',x2)
letra = input('Digite uma letra: ') if letra == 'a' or letra == 'e' or letra == 'i' or letra == 'o' or letra == 'u': print('A letra ', letra ,' é uma vogal') elif letra != 'a' or letra != 'e' or letra != 'i' or letra != 'o' or letra != 'u': print('A letra',letra,'é uma consoante')
numero = int(input('Digite um numero: ')) total = 0 total_divisoes = 0 divisores = [] for n in range(1 , numero + 1): if numero % n == 0: total += 1 total_divisoes = total divisores.append(n) if total == 2: print('Foi feito: ',total_divisoes,'divisoes') print('O numero: ',numero,'é primo seus divisores são: ',divisores) else: print('Foi feito: ',total_divisoes,'divisoes') print('O numero: ',numero,'nao é primo e seus divisores sao: ',divisores)
numero = float(input('Digite um numero: ')) if numero == round(numero): print('Inteiro') else: print('Decimal')
import io def q1(): r = range(0,5) l = [i for i in r] l = [[i for i in r] for j in r] print (l) # NB: I had to look this up. I would not have come up with that on my own def q2(): l = [[1,2,3],[4,5,6],[7,8,9]] out = [j for sub in l for j in sub] print (out) def q3(): planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']] out = [p for sub in planets for p in sub if len(p) < 6] print (out) def q4(): original={'Name':'iphone5','Brand':'Apple','Color':'silver'} out = {v:k for k,v in original.items()} print (out) q1() q2() q3() q4()
import unittest from app.models import Article class ArticleTest(unittest.TestCase): ''' Test class to test behaviours of the Article class Args: unittest.TestCase : Test case class that helps create test cases ''' def setUp(self): ''' Set up method to run before each test case ''' self.new_article = Article('the-next-web','PlayStation\'s $30 PS4 gamepad for kids is totally adorable', 'https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/10/PS4-Mini-gamepad-social.jpg', 'Sony\'s teamed up with Hori on its new $30 Mini Wired Gamepad, which is designed for younger PS4 players with smaller hands.', 'https://thenextweb.com/gaming/2017/10/19/playstations-30-ps4-gamepad-for-kids-is-totally-adorable/', '2017-10-19T13:00:00Z') def test_instance(self): ''' Test case to check if self.new_article is an instance of Article ''' self.assertTrue( isinstance( self.new_article, Article ) ) def test_init(self): ''' Test case to check if the Article class is initialised ''' self.assertEqual( self.new_article.source, 'the-next-web') self.assertEqual( self.new_article.title, 'PlayStation\'s $30 PS4 gamepad for kids is totally adorable') self.assertEqual( self.new_article.urlToImage, 'https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/10/PS4-Mini-gamepad-social.jpg') self.assertEqual( self.new_article.description, 'Sony\'s teamed up with Hori on its new $30 Mini Wired Gamepad, which is designed for younger PS4 players with smaller hands.') self.assertEqual( self.new_article.urlToArticle, 'https://thenextweb.com/gaming/2017/10/19/playstations-30-ps4-gamepad-for-kids-is-totally-adorable/') self.assertEqual( self.new_article.publishedAt, '2017-10-19T13:00:00Z') def test_publish_date_format(self): ''' Test case to check if UTC date format is converted to a display-friendly format ''' display_friendly_format = self.new_article.publish_date_format(self.new_article.publishedAt) self.assertEqual( display_friendly_format, '2017-10-19')
#!/usr/bin/env python #-*- coding:utf-8 -*- def pawns_ratio(plansza, kolor): assert kolor in ['W', 'B'] whites, blacks = plansza.count_pawnsWB() if kolor == 'W': return float(whites)/blacks else: return float(blacks)/whites def pawns_difference(plansza, kolor): assert kolor in ['W', 'B'] whites, blacks = plansza.count_pawnsWB() if kolor == 'W': return whites - blacks else: return blacks - whites def pawns_count(plansza, kolor): assert kolor in ['W', 'B'] whites, blacks = plansza.count_pawnsWB() if kolor == 'W': return whites else: return blacks
""" Tahsin Islam Sakif 25 February 2018 CS 293B Homework 3 """ from statistics import * Berkeley = [16,22,16,22,28,33,46,46,48] McDowell = [18,23,23,24,26,15,22,22,28] Mercer = [25,29,14,34,51,37,25,47,38] Raleigh = [22,19,12,45,60,58,37,39,62] def functionAverage(String,list1): average=mean(list1) return (String,average) def functionZScore(zscoredata): zscoreNEW=[] for i in zscoredata: (i-mean(zscoredata)/stdev(zscoredata)) zscoreNEW.append((i-mean(zscoredata))/stdev(zscoredata)) return zscoreNEW def functionYear(String,list2): print(functionAverage(String,list2)) for year in range(0,9): print("In the year:",year+2007) print("The number of deaths is:",list2[year]) print("The z score is:",functionZScore(list2)[year]) def main(): functionYear("Berkeley",Berkeley) functionYear("McDowell",McDowell) functionYear("Mercer",Mercer) functionYear("Raleigh",Raleigh) if __name__== "__main__": main() """ The drug overdoses have generally increased in all of the counties. Some counties such as Raleigh are having more deaths than the other ones. I propose that there should be more awareness to the locals there on the dangers of drug overdose, and have a stricter law to prevent these deaths. Best solution is to make the public more aware of its risks. """
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import abc class MiColeccionIterador(abc.Collection, abc.Iterator): def __init__(self): self.siguiente_valor_a_devolver = 0 def __len__(self): return 3 def __contains__(self, x): return x is "PRIMERO" or x is "SEGUNDO" or x is "TERCERO" def __next__(self): self.siguiente_valor_a_devolver += 1 if self.siguiente_valor_a_devolver == 1: return "PRIMERO" elif self.siguiente_valor_a_devolver == 2: return "SEGUNDO" elif self.siguiente_valor_a_devolver == 3: return "TERCERO" else: raise StopIteration def __iter__(self): self.siguiente_valor_a_devolver = 0 return self if __name__ == "__main__": mi_coleccion_iterador = MiColeccionIterador() print('mi_coleccion_iterador tiene {} elementos'.format(len(mi_coleccion_iterador))) if "ALGO" in mi_coleccion_iterador: print('"ALGO" Existe en mi_coleccion_iterador') else: print('"ALGO" NO existe en mi_coleccion_iterador') if "SEGUNDO" in mi_coleccion_iterador: print('"SEGUNDO" Existe en mi_coleccion_iterador') else: print('"SEGUNDO" NO existe en mi_coleccion_iterador') for valor in mi_coleccion_iterador: print('Elemento de mi_coleccion_iterador: {}'.format(valor))
#!/usr/bin/env python # -*- coding: utf-8 -*- class MisDeportes(object): def __init__(self, listado_deportes=None): if listado_deportes is None: self.listado_deportes = [] else: self.listado_deportes = listado_deportes def add_deporte(self, deporte: str): self.listado_deportes.append(deporte) def __str__(self) -> str: str_con_el_resultado = 'Objeto de deportes: ' for deporte in self.listado_deportes: str_con_el_resultado += "\n * {}".format(deporte) return str_con_el_resultado def __repr__(self) -> str: representacion_interpretable = '{self.__class__.__name__}({self.listado_deportes})'.format(self=self) return representacion_interpretable
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import abc class IteradorIterable(abc.Iterator): def __init__(self): self.siguiente_valor_a_devolver = 0 def __next__(self): self.siguiente_valor_a_devolver += 1 if self.siguiente_valor_a_devolver == 1: return "PRIMERO" elif self.siguiente_valor_a_devolver == 2: return "SEGUNDO" elif self.siguiente_valor_a_devolver == 3: return "TERCERO" else: raise StopIteration def __iter__(self): return self if __name__ == "__main__": mi_iterador_iterable = IteradorIterable() for valor in mi_iterador_iterable: print('Elemento de mi_iterador_iterable: {}'.format(valor))
#!/usr/bin/env python # -*- coding: utf-8 -*- def busca(cosa_a_buscar): listado_cosas = ["boligrafo", "taza", "cuchara"] for cosa in listado_cosas: if cosa == cosa_a_buscar: print("Encontrado") return print("No encontrado") return # El return vacío al final de la declaración de la función se puede omitir if __name__ == "__main__": busca("taza") busca("armario")
from tkinter import* import sys import sqlite3 import tkinter.messagebox class ATM1(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Select Language",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=480,y=150) #========================= BUTTON =================================================================== button1 = Button(self.mOffsets,font=('bold italic',20),text="English",bg="yellow",fg="blue",height=1,width=20,command=CALL2) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="हिन्दी",bg="yellow",fg="blue",height=1,width=20) button2.place(x=1005,y=500) button9 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button9.place(x=1005,y=600) #==============================================enter pin for withdraw===================================================== class ATM2(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() #========================================================================== lblInfo=Label(self.mOffsets ,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets ,font=('arial',40),text="Please Enter Your Pin",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=430,y=150) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets ,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=520,y=320) button1 = Button(self.mOffsets ,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL3) button1.place(x=1005,y=500) button2 = Button(self.mOffsets ,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #===========================================================main menu two===================================================== class ATM3(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('arial',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Select Transaction",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=450,y=150) #========================= BUTTON =================================================================== button1 = Button(self.mOffsets,font=('bold italic',20),text="DEPOSIT",bg="yellow",fg="blue",height=1,width=20,command=CALL16) button1.place(x=30,y=300) button2 = Button(self.mOffsets,font=('bold italic',20),text="TRANSFER",bg="yellow",fg="blue",height=1,width=20,command=CALL14) button2.place(x=30,y=400) button3 = Button(self.mOffsets,font=('bold italic',20),text="PIN CHANGE",bg="yellow",fg="blue",height=1,width=20,command=CALL7) button3.place(x=30,y=500) button4 = Button(self.mOffsets,font=('bold italic',20),text="CHANGE ACC. Detail",bg="yellow",fg="blue",height=1,width=20,command=CALL15) button4.place(x=30,y=600) button5 = Button(self.mOffsets,font=('bold italic',20),text="FAST CASH",bg="yellow",fg="blue",height=1,width=20) button5.place(x=1005,y=300) button6 = Button(self.mOffsets,font=('bold italic',20),text="CASH WITHDRAWAL",bg="yellow",fg="blue",height=1,width=20,command = CALL4) button6.place(x=1005,y=400) button7 = Button(self.mOffsets,font=('bold italic',20),text="BALANCE INQ.",bg="yellow",fg="blue",height=1,width=20,command=CALL11) button7.place(x=1005,y=500) button8 = Button(self.mOffsets,font=('bold italic',20),text="MINI STATEMENT",bg="yellow",fg="blue",height=1,width=20) button8.place(x=1005,y=600) #================================================= Quit Button =================================================== button9 = Button(self.mOffsets,font=('bold italic',20),text="CANCEL",bg="yellow",fg="blue",height=1,width=20,command = exit1) button9.place(x=510,y=600) #=========================================================withdraw current and saving========================================================= class ATM4(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Select Any Option",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=400,y=150) #========================= BUTTON =================================================================== button1 = Button(self.mOffsets,font=('bold italic',20),text="From Current",bg="yellow",fg="blue",height=1,width=20,command = CALL5) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="From Saving",bg="yellow",fg="blue",height=1,width=20,command = CALL5) button2.place(x=1005,y=500) #======================================================withdraw amount============================================================ class ATM5(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY WITHDRAWAL FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=370,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="Deposit Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account10,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=430,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount10,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=430,y=420) button1 = Button(self.mOffsets,font=('bold italic',20),text="Save",bg="yellow",fg="blue",height=1,width=20,command=Update3) button1.place(x=1005,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL6) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #==========================================================withdraw transaction process======================================================== class ATM6(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) #=========================================================pin change process======================================================= class ATM7(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="YOU CAN CHANGE YOUR PIN",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=310,y=150) #========================= BUTTON =================================================================== lblInfo1=Label(self.mOffsets,font=('arial',20),text="Account No. :=",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=400) lblInfo1=Label(self.mOffsets,font=('arial',20),text="New Pin :=",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=500) lblInfo1=Label(self.mOffsets,font=('arial',20),text="Renter :=",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=600) lblInfo1=Label(self.mOffsets,font=('arial',20),text="New Pin ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=650) entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account5,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=320,y=400) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password5,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=320,y=500) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=320,y=600) button1 = Button(self.mOffsets,font=('bold italic',20),text="SAVE",bg="yellow",fg="blue",height=1,width=20,command = Update1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL8) button2.place(x=1005,y=600) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=700) #===================================================pin changed sucessfull============================================================== class ATM8(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Pin Has Changed ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=420,y=150) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Log In With New Pin",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=360,y=280) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #===================================================withdraw process=============================================================== class ATM9(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Enter Account No.",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=130,y=220) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Enter Amount",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=130,y=320) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=720,y=220) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=720,y=320) button1 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL10) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #=======================================================deposite transaction process========================================================== class ATM10(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your amount has been deposited in your account",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=130,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #======================================================balance inquiary process=========================================================== class ATM11(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) lblInfo1=Label(self.mOffsets,font=('arial',40),text="your current balance is :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=330,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #==================================================registration form=============================================================== class ATM12(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="REGISTRATION FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=400,y=150) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',40),text="First Name :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',40),text="Password :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) lblInfo4=Label(self.mOffsets,font=('arial',40),text="Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo4.place(x=50,y=608) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account1,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Firstname1,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password1,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) entry4=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount1,bd=10,insertwidth=8,bg="yellow",justify='left') entry4.place(x=420,y=620) button1 = Button(self.mOffsets,font=('bold italic',20),text="Save",bg="yellow",fg="blue",height=1,width=20,command = Insert) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button2.place(x=1005,y=600) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=700) #========================================================registration successfull========================================================= class ATM13(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',30),text="REGISTRATION SUCCESSFULL",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=385,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Please Again Log In",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=500,y=250) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #==================================================transfer form=============================================================== class ATM14(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY TRANSFER",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=450,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="From Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="To Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',30),text="Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) button1 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #============================================detail change============================================================= class ATM15(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="DETAILED UPDATION FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=300,y=150) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Old Acc. No.:",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',40),text="First Name :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',40),text="Password :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account3,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Firstname3,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password3,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) button1 = Button(self.mOffsets,font=('bold italic',20),text="Save",bg="yellow",fg="blue",height=1,width=20,command = Update) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button2.place(x=1005,y=600) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=700) #=============================================Deposit menu======================================================= class ATM16(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY DEPOSITE FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=370,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="Deposit Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account7,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=430,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount7,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=430,y=420) button1 = Button(self.mOffsets,font=('bold italic',20),text="Save",bg="yellow",fg="blue",height=1,width=20,command=Update2) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command=CALL10) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="No",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #===================================================function call=============================================== def CALL1(): atm = ATM1(root) def CALL2(): atm = ATM2(root) def CALL3(): atm = ATM3(root) def CALL4(): atm = ATM4(root) def CALL5(): atm = ATM5(root) def CALL6(): atm = ATM6(root) def CALL7(): atm = ATM7(root) def CALL8(): atm = ATM8(root) def CALL9(): atm = ATM9(root) def CALL10(): atm = ATM10(root) def CALL11(): atm = ATM11(root) def CALL12(): atm = ATM12(root) def CALL13(): atm = ATM13(root) def CALL14(): atm = ATM14(root) def CALL15(): atm = ATM15(root) def CALL16(): atm = ATM16(root) def CALL17(): atm = ATM17(root) #==============================================================main menu===================================== root = Tk() root.geometry("1400x900+0+0") root.title("STATE BANK OF INDIA") root.configure(bg='blue') #==========================================create table ========================================================= db=sqlite3.connect('ATM.db') cursor=db.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS ATMDATA(AccountNumber TEXT,FirstName TEXT,Password TEXT,Amount TEXT)") db.commit() #========================================insert data in table ========================================================== Account1=StringVar() Firstname1=StringVar() Password1=StringVar() Amount1=StringVar() def Insert(): Account2=Account1.get() Firstname2=Firstname1.get() Password2=Password1.get() Amount2=Amount1.get() ins=sqlite3.connect('ATM.db') with ins: cursor=ins.cursor() cursor.execute('INSERT INTO ATMDATA(AccountNumber,FirstName,Password,Amount) VALUES(?,?,?,?)',( Account2,Firstname2,Password2,Amount2)) db.close() #=======================================================update data in tabble ============================================= Account3=StringVar() Firstname3=StringVar() Password3=StringVar() def Update(): Account4=Account3.get() Firstname4=Firstname3.get() Password4=Password3.get() up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET FirstName = ? ,Password = ? WHERE AccountNumber = ?",(Firstname4,Password4,Account4)) up.commit() #================================================update pin ================================================================== Account5=StringVar() Password5=StringVar() def Update1(): Account6=Account5.get() Password6=Password5.get() up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Password = ? WHERE AccountNumber = ?",(Password6,Account6)) up.commit() #================================================Deposit money ================================================================== Account7=StringVar() Amount7=IntVar() def Update2(): Account8=Account7.get() Amount8=Amount7.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA") for row in cursor.fetchall(): Amount9=int(row[3])+Amount8 up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE AccountNumber = ?",(Amount9,Account8)) up.commit() #================================================Deposit money ================================================================== Account10=StringVar() Amount10=IntVar() def Update3(): Account11=Account10.get() Amount11=Amount10.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA") for row in cursor.fetchall(): Amount12=int(row[3])-Amount11 up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE AccountNumber = ?",(Amount12,Account11)) up.commit() #===================================main menu ==================================================================== def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(root,font=('arial',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(root,font=('arial',40),text="Please Select Banking",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=420,y=150) #========================= BUTTON =================================================================== button1 = Button(root,font=('bold italic',20),text="SERVICES",bg="blue",fg="white",height=1,width=20) button1.place(x=30,y=300) button2 = Button(root,font=('bold italic',20),text="MINI STATEMENT",bg="blue",fg="white",height=1,width=20) button2.place(x=30,y=400) button3 = Button(root,font=('bold italic',20),text="REGISTRATION",bg="blue",fg="white",height=1,width=20,command = CALL12) button3.place(x=30,y=500) button4 = Button(root,font=('bold italic',20),text="QUICK CASH",bg="blue",fg="white",height=1,width=20) button4.place(x=30,y=600) button5 = Button(root,font=('bold italic',20),text="BANKING",bg="blue",fg="white",height=1,width=20,command = CALL1) button5.place(x=1005,y=300) button6 = Button(root,font=('bold italic',20),text="BALANCE INQ.",bg="blue",fg="white",height=1,width=20,command = CALL1) button6.place(x=1005,y=400) button7 = Button(root,font=('bold italic',20),text="TRANSFER",bg="blue",fg="white",height=1,width=20,command = CALL1) button7.place(x=1005,y=500) button8 = Button(root,font=('bold italic',20),text="PIN GENERATION",bg="blue",fg="white",height=1,width=20) button8.place(x=1005,y=600) #================================================= Quit Button =================================================== button9 = Button(root,font=('bold italic',20),text="Cancel",bg="blue",fg="white",height=1,width=20,command = exit1) button9.place(x=510,y=600) root.mainloop()
# ===YOU SHOULD EDIT THIS FUNCTION=== def mean_naive(X): """Compute the mean for a dataset by iterating over the dataset Arguments --------- X: (N, D) ndarray representing the dataset. Returns ------- mean: (D, ) ndarray which is the mean of the dataset. """ N, D = X.shape mean = np.zeros(D) for m in range(D): k=0 for n in range(N): k+=X[n,m] smean=k/N mean[m]=smean return mean # ===YOU SHOULD EDIT THIS FUNCTION=== def cov_naive(X): N, D = X.shape covariance = np.zeros((D, D)) for i in range (D): eDi=sum(X[:,i])/N for j in range (D): eDj=sum(X[:,j])/N m=0 for k in range(N): m+=(X[k,i]-eDi)*(X[k,j]-eDj) co=m/N covariance[i,j]=co return covariance # GRADED FUNCTION: DO NOT EDIT THIS LINE # ===YOU SHOULD EDIT THIS FUNCTION=== def mean(X): """Compute the mean for a dataset Arguments --------- X: (N, D) ndarray representing the dataset. Returns ------- mean: (D, ) ndarray which is the mean of the dataset. """ mean = np.zeros(X.shape[1]) # EDIT THIS mean = np.mean(X, axis=0) return mean # ===YOU SHOULD EDIT THIS FUNCTION=== def cov(X): """Compute the covariance for a dataset Arguments --------- X: (N, D) ndarray representing the dataset. Returns ------- covariance_matrix: (D, D) ndarray which is the covariance matrix of the dataset. """ # It is possible to vectorize our code for computing the covariance, i.e. we do not need to explicitly # iterate over the entire dataset as looping in Python tends to be slow N, D = X.shape covariance_matrix = np.zeros((D, D)) # EDIT THIS Y = np.transpose(X) covariance_matrix = np.cov(Y) return covariance_matrix # GRADED FUNCTION: DO NOT EDIT THIS LINE # ===YOU SHOULD EDIT THIS FUNCTION=== def affine_mean(mean, A, b): """Compute the mean after affine transformation Args: mean: ndarray, the mean vector A, b: affine transformation applied to x Returns: mean vector after affine transformation """ affine_m = A@mean+b return affine_m # ===YOU SHOULD EDIT THIS FUNCTION=== def affine_covariance(S, A, b): v=A@S y=np.transpose(A) affine_cov=v@y return affine_cov
w=int(input()) if (w%2==0 and w!=2) : print('YES') else : print('NO')
str = input() for i in str: if i=='A' or i=='a' or i=='O' or i=='o' or i=='Y' or i=='y' or i=='E' or i=='e' or i=='U' or i=='u' or i=='I' or i=='i' : print("", end='') else : if i > 'a': print(".%c" %i, end='') else : print(".%c" %i.lower(), end='')
#!python #cython: language_level=3, boundscheck=False # CS 4341 Project 2 # Last updated: 9/26/2017 # Chad Underhill, Daniel Kim, Spyridon Antonatos # # Usage: # Contains methods for running the alpha-beta pruning algorithm. import math import time import Evaluation import Board # Depth allowed to run minimax until the evaluation function is used MAX_NODES_VISITED = 10 nodes_visited = 0 MAX_DEPTH = 1 TIME_START = 0 TIME_STOP = 3 # Checks to see if the evaluation function should be used def checkCutOff(currentDepth): global nodes_visited, MAX_NODES_VISITED, MAX_DEPTH, TIME_START, TIME_STOP if (currentDepth >= MAX_DEPTH) or (nodes_visited >= MAX_NODES_VISITED) or (time.time() - TIME_START >= TIME_STOP): #print(time.time() - TIME_START,nodes_visited,currentDepth) return True else: return False # "Max" in the minimax algorithm def maximumValue(state, alpha, beta, depth): global nodes_visited nodes_visited += 1 # Check for terminal states result = state.check_terminal_state() if result: if result == "tie": return 0 else: return float(result) # Check for time to use evaluation function if checkCutOff(depth): return Evaluation.evaluationFunction(state)[0] # Maximize #state.print_board() value = -math.inf for child in state.get_children(): value = max(value, minimumValue(child, alpha, beta, depth+1)) if value >= beta: return value alpha = max(alpha, value) return value # "Min" in the minimax algorithm def minimumValue(state, alpha, beta, depth): global nodes_visited nodes_visited += 1 # Check for terminal states result = state.check_terminal_state() if result: if result == "tie": return 0 else: return float(result) # Check for time to use evaluation function if checkCutOff(depth): return Evaluation.evaluationFunction(state)[0] # Minimize #state.print_board() value = math.inf for child in state.get_children(): value = min(value, maximumValue(child, alpha, beta, depth+1)) if value <= alpha: return value beta = min(beta, value) return value # Minimax algorithm with alpha-beta pruning def minimaxABPruning(gameBoard): global TIME_START, nodes_visited nodes_visited = 0 TIME_START = time.time() # Current player player = gameBoard.color_turn # Make second move #if (gameBoard.turns == 1 and # gameBoard.board["H8"].color != gameBoard.our_color and gameBoard.color_turn == gameBoard.our_color): # Replace middle piece # gameBoard.last_move = ("H","8")#board["H8"].color = gameBoard.color_turn # return gameBoard #MOVE # if gameBoard.turns == 0 and gameBoard.color_turn == gameBoard.our_color: # gameBoard.make_move("H","8") # Maximize first alpha = -math.inf beta = math.inf children = gameBoard.get_children() bestMove = None for child in children: # Call minimumValue() to start the recursion value = minimumValue(child, alpha, beta, 1) if value > alpha: alpha = value bestMove = child return bestMove
#!python #cython: language_level=3, boundscheck=False # CS 4341 Project 2 # Last updated: 9/26/2017 # Chad Underhill, Daniel Kim, Spyridon Antonatos # Based on the theory described here: http://www.renju.nu/wp-content/uploads/sites/46/2016/09/Go-Moku.pdf """ Functionality we need from Board: size: the size of the board (x or y, should be square) validMove: check if proposed move is valid? getTurn: get the current turn from the board (black or white) getNot: get the opposite of the current turn from the board) connect: Requirements to win a game (how many in a row do we need?) onBoard: Returns true if position is within board black: List of all of black's pieces white: List of all of white's pieces """ from queue import * import Board as b import time import random def firstMove(board): """ The most logical first move is dead-center of the board, so the AI should do just this. @param: board The playing board. @returns: A tuple containing the coordinates of the move. """ x = board.size / 2 return (x, x) def secondMove(board): """ The most strategic second move is diagonal-adjacent to the first placed tile. This move is more strategic if it's diagonal into the larger area of the board, if possible @param: board The playing board. @returns: A tuple containing the coordinates of the move. """ # Get position of first tile (y1, x1) = board.black[0] if y1 <= board.size / 2: y2 = 1 else: y2 = -1 if x1 <= board.size / 2: x2 = 1 else: x2 = -1 return (y1 + y2, x1 + x2) def randomMove(board): """ Randomly chooses a location to place the tile @param: board The playing board. @returns: A tuple containing the coordinates of the move. """ go = True while go: y = random.randint(0, board.size - 1) x = random.randint(0, board.size - 1) go = not board.validMove((y, x)) return (y, x) def evalFunction(board, position, mode): """ Evaluates the importance of a given position on the board, based on the number of ways the board can connect if a tile is placed there. The position is weighted exponentially based on the number of pieces that can be connected from that position. The mode controls whether the player is "on the attack" or "defending" (think Min/Max?), where connections are weighted heavier in attack mode - thus the function prefers taking a winning move in "attack" mode over taking a move that blocks another players winning move. @param: board The playing board. @param: position Coordinates of a location on the board. @param: mode Positional strategy. True if "attack", false if "defend". @returns: The importance/strategic value of the position. """ (x0, y0) = position evaluation = 0 opts = ((1, 0), (0, 1), (1, 1), (1, -1)) # Determine how we're weighing the evaluation (for attack or defend) color = board.our_color if color == "white": not_color = "black" else: not_color = "white" #print("Color: " + color + ", Not Color: " + not_color) # Evaluate all neighboring nodes of current position for pair in opts: # Establish the position and instantiate the pathlist (x1, y1) = pair pathlist = ["."] for j in (1, -1): for i in range(1, board.connect): # Determine new coordinates to check for potential impact on position's value y2 = y0 + y1 * i * j x2 = x0 + x1 * i * j x_ol = x2 + x1 * j y_ol = y2 + y1 * j #print("newCoords: " + str(y2) + " " + str(x2) + " " + str(y_ol) + " " + str(x_ol)) """ Check if the projected position is not on the board, is already taken by the opponent, or if move would form an overline. If yes, then break. Otherwise, check to see where the move is added to the list of paths """ if (not board.cell_exists(x2, y2) or board.get_cell(x2, y2).color == not_color) or \ (i + 1 == board.connect and board.cell_exists(x_ol, y_ol) and board.get_cell(x_ol, y_ol).color == color): break elif j > 0: # Insert at back of list if right of position pathlist.append(board.get_cell(x2, y2).color) elif j < 0: # Insert at front of list if left of position pathlist.insert(0, board.get_cell(x2, y2).color) # Determine the number of connections that can be formed at the given position paths_num = len(pathlist) - board.connect + 1 # Determine the total consecutive score for the given position if paths_num > 0: #print("here5" + str(paths_num)) for i in range(paths_num): if mode: consec = pathlist[i:i + board.connect].count(color) else: consec = pathlist[i:i + board.connect].count(not_color) if consec != board.connect - 1: if consec != 0: evaluation += 5**consec else: if mode: evaluation += 100000 #print(color + " " + str(mode)) else: evaluation += 1000 #print("evaluation: " + str(evaluation)) return evaluation def evaluatePosition(board, position): """ Evaluates the net value of a given position on the board by finding summing the position's value to both the player and their opponent. By choosing the position with the most value to the player and the most value to the opponent, we are effectively making the move with the greatest offensive and defensive value, thus making it the most strategic. An invalid move is returned with an importance value of 0. @param: board The playing board. @param: position Coordinates of a location on the board. @returns: The importance/strategic value of the position. """ (x, y) = position if board.cell_exists(x, y): result = evalFunction(board, position, True) + \ evalFunction(board, position, False) #print("RESULT: " + str(result)) return result else: return 0 def attackArea(initPair, connect): """ Determines the coordinates of connect spaces at a position. @param: pair The starting coordinates in the format (y, x). @param: connect Connect size. @returns: A list containing coordinates of connect spaces. """ area = [] opts = ((1, 0), (0, 1), (1, 1), (1, -1)) (x, y) = initPair for pair in opts: (x1, y1) = pair for s in (1, -1): for i in range(1, connect): x2 = x + x1 * i * s y2 = y + y1 * i * s area.append((x2, y2)) return area def topMoves(board, limit): """ Determines a limited amount of "top moves" based on the evaluatePosition function. @param: board The playing board. @param: limit The number of "top" moves to return. @returns: A map of the top moves available along with their values as the key. """ spots = set() top_list = [] top_queue = PriorityQueue() # For each piece on the board # TODO: This should be all I need #board.print_board() #print(board.get_filled_coordinates()) for n in board.get_filled_coordinates(): # For each potential connect space within range for m in attackArea(n, board.connect): (x, y) = m # If the connect space is on the board, add to list of potential spots if board.cell_exists(x, y) and m not in board.get_filled_coordinates(): spots.add(m) trackingList = [] # Evaluate potential of each spot, and add to queue for p in spots: top_queue.put((evaluatePosition(board, p) * (-1), p)) trackingList.append(str((evaluatePosition(board, p) * (-1), p))) for z in range(limit): top_list.append(top_queue.get()) #print("Queue: " + str(trackingList)) for record in top_list: #print(str(record)) pass # return map(lambda (x, y): (-x, y), top_list) return top_list[0] def evaluationFunction(board): return topMoves(board, 1)