text
stringlengths
37
1.41M
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" O(n*n)。对于每一个字符,以之作为中间元素往左右寻找。 注意 1.处理奇偶两种模式:aba, abba 2.奇偶两种情况都得算,然后做比较才能得出longest。因为对于caaaa,奇数的结果是aaa,偶数的结果是aaaa code: Version 0: 设置一个self.longest全局变量,直接在find_palindrom函数中对self.longest取最大值 class Solution(object): def __init__(self): self.longest = '' def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' if len(s) == 2 and s[0] != s[1]: return s[0] for middle in range(len(s)): sub = self.find_palindrom(s, middle, middle + 1) sub = self.find_palindrom(s, middle, middle) return self.longest def find_palindrom(self, s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 # left += 1 # if len(self.longest) < right - left: # self.longest = s[left:right] if len(self.longest) < right - left - 1: self.longest = s[left + 1:right] Version 1: 最常规的方法 class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' longest = '' for middle in range(len(s)): sub = self.find_palindrom(s, middle, middle + 1) if len(longest) < len(sub): longest = sub sub = self.find_palindrom(s, middle, middle) if len(longest) < len(sub): longest = sub return longest def find_palindrom(self, s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right]
class Counter(dict): def __missing__(self, key): return 0 def anagram(str1='', str2=''): str1 = str1.replace(' ','').lower() str2 = str2.replace(' ','').lower() if len(str1) != len(str2): return False counter = Counter() for el in str1: counter[el] += 1 for el in str2: counter[el] -= 1 for el in counter.values(): if el != 0: return False return True print(' ab c'.replace(" ", '').center(5,('_'))) print(anagram('lIsten', 'silent'))
l = list(range(1, 100)) for a in l: count = 0 for i in range(2, (a // 2 +1)): if (a % i == 0): count = count + 1 break if(count ==0 and a != 1): print("Prime Number is: ", a)
#! /usr/bin/env python3 print("Hello, World") name = input("Who are you? ") print("Indeed, {}.".format(name))
def recursion(num): if num==1: return num else: return num*recursion(num-1) Number=int(input("Enter the number to find Recurdion:")) #result=recursion(Number) result=recursion(Number) print("recursion factorial is ", result)
num1=int(input('Digite o primeiro número: ')); num2=int(input('Digite o segundo número: ')); print('Antes %d' %num1, 'e %d' %num2); num1, num2 = num2, num1; print('Depois %d' %num1, 'e %d' %num2);
nume=int(input('Digite um valor inteiro maior que 0: ')) if nume>0: den=1 num=1 while num<=nume: print(' %d/%d '%(num,den), end='') num+=1 den+=2 else: print('Valor Inválido')
custo = int (input ('Digite o custo de fábrica do carro: ')); distri = custo * 32 / 100; impos = custo * 41 / 100; result = custo + distri + impos; print ('O custo é igual a %d' %result);
num1=int(input('Digite o número: ')); result=num1+1; result2=result+1; result3=result2+1; print('Os números são %d' %result, ', %d' %result2, 'e %d' %result3)
'''Sistema para acréscimo de nota Conforme combinado com os estudantes: -Aluno com nota azul no trabalho recebe um ponto na média -Aluno com nota vermelha no trabalho perde 0,5 ponto na prova mensal -Com a média azul sendo par o aluno recebe uma caneta azul de prêmio, caso seja ímpar recebe uma caneta preta.''' print('Sistema para acréscimo de nota') p1=float(input('Entre com a nota da prova mensal: ')); p2=float(input('Entre com a nota da prova semestral: ')); trab=float(input('Entre com a nota do trabalho: ')); media=((p1*3.0)+(p2*4.5)+(trab*2.5))/10 premio=media%2.00 if p1>=0 and p1<=10.00 and p2>=0 and p2<=10.00 and trab>=0 and trab<=10.00: if trab>=6.00 and media!=10.00: media+=1 if media>=10: media=10 print('A média do aluno é: %.2f' %media) if media>=6.00: if premio==0: print('Aluno ganha caneta azul') else: print('Aluno ganha caneta preta') else: print('Aluno não ganha prêmio') elif trab<=6.00: p1=p1-0.5 print('A média do aluno é: %.2f' %media) if media>=6.00: if premio==0: print('Aluno ganha caneta azul') else: print('Aluno ganha caneta preta') else: print('Aluno não ganha prêmio') else: print('Os valores das notas são inválidos!')
cont = 1 neg = 0 while cont <= 5: num=int(input('Escreva um valor: ')) if num<0: print('O número %d' %num, ' é negativo') neg = neg + 1 cont=cont+1 print('A quantidade de nº negativos é %d' %neg) print('Fim do programa')
num=[0]*5 i=0 while (i<5): num[i]=int(input('Digite um valor: ')) i=i+1 impar=num[i]%2 i=0 if impar!=0: result=impar print(result)
import pandas as pd import numpy as np import matplotlib.pyplot as plt import mglearn from pandas.plotting import scatter_matrix from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # this initiate the class KNeighborsClassifier so we can use the prediction model from sklearn.neighbors import KNeighborsClassifier # getting the data and printing some info iris_dataset = load_iris() print("Keys of iris_dataset: \n{}".format(iris_dataset.keys())) print("Type of target: {}".format(type(iris_dataset['target']))) # splitting the iris_dataset in train and test # X mean the data points while y mean the lables of the data points X_train, X_test, y_train, y_test = train_test_split( iris_dataset['data'], iris_dataset['target'], random_state=0) # create dataframe from data in X_train # label the columns using the strings in iris_dataset.feature_names iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names) # create a scatter matrix from the dataframe, color by y_train grr = scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins': 20}, s=60, alpha=.8, cmap=mglearn.cm3) plt.show() # Initiate the class KNeighborsClassifier with one neighbor for searching knn = KNeighborsClassifier(n_neighbors=1) # Add the training data to the model with the function fit knn.fit(X_train, y_train) # print(knn) # Suppose we found an iris with the following measurements: 5, 2.9, 1 and 0.2. apply the knn to the data to get # iris variation # First convert de data to a shape so the knn can read. For the conversion we use a numpy array. This is a matrix with # one row so we use two square brackets X_new = np.array([[5, 2.9, 1, 0.2]]) print("X_new.shape: {}".format(X_new.shape)) # We use the function "prediction" to infer the iris variation from X_new prediction = knn.predict(X_new) print("Prediction: {}".format(prediction)) print("Predicted target name: {}".format( iris_dataset['target_names'][prediction])) # For testing our model we use the X_test shape. Since we apply the "predict" function to knn, the knn object saves the # predictions results y_prediction = knn.predict(X_test) # this are the predictions from the X_test print("Test set predictions:\n {}".format(y_prediction)) # Now we calculate the percentage of accurate predictions print("Test set score: {:.2f}".format(np.mean(y_prediction == y_test))) # A similar way to get the percentage of accurate predictions print("Test set score: {:.2f}".format(knn.score(X_test, y_test)))
'''Extract a structured data set from a social media of your choice. For example, you might have user_ID associated with forum_ID. Use relational algebra to extract a social network (or forum network) from your structured data. Create a visualization of your extracted network. What observations do you have in regards to the network structure of your data? Create a network using authors of comments from subreddits''' import praw from igraph import * def getCommentAuthors(r, authors, subreddits, authorCount): for subredditName in subreddits: subreddit = r.subreddit(subredditName) for post in subreddit.comments(limit=authorCount): if post.author and post.author.name: author = post.author.name if author in authors: if subreddit.display_name not in authors[author]['subreddits']: authors[author]['subreddits'].append(subreddit.display_name) else: authors[author] = {'subreddits': [subreddit.display_name]} def formatGraph(g, authors, subreddits): authorList = list(authors.keys()) labels = subreddits + ['' for x in range(len(authorList))] g.vs['label'] = labels colors = ['teal' for x in range(len(subreddits))] + ['purple' for x in range(len(authors.keys()))] g.vs['color'] = colors addEdges(g, authorList, authors, subreddits) def addEdges(g, authorList, authors, subreddits): for i in range(len(authorList)): author = authorList[i] authorSubreddits = authors[author]['subreddits'] vertexNumber = i + len(subreddits) subredditNumbers = [subreddits.index(s) for s in authorSubreddits] for subredditNumber in subredditNumbers: g.add_edge(vertexNumber, subredditNumber) def createGraph(authors, subreddits): g = Graph() g.add_vertices(len(authors) + len(subreddits)) formatGraph(g, authors, subreddits) plot(g) def main(): r = praw.Reddit(client_id='1RmB7ChqHgjuZw', client_secret='xl04Tf2edeM6k_0hmnQrWFdmvrs', user_agent='me') authors = {} authorCount = 50 subreddits = ['dance', 'ballet', 'dancemoms', 'dancingwiththestars', 'worldofdance', 'thebachelor'] getCommentAuthors(r, authors, subreddits, authorCount) createGraph(authors, subreddits) main()
# all the class logic class Car: """ Class car props - registrationNumber(str), color(str), slotNumber(int) methods - getter for registrationNumber and color. getter and setter for slotNumber. """ def __init__(self,registrationNumber,color): """ constructor to initialize registration and color of car arguments- <registrationNumber>,<color> """ self.registrationNumber = registrationNumber self.color = color # car slotNuber is initialze with None, to be later updated when car is parked self.slotNumber = None def get_registration_number(self): """ getter for registration number """ return self.registrationNumber def get_color(self): """ getter for color """ return self.color def set_slot(self,slot): """ setter car slot argument - <slot> """ self.slotNumber = slot def get_slot(self): """ getter car slot""" return self.slotNumber class ParkingLot: """ class Parking lot props - carsCount(int), slots(dict) . slots structure{1:car_object_1,2:car_object_2, 3: None, 4: NOne} methods - getters carsCount and slots, increment and decrement carsCount, setter for slots """ def __init__(self,n): """ constructore to create slots of size n argument - <n>(int) """ self.carsCount = 0 # initialize slots as key value pair with key as slot number and value as None, later to be updated with car object self.slots = dict() for i in range(1,int(n+1)): self.slots[i]=None def get_cars_count(self): """ getter for parked cars count""" return self.carsCount def get_slots(self): """ getter for slots""" return self.slots def increment_cars_count(self): """ increase parked cars count """ self.carsCount += 1 def decrement_cars_count(self): """ decrement parked cars count """ self.carsCount -= 1 def set_slots(self,slot,car): """ setter for slots arguments - slot(int), car(object of type Car) """ self.slots[slot]=car def create_parking_lot(n): """ create a parking lot object with n slots arguments - <n>(str) """ # valid n is digit if n is not None and n.isdigit(): parkingLot = ParkingLot(int(n)) print('Created a parking lot with {} slots'.format(n)) return parkingLot else: print('slot size sould be an integer') return None def parking_available(parkingLot): """ check if parking lot is full or not. returns boolean argument - <parkingLot> (object) """ return parkingLot.get_cars_count() < len(parkingLot.get_slots()) def registration_number_is_repeated(parkingLot,registrationNumber): """ check for duplicate registration number. retun boolean arguments- <parkingLot>(object),<registrationNumber>(str) """ slots = parkingLot.get_slots() for i in slots.keys(): if slots[i] is not None: if slots[i].registrationNumber == registrationNumber: return True return False def park_car(parkingLot,registrationNumber,color): """park a car to the slot of parkingLot arguments - <parkingLot> (object), <registrationNumber>(str), <color>(str) return True if car is parked, else return false """ # check if parking lot is defined if parkingLot: # check if parking lot has available space if parking_available(parkingLot): # check for duplicate registrationNumber. if not registration_number_is_repeated(parkingLot,registrationNumber): slots = parkingLot.get_slots() for i in slots.keys(): if slots[i] is None: # create new car object car = Car(registrationNumber,color) car.set_slot(i) parkingLot.set_slots(i,car) parkingLot.increment_cars_count() print('Allocated slot number: {}'.format(i)) return True else: print("Sorry, this car is already parked") return False else: print('Sorry, parking lot is full') return False else: print('sorry, parking lot not defined') return False def leave_parking(parkingLot,slot): """ car is checking out of parking so make the slot empty arguments - <parkingLot>(object), <slot>(str) """ result = "" if parkingLot: if slot.isdigit(): slots = parkingLot.get_slots() slot = int(slot) if slot not in slots.keys(): result = "Slot number not in parking lot" elif slots[slot] is not None: parkingLot.set_slots(slot,None) parkingLot.decrement_cars_count() result = 'Slot number ' + str(slot) + ' is free' else: result = 'Slot is already empty' else: result = 'Slot number should be a digit' else: result = 'sorry, parking lot not defined' return result def status(parkingLot): """ returns status of the parkingLot with slot no., registration no., color. """ result = '' if parkingLot: result = "Slot No. Registration No Colour\n" slots = parkingLot.get_slots() for key in slots.keys(): if slots[key] is not None: result += str(key) + " " + slots[key].registrationNumber + " " + slots[key].color + '\n' else: result = "sorry, parking lot not defined" return result def get_registration_numbers_by_color(parkingLot,color): """ returns all the cars' registration number of given color arguments - <parkingLot>(object), <color>(string) """ result = "" isPresent = False if parkingLot: slots = parkingLot.get_slots() for key in slots: if slots[key] is not None: if slots[key].get_color() == color: isPresent = True if len(result)>0: result += ', ' + slots[key].get_registration_number() else: result = slots[key].get_registration_number() else: result = "sorry, parking lot not defined" if not isPresent: result = "Not found" return result def get_slot_numbers_by_color(parkingLot,color): """ returns all the cars' slot number of given color arguments - <parkingLot>(object), <color>(string) """ result = "" isPresent = False if parkingLot: slots = parkingLot.get_slots() for key in slots: if slots[key] is not None: if slots[key].get_color() == color: isPresent = True if len(result)>0: result += ', ' + str(slots[key].get_slot()) else: result = str(slots[key].get_slot()) else: result = "sorry, parking lot not defined" if not isPresent: result = "Not found" return result def get_slot_number_for_registration_number(parkingLot,registrationNumber): """ returns cars' slot number of given registrationNnumber arguments - <parkingLot>(object), <registrationNumber>(string) """ result = "" isPresent = False if parkingLot: slots = parkingLot.get_slots() for key in slots: if slots[key] is not None: if slots[key].get_registration_number() == registrationNumber: isPresent = True result = str(slots[key].get_slot()) else: result = "sorry, parking lot not defined" if not isPresent: result = "Not found" return result
#!/usr/bin/python nume=input ("ingrese dia de la semana: ") dias = {1: "Domingo", 2: "Lunes", 3: "Martes", 4: "Miercoles", 5: "Jueves", 6: "Viernes", 7:"Sabado"} if (nume) <= 7: dia= dias [nume] print "El dia es: %s" % (dia) else: print "El numero %s no es valido" % (nume)
#everytime a computation is correctly executed, a .txt file is created #everytime this script runs, it overrides the previous .txt files import json from calculator import Calculator1 if __name__ == "__main__": calc = Calculator1("calculator_1"); # op = Operation("operation_1") n = 1 # JSON_outputn.txt while True: print "Please select an operation:" print "add" print "sub" print "mul" print "div" print "Type 'exit' to close your calculator!" op = raw_input("---->") if op == "exit": print "Bye" break if op == "add" or op == "sub" or op == "mul" or op == "div": print "Great choice! Choose 2 numbers: " NaD = 1 # Not a Digit: we assume that the user is a rascal while NaD: op1 = raw_input("first number: ") op2 = raw_input("second number: ") if op1.replace('.','',1).isdigit() and op2.replace('.','',1).isdigit(): op1 = float(op1) op2 = float(op2) NaD = 0 else: print "That was not a number. Try again" if op == "add": res = calc.add(op1, op2) if op == "sub": res = calc.sub(op1, op2) if op == "mul": res = calc.mul(op1, op2) if op == "div": if op2 == 0: while op2 == 0: print "WARNING: second number can not be zero. Try another number: " op2 = float(raw_input("second number: ")) res = calc.div(op1, op2) print op1, op, op2 print "The result is: ", res s = str(n) filename = "JSON_output" + s + ".txt" fp = open(filename, 'w') fp.truncate() JSON_obj = {"operation": op,"operator1": op1,"operator2": op2, "result": res} JSON_string = json.dumps(JSON_obj) fp.write(JSON_string) fp.close() n = n+1 else: print "Please, select a proper operation"
# Ліпше стилізувати словники наступним чином # це дозволить ліпше сприймати інформацію names = { 'Taras':'Taras Palagnuk', 'Nazar':'Nazar Gardienko', 'Andrey':'Andrey Myzik', 'Vlad':'Vlad Kulcziskiy', 'Franc':'Franc Gaur' } # бажано старатися мінімізувати логічні вкладення і розбивати їх на блоки # while можна застосувати для очікування введення даних # пропоную вивести код наступним чином: # за необхідності, користувач запустить програму ще раз # 1 - виводимо список імен # при цьому використання format це чудова ідея for item in names.keys(): print('Enter this name {0} for look their full names'.format(item)) # 2 - отримуємо ім"я користувача print('For start enter key \'s\' and for enter key \'e\'') name = input('Please enter the short name: ') # 3 - шукаємо користувача та видаємо результат if name in names: print('Full name {0}'.format(names[name])) else: print('Hello strange. I do not familiar with you.') value = True while value: print('For start enter key \'s\' and for enter key \'e\'') #comand -> command comand = input('Enter key s for start') if comand == 's': name = input('Please enter the short name: ') if name in names: print('Full name {0}'.format(names[name])) else: print('Hello strange. I do not familiar with you.') elif comand == 'e': print('End of the programe') value = False
import pickle def main(): ## Display the data for an individual country. nations = getDictionary("UNdict.dat") nation = inputNameOfNation(nations) displayData(nations, nation) def getDictionary(fileName): infile = open(fileName, 'rb') nations = pickle.load(infile) infile.close() return nations def inputNameOfNation(nations): nation = input("Enter the name of a UN member nation: ") while nation not in nations: print("Not a member of the UN. Try again.") nation = input("Enter the name of a UN member nation: ") return nation def displayData(nations, nation): print("Continent:", nations[nation]["cont"]) print("Population:", nations[nation]["popl"], "million people") print("Area:", nations[nation]["area"], "square miles") main()
def main(): winnerslist=getlistfromfile("Rosebowl.txt") wins=creatfreqdict(winnerslist) displaywinners(wins) def getlistfromfile(filename): infile=open(filename) winnerslist=[line.rstrip() for line in infile] return winnerslist def creatfreqdict(winnerslist): wins={} for winner in winnerslist: wins[winner]=0 for winner in winnerslist: wins[winner]+=1 return wins def displaywinners(wins): print("Teams with four or more\n Rose Bowl wins as of 2014:") winnersslist=[(winner,wins[winner]) for winner in wins if wins[winner]>=4] winnersslist.sort(key= lambda x: x[1],reverse=True) print (winnersslist) for item in winnersslist: print(" ",item[0],":",item[1]) main()
import requests from bs4 import BeautifulSoup import csv #Here in URL we can use any link of website for copy of that website table data. url = "https://www.website.com" agent = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'} page = requests.get(url, headers=agent) htmlContent = page.content soup = BeautifulSoup(htmlContent, 'html5lib') spacification = soup.prettify() #heading = soup.find('h2') #print(heading.prettify()) filename = 'filename.csv' csv_writer = csv.writer(open(filename,'w')) #run a for loop to extract the data and store it in csv file for tr in soup.find_all('tr'): print(tr) data = [] #for extracting the table heading will execute only once for th in tr.find_all('th'): data.append(th.text) print(th) if data: print("inserting headers:{}".format(','.join(data))) csv_writer.writerow(data) continue #for scraping the actual table data values for td in tr.find_all('td'): data.append(td.text.strip()) if data: print("inserting table data:{}".format(','.join(data))) csv_writer.writerow(data)
#interactive python program for converting every letter after a fullstop and every starting letter into uppercase letter #the statement is entered by the user sentence = input("Enter the statement:") sen_list=list(sentence) sen_list_final=[] for i in range(len(sen_list)): #checking and conversion to upper case letter if (i==0): tmp=sen_list[i].upper() sen_list_final.append(tmp) elif (sen_list[i-1]=="."): tmp=sen_list[i].upper() sen_list_final.append(tmp) else: sen_list_final.append(sen_list[i]) for i in sen_list_final: print(i , end="")
#!/usr/bin/env python # Steven Phillips / elimisteve # 2015.07.16 import collections import math import random import exphil def borda(prefs): ''' prefs should be a tuple of tuples indicating preferences. E.g., (('A', 'B', 'C'), ('A', 'C', 'B'), ('C', 'B', 'A')) TODO(elimisteve): Handle ties, like ('A', ('B', 'C')) or perhaps ('A', {'B', 'C'}) means that A is preferred to B and C, but neither B nor C is preferred to the other. NOTE(elimisteve): Supposedly always spits out an ordering, unlike Condorcet (as per MathPhil lecture 7-1) Violates Independence of Irrelevant Alternatives ''' # assert len(pairs) == math.factorial(numvoters)/2 if not prefs: return None # If only 1 person voted, the first person's favorite candidate is # the winner if len(prefs) == 1: return prefs[0][0] assert len(prefs) > 1 vote_totals = collections.defaultdict(int) # Tally votes for each candidate. Each time a candidate is # preferred over another one, add 1 to its vote total. # # (This is equivalent to, but simpler to implement than, assigning # points based upon ordering; those point assignments are # mathematically identical to the sum of the number of opponents # beaten by each candidate according to each voter, which is how # this algorithm is implemented below.) # # Also track the candidate with the most votes with `winners`. winners = set() max_votes = 0 for vote in prefs: for left_ndx in xrange(len(vote)): for _ in vote[left_ndx+1:]: # left candidate l_candidate = vote[left_ndx] vote_totals[l_candidate] += 1 # Keep track of who's winning candidate_total = vote_totals[l_candidate] if candidate_total == max_votes: winners.add(l_candidate) elif candidate_total > max_votes: winners = set([l_candidate]) max_votes = candidate_total if len(winners) == 1: return winners.pop() # Multiple winners return frozenset(winners) def condorcet(prefs): ''' Pair-wise comparison of all candidates Violates Universal Domain ''' vote_totals = collections.defaultdict(int) for vote in prefs: for left_ndx in xrange(len(vote)): for right in vote[left_ndx+1:]: left = vote[left_ndx] vote_totals[(left, right)] += 1 # # Detect winner(s) # winners = set() # max_votes = 0 # TODO(elimisteve): Detect cycles # The winner is the one that defeats all other candidates in a # pair-wise comparison, unless vote_totals[A] == vote_totals[B] # and A and B each beat all other candidates. # Only bother comparing (A, B), not (B, A); that's wasteful # "There's a cycle => Transitivity was violated". So check for # transitivity violations to check for cycles? # When detecting cycles, remember that there could be one option # as a winner and a cycle between the remaining options! # FIXME(elimisteve): For now, assume there is either 1 winner, or a tie # between all candidates candidates = prefs[0] for c in candidates: other_candidates = [other for other in candidates if other != c] if all(vote_totals[(c, other)] > vote_totals[(other, c)] for other in other_candidates): # c beat all others return c # To repeat... # FIXME(elimisteve): For now, assume there is either 1 winner, or a tie # between all candidates return frozenset(candidates) # if len(winners) == 1: # return winners.pop() # # Multiple winners # return winners def approval_n(prefs, top_n): ''' Approval Voting. Voters state their preferences, then we ignore all but their favorite top_n candidates and see who gets more votes, ignoring the ordering of those top_n candidates and just counting how many times a candidate shows up in the top_n (0 or 1 times per voter). Assumes every voter states their opinion on every candidate running. Violates Universal Domain (right? Since someone's first n choices could be swapped and that won't affect the outcome?). ''' winners = set() max_votes = 0 vote_totals = collections.defaultdict(int) for pref in prefs: for candidate in pref[:top_n]: vote_totals[candidate] += 1 # Keep track of who's winning candidate_total = vote_totals[candidate] if candidate_total == max_votes: winners.add(candidate) elif candidate_total > max_votes: winners = set([candidate]) max_votes = candidate_total if len(winners) == 1: return winners.pop() # Multiple winners return frozenset(winners) def approval_2(prefs): return approval_n(prefs, 2) def approval_3(prefs): return approval_n(prefs, 3) def majority(prefs): ''' Which candidate is the first choice of the most voters? ''' # Majority voting is a special case of approval voting, where # voters only approve of their top 1 favorite candidate. return approval_n(prefs, 1) all_theories = ( borda, condorcet, approval_2, approval_3, majority, ) def randomly(prefs): ''' Randomly choose a candidate among those included in the first voter's preferences. Assumes the first voter states his/her opinion on every candidate. ''' candidates = prefs[0] return random.choice[candidates] ## ## When in doubt, go meta ## def metatheory_simple(prefs, theories=all_theories): ''' Which candidate do most theories consider to be the winner? ''' borda_winner = borda(prefs) condorcet_winner = condorcet(prefs) approval2_winner = approval_2(prefs) approval3_winner = approval_3(prefs) majority_winner = majority(prefs) winners = ( tuple([borda_winner]), tuple([condorcet_winner]), tuple([approval2_winner]), tuple([approval3_winner]), tuple([majority_winner]), ) return majority(winners) # def metatheory_approval_n(prefs, top_n_candidates, top_n_theories, weighers, theories=all_theories): # theories if __name__ == '__main__': all_prefs = [] # A prefs1 = ( ('A', 'B', 'C'), ('A', 'B', 'C'), ('A', 'B', 'C'), ) all_prefs.append(prefs1) # Usually A prefs2 = ( ('A', 'B', 'C'), ('B', 'A', 'C'), ('C', 'A', 'B'), ) all_prefs.append(prefs2) # No preference prefs3 = ( ('A', 'B', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ) all_prefs.append(prefs3) # D borda-helps A prefs4 = ( ('A', 'D', 'B', 'C'), ('B', 'C', 'A', 'D'), ('C', 'A', 'D', 'B'), ) all_prefs.append(prefs4) # A is majority winner & condorcet loser; B is borda winner prefs5 = ( ('A', 'B', 'C', 'D'), ('A', 'B', 'C', 'D'), ('B', 'C', 'D', 'A'), ('D', 'B', 'C', 'A'), ('C', 'D', 'B', 'A'), ) all_prefs.append(prefs5) # dict[prefs] -> dict[theory] -> winner(s) results = collections.defaultdict(dict) for prefs in all_prefs: print "\n\n\nVotes:", prefs print for theory in all_theories: winners = theory(prefs) results[prefs][theory.func_name] = winners print theory.func_name, ' \t', winners # Compare each individual theory's computed winners with those # from metatheory_simple, which computes the most common winner # among all the other (non-meta) theories of voting. print "\n\n\nWhich theory agrees with a majority of the other theories" + \ " most frequently (regarding the winners of the above elections)?\n" agreement_with_most_theories = collections.defaultdict(int) for prefs in results: metatheory_simple_winner = metatheory_simple(prefs) for theory in results[prefs]: # If theory agrees with metatheory_simple regarding who # won, track this if results[prefs][theory] == metatheory_simple_winner: agreement_with_most_theories[theory] += 1 winners = sorted(agreement_with_most_theories.keys(), key=lambda x: agreement_with_most_theories[x], reverse=True) for winner in winners: print winner, ' \t', agreement_with_most_theories[winner]
# Created by @Saksham Solanki # This is a program which will control a sophisticated system of lawn mower. # It can detect and avoid obstacles through a method never made before. # It has a simple GUI which is easy to use. The program has 2 modes, out of # which one is Manual Mode --> In this mode the user has to create path by # maneuvering the mower around the field through GUI. They can get current # stats of sensors through GUI too including lat and longgiven by GPS # sensor. Then this path will be used on later for automatic maneuvering. # Now, the other mode is Automatic mode --> Here the saved path will be # used for Automatic maneuvering. Along side this, live feed from the camera # will be shown in order to get the exact position and work around of the mower. # If the sensors detects any kind off obstacle is detected from right, left # or back then it will shut itself down for 10 seconds and will pause all motors # and on going functions, also it turn on the alarm for 1 sec and will turn it # off to the user let know. After the obstacle is removed it will continue its # maneuver. The main feature of the mode is that along side maneuver it can detect # obstacles and can surpass them easily. #---------------------------------------------- Import Libraries ----------------------------------------------# import numpy as np # Library used for some mathematical calculations import tkinter as tk # library for GUI from PIL import Image, ImageTk #Library to process video processing for live feed import multiprocessing #library for running multiple process at same time from cv2 import cv2# library for video processing import RPi.GPIO as GPIO # library to control and get inputs from GPIO pins of pi import time # library to get exact time for moving import serial # lirbrary to get data from GPS import adafruit_gps # library to parse data from GPS import os # library for file handling to create paths import psutil # library which will be used to pause process (a part of moving algorithm) from dual_g2_hpmd_rpi import Motor, motors, MAX_SPEED # library to control motors import math #--------------------------------------------------------------------------------------------------------------# #-------------------------------------------- Init Speed for Motors -------------------------------------------# # These Values will be used as the forward and as the backward values test_forward_speeds = list(range(0, MAX_SPEED, 1)) + \ [MAX_SPEED] * 200 + list(range(MAX_SPEED, 0, -1)) + [0]# Forward value test_reverse_speeds = list(range(0, -MAX_SPEED, -1)) + \ [-MAX_SPEED] * 200 + list(range(-MAX_SPEED, 0, 1)) + [0]# Backward value #--------------------------------------------------------------------------------------------------------------# main_time = 0 command = "" #____________________________________________ Output of all sensors ___________________________________________# class Sensors: #-------------------------------------------- Ultrasonic Sensor_1 ---------------------------------------------# def Ultrasonic_sensor_1(): # This is the function to get distance from Ultrasonic sensor placed forward GPIO.setmode(GPIO.BOARD) TRIG = 22 ECHO = 38 i=0 GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) GPIO.output(TRIG, False) pulse_end = 0 pulse_start = 0 time.sleep(2) try: while True: GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance+1.15, 2) return distance except: pass GPIO.cleanup() #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Ultrasonice Sensor_2 -------------------------------------------# def Ultrasonic_sensor_2(): # This is the function to get distance from Ultrasonic sensor placed forward GPIO.setmode(GPIO.BOARD) TRIG = 36 ECHO = 40 i=0 GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) GPIO.output(TRIG, False) pulse_start = 0 pulse_end = 0 time.sleep(2) try: while True: GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance+1.15, 2) return distance except: pass GPIO.cleanup() #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- IR Sensor 1 ------------------------------------------------# def IR_1(): #This is the function to get value of object being placed or not, from IR sensor 1 placed forward GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(11,GPIO.IN) while(True): if GPIO.input(11): return GPIO.input(11) else: return False #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- IR Sensor 2 ------------------------------------------------# def IR_2(): #This is the function to get value of object being placed or not, from IR sensor 2 placed Backward GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(37,GPIO.IN) while(True): if GPIO.input(37): return GPIO.input(37) else: return False #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- IR Sensor 3 ------------------------------------------------# def IR_3(): #This is the function to get value of object being placed or not, from IR sensor 3 placed Left GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(35,GPIO.IN) while(True): if GPIO.input(35): return GPIO.input(35) else: return False #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- IR Sensor 4 ------------------------------------------------# def IR_4(): #This is the function to get value of object being placed or not, from IR sensor 4 placed Right GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(13,GPIO.IN) while(True): if GPIO.input(13): return GPIO.input(13) else: return False #---------------------------------------------------------------------------------------------------------------# #------------------------------------- Set values of ultrasonic sensors ----------------------------------------# def get_us_sensors(): # This function will alter the value of Ultrasonic sensors in GUI in manual mode s1 = str(Sensors.Ultrasonic_sensor_1()) s2 = str(Sensors.Ultrasonic_sensor_2()) Ultrasonic_s_1.config(text="US Sensor_1 = "+s1) Ultrasonic_s_2.config(text="US Sensor_2 = "+s2) #---------------------------------------------------------------------------------------------------------------# #----------------------------------------- Set values of IR Sensors --------------------------------------------# def get_ir_sensors(): # This function will alter the value of IR sensors in GUI in manual mode i1 = Sensors.IR_1() if i1 == True: IR_1.config(text="IR Sensor_1 = Object Detected") else: IR_1.config(text="IR Sensor_1 = Clear") i2 = Sensors.IR_2() if i2 == True: IR_2.config(text="IR Sensor_2 = Object Detected") else: IR_2.config(text="IR Sensor_2 = Clear") i3 = Sensors.IR_3() if i3 == True: IR_3.config(text="IR Sensor_3 = Object Detected") else: IR_3.config(text="IR Sensor_3 = Clear") i4 = Sensors.IR_4() if i4 == True: IR_4.config(text="IR Sensor_4 = Object Detected") else: IR_4.config(text="IR Sensor_4 = Clear") #---------------------------------------------------------------------------------------------------------------# #---------------------------------------- Set Lat and Long values of GPS ---------------------------------------# def get_GPS(): # This function will alter the value of Lat and Long in GUI in manual mode lat, long = Motor_Controlling.GPS() lat, long = str(lat), str(long) Gps.config(text="Lat, Long = " + lat + ", " + long) #---------------------------------------------------------------------------------------------------------------# #_______________________________________________________________________________________________________________# #___________________________________________________ Live Feed _________________________________________________# class MainWindow(): # Here I have made a simple class which will display live feed from the camera in automatic mode. How this # works is that it takes image, convert it to the right format and then display it. This will happen every # 20 millisecond which will make it look like as a video and won't put much processing power into use. #--------------------------------------------- Initialize class ------------------------------------------------# def __init__(self, window, cap): self.window = window self.cap = cap self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) self.interval = 20 # Interval in ms to get the latest frame # Create canvas for image self.canvas = tk.Canvas(self.window, width=self.width, height=self.height) self.canvas.grid(row=0, column=0) # Update image on canvas self.update_image() #---------------------------------------------------------------------------------------------------------------# #------------------------------------------------ Update Video -------------------------------------------------# def update_image(self): # Get the latest frame and convert image format self.image = cv2.cvtColor(self.cap.read()[1], cv2.COLOR_BGR2RGB) # to RGB self.image = Image.fromarray(self.image) # to PIL format self.image = ImageTk.PhotoImage(self.image) # to ImageTk format # Update image self.canvas.create_image(0, 0, anchor=tk.NW, image=self.image) # Repeat every 'interval' ms try: self.window.after(self.interval, self.update_image) except: pass #_______________________________________________________________________________________________________________# #-------------------------------------------------- Exception class --------------------------------------------# # This is a class which will be used for creating exception if the motors get any issues class DriverFault(Exception): def __init__(self, driver_num): self.driver_num = driver_num #---------------------------------------------------------------------------------------------------------------# #_________________________________ Functions which will control all motors _____________________________________# class Motor_Controlling: #---------------------------------------------- Get Lat and Long -----------------------------------------------# def GPS(): uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) gps = adafruit_gps.GPS(uart, debug=False) gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") gps.send_command(b"PMTK220,1000") last_print = time.monotonic() while True: gps.update() current = time.monotonic() if current - last_print >= 1.0: last_print = current if not gps.has_fix: continue lat = gps.latitude long = gps.longitude try: lat = round(lat, 5) long = round(long, 5) except: continue if lat == None or long == None: continue else: return lat, long #---------------------------------------------------------------------------------------------------------------# #------------------------------------ Timer function to run multiple things ------------------------------------# def timer(sleep_duration=1): while sleep_duration != 0: time.sleep(1) sleep_duration -= 1 #---------------------------------------------------------------------------------------------------------------# #------------------------------------- Raise fault if there is an exception-------------------------------------# def raiseIfFault(): if motors.motor1.getFault(): raise DriverFault(1) if motors.motor2.getFault(): raise DriverFault(2) #-------------------------------------------------- Right direction --------------------------------------------# # First of all it will take a right and move forward till 1 second. After that it will proceed to move # forward untill path is changed def Right(): def right(): for s in test_reverse_speeds: motors.motor1.setSpeed(s) Motor_Controlling.raiseIfFault() time.sleep(0.002) timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(3,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == False: Motor_Controlling.stop() check = False elif timer_thread.is_alive() == True: right() else: continue #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- Left direction ---------------------------------------------# # First of all it will take a left and move forward till 2 second. After that it will proceed to move # forward untill path is changed def Left(): def left(): for s in test_forward_speeds: motors.motor2.setSpeed(s) Motor_Controlling.raiseIfFault() time.sleep(0.002) timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(3,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == False: Motor_Controlling.stop() check = False elif timer_thread.is_alive() == True: left() else: continue #---------------------------------------------------------------------------------------------------------------# #--------------------------------------------- Reverse right and left ------------------------------------------# # These functions are not used in the program but still have been made in case a require for them persists in # future def reverse_right(): for s in test_reverse_speeds: motors.motor1.setSpeed(s) Motor_Controlling.raiseIfFault() time.sleep(0.2) def reverse_left(): for s in test_forward_speeds: motors.motor2.setSpeed(s) Motor_Controlling.raiseIfFault() time.sleep(0.002) #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Backward direction ---------------------------------------------# def backward(): motors.setSpeeds(0, 0) for (s,s2) in zip(test_forward_speeds, test_reverse_speeds): motors.motor1.setSpeed(s) motors.motor2.setSpeed(s2) Motor_Controlling.raiseIfFault() time.sleep(0.002) #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Forward direction ----------------------------------------------# def forward(): motors.setSpeeds(0, 0) for (s, s2) in zip(test_reverse_speeds, test_forward_speeds): motors.motor1.setSpeed(s) motors.motor2.setSpeed(s2) Motor_Controlling.raiseIfFault() time.sleep(0.002) #---------------------------------------------------------------------------------------------------------------# #------------------------------------------------- Stop motors -------------------------------------------------# def stop(): global main_time global command data = Manual.path_data() if main_time != 0: time_2 = int(time.time()-main_time) with open(n_path, 'w') as f: f.write(data+'\n'+command+'\n'+str(int(time_2))) motors.forceStop() motors.disable() motors.enable() def stop_2(): motors.forceStop() motors.disable() motors.enable() #---------------------------------------------------------------------------------------------------------------# #------------------------------------------ Automatic mode initializer -----------------------------------------# # 3 processes will run together where one is to move according to the given path, one is to check for all values # of all sensors and the last one is for obstacle avoiding. All three of them will run parallely and will make # sure to pause each one if any kind of disturbance is found def main(): p1 = multiprocessing.Process(target=Automatic.file_parser, args=(n_path, )) p2 = multiprocessing.Process(target=Motor_Controlling.check_forward) p3 = multiprocessing.Process(target=Motor_Controlling.check_sensors) global p_0 global p_1 global p_2 p_0 = psutil.Process(p1.pid) p_1 = psutil.Process(p2.pid) p_2 = psutil.Process(p3.pid) p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() #---------------------------------------------------------------------------------------------------------------# #------------------------------------------- Sensors output checking -------------------------------------------# # If any of the sensors gets blocked, it will let out a siren for 1 sec and then turn off itself for 10 seconds # and will continue doing this until the obstacle is removed from the sides or back. def check_sensors(): while Sensors.IR_3() == True or Sensors.IR_4() == True or (Sensors.Ultrasonic_sensor_2() <=10 and Sensors.IR_2() == True): p_0.suspend() p_1.suspend() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, False) GPIO.setup(21, GPIO.OUT) GPIO.output(21, True) time.sleep(1) GPIO.setup(21, GPIO.OUT) GPIO.output(21, False) time.sleep(10) GPIO.setup(19, GPIO.OUT) GPIO.output(19, True) p_0.resume() p_1.resume() #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Obstacle avoiding ----------------------------------------------# # If it finds anything in front of it, it will automatically stop itself for 10 seconds and if # the obstacle is still there then it will first of all check if there is an obstacle on the # right or not, if there is then it will check for left and if there is too then it will set # the alarm on until it is removed. Else if there is not any one on the right, it will take a # turn on right, move forward till the corner of the obstacle, and will also store the time it # took to reach the corner. After this it will take a left and move forward until it reaches # the end of the obstacle, after that it will take left again and will move forward till the # time it took it at the start to reach corner of the obstacle. After this it will take a right # and will then resume the process of maneuvering. Also if there is something on left it will # repeat the same process from the left side. def check_forward(): while True: s1 = Sensors.Ultrasonic_sensor_1() s2 = Sensors.IR_1() if s1 <= 10 and s2 == True: p_0.suspend() p_2.suspend() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, False) time.sleep(10) if Sensors.IR_4() == False: Motor_Controlling.Right() start = time.time() while Sensors.IR_3() == True: Motor_Controlling.forward() end = int((time.time() - start)) while Sensors.IR_3() == False: Motor_Controlling.Left() Motor_Controlling.forward() while Sensors.IR_3() == True: Motor_Controlling.forward() Motor_Controlling.Left() timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(end,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.forward() elif timer_thread.is_alive() == False: check = False else: continue Motor_Controlling.Right() Motor_Controlling.stop() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, True) p_0.resume() p_2.resume() elif Sensors.IR_3() == False: Motor_Controlling.Left() start = time.time() while Sensors.IR_4() == True: Motor_Controlling.forward() end = int((time.time() - start)) while Sensors.IR_4() == False: Motor_Controlling.Right() Motor_Controlling.forward() while Sensors.IR_4() == True: Motor_Controlling.forward() Motor_Controlling.Right() timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(end,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.forward() elif timer_thread.is_alive() == False: check = False else: continue Motor_Controlling.Left() Motor_Controlling.stop() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, True) p_0.resume() p_2.resume() else: GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(21, GPIO.OUT) GPIO.output(21, True) else: continue #---------------------------------------------------------------------------------------------------------------# #_______________________________________________________________________________________________________________# #______________________________________________ Automaic maneuvering ___________________________________________# class Automatic: #------------------------------------------------- File reader -------------------------------------------------# # The function will read the file, convert lines to commands and will decide accordingly to it def file_parser(file): with open(file, 'r') as f: path = f.read() f.close() paths = list(path.split(",")) GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(19, GPIO.OUT) GPIO.output(19, True) for way_point in paths: way_points = list(way_point.split("\n")) try: s = way_points[2] del(way_points[0]) except: pass try: auto_time = int(way_points[1]) except: print("maneuver completed") exit() if "Forward" in way_points[0]: timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(auto_time,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.forward() elif timer_thread.is_alive() == False: check = False else: continue elif "Backward" in way_points[0]: timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(auto_time,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.backward() elif timer_thread.is_alive() == False: check = False else: continue elif "Right" in way_points[0]: timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(auto_time,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.Right() elif timer_thread.is_alive() == False: check = False else: continue elif "Left" in way_points[0]: timer_thread = multiprocessing.Process(target=Motor_Controlling.timer, args=(auto_time,)) timer_thread.start() check = True while check: if timer_thread.is_alive() == True: Motor_Controlling.Left() elif timer_thread.is_alive() == False: check = False else: continue else: pass #---------------------------------------------------------------------------------------------------------------# #_______________________________________________________________________________________________________________# #______________________________________________ Manual maneuvering _____________________________________________# class Manual: #------------------------------------------ Create path and directory ------------------------------------------# # The function will first here try to read a file, if it fails it will create the path, else if it is able to do # it then it will simply just return the absolute path. def path_file(): try: with open("paths/path0.txt", 'r') as f: f.close() fin_path = "paths/path0.txt" return fin_path except: if not os.path.exists("paths"): os.mkdir("paths") with open("paths/path0.txt", 'w+') as f: f.close() fin_path = "paths/path0.txt" return fin_path #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- Init path --------------------------------------------------# def init(): global n_path n_path = Manual.path_file() #---------------------------------------------------------------------------------------------------------------# #------------------------------------------- Read path and return it -------------------------------------------# def path_data(): with open(n_path) as f: data = f.read() f.close() return data #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Forward direction ----------------------------------------------# def forward(): global main_time global command data = Manual.path_data() if main_time != 0: time_2 = (time.time()-main_time) time_2 = math.ceil(time_2) print(time_2) with open(n_path, 'w') as f: f.write(data+'\n'+command+'\n'+str(int(time_2))+',') f.close() command = "Forward" main_time = time.time() Motor_Controlling.forward() #---------------------------------------------------------------------------------------------------------------# #---------------------------------------------- Backward direction ---------------------------------------------# def backward(): global main_time global command data = Manual.path_data() if main_time != 0: time_2 = (time.time()-main_time) time_2 = math.ceil(time_2) print(time_2) with open(n_path, 'w') as f: f.write(data+'\n'+command+'\n'+str(int(time_2))+',') f.close() command = "Backward" main_time = time.time() Motor_Controlling.backward() #---------------------------------------------------------------------------------------------------------------# #----------------------------------------------- Right direction -----------------------------------------------# def right(): global main_time global command data = Manual.path_data() if main_time != 0: time_2 = (time.time()-main_time) time_2 = math.ceil(time_2) print(time_2) with open(n_path, 'w') as f: f.write(data+'\n'+command+'\n'+str(int(time_2))+',') f.close() command = "Right" main_time = time.time() Motor_Controlling.Right() #---------------------------------------------------------------------------------------------------------------# #----------------------------------------------- Left direction ------------------------------------------------# def left(): global main_time global command data = Manual.path_data() if main_time != 0: time_2 = (time.time()-main_time) time_2 = math.ceil(time_2) print(time_2) with open(n_path, 'w') as f: f.write(data+'\n'+command+'\n'+str(int(time_2))+',') f.close() command = "Left" main_time = time.time() Motor_Controlling.Left() #---------------------------------------------------------------------------------------------------------------# #-------------------------------------------- Reverse left and right -------------------------------------------# # # These functions are not used in the program but still have been made in case a require for them persists in # # future # def reverse_left(): # lat,long = Motor_Controlling.GPS() # Motor_Controlling.reverse_left() # data = Manual.path_data() # with open(n_path, 'w+') as f: # f.write(data + '\n' + "Reverse_L" + '\n' + str(lat) + "/" + str(long) + ",") # f.close() # def reverse_right(): # lat,long = Motor_Controlling.GPS() # Motor_Controlling.reverse_right() # data = Manual.path_data() # with open(n_path, 'w+') as f: # f.write(data + '\n' + "Reverse_R" + '\n' + str(lat) + "/" + str(long) + ",") # f.close() # #---------------------------------------------------------------------------------------------------------------# #_______________________________________________________________________________________________________________# #______________________________________________________ GUI ____________________________________________________# #---------------------------------------- Live feed and Automatic frame ----------------------------------------# def Live_feed(): root = tk.Tk() root.title("Automatic Mode") try: MainWindow(root, cv2.VideoCapture(0)) except: pass GPIO.cleanup() maneuver = tk.Button(root, text="Start Maneuver",command=lambda:[Manual.init(), Motor_Controlling.main()]).place(relx=0.4, rely=0.9) Stop = tk.Button(root, text="Stop", command=lambda:Motor_Controlling.stop_2()).place(relx=0.3, rely=0.9) Manual_mode = tk.Button(root, text="Manual", command=lambda:[root.destroy(),Manual.init(), Manual_frame()]).place(relx=0.61, rely=0.9) root.mainloop() #---------------------------------------------------------------------------------------------------------------# #------------------------------------------------- Manual Frame ------------------------------------------------# def Manual_frame(): #GPIO.cleanup() m_frame = tk.Tk() m_frame.title("Manual Mode") m_frame.geometry("600x650") Stop = tk.Button(m_frame, text="Stop", command=lambda:Motor_Controlling.stop()).place(relx=0.35) automatic = tk.Button(m_frame, text="Automatic", command=lambda:[m_frame.destroy(), Live_feed()]).place(relx=0.46) Up = tk.Button(m_frame, text="Forward", background="red", command=lambda:Manual.forward()).place(relx=0.43, rely=0.2) Down = tk.Button(m_frame, text="Reverse", background="red", command=lambda:Manual.backward()).place(relx=0.43, rely=0.36) Left = tk.Button(m_frame, text=" Left", background="blue", command=lambda:Manual.left()).place(relx=0.3, rely=0.28) Right = tk.Button(m_frame, text="Right", background="blue", command=lambda:Manual.right()).place(relx=0.6, rely=0.28) Get_stats = tk.Button(m_frame, text="Get Status", command=lambda:[Sensors.get_us_sensors(), Sensors.get_ir_sensors(), Sensors.get_GPS()]).place(relx=0.1, rely=0.6) global IR_1 global IR_2 global IR_3 global IR_4 global Ultrasonic_s_1 global Ultrasonic_s_2 global Gps IR_1 = tk.Label(m_frame, text="IR Sensor_1 = 0") IR_1.place(relx=0.1, rely=0.69) IR_2 = tk.Label(m_frame, text="IR Sensor_2 = 0") IR_2.place(relx=0.1, rely=0.72) IR_3 = tk.Label(m_frame, text="IR Sensor_3 = 0") IR_3.place(relx=0.1, rely=0.75) IR_4 = tk.Label(m_frame, text="IR Sensor_4 = 0") IR_4.place(relx=0.1, rely=0.78) Ultrasonic_s_1 = tk.Label(m_frame, text="US Sensor_1 = 0") Ultrasonic_s_1.place(relx=0.1, rely=0.82) Ultrasonic_s_2 = tk.Label(m_frame, text="US Sensor_2 = 0") Ultrasonic_s_2.place(relx=0.1, rely=0.85) Gps = tk.Label(m_frame, text="Lat, Long = 0, 0") Gps.place(relx=0.1, rely=0.88) m_frame.mainloop() #----------------------------------------------------------------------------------------------------------------# #-------------------------------------------------- Main Frame --------------------------------------------------# def Dashboard(): window_2 = tk.Tk() window_2.title("Lawn Mower") window_2.geometry("500x400") manual = tk.Button(window_2, text=" Manual ", command=lambda:[window_2.destroy(), Manual.init(), Manual_frame()]).place(relx=0.52, rely=0.4) automatic = tk.Button(window_2, text="Automatic", command=lambda:[window_2.destroy(), Live_feed()]).place(relx=0.33, rely=0.4) window_2.mainloop() #----------------------------------------------------------------------------------------------------------------# #________________________________________________________________________________________________________________# #----------------------------------------------- Init Main frame ------------------------------------------------# if __name__ == '__main__': Dashboard() #----------------------------------------------------------------------------------------------------------------#
alien_0 = {'color' : 'green', 'points':5} alien_0['position'] = (0,10); alien_0['speed'] = 'fast' alien_0['speed_1'] = 'medium' del alien_0['speed_1'] print(alien_0 ,"\n") for key,value in alien_0.items(): print("key is " + key.title() +", value is " , value , "\n") for key in sorted(alien_0.keys()): print('key:' + key.title()) favorite_languages = { 'Kai' : 'python', 'Dennis' : 'c++', 'Alex' : 'java', 'Hao' : 'python' } print('\n') for language in set(favorite_languages.values()): print(language) prompt = "test while, input 'quit' to stop this.\n" message = "" while message != 'quit': message = input(prompt); print(message) def describe_pets( animal_type, animal_age,animal_name = 'unknown'): print('I am a ' + animal_type, ',my name is ',animal_name.title(), '. I am ', animal_age, 'years old.\n' ) return 0 describe_pets('dog', 5,'coco') describe_pets(animal_type = 'cat', animal_age = '3')
# users input is assigned to the number variable Number = int(input('Please enter a postive number: ')) # we need an ititial guess of the square root of number to apply newton's method. # the initial guess should not be zero, or zero will be in the denominator in the function. guess = 1 # how many times we want to repeat the method maxIterations = 10 #create a funtion. It takes Number as the input and applies newton's method to approximate the square root. def newtonsMethod(Number): x0 = guess # the first value for x0 is the guess. # Use a for loop for iteration. This will repeat the proccess according to maxIterations. for i in range(maxIterations): fx = x0**2 - Number # applying formula to solve for f(x) yprime = 2*x0 # applying formula to solve for f'(x) x1 = x0 - fx/yprime # applying the formula to get x1, a closer guess to the square root of Number x0=x1 # x0 is updated so that we can start the loop again. return x1 # when the loop is completed for the specified iterations the function returns x1, the best approximation for the root of Number. print(newtonsMethod(Number)) # call the function newtonsMethod(Number) and print the result. # further explanation # if no loop was used it would also be possible to solve for x2, x3 ... # fx = x1**2 # yprime = 2*x1 # x2 = x1 - fx/yprime # and repeat #https://www.w3schools.com/python/python_for_loops.asp #reference for using for loops. #https://www.w3schools.com/python/python_functions.asp #reference for functions #https://stackoverflow.com/questions/818828/is-it-possible-to-implement-a-python-for-range-loop-without-an-iterator-variable # I could not think of a way to reference i in the loop. But I found this method was okay and used in one of the labs. #https://www.math.ubc.ca/~pwalls/math-python/roots-optimization/newton/ #slightly different approach
""" Forward modeling magnetic data using spheres in Cartesian coordinates ----------------------------------------------------------------------- The :mod:`fatiando.gravmag` has many functions for forward modeling gravity and magnetic data. Here we'll show how to build a model out of spheres and calculate the total field magnetic anomaly and the 3 components of the magnetic induction. """ from __future__ import division, print_function from fatiando import mesher, gridder, utils from fatiando.gravmag import sphere import matplotlib.pyplot as plt import numpy as np # %% # Create a model using geometric objects from fatiando.mesher # Each model element has a dictionary with its physical properties. # The spheres have different total magnetization vectors (total = induced + # remanent + any other effects). Notice that the magnetization has to be a # vector. Function utils.ang2vec converts intensity, inclination, and # declination into a 3 component vector for easier handling. def anomag_model(coords,radii=1.5e3,inc=50, dec=-30): model =[] for coord, radius in zip(coords, radii): model_tmp = mesher.Sphere(x=coord[0], y=coord[1], z=coord[2], radius=radius, props={'magnetization': utils.ang2vec(1, inc=50, dec=-30)}) model.append(model_tmp) return model def fwd_model(model, shape = (300, 300), area = [0, 30e3, 0, 30e3]): # Set the inclination and declination of the geomagnetic field. inc, dec = -10, 13 # Create a regular grid at a constant height shape = shape area = area x, y, z = gridder.regular(area, shape, z=-10) field = ['Total field Anomaly (nt)', sphere.tf(x, y, z, model, inc, dec)] return x, y, z, field, shape def plot_model(x, y, field, shape): # Make maps of all fields calculated fig = plt.figure() ax = plt.gca() plt.rcParams['font.size'] = 10 X, Y = x.reshape(shape)/1000, y.reshape(shape)/1000 field_name, data = field scale = np.abs([data.min(), data.max()]).max() ax.set_title(field_name) plot = ax.pcolormesh(X, Y, data.reshape(shape), cmap='RdBu_r', vmin=-scale, vmax=scale) plt.colorbar(plot, ax=ax, aspect=30, pad=0) ax.set_xlabel('x (km)') ax.set_ylabel('y (km)') plt.tight_layout(pad=0.5) plt.show() def load_mag_synthetic(): A= [10e3,10e3,2e3] B= [25e3,10e3,1e3] coord= np.array([A,B]) # coord = np.array([A]) radius = 1.5e3*np.ones(len(coord)) modelmag = anomag_model(coord,radii=radius,inc=50, dec=-30) xp, yp, zp, field2d, shape = fwd_model(modelmag, shape = (300, 300),area = [0, 30e3, 0, 30e3]) plot_model(xp, yp, field2d, shape) U = field2d[1] p1, p2 = [min(xp), 10e3], [max(xp), 10e3] return xp, yp, zp, U, shape, p1, p2, coord def load_mag_synthetic_ploxy_test(A=[10e3,10e3,2e3], radius=1.5e3): A= [10e3,10e3,2e3] # B= [25e3,10e3,1e3] # coord= np.array([A,B]) coord = np.array([A]) radius = radius*np.ones(len(coord)) modelmag = anomag_model(coord,radii=radius,inc=50, dec=-30) xp, yp, zp, field2d, shape = fwd_model(modelmag, shape = (300, 300),area = [0, 30e3, 0, 30e3]) plot_model(xp, yp, field2d, shape) U = field2d[1] p1, p2 = [min(xp), 10e3], [max(xp), 10e3] return xp, yp, zp, U, shape, p1, p2, coord # %% pygimli exemple
class Account: """ A simple account class """ """ The constructor that initializes the objects fields """ def __init__(self, owner, amount=0.00): self.owner = owner self.amount = amount self.transactions = [] def __repr__(self): return f'Account {self.owner},{self.amount} ' def __str__(self): return f'Account belongs to {self.owner} and has a balance of {self.amount} Ksh Only ' """ Create new Accounts""" acc1 = Account('Victor') # Amount is initialized with a default value of 0.0 acc2 = Account('Roseline', 1000.00) # Amount is initialized with the value 1000.00 print('') print(str(acc2)) print(repr(acc1))
""" Dunder methods is a fancy name for 'under under method under under' or __method__() They are built-in functions that add functionality to python code and also unlock new features on objects """ class Garage: """ Stores cars in a garage object """ def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def __getitem__(self, car): return self.cars[car] def __repr__(self): return f'--> {self.cars}' def __str__(self): return f'--> {self.cars}' Toyota = Garage() print(Toyota.cars) Toyota.cars.append('Mark X') Toyota.cars.append('Allion') Toyota.cars.append('Crown') Toyota.cars.append('Prado') Toyota.cars.append('Noah') print(Toyota.cars) print(len(Toyota)) # Its now possible to check the # of cars in the garage because of the __len__() dunder method print(Toyota[0]) # Use the __getitem__() dunder method to enable indexing of cars in the garage print('') # These two methods also unlock a new functionality on the garage, iterating over cars in the garage for cars in Toyota: print(f'--> {cars}') print('') print(repr(Toyota.cars)) # Using __repr__() to print out cars in the garage print(str(Toyota.cars)) # Using __str__() to print out cars in the garage
""" Storing and retrieving data using CSV (Comma Separated Values) files """ # READING FROM THE FILE # Ignore the first line --> strip spaces from the second line for lines in lines[1:] using a list comprehension # Open ,read and close the file...iterate over the file contents using a for loop and use item indexes to access them from typing import List read_csv = open('salesdata.csv', 'r') read_csv_contents = read_csv.readlines() read_csv.close() read_csv_contents = [line.strip() for line in read_csv_contents[0:]] for lines in read_csv_contents: data: List[str] = lines.split(',') print(data) """ for line in read_csv_contents: person_data = line.split(',') # Split the contents by a ',' name = person_data[0].title() # Methods from the string class to format text appearance age = person_data[1] university = person_data[2].capitalize() degree = person_data[3].capitalize() print(f'{name} is {age} years old, and studies {degree} at {university} university') """ # WRITING TO THE FILE # csv_values = ','.join([Pass a list of your data separated by commas]) # ['Mary', '21', 'Cambridge', 'Business and Commerce'] for lines in read_csv_contents: data_to_write = lines.split(',') write_to_csv = ','.join(data_to_write) csv_file = open('csv_data.csv', 'w') csv_file.write(write_to_csv) csv_file.close() print(data_to_write)
space="========================================" #1. print("1.") x=int(input("Enter a number: ")) if x%2==0: print("Great!") else: print("Invalid.") print(space) ################################################ #2. print("2.") a=int(input("Number #1: ")) b=int(input("Number #2: ")) c=int(input("Number #3: ")) if a>b and a>c: print(a) elif b>a and b>c: print(b) elif c>a and c>b: print(c) print(space) ################################################ pc=input("How many computers did you fix today? ") if pc=="" or pc==str(pc): pc=15 else: pc=int(pc) print(f"You have {pc*2} computers to take care of tomorrow.")
a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: ")) while a+b==10: print(a+b) a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: "))
i=0 sum = 0 for i in range(6): x = int(input("Enter number: ")) sum+=x print(sum) print(sum/6)
class Person(): def info(self): print("Name:",self.name) print("Age:",self.age) print("No. of children:",self.children) def hasChildren(self): if self.children==0: return False else: return True def ageGroup(self): if 0<=self.age<18: return "Child" elif 19<self.age<60: return "Adult" elif 61<self.age<120: return "Senior"
#If a number is divisible by the sum of its digits, then it will be known as a Harshad Number. For example: # The number 156 is divisible by the sum (12) of its digits (1, 5, 6 ). # Some Harshad numbers are 8, 54 156 num=int(input("enter the harshad number")) i=num sum=0 while i>0: b=i%10 i=i//10 sum=sum+b if num%sum==0: print("it is harshad number") else: print("it is not harshad number")
#write a program check prime number num=int(input("enter the number")) i=2 while i<num: if num%i==0: print("it is not prime number") i=i+1 else: print("it is prime number")
#write a program using count function in loop i=1 while i<=100: count=0 j=2 while j<=i//2: if i%j==0: count=count+1 break j=j+1 if count==0 and i!=1: print(i) i=i+1
# 1 # 22 # 333 # 4444 # 55555 i=1 while i<=5: j=5 while j>=i: print( " ",end=" ") j=j-1 k=0 while k<=j: print(i,end=" ") k=k+1 i=i+1 print()
class Solution: # @param {integer} n # @return {integer} 'Recursive Binary search: using varying array size' def BinarySearch(self, nums,target): if len(nums)==0: return False mid=int(len(nums)/2) if target<nums[mid]: return self.BinarySearch(nums[:mid],target) elif target>nums[mid]: return self.BinarySearch(nums[mid:],target) else: return True 'Recursive Binary search: using varying indexes' 'always note that l says left index and r says right index, l<=r means we have at least one element' def binarySearch(self, nums,l, r,target): if l>r: return False mid=(l+r)/2 if nums[mid]==target: return True if target<nums[mid]: return self.binarySearch(nums,l,mid-1,target) else: return self.binarySearch(nums,mid+1,r,target) 'Iterative Binary search: using varying array indexes' 'what conditions it fails? when target< nums, target>nums, target within the nums range but not present' 'in those cases l>r, either l gives 0 or >0, l denotes first number greater than target' 'In binary search if element is not found and if low>0, then low will give the index of the element just' 'greater than the target, so if low=0 then all elements are greater than target. Say 10,20,30,40 finding 0 will give low=0, finding 50 will give low=4, finding 32 will give low=3.' def binarySearch(self, nums,target): l,r=0,len(nums)-1 while l<=r: mid=(l+r)/2 if nums[mid]==target: return True if target<nums[mid]: r=mid-1 else: l=mid+1 return False def searchRange(self, nums, target): """ Given a sorted array of integers, find the starting and ending position of a given target value. [1,2,3,3,3,4,5] and target=3 will return [2,4] Following solution is ok, but worst case O(n), better solution is below """ if not nums: return [-1,-1] low,high=0,len(nums)-1 while low<=high: mid=(low+high)/2 if target>nums[mid]: low=mid+1 elif target<nums[mid]: high=mid-1 else: start,end=mid,mid while start>=0 and nums[mid]==nums[start]: start-=1 while end<=len(nums)-1 and nums[mid]==nums[end]: end+=1 return [start+1,end-1] return [-1,-1] def firstIndex(self,nums,low,high,target): if low>high: return -1 mid=(low+high)/2 if target<nums[mid]: return self.firstIndex(nums,low,mid-1,target) elif target>nums[mid]: return self.firstIndex(nums,mid+1,high,target) else: found=self.firstIndex(nums,low,mid-1,target) if found==-1: return mid else: return found def lastIndex(self,nums,low,high,target): if low>high: return -1 mid=(low+high)/2 if target<nums[mid]: return self.lastIndex(nums,low,mid-1,target) elif target>nums[mid]: return self.lastIndex(nums,mid+1,high,target) else: found=self.lastIndex(nums,mid+1,high,target) if found==-1: return mid else: return found def countOccurrences(self,nums,target): 'count the number of occurrences of target in nums' 'find the first and last index of the target using binary search' 'occurrences is last-first+1 O(logn) complexity' return self.lastIndex(nums,0,len(nums)-1,target)-self.firstIndex(nums,0,len(nums)-1,target)+1 def firstBadVersion(self, n): """ n versions, find the first bad version https://leetcode.com/problems/first-bad-version/ bad is definately there """ if n <= 1: return n front = 1 end = n while front < end: middle = (front + end)//2 'if mid is bad then results in the left including middle' if isBadVersion(middle): end = middle 'if mid is good then result is in the right side' else: front = middle + 1 return front def firstBadVersion(self, n): if n == 0: return 0 return self.search(1, n) def search(self, l, r): mid = (l+r)//2 if isBadVersion(mid): r = mid - 1 'if mid is bad and before the mid is good then mid is the answer, else search left of the mid' if not isBadVersion(r): return mid else: return self.search(l, r) else: 'if mid is good and the next of mid is bad then next is the answer, else search right' l = mid + 1 if isBadVersion(l): return l else: return self.search(l, r) def searchMaxIncreasingDecreasing(self,nums): "Given an array of integers which is initially increasing and then decreasing, find the maximum value in the array. 8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1 will return 500" "compare the mid with left and right element" l,r=0,len(nums)-1 if r<=1: return max(nums) while l<=r: mid=(l+r)/2 if nums[mid]>nums[mid-1] and nums[mid]>nums[mid+1]: return nums[mid] elif nums[mid]>nums[mid-1] and nums[mid]<nums[mid+1]: l=mid+1 else: r=mid-1 def magicIndex(self,nums): # return i if nums[i]==i, where nums is sorted # easy, using binary search, but if duplicate num exists then modification required if not nums: return -1 mid=len(nums)/2 if nums[mid]==mid: return mid # if mid number is less than mid index, then after mid number'th index element are not magic (as indexes are larger and elements are at most mid), # so recursing left until min(mid-1, nums[mid]) if nums[mid]<mid: leftIndex=min(mid-1, nums[mid]) left=self.magicIndex(nums[:leftIndex+1]) if left>=0: return left # also recurse right if nums[mid]>mid: rightIndex=max(mid+1, nums[mid]) right=self.magicIndex(nums[rightIndex:]) if right>=0: return right def mySqrt(self, x): # find sqrt of x # using binary serch find mid start=0 end=x while start<=end: mid=(start+end)/2 # if following doesn't happen then either mid is the ans/ ans is the upper half if mid*mid>x: end=mid-1 else: if (mid+1)*(mid+1)>x: return mid else: start=mid+1 def searchMatrix1(self, matrix, target): # this is O(nlogm) solution, for each row we are doing binary search, a better O(logn+logm) solution is below rows,cols=len(matrix),len(matrix[0]) for i in range(rows): low,high=0,cols-1 while low<=high: mid=(low+high)/2 if matrix[i][mid]==target: return True else: if target<matrix[i][mid]: high=mid-1 else: low=mid+1 return False def searchMatrix(self, matrix, target): # easy!, two binary search, first through all first columns to get which row might have the number # then another binary search to that row to get the element # low in first search gives the index who has greater value than the target, so basically we have to search previous row low = 0 high = len(matrix)-1 while low<=high: midpoint = (low + high)//2 if matrix[midpoint][0] == target: return True else: if target < matrix[midpoint][0]: high = midpoint-1 else: low = midpoint+1 if low>0: i=low-1 else: i=low low,high=0,len(matrix[0])-1 while low<=high: midpoint = (low + high)//2 if matrix[i][midpoint] == target: return True else: if target < matrix[i][midpoint]: high = midpoint-1 else: low = midpoint+1 return False def searchMatrix1(self, matrix, target): # This also simple, based on previous searchMatrix # we start with first column an find a 'low' (next line), then we have to search only low number of rows for a search starting at second line and the process will continue # low in first search gives the index who has greater value than the target, so basically we have to search previous row main=matrix m,n=len(matrix),len(matrix[0]) for j in range(n): low = 0 high = m-1 while low<=high: midpoint = (low + high)//2 if matrix[midpoint][j] == target: return True else: if target < matrix[midpoint][j]: high = midpoint-1 else: low = midpoint+1 if low>0: i=low-1 else: i=low #print i m=i+1 return False def findMin(self, nums): #Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element.You may assume no duplicate exists in the array. #This problems seems like a binary search, and the key is how to break the array to two parts, so that we only need to work on half of the array each time, i.e.,when to select the left half and when to select the right half. #If we pick the middle element, we can compare the middle element with the left-end element. If middle is less than leftmost, the left half should be selected; if the middle is greater than the leftmost, the right half should be selected. Using simple recursion, this problem can be solve in time log(n). #In addition, in any rotated sorted array, the rightmost element should be less than the left-most element, otherwise, the sorted array is not rotated and we can simply pick the leftmost element as the minimum. l = len(nums)-1 if l==0: return nums[0] mid = l/2 if nums[mid]<nums[0]: # right side is sorted, so rotation has been done on leftside, so exclude first element and include mid and search there return self.findMin(nums[1:mid+1]) else: return self.findMin([nums[0]]+nums[mid+1:]) def search(self, nums, target): """ Search in a rotated sorted array """ l,r=0,len(nums)-1 while l<=r: mid=(l+r)/2 if nums[mid]==target: return mid # if left is sorted, then target might be there if inside, or target in other side if nums[l]<=nums[mid]: if target>=nums[l] and target<=nums[mid]: r=mid-1 else: l=mid+1 else: # if right is sorted, then target might be there if inside or target in other side if target>nums[mid] and target<=nums[r]: l=mid+1 else: r=mid-1 return -1 def search(self, nums, target): # search is a rotated sorted array, when duplicates are allowed left,right=0,len(nums)-1 while left<=right: mid=(left+right)/2 if nums[mid]==target: return True # if left is sorted, then target might be there if inside, or target in other side if nums[left]<nums[mid]: if nums[left]<=target and target<nums[mid]: right=mid-1 else: left=mid+1 # if right is sorted, then target might be there if inside or target in other side elif nums[left]>nums[mid]: if nums[mid]<target and target<=nums[right]: left=mid+1 else: right=mid-1 # else, we have one element left and that is not equal to target else: left+=1 return False def findPeakElement(self, nums): # A peak element is an element that is greater than its neighbors. Given an array nums with nums[i]!=nums[i+1],num[-1]=num[n]=-inf find a peak element and return its index. e.g. [1,2,3,1] 3 is a peak element and your function should return the index number 2. # The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. # binary search, if mid is less than mid-1 then serach in left, else search right # we always will get a peak in either side, if we were to get a global peak then binary search will not work if not nums: return -1 low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) / 2 if low==high: return low if nums[mid]>nums[mid+1] and nums[mid]>nums[mid-1]: return mid if nums[mid] < nums[mid+1]: low = mid + 1 else: high = mid-1 solution=Solution() #print solution.trailingZeroes(100) #print solution.romanToInt('MMCCCXCIX') #print solution.isHappy(882) #print solution.countPrimes(100) #print solution.isValid("[{}]") #print solution.merge([1,0],1,[2],1) #print(solution.countPrimes(113)) #print solution.binarySearch([2,3,4],1) #print solution.mySqrt(1000) #print solution.minSubArrayLen(15,[5,1,3,5,10,7,4,9,2,8]) #print solution.searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]],23) #print solution.findMin([1,2]) #print solution.findPeakElement([1,2,3,1]) #print solution.searchMatrix1([[-5]], -2) #solution.numIslands([]) #solution.numIslands([['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]) #solution.solve([['X','X','X','X'],['X','0','0','X'],['X','X','0','X'],['X','0','X','X']]) #solution.solve([['X','X','X'],['X','0','X'],['X','X','X']]) solution.CountingSort([2,5,3,0,2,3,0,3])
"Ternary search Tree: https://www.youtube.com/watch?v=CIGyewO7868" class Node: def __init__(self,data=None): self.data=data self.right=None self.eq=None self.left=None self.isEndOfString=0 class Ternary: def insert(self,root,word): if not root: "add a new node with char if root none (means char not present)" root=Node(word[0]) "create left or right nodes if char is less or greater" if word[0]<root.data: root.left=self.insert(None,word) elif word[0]>root.data: root.right=self.insert(None,word) else: "else the created node's case and proceeds with new elements" word=word[1:] if word: root.eq=self.insert(None,word) else: root.isEndOfString=1 return root def search(self,root,word): if not root: return False if word[0]<root.data: return self.search(root.left,word) elif word[0]>root.data: return self.insert(root.right,word) else: word=word[1:] if word: return self.search(root.eq,word) else: if root.isEndOfString: return True else: return False root=None ternary=Ternary() root=ternary.insert(root,"cat") root=ternary.insert(root,"bat") root=ternary.insert(root,"cats") print ternary.search(root,"bat")
#recursion and memoization are used to solve DP problems but they are totally separate things. #And divide and conquer problems differ from DP in that the sub-problems do not overlap. #Divide-&-conquer works best when all subproblems are independent. So, pick partition that makes algorithm most efficient & simply combine solutions to solve entire problem. #In dynamic approach, we dont know where to partition the problem, because if we do, solution(left)+solution(right)!=solution(entire) #dynamic programming automatically solves every subproblem that could conceivably be needed, while memoization only ends up solving the ones that are actually used. # For instance, suppose that W and all the weights wi are multiples of 100. Then a subproblem K(w) is useless if 100 does not div #Knapsack is a good example to understand difference DP vs recursion+memoization #Must to do: http://people.cs.clemson.edu/~bcdean/dp_practice/ class Solution: def minDistance(self, word1, word2): # if eiter one exist, penalty=length (need to insert all chars) # set zero rows and colums of the metric, penalty=lenth of the word if other dont exist matrix = [[0 for i in range(len(word2)+1)] for j in range(len(word1)+1)] for i in range(len(word1)+1): matrix[i][0]=i for j in range(len(word2)+1): matrix[0][j]=j for i in range (1,len(word1)+1): for j in range(1,len(word2)+1): # if two chars are the same penalty is 1, else 0 cost=1 if word1[i-1]==word2[j-1]: cost=0 # result will be minimum of either including any of the char to the solution (1+matrix[i-1][j],1+matrix[i][j-1]) or including none (cost+matrix[i-1][j-1]) matrix[i][j]=min(1+matrix[i-1][j],1+matrix[i][j-1],cost+matrix[i-1][j-1]) return matrix[len(word1)][len(word2)] def knapsack01(self,Values,Weight,W): # A thief robbing a store and can carry a maximal weight of W into their knapsack. There are n items and ith item weigh wi and is worth vi dollars. What items should thief take? # we will use K(i,w) to denote what is maximum value with i items and w weights, so k[len(values)][W] is the answer m,n = len(Values), W K = [[0 for i in range(n+1)] for j in range(m+1)] # note this, it's a K[m][n] matrix for i in range(1,m+1): for j in range(1,n+1): # consider i items, if i'th items (that means W[i-1] weight) have greater value than what to fill (j) then j fill have to be done i-1 items if Weight[i-1]>j: K[i][j]=K[i-1][j] # otherwise max values including or excluding i'th item else: K[i][j]=max(K[i-1][j],Values[i-1]+K[i-1][j-Weight[i-1]]) return K[m][n] def coinChange(self,nums,coins): # Given a set of coins and a num, what is the minimum number of coins required to change the num # coins are repeated # let m(i) is the minimum coins possible to change i # for each nums from 0 to nums, if j is a coin that is less than the number then total min(1+M[j-number]) coins is the smallest number of coins, M[j-number] will be aleary calculated M=[-1 for i in range(nums+1)] # or initize M with big numbers e.g., M=[0]+[nums+1]*nums, here M[1]=num+1 which indicates no coin change is possible M[0]=0 for i in range(1,nums+1): output=[] for j in range(len(coins)): if i>=coins[j]: # if change of i-coins[j] is possible if M[i-coins[j]]>-1: # or we can simply use M[i]=min(M[i],M[i-coins[j]]) output.append(1+M[i-coins[j]]) # if any change possible then take the min one M[i]=min(output) if output else -1 # or we can just check if M[num] is num+1 in this case no change is possible for num return M.pop() def coinChange1(self, coins, amount): # Given a set of coins and a num, what is the minimum number of coins required to change the num # coins are repeated. If coins are single in the following program use M[i-coins[j-1]][j-1] rather than M[i-coins[j-1]][j] # let M[i,j] is minimum coins when we have i amount and j coins # a recursive solution is below M=[[0 for j in range(len(coins)+1)] for i in range(amount+1)] # an amoung couldn't be changed with 0 coins, set -1 for i in range(1,amount+1): M[i][0]=-1 row,col=amount+1,len(coins)+1 for i in range(1,row): for j in range(1,col): # if amount greater than current coin, two cases: either include the coin to the solution or exclude if i>=coins[j-1]: # if include the coin then check whether two options are possible or not (e.g., both are -1) if M[i-coins[j-1]][j]==-1 and M[i][j-1]==-1: M[i][j]=-1 if M[i-coins[j-1]][j]>-1 and M[i][j-1]>-1: M[i][j]=min(1+M[i-coins[j-1]][j],M[i][j-1]) else: M[i][j]= 1+M[i-coins[j-1]][j] if M[i][j-1]==-1 else M[i][j-1] #otherwise, we cant include the coin else: M[i][j]=M[i][j-1] return M[row-1][col-1] def MakingChange1(self,num,coins): # coins are sorted in descending order, # if you want to make memoization, a matrix with num*colums is required. A special value might say whether a cell has been computed yet. if num<0: return -1 if num==0: return 0 # in num is larger than first coin then 1+self.MakingChange(num-coins[0],coins) is answer if exist if num>=coins[0]: if self.MakingChange(num-coins[0],coins)>-1: return 1+self.MakingChange(num-coins[0],coins) else: return -1 # otherwise self.MakingChange(num,coins[1:]) is the answer else: return self.MakingChange(num,coins[1:]) def coinChange(self,coins,target): # how many total ways coin change possible # M[i,j] = total ways when we have i amount and j coins M=[[0 for j in range(len(coins)+1)] for i in range(target+1)] # zero amoung could be changed with 1 possible ways for each coins for j in range(len(coins)+1): M[0][j]=1 row,col=target+1,len(coins)+1 for i in range(1,row): for j in range(1,col): # if amount greater than current coin, two cases: either include the coin to the solution or exclude if i>=coins[j-1]: M[i][j]=M[i-coins[j-1]][j]+M[i][j-1] #otherwise, we cant include the coin else: M[i][j]=M[i][j-1] print M def rob(self, nums): # line of houses, each have a value, adjacent houses are connected, get maximum ammount from the houses without getting values from two cosequtive # let v[i] is maximum value we can get with i nums if not nums: return 0 if len(nums)<=2: return max(nums) for i in range(2,len(nums)): # for i'th nums, we can either take it or not v[i]=max(nums[i]+v[i-2],v[i-1]) return v[len(nums)-1] def rob2(self, nums): # previos problem, but all houses are arranged in a circle # There are two cases, if we do not rob house[n], we can rob nums[:n-1] else we can rob nums[1:n-2] if not nums: return 0 if len(nums)<=3: return max(nums) return max(nums[len(nums)-1]+self.rob1(nums[1:len(nums)-2]),self.rob1(nums[:len(nums)-1])) def climbStairs(self, n): # You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # let v[i] is the number of ways to reach at i'th steps if n<2: return 1 if n==2: return 2 v=[0 for i in range(n+1)] v[0]=0 v[1]=1 v[2]=2 # can reach from either previos or previous previous stairs for i in range(3,n+1): v[i]=v[i-1]+v[i-2] return v[n] def uniquePaths(self, m, n): # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. # The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).How many possible unique paths are there? # let K[i][j] is the number of ways a robot can reach in i-1,j-1 th grid # in a cell it can come from either [i-1][j] or [i][j-1] cells # however in first row or colum it can go only one way as for those it can come from up (for first colums) or left (for first rows) if m==0 or n==0: return 1 # setting all in all the cells (so, first row and colum need to be set separately) K=[[1 for i in range(n)] for j in range(m)] for i in range(1,m): for j in range(1,n): K[i][j]=K[i-1][j]+K[i][j-1] return K[m-1][n-1] def uniquePathsWithObstacles(self, obstacleGrid): # Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle is marked as 1 or 0 in the grid # similar to thre uniquePaths problems with some minor changes # in a cell it can come from either [i-1][j] or [i][j-1] cells # however in first row or colum it can go only one way as for those it can come from up (for first colums) or left (for first rows), but if there is an obstacle all remaining (including that) wil be zero m,n=len(obstacleGrid),len(obstacleGrid[0]) grid=[[0 for j in range(n)] for i in range(m)] # for first row and column if obstacle then later cells are not accessible for i in range(m): if obstacleGrid[i][0]==0: grid[i][0]=1 else: break for j in range(n): if obstacleGrid[0][j]==0: grid[0][j]=1 else: break # only one row or colum, finally we return grid[m-1][n-1], so we need special handling for 1 row and 1 col if m==1: return grid[0][n-1] if n==1: return grid[m-1][0] for i in range(1,m): for j in range(1,n): # if obostacke then no way to go there grid[i][j]=grid[i-1][j]+grid[i][j-1] if obstacleGrid[i][j]==0 else 0 return grid[m-1][n-1] def minPathSum(self, grid): # Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. # Note: You can only move either down or right at any point in time. # same concept with the previous one m,n=len(grid),len(grid[0]) for i in range(1,m): grid[i][0]+=grid[i-1][0] for j in range(1,n): grid[0][j]+=grid[0][j-1] for i in range(1,m): for j in range(1,n): grid[i][j]+=min(grid[i-1][j],grid[i][j-1]) return grid[m-1][n-1] def maxProduct(self, nums): # Find the contiguous subarray within an array (containing at least one number) which has the largest product. (number can be negative) # let max(i) and min(i) is the maximum and minimum product respectively when we have i elements # maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element # so we will keep max and min for each element if not nums: return maxs=[x for x in nums] mins=[x for x in nums] for i in range(1,len(nums)): if nums[i]>=0: maxs[i]=max(nums[i],maxs[i-1]*nums[i]) mins[i]=min(nums[i],mins[i-1]*nums[i]) else: maxs[i]=max(nums[i],mins[i-1]*nums[i]) mins[i]=min(nums[i],maxs[i-1]*nums[i]) return max(maxs) def maximumValueContiguousSubsequence(self,nums): # this is also maxium subarry problem but here output is all the indexes # for i'the element it will be included in previous solution having i-1 elements or a new solution has to be started from here output=[0 for i in range(len(nums))] parent=[0 for i in range(len(nums))] output[0]=nums[0] parent[0]=0 for i in range(1,len(nums)): if output[i-1]+nums[i]>nums[i]: output[i]=output[i-1]+nums[i] parent[i]=i-1 else: output[i]=nums[i] parent[i]=i currentIndex=output.index(max(output)) # this one is for processing output indexList=[] while currentIndex!= parent[currentIndex]: indexList.append(currentIndex) currentIndex=parent[currentIndex] indexList.append(currentIndex) print indexList[::-1] def maxSubArray(self, nums): # Find the contiguous subarray within an array (containing at least one number) which has the largest sum. # let output[i] is the maxium subarry sum with i+1 elements # for the i'th element it will be included in previous solution having i-1 elements or a new solution has to be started from here if not nums: return output=[0 for i in range(len(nums))] output[0]=nums[0] for i in range(1,len(nums)): output[i]=output[i-1]+nums[i] if output[i-1]+nums[i]>nums[i] else nums[i] return max(output) def LongestIncreasingSubsequence(self,nums): # for longest increasing subsequence ending at j, we want to extent some (max) subsequece ending at in index i, i<j if j'th element is larger then i'th and add 1 for the j'th element # Another similar problem: consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with # x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, # you can only connect city i on the northern bank to city i on the southern bank. # solution of this: http://people.cs.clemson.edu/~bcdean/dp_practice/dp_6.swf # box stacking is also LIS http://people.cs.clemson.edu/~bcdean/dp_practice/dp_5.swf if not nums: return 0 M=[0 for i in range(len(nums))] M[0]=1 for i in range(1,len(nums)): maxs=0 for j in range(0,i): if nums[i]>nums[j]: if M[j]>maxs: maxs=M[j] M[i]=maxs+1 return max(M) def minimumTotal(self, triangle): #Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. #for a given row [1,2,3], M[first/last]=this row first/last+ previous row fast/last. M[other element]=element+ min(previous row's this and left element) #finally the min in the last row is the output # in this solution we are using O(n*n) space, if we want to keep the traiangle intact, a less extra space solution is O(n) if we do the comuputation from bottom to up # in that case we need an array size with max row len of the traingle and we row by row from bottom to the up top, calculate the minimum value to each point. we just use one array to "remember" what is the minimum total value to each point from bottom. m=len(triangle) if m==0: return if m==1: return triangle[0][0] for i in range(1,m): triangle[i][0]+=triangle[i-1][0] triangle[i][len(triangle[i])-1]+=triangle[i-1][len(triangle[i-1])-1] for j in range(1,len(triangle[i])-1): triangle[i][j]+=min(triangle[i-1][j-1],triangle[i-1][j]) return min(triangle[m-1]) def wordBreak(self, s, wordDict): # Given a string s and a dictionary of words dict (a list of words), determine if s can be segmented into a space-separated sequence of one or more dictionary words. # let status[i] is true/false if first i+1 of s could be built/not from the wordDict # consider "leetcode" as s, status[i]=True if s(0--i) is in the dictionary, else False. #s(0--i) is in dictionary is s(0--i) in dictionary of s(0..j),s(j+1...i) both in dictionary) if not s: return True status=[0 for i in range(len(s))] for i in range(len(s)): # if the whole word upto is in the dictionary if s[:i+1] in wordDict: status[i]=True # else determine whether we can build it else: for j in range(i): if status[j] and s[j+1:i+1] in wordDict: status[i]=True return status[-1] def maximalSquare(self, matrix): # Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area., https://leetcode.com/problems/maximal-square/ #The idea of the algorithm is to construct an auxiliary size matrix dp in which each entry dp[i][j] represents size of the square #sub-matrix with all 1s including matrix[i][j] where matrix[i][j] is the rightmost and bottommost entry in sub-matrix. #First copy first row and first columns as it is from matrix[][] to dp[][] if not matrix: return 0 m,n = len(matrix),len(matrix[0]) dp=list(matrix) for i in range(m): dp[i][0]=int(matrix[i][0]) for j in range(n): dp[0][j]=int(matrix[0][j]) for i in xrange(1,m): for j in xrange(1,n): if matrix[i][j] =='1': dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 else: dp[i][j] = 0 ans = max([max(i) for i in dp]) # ** is ans square return ans**2 def maxProfit(self, prices): # Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. # for a day, either you buy or sale, if sale then max profit might be obtained if buy price is the lowest # mins holds lowest price until that day, if that day price is lower then the mins then update mins # note that you might do thing in all days (because consider all days prices are going higher), in that case K[0] is giving the answer 0 if len(prices)==0: return 0 mins=prices[0] K=[0 for i in range(len(prices))] for i in range(1,len(prices)): K[i]=prices[i]-mins if prices[i]<mins: mins=prices[i] return max(K) def maxProfit1(self, prices): # same problem above but condition: you may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). # for a day, either you buy or sale, if sale then max profit is obtained the day you earned highest profit from buing that one one (maxBuy tack this) if not prices: return 0 buy=[0 for x in prices] sale=[0 for x in prices] maxBuy=-prices[0] maxSale=0 for i in range(1,len(prices)): # if we buy today, max profit is maxSale we have achieved in a selling day minus today's buy price buy[i]=maxSale-prices[i] # if we sale today maximum profit is today's price+highest profit in a previus buing day: sale[i]=maxBuy+prices[i] # maxBuy is highest buying profit upto today maxBuy=max(buy[i],maxBuy) # maxSale is highest sale profit upto today maxSale=max(sale[i],maxSale) return max(sale) def maxProfit2(self, prices): "same as above, but one added restrictions -->After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)" buy=[0 for i in range(len(prices))] sale=[0 for i in range(len(prices))] if len(prices)==0 or len(prices)==1: return 0 buy[0]=-prices[0] maxBuy,maxSale=buy[0],0 for i in range(1,len(prices)): # if we buy today, max profit is maxSale we have achieved in a selling day minus today's buy price buy[i]=maxSale-prices[i] # if we sale today maximum profit is today's price+highest profit in a previus buing day sale[i]=maxBuy+prices[i] # maxBuy is highest buying profit upto today maxBuy=max(maxBuy,buy[i]) # maxSale is highest sale profit upto today, note that we are keeping track of maxSale until i-1'th day, because if we buy today maxSale is before day i-1 as we cant sale today if we buy yesterday # an easy undestanding of this code is below maxSale=max(maxSale,sale[i-1]) return max(sale)) def maxProfit2Easy(self, prices): buy=[0 for i in range(len(prices))] sale=[0 for i in range(len(prices))] buy[0]=-prices[0] maxBuy,maxSale=0,0 for i in range(1,len(prices)): buy[i]=-prices[i] if not sale[:i-1] else max(sale[:i-1])-prices[i] sale[i]=max(buy[:i])+prices[i] return max(sale) solution=Solution() #print solution.minDistance("a","b") #print solution.knapsack01([9,14,16,30],[2,3,4,6],10) #print solution.knapsack01([3,7,2,9],[2,3,4,5],5) #print solution.rob([4,1,7,12,3]) #print solution.climbStairs(4) #print solution.minPathSum([[1,2,3],[4,5,6],[7,8,9]]) #print solution.maxProduct([1,2,-3,4,5,2,1]) #solution.maximumValueContiguousSubsequence([2,7,-10,-1,5,7,10]) #print solution.MakingChange(267,[1,5,10,50,100]) #solution.LongestIncreasingSubsequence([5,3,7,10,15,4,3]) #print solution.maxProduct([-1,-2,-9,-6]) #print solution.minimumTotal([[2],[3,4]]) #print solution.wordBreak("as",[""]) #print solution.canJump([3,2,1,0,4]) #print solution.canCompleteCircuit([15,0],[10,10]) #print solution.maximalSquare([['1','0','1','0','0'],['1','0','1','1','1'],['1','1','1','1','1'],['1','0','0','1','0']]) #print solution.uniquePathsWithObstacles([[1]]) #print solution.maxProfit1([3,4,1,5,7]) #print solution.rob2([2,7,9,3,1]) #print solution.canCompleteCircuit([1,2],[2,1]) print solution.LongestIncreasingSubsequence([10,9,2,5,3,7,101,18])
numero = int(input()) if(i > 1): for i in range(2, numero): if(numero % i == 0): print("No es primo.") break else: print("Es primo.") else: print("No es primo")
## numbers=[] for i in range(10): numbers.append(i) print(numbers) ## numbers=[x for x in range(10)] print(numbers) ## for x in range(10): print(x**2) numbers=[x**2 for x in range(10)] print(numbers) ## numbers=[x*x for x in range(10) if x&3==0] print(numbers) ## myString="hello" myList=[] for letter in myString: myList.append(letter) print(myList) ## myList=[letter for letter in myString] print(myList) ## years=[1998,1987,1856,1993] ages=[2019-x for x in years] #2019-x listeye yazdırılacak olan değerdir. print(ages) ## results=[x if x%2==0 else "Tek" for x in range(1,10)] print(results) ## result=[] for x in range(3): for y in range(3): result.append((x,y)) print(result) ## numbers=[(x,y) for x in range(3) for y in range(3)] print(numbers) ##
#Çift sayıların toplamını yazdıran kod. #Continue komutuna gelince program orayı atlar ve başa döner. toplam=0 i=0 while i<100: i+=1 if i%2==1: #Tek sayılar gelince atlıyor. continue toplam+=i print(toplam) #MemduhFırat isminde u harfine gelince atladı fakat çalışmaya devam etti. isim="MemduhFırat" for i in isim: if i=="u": continue print(i) #Break komutuna gelene kadar sayıları yazdırır. Fakat break komutuna gelince kod çalışmayı durdurur. a=0 while a<58: if a==27: break print(a) a+=1
#Girilecek kelimeyi girilecek sayı kadar ekrana bastıran kod. def EkranaYazdir(kelime, adet): print(kelime*adet) EkranaYazdir('Merhaba\n', 10) #Kendisine girilen sınırsız sayıdaki bilgiyi listeye ekleyen kod. def liste(*args): liste=[] for i in args: liste.append(i) return liste result=liste(10, 20, "araba") print(result) #Girilen iki sayı arasındaki asal sayıları ekrana basan kod. def asalSayiBul(sayi1, sayi2): for i in range(sayi1, sayi2+1): if i>1: for j in range(2,i): if (i%j==0): break else: print(i) sayi1=int(input("1.sayı: ")) sayi2=int(input("2.sayı: ")) asalSayiBul(sayi1,sayi2) #Sayının tam bölenlerini bulan kod. def tambolenbul(sayi): TamBolen=[] for i in range(2,sayi): if sayi%i==0: TamBolen.append(i) return TamBolen print(tambolenbul(20))
#miktar=input("Çekmek istediğiniz tutarı giriniz: ") FiratHesap={ "Ad": "Memduh Fırat Şahin", "HesapNo": "12354648", "Bakiye": 3000, "EkHesap": 2000 } ZahirHesap={ "Ad":"Zahir Şahin", "HesapNo":"1236465", "Bakiye":2000, "EkHesap":1000 } def ParaCek(hesap, miktar): print(f"Merhaba {hesap['Ad']}") if (hesap["Bakiye"]>=miktar): hesap["Bakiye"]-=miktar print("Paranızı Alabilirsiniz.") else: toplam= hesap["Bakiye"]+ hesap["EkHesap"] if (toplam >= miktar): ekHesapKullanimi= input("Ek Hesap Kullanılsın Mı? e/h") if ekHesapKullanimi =='e': ekHesapKullanilacakMiktar=miktar-hesap["Bakiye"] hesap["Bakiye"]=0 hesap["EkHesap"]-=ekHesapKullanilacakMiktar print("Paranızı Alabilirsiniz.") else: print(f"{hesap['HesapNo']} nolu hesabınızda {hesap['Bakiye']} lira bulunmaktadır.") else: print("Yetersiz Bakiye.") def bakiyeSorgula(hesap): print(f"{hesap['HesapNo']} nolu hesabınızda {hesap['Bakiye']} TL bulunmaktadır. Ek hesap limitiniz ise {hesap['EkHesap']} TL'dir.") ParaCek(FiratHesap, 2000) bakiyeSorgula(FiratHesap) print("**********************") ParaCek(FiratHesap, 2000) bakiyeSorgula(FiratHesap)
list1= ["Fırat",20,True,5.8] print(list1) print(list1[0]) my_numberlist=["one","two","three"] my_numberlist2=["four","five","six"] numberlist= my_numberlist+my_numberlist2 print(numberlist) numberlist2= [my_numberlist,my_numberlist2] print(numberlist2[0]) lenght=len(numberlist) lenght2=len(numberlist2) print(lenght) print(lenght2)
#Girilen 2 sayıdan hangisi büyüktür? """ a=int(input("a değerini giriniz ")) b=int(input("b değerini giriniz ")) result= (a<b) print(f"a değeri: {a} b değerinden: {b} küçük müdür? {result}") #Kullanıcıdan 2 adet vize (%60) ve 1 final (%40) notu al. Ortalama 50ye eşit veya büyükse geçti, #değilse kaldı yazsın. vize1=float(input("1.Vize: ")) vize2=float(input("2.Vize: ")) final=float(input("Final: ")) ortalama= ((vize1+vize2)/2)*6/10 + final*4/10 result= (ortalama>=50) print(f"Not Ortalamanız: {ortalama} \nDersten geçtiniz mi? {result}") #Girilen sayının tek mi çift mi olduğunu yazdırın. x=int(input("Sayıyı giriniz: ")) tekcift= (x%2==0) print(f"Girilen sayı: {x}.\nSayı çift mi? {tekcift}") #Girilen sayı negatif mi pozitif mi? y=float(input("Sayıyı giriniz: ")) pozitifmi= (y>0) print(f"Girilen sayı: {y}.\nSayı pozitif mi? {pozitifmi}") """ #Parola ve email bilgisini isteyip doğruluğunu kontrol edin. email, parola="email@firatsahin.com","parola123" emailx=str(input("Email giriniz: ")) parolax=str(input("Parola giriniz: ")) esitmi= (email==emailx.lower().strip()) and (parola==parolax.lower().strip()) print(f"Girdiğiniz bilgiler uyuştu mu? {esitmi}")
num = input ('give me the number: ') num = int (num) if num < 0 or num > 36 print ('give me a valid number') return if num == 0 color = 'green' elif num >= 1 and num <= 10 \ or \ num >= 19 and num <= 28 if num % 2 == 0 color = 'black' else color = 'red' elif num >= 11 and num <= 18 \ or \ num >= 29 and num <= 36 if num % 2 == 0 color = 'red' else color = 'black' print ('your color is' color)
def check_bin_palindrome(num): c = [] bin_str = str(bin(num))[2:] for i in bin_str: c.append(int(i)) return (c == c[::-1]) def check_num_palindrome(num): c = [] for i in str(num): c.append(int(i)) return (c == c[::-1]) MAX_NUM = 1000000 num = 1 max_sum = 0 while True: if (check_bin_palindrome(num) and check_num_palindrome(num)): #print num max_sum += num num += 1 if (num == MAX_NUM): break print max_sum
NUM = 100 def sum_of_squares( max_num): sum = 0 for i in range(1,max_num + 1): sum += i * i return sum def square_of_sum( max_num): sum = 0 for i in range(1,max_num + 1): sum += i return sum * sum print square_of_sum(NUM) - sum_of_squares(NUM)
''' Тестируем функцию CB_Quotes, определенную в модуле CBR_Daily_Quotes.py Эта функция возвращает "словарь словарей" histquotes = {'0':{}, '15':{}, '30':{}, '90':{}} ''' from CBR_Daily_Quotes import * histquotes = CB_Quotes() # print('Котировки сегодня') # print(histquotes['0']) # print('---') # # print('Котировки 15') # print(histquotes['15']) # print('---') # # print('Котировки 30') # print(histquotes['30']) # print('---') # # print('Котировки 90') # print(histquotes['90']) # print('---') print('USD сегодня') print(histquotes['0']['USD'][2]) print('---') print('USD 15') print(histquotes['15']['USD'][2]) print('---') print('USD 30') print(histquotes['30']['USD'][2]) print('---') print('USD 90') print(histquotes['90']['USD'][2]) print('---')
#!/usr/bin/env python # -*- coding: utf-8 -*- from matrix import * #тестирование программы if __name__ == "__main__": try: rle = SLE(5) print("Система уравнений:") rle.print() print('\nРешение системы: ' + str(rle.solve())) print('\nОбратная матрица:') Matrix.print(matrix = Matrix.inverse(rle.getMatrix()), precision = 2) print("Произведение обратной матрицы и исходной:") Matrix.print(Matrix.mul(Matrix.inverse(rle.getMatrix()),rle.getMatrix()), precision=2) print("A*x " + str(Matrix.mulVector(rle.getMatrix(), rle.solve()))) print("Максимум-норма невязки: " + str(abs(max(Vector.sub(Matrix.mulVector(rle.getMatrix(),rle.solve()),rle.getF()))))) print("Определитель: " + str(Matrix.det(rle.getMatrix()))) except Exception as e: print(repr(e))
import numpy as np import matplotlib.pyplot as plt from data import data_matrix, mask_matrix, eval_loss def shrinkage_threshold(x, gamma): """ Applies the shrinkage/soft-threshold operator given a vector and a threshold. It's defined in the equation 1.5 in the paper of FISTA. Input: x: vector to apply the soft-threshold operator. gamma: threshold. Output: x_out: vector after applying the soft-threshold operator. """ return np.sign(x) * np.maximum(np.abs(x) - gamma, 0) def singular_value_shrinkage(X, gamma): """ Performs the called singular value shrinkage defined in the equation 2.11 from the report. Input: X: matrix to apply the singular value shrinkage operator. gamma: threshold. newshape: (optional) if we need to reshape the input (e.g. a vector), we can pass a new shape. Output: X_out: matrix after applying the singular value shrinkage operator. """ U, s, VT = np.linalg.svd(X, full_matrices=True) s_th = shrinkage_threshold(s, gamma) S = np.zeros_like(X) np.fill_diagonal(S, s_th) return (U @ S @ VT) def fista(X, O, i_eval=10, gamma=1, t_k=1, L_hat=0.5, n_iter=2): """ Performs the Fast Iterative Shrinkage-Thresholding Algorithm (FISTA) defined in the paper of FISTA adapted to the problem of matrix completion. Input: X: noisy matrix. A: matrix that encodes the known entries gamma: threshold for the singular value shrinkage operator. n_iter: Number of iteration that the algorithm executes. Output: Y_k: reconstructed matrix after n_iter iterations of the algorithm. """ X_k = X.copy() Y_k = X.copy() gamma = gamma / (1 / L_hat) solutions = [] for i in range(n_iter): X_kk = singular_value_shrinkage(Y_k + L_hat * O * (X - Y_k), gamma) t_kk = (1 + np.sqrt(1 + 4 * t_k ** 2)) / 2 Y_k = X_kk + ((t_k - 1) / t_kk) * (X_kk - X_k) X_k = X_kk t_k = t_kk if i % i_eval == 0: solutions.append(Y_k) solutions.append(Y_k) return solutions def main_first_order(): n_iter = 5000 M = data_matrix() O = mask_matrix() X = M * O fig, ax = plt.subplots() for gamma in [0.5, 0.1, 0.01, 0.001]: solutions = fista(X, O, gamma=gamma, n_iter=n_iter) losses = [eval_loss(M, M_hat) for M_hat in solutions] print("Min loss:", losses[-1]) ax.plot(losses, label=f"$\gamma = {{{gamma}}}$") ax.set_xticks(np.linspace(0, len(losses), 6, dtype=int)) ax.set_xticklabels(np.linspace(1, n_iter, 6, dtype=int)) ax.set_xlabel("Epoch") ax.set_ylabel("Loss") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.axhline(y=0.3382029640059954, linestyle="--", c="maroon", label=r"CVXPY ($\gamma = 0.01$)", alpha=0.7) plt.legend() plt.savefig("loss_approx.pdf") if __name__ == "__main__": main_first_order()
''' ''' def maxItems(numGroups, arr): arr.sort() arr[0] = 1 for i in range(1, numGroups): if arr[i] - arr[i-1] > 1: arr[i] = arr[i-1] + 1 return arr[-1] ''' Top K frequent words https://leetcode.com/discuss/interview-question/542597/ ''' import heapq class Solution: def topKFrequent(self, words: List[str], K: int) -> List[str]: heap = [] count = collections.Counter(words) for key, val in count.items(): heap.append((-val, key)) heapq.heapify(heap) return [heapq.heappop(heap)[1] for _ in range(K)] # n log n solution # count = collections.Counter(words) # candidates = list( count.keys() ) # candidates.sort( key = lambda w: ( -count[w], w) ) # return candidates[:K] ''' Rotten oranges / Zombies in matrix / min hours to send files to all the servers similar questions related to walls / servers refer bfs.py https://leetcode.com/problems/rotting-oranges/ ''' ''' Product suggestions https://leetcode.com/problems/search-suggestions-system/submissions/ ''' class Trie: def __init__(self): self.root = {} self.endSymbol = '*' def insert(self, word): root = self.root for char in word: if char not in root: root[char] = {} root = root[char] root[self.endSymbol] = word def findMatches(self, word): root = self.root self.result = [] for char in word: if char not in root: return [] root = root[char] self.dfs(root) return self.result def dfs(self, root): if type(root) == str: return if self.endSymbol in root: self.result.append(root[self.endSymbol]) for key in list(root.keys()): self.dfs(root[key]) return class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: trie = Trie() result = [] for product in products: trie.insert(product) for i in range(len(searchWord)): matches = trie.findMatches(searchWord[:i + 1]) words = sorted(matches) result.append(words[:3]) return result ''' Reorder Data in Log Files ''' class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: rNum, rAlpha = [], [] for log in logs: print(log.split(" ")[1]) if log.split(" ")[1].isalpha(): rAlpha.append(log) else: rNum.append(log) def sortFun(word): contents = word.split() iden, values = contents[0], contents[1:] return " ".join(values) + iden rAlpha.sort(key=lambda x: sortFun(x)) return rAlpha + rNum ''' Partitions labels https://leetcode.com/problems/partition-labels/ ''' class Solution: def partitionLabels(self, S: str) -> List[int]: endOcc = collections.defaultdict() partitions = [] for i in range(len(S)): c = S[i] endOcc[c] = i p, q = 0, 0 while p < len(S): char = S[p] q = endOcc[char] s = p while p <= q: char = S[p] eo = endOcc[char] if eo > q: q = eo p += 1 partitions.append(q - s + 1) p = q + 1 return partitions ''' Lowest Common Ancestor for binary search tree ''' class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # iterative pv = p.val qv = q.val while root: parent = root.val if pv > parent and qv > parent: root = root.right elif pv < parent and qv < parent: root = root.left else: return root # Recursive parent = root.val pv = p.val qv = q.val if pv > parent and qv > parent: return self.lowestCommonAncestor(root.right, p, q) elif pv < parent and qv < parent: return self.lowestCommonAncestor(root.left, p, q) else: return root ''' Lowest common ancestor for binary tree https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ ''' class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': stack = [root] # Dictionary for parent pointers parent = {root: None} # Iterate until we find both the nodes p and q while p not in parent or q not in parent: node = stack.pop() # While traversing the tree, keep saving the parent pointers. if node.left: parent[node.left] = node stack.append(node.left) if node.right: parent[node.right] = node stack.append(node.right) # Ancestors set() for node p. ancestors = set() # Process all ancestors for node p using parent pointers. while p: ancestors.add(p) p = parent[p] # The first ancestor of q which appears in # p's ancestor set() is their lowest common ancestor. while q not in ancestors: q = parent[q] return q # def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # self.ans = None # self.dfs(root, p, q) # return self.ans # def dfs(self, root, p, q): # if not root: # return False # left = self.dfs( root.left, p, q ) # right = self.dfs( root.right, p, q ) # mid = p == root or root == q # if ( left and right ) or ( mid and left ) or ( mid and right ): # self.ans = root # return mid or left or right ''' Optimal utilization https://leetcode.com/discuss/interview-question/373202 ''' class Solution: def findPairs(self, a, b, target): a.sort(key=lambda x: x[1]) b.sort(key=lambda x: x[1]) l, r = 0, len(b) - 1 ans = [] curDiff = float('inf') while l < len(a) and r >= 0: id1, i = a[l] id2, j = b[r] if (target - i - j == curDiff): ans.append([id1, id2]) elif (i + j <= target and target - i - j < curDiff): ans.clear() ans.append([id1, id2]) curDiff = target - i - j if (target > i + j): l += 1 else: r -= 1 return ans ''' Connecting sticks / Min Cost to Connect Ropes / Min Time to Merge Files ''' class Solution: def connectSticks(self, sticks: List[int]) -> int: pq = sticks heapq.heapify(pq) res = 0 while len(pq) > 1: i, j = heapq.heappop(pq), heapq.heappop(pq) res += (i + j) heapq.heappush(pq, i + j) return res ''' Treasure Island / Treasure Island / Min Distance to Remove the Obstacle https://leetcode.com/discuss/interview-question/347457 ''' class TreasureMap: def min_route(self, grid): if len(grid) == 0 or len(grid[0]) == 0: return -1 self.max_r, self.max_c = len(grid), len(grid[0]) queue = collections.deque() queue.append((0, 0, 0)) grid[0][0] = "D" while queue: row, col, level = queue.popleft() for r, c in self.getNeighbors(row, col, grid): if grid[r][c] == "D": pass elif grid[r][c] == "X": return level + 1 else: queue.append((r, c, level + 1)) grid[r][c] = "D" return -1 def getNeighbors(self, row, col, grid): for r, c in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)): if 0 <= r < self.max_r and 0 <= c < self.max_c: yield r, c ''' Treasure Island 2 https://leetcode.com/discuss/interview-question/356150 ''' def treasure_island(A): row = len(A) if row == 0: return -1 col = len(A[0]) q = [] directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] for i in range(row): for j in range(col): if A[i][j] == "S": q.append([0, i, j]) while (len(q)): step, r, c = q.pop(0) A[r][c] = 'D' for dr, dc in directions: nr = r + dr nc = c + dc if 0 <= nr < row and 0 <= nc < col: if A[nr][nc] == 'X': return step + 1 elif A[nr][nc] == 'O': q.append([step + 1, nr, nc]) return -1 ''' chopping gold course ( same as above ) https://leetcode.com/problems/cut-off-trees-for-golf-event/ ''' class Solution: def cutOffTree(self, forest): # iterate over forest and find r, c for all trees. sort them according to v. trees = [] for r in range(len(forest)): for c in range(len(forest[0])): if forest[r][c] > 0: trees.append((forest[r][c], r, c)) print(sorted(trees)) # iterate over sorted trees, and find distance between first two trees, and so on. trees = sorted(trees) sr = sc = ans = 0 for _, tr, tc in trees: d = self.bfs(forest, sr, sc, tr, tc) if d < 0: return -1 ans += d sr, sc = tr, tc return ans # classic BFS def bfs(self, forest, sr, sc, tr, tc): R, C = len(forest), len(forest[0]) queue = collections.deque([(sr, sc, 0)]) seen = {(sr, sc)} while queue: r, c, d = queue.popleft() if r == tr and c == tc: return d for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): if (0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen and forest[nr][nc]): seen.add((nr, nc)) queue.append((nr, nc, d + 1)) return -1 ''' 2 sum / movies in flight https://leetcode.com/discuss/interview-question/356960 ''' ''' Deep copy of Linked List with random pointer. https://leetcode.com/problems/copy-list-with-random-pointer/ ''' class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None p = head while p: new_node = Node(p.val, None, None) new_node.next = p.next p.next = new_node p = new_node.next ptr = head while ptr: ptr.next.random = ptr.random.next if ptr.random else None ptr = ptr.next.next oldhead = head newhead = head.next newH = head.next while oldhead: oldhead.next = oldhead.next.next newhead.next = newhead.next.next if newhead.next else None oldhead = oldhead.next newhead = newhead.next return newH ''' Merge two sorted list https://leetcode.com/problems/merge-two-sorted-lists/ ''' class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 p, q = l1, l2 newhead = ListNode(-1, None) R = newhead while p and q: if p.val <= q.val: newhead.next = p p = p.next else: newhead.next = q q = q.next newhead = newhead.next if p: newhead.next = p elif q: newhead.next = q return R.next ''' Subtree of another tree https://leetcode.com/problems/subtree-of-another-tree/ ''' class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not t: return False return self.check(s, t) def check(self, s, t): if not s: return False if (s.val == t.val) and self.checkSame(s, t): return True return self.check(s.left, t) or self.check(s.right, t) def checkSame(self, s, t): if not s and not t: return True elif not s or not t: return False elif s.val != t.val: return False else: return self.checkSame(s.left, t.left) and self.checkSame(s.right, t.right) ''' Search 2D matrix ''' class Solution: def searchMatrix(self, matrix, target): i, j = len(matrix) - 1, 0 while (i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix[0])): num = matrix[i][j] if num == target: return True elif num < target: j += 1 elif num > target: i -= 1 return False ''' Favorite genre https://leetcode.com/discuss/interview-question/373006 ''' ''' Spiral traverse https://www.algoexpert.io/questions/Spiral%20Traverse ''' ''' VVV important question to understand. Subarrays with K distinct integers https://leetcode.com/discuss/interview-question/370157 ''' class Solution: def subarraysWithKDistinct(self, A: List[int], K: int) -> int: def helper(A, K): count = 0 i, j = 0, 0 distinct = {} while j < len(A): distinct[A[j]] = distinct.get(A[j], 0) + 1 while len(distinct) > K: distinct[A[i]] -= 1 if distinct[A[i]] == 0: del distinct[A[i]] i += 1 count += j - i + 1 j += 1 return count return helper(A, K) - helper(A, K - 1) ''' Minimum path sum number of unique paths https://leetcode.com/problems/minimum-path-sum/ ''' class Solution: def minPathSum(self, grid: List[List[int]]) -> int: # Dynamic programming - storing min to reach a point from destination. for i in reversed(range(len(grid))): for j in reversed(range(len(grid[0]))): # elements on the bottom of the row if i == len(grid) - 1 and j != len(grid[0]) - 1: grid[i][j] += grid[i][j + 1] # elements on the right column if j == len(grid[0]) - 1 and i != len(grid) - 1: grid[i][j] += grid[i + 1][j] # elements not on the border. if j != len(grid[0]) - 1 and i != len(grid) - 1: grid[i][j] += min(grid[i + 1][j], grid[i][j + 1]) return grid[0][0] ''' Unique paths 2 number of unique paths with obstacles ''' class Solution: def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int: if grid[0][0] == 1: return 0 rows = len(grid) columns = len(grid[0]) grid[0][0] = 1 # 1 path to reach the start for i in range(1, rows): grid[i][0] = int(grid[i][0] == 0 and grid[i - 1][0] == 1) for j in range(1, columns): grid[0][j] = int(grid[0][j] == 0 and grid[0][j - 1] == 1) for i in range(1, rows): for j in range(1, columns): if grid[i][j] == 0: grid[i][j] = grid[i - 1][j] + grid[i][j - 1] else: grid[i][j] = 0 return grid[rows - 1][columns - 1] ''' Max of min altitudes https://leetcode.com/discuss/interview-question/383669/ ''' res = [[0 for col in range(len(grid[0]))] for row in range(len(grid))] row = len(grid) - 1 col = len(grid[0]) - 1 for i in range(row, -1, -1): for j in range(col, -1, -1): if i == row and j == col: res[i][j] = float('inf') elif i == row and j != col: res[i][j] = min(grid[i][j], res[i][j + 1]) elif i != row and j == col: res[i][j] = min(grid[i][j], res[i + 1][j]) elif i == 0 and j == 0: res[i][j] = max(res[i + 1][j], res[i][j + 1]) else: res[i][j] = max(min(grid[i][j], res[i][j + 1]), min(grid[i][j], res[i + 1][j])) return res[0][0] ''' K closest points to origin ''' class Solution(object): def kClosest(self, points, K): points.sort(key = lambda P: P[0]**2 + P[1]**2) return points[:K] ''' Dont worry about this question Too mathematical https://leetcode.com/problems/generate-parentheses/solution/ ''' ''' Prison after N days ''' class Solution: def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]: trackCombinations = {} combination = tuple(cells) while True: combination = self.getNextCombination(combination) if combination in trackCombinations: break else: trackCombinations[combination] = combination patternRepeatsAfter = (N) % len(trackCombinations) combinations = list(trackCombinations.values()) return combinations[patternRepeatsAfter - 1] def getNextCombination(self, combination): cells = list(combination) for i in range(1, len(combination) - 1): if combination[i - 1] ^ combination[i + 1] == 0: cells[i] = 1 else: cells[i] = 0 cells[0] = 0 cells[-1] = 0 return tuple(cells) ''' Min Cost to Repair Edges Min Cost to Connect All Nodes (a.k.a. Min Cost to Add New Roads) https://leetcode.com/discuss/interview-question/356981 https://leetcode.com/discuss/interview-question/357310 Just take the unionFindKruskalsAlgorithm and update already connected node's cost as 0. ''' ''' Highest Profit https://leetcode.com/discuss/interview-question/823177/Amazon-or-OA-2020-or-Find-The-Highest-Profit ''' ''' baseball https://leetcode.com/problems/baseball-game/description/ ''' ''' maximum units https://leetcode.com/discuss/interview-question/793606/Amazon-or-OA-2020-or-Maximum-Units ''' ''' All possible lengths of substring with k - 1 largest item association https://leetcode.com/discuss/interview-question/783947/Amazon-or-OA-or-SDE-1-or-Aug-2020 '''
''' Basic stack: Use list to implement stack ''' ''' The below sum is building min max stack ''' # Feel free to add new properties and methods to the class. class MinMaxStack: def __init__(self): self.minMaxStack = [] self.stack = [] def peek(self): return self.stack[len(self.stack) - 1] def pop(self): self.minMaxStack.pop() return self.stack.pop() def push(self, number): newMinMax = {"min": number, "max": number} if self.minMaxStack: lastElement = self.minMaxStack[len(self.minMaxStack)-1] newMinMax["min"] = min(lastElement["min"], newMinMax["min"]) newMinMax["max"] = max(lastElement["max"], newMinMax["max"]) self.minMaxStack.append(newMinMax) self.stack.append(number) def getMin(self): return self.minMaxStack[len(self.minMaxStack) - 1]["min"] def getMax(self): return self.minMaxStack[len(self.minMaxStack) - 1]["max"] ''' The below sum is building a queue using 2 stacks ''' class MyQueue: def __init__(self): self.stack1 = [] self.stack2 = [] def push(self, x: int) -> None: self.stack1.append(x) def pop(self) -> int: self.peek() return self.stack2.pop() def peek(self) -> int: if not self.stack2: while self.stack1: self.stack2.append(self.stack1.pop()) return self.stack2[-1] def empty(self) -> bool: return not self.stack1 and not self.stack2 ''' Circular tour. https://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/ 1. Start inserting each station into queue. if petrol is negative, dequeue from front. and enqueue again.. ''' ''' Next Greater Element 1 https://leetcode.com/problems/next-greater-element-i/ ''' class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: res = [] stack = [] mapping = {} for n in nums2: while stack and n > stack[-1]: mapping[stack.pop()] = n stack.append(n) while stack: mapping[stack.pop()] = -1 for n in nums1: res.append(mapping[n]) return res ''' Next Greater Element 2 https://leetcode.com/problems/next-greater-element-ii/ ''' class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: stack = [] result = [-1 for i in range(len(nums))] n = len(nums) for i in reversed(range(2 * len(nums))): while stack and nums[i % n] >= nums[stack[-1]]: stack.pop() result[i % n] = nums[stack[-1]] if stack else -1 stack.append(i % n) return result ''' Basic Calculator - I ''' class Solution: def calculate(self, s: str) -> int: operand, n = 0, 0 res, num = 0, 0 stack = [] sign = 1 for c in s: if c.isdigit(): num = (num * 10) + int(c) elif c in ['+', '-']: res += sign * num sign = 1 if c == '+' else -1 num = 0 elif c == '(': stack.append(res) stack.append(sign) sign, res = 1, 0 elif c == ')': res += sign * num res *= stack.pop() res += stack.pop() num = 0 return res + num * sign
class Solution: def isKangarooWord(self, words, synonyms, antonyms)): if not synonyms and not antonyms: return 0 score = 0 seen= set() seen = collections.defaultdict() for synonym in synonyms: word, syns = synonym.split(":") if word not in words: continue for syn in syns.split(","): if subsequence(syn, word): score += 1 if syn not in seen: seen.add(syn) else: score += 1 seen.remove(syn) for antonym in antonyms: word, antons = antonym.split(":") if word not in words: continue for ant in antons.split(","): if subsequence(ant, word): score -= 1 return score def subsequence(self, s, t): LEFT_BOUND, RIGHT_BOUND = len(s), len(t) p_left = p_right = 0 while p_left < LEFT_BOUND and p_right < RIGHT_BOUND: if s[p_left] == t[p_right]: p_left += 1 p_right += 1 return p_left == LEFT_BOUND and s not in t
''' Design Parking Lot System https://leetcode.com/problems/design-parking-system/ ''' ''' 1. Domain Entities: 1. Car : CarSize - CarSize size # or this can be enum 2 CarSize - small = 1 - medium = 2 - large = 3 2. ParkingLot - int capacity_small - int capacity_medium - int capacity_large 2. Application AddCar() 3. Data / repositories 4. Intrastructure ''' import enum class CarSize(enum.Enum): small = 1 medium = 2 large = 3 class ParkingLot: def __init__(self, small, medium, large): self.parkinglot = { CarSize.small.value: small, CarSize.medium: medium, CarSize.large: large } def addCar(self, size): if self.parkinglot[size]: self.parkinglot[size]-=1 return True return False
# -*- coding: utf-8 -*- # Invesigate the demand data for products # First positive sample is extracted # Assuming the 0 demand at the beginning of each series are due to the new product # New products do not have demand before they are commercialized import numpy as np import pandas as pd import util filename = "Forecasting_Exercise.csv" #generate 100 input file for each product, if not done yet lstm.input_prep(filename, "input_") #calculte and plot the first positive index first_pos = [] for i in range(1, 101, 1): inp = pd.read_csv("./input/input_" + str(i) + ".csv") first_pos.append(util.first_Positive(inp[str(i)])) #visualizing the weekly demand series for all the 100 products # layout of 4 for each row and 25 rows totally rws = 25 cls = 4 sx = 6*cls sy = 4.2*rws hs = 0.5 inpname = "input_" util.plot_nxm(inpname, rws, cls, sx, sy, hs)
from tensorflow.examples.tutorials.mnist import input_data import keras as ks from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten, Activation import tensorflow as tf import numpy as np mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_images = mnist.train.images train_labels = mnist.train.labels test_images = mnist.test.images test_labels = mnist.test.labels ''' def initializeWeights(shape): initial_weights = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial_weights) ''' train_images = np.reshape(train_images, (-1, 28, 28, 1)) test_images = np.reshape(test_images, (-1, 28, 28, 1)) #conv2d = Conv2D(data_format='') model = ks.models.Sequential() model.add(Conv2D(32, (3,3), input_shape=(28, 28, 1))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Conv2D(32, (3,3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Conv2D(64, (3,3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) adam = ks.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) model.fit(train_images, train_labels, epochs=20, batch_size=100) score = model.evaluate(test_images, test_labels, batch_size=100) print(score)
x = input("Enter a word here: ") def foo(s): ret = "" i = True for char in s: if i: ret += char.lower() else: ret += char.upper() if char != ' ': i = not i return ret def replace_vowel(s): word = foo(x) vowels = ("A", "E", "I", "O", "U") for vowels in vowels: word = word.replace(vowels, "*") return word def check_parentheses(s): word = foo(x) if word.count("(") == word.count(")"): print("Balanced? True.") else: print("Balanced? False.") return "" print (foo(x)) print (replace_vowel(x)) print(check_parentheses(x))
"""This code solves the lorentz system""" import numpy as np class Lorentz: """This is the Lorentz Class""" def __init__(self,x,y,z,sigma,beta,rho): self.x=np.array([x]) self.y=np.array([y]) self.z=np.array([z]) self.sigma=sigma self.beta=beta self.rho=rho def time_step(self,dt): """This calculate the next step""" x1=self.x[-1] y1=self.y[-1] z1=self.z[-1] dx=self.sigma*(y1-x1) dy=x1*(self.rho-z1)-y1 dz=x1*y1-self.beta*z1 self.x=np.append(self.x,x1+dx*dt) self.y=np.append(self.y,y1+dy*dt) self.z=np.append(self.z,z1+dz*dt)
""" Traveling Salesman problem for 2d (x,y) case author: Valentyn Stadnytskyi data: 2017 - Nov 17 2018 The traveling salesman algorithm takes an input array of coordinates and vary array (True/False) """ __vesrion__ = '1.0.0' from time import time, sleep import sys if sys.version_info[0] == 2: from time import clock as perf_counter else: from time import perf_counter import platform def create_test_sequence(N, dim = 2): """ """ from numpy import random, array arr = (random.rand(N, dim)-0.5)*10 arr[0] = array([0]*dim) arr[-1] = array([0]*dim) vary = arr[:,0]*0+1 vary[0] = 0 vary[-1] = 0 return arr, vary def euclidean_distance(i,j): """ return euclidean_distance between two points """ from numpy import array, nan dim_i = len(i) dim_j = len(j) if dim_i == dim_j: dim = dim_i distance = ((array(i) - array(j))**2).sum()**0.5 else: distance = nan return distance def total_distance(arr): """ returns total distance as a sum of distances. """ length = arr.shape[0] sum_distance = 0.0 for i in range(length-1): a = arr[i] b = arr[i+1] sum_distance += euclidean_distance(a,b) return sum_distance def distance(i,j): """ simple wrapper around euclidean_distance """ return euclidean_distance(i,j) def minimize(arr, vary, method = 'brute_force', N = 300): if method == 'brute_force': for i in range(int(N)): arr = minimize_brute_force_once(arr) return arr elif method == 'temperature': return arr def minimize_brute_force_once(arr): """ complete random minimization algorithm; slow and inefficient """ from numpy.random import shuffle from numpy import concatenate, copy mid_array = arr[1:-1] new_mid_array = copy(mid_array) new_arr = copy(arr) new_arr[0] = arr[0] new_arr[-1] = arr[-1] shuffle(new_mid_array) new_arr[1:-1] = new_mid_array distance = total_distance(arr) new_distance = total_distance(new_arr) if new_distance < distance: return new_arr else: return arr def minimize_temperature(self): """ """ import random, numpy, math, copy tour = list(self.sequence) cities = self.data N = len(self.sequence) for temperature in numpy.logspace(0,5,num=100000)[::-1]: [i,j] = sorted(random.sample(list(range(N)), 2)); newTour = tour[:i] + tour[j:j + 1] + tour[i + 1:j] + tour[i:i + 1] + tour[j+1:]; if math.exp((sum([ math.sqrt(sum([(cities[tour[(k+1) % N]][d] - cities[tour[k % N]][d])**2 for d in [0,1] ])) for k in [j,j-1,i,i-1]]) - sum([math.sqrt(sum([(cities[newTour[(k+1) % N]][d] - cities[newTour[k % N]][d])**2 for d in [0,1] ])) for k in [j,j-1,i,i-1]])) / temperature) > random.random(): self.sequence = copy.copy(newTour); def init(data): from numpy import array self.data = data self.length = int(data.size/2) self.sequence = range(1, self.length) def run(data): self.init(data) self.minimize(N=500) return self.sorted_data @property def sorted_data(self): from numpy import array data = [] data.append(self.data[0]) for item in self.sequence: data.append(self.data[item]) data.append(self.data[0]) return array(data) ##### OLD functions def matrix(arr): from numpy import zeros, roll, nan, nanmax, arange length = int(arr.size/2) N_vector = arange(0, length,1) x_vector = arr[:, 0] y_vector = arr[:, 1] Mx = zeros((length, length)) My = zeros((length, length)) Mn = zeros((length, length)) for i in range(length): Mx[i] = roll(x_vector, i) My[i] = roll(y_vector, i) Mn[i] = roll(N_vector, i) return Mx, My, Mn def minimize_matrix(Mx, My, Mn): from numpy import matmul, nan, where, nanmax Dx = matmul(Mx, Mx.T) Dy = matmul(My, My.T) length = Mx.shape[0] D = Dx+Dy for i in range(length): D[i,i] = nan res = where(D == nanmax(D)) return res def test(self): global Mn N = 5 self.init(N) print(self.minimize()) Mx, My, Mn = self.matrix() print(Mn) self.plot_x() return Mn,Mx,My def plot(arr, vary = None, labels = None): """ visualizes the array of coordintes. Parameters vary and labels can be used to customize the graph. Do not work for now. TODO. """ from matplotlib import pyplot as plt from numpy import where plt.ion() if vary is None: vary = arr[:,0]*0+1 vary[0] = vary[-1] = 0 x = arr[:,0] y = arr[:,1] x_data = x[where(vary != 0)] y_data = y[where(vary != 0)] x_center = x[where(vary == 0)] y_center = y[where(vary == 0)] if labels is None: n = list(range(len(x-2))) fig, ax = plt.subplots() ax.plot(x, y, '-o') for i, txt in enumerate(n): ax.annotate(txt, (x[i], y[i])) plt.show() if __name__ == '__main__': from pdb import pm arr, vary = create_test_sequence(10) total_dist = total_distance(arr)
class Patient (object): id=0 def __init__ (self,name,allergies): patient.id +=1 self.name = name self.allergies = allergies self.bed_number = None return self class Hospital (object): bed_number = 0 def __init__ (self,hospital_name,capacity): self.patients = [] self.hospital_name = hospital_name self.capacity = capacity def admit (self,patient): if len(self.patients)>=self.capacity: print "We cannot accept more patients, we are full!" else: self.patients.append(patient) print self.patients Hospital.bed_number += 1 patient.bed_number = Hospital.bed_number return "Admission confirmed" def discharge(self, patient): patient.bed_number = None self.patients.remove(patient) p1 = Patient("Todd", "Gluten") p2 = Patient("Brittany", "Gluten, Soy, Dairy, Sesame, Mushroom, Almond") p3 = Patient("Connie", "Sulfa") h1 = Hospital("Mercy General",3) h1.admit(p1) h1.admit(p2) h1.admit(p3) print h1.admit(p1) print h1.patients h1.discharge(p1) print h1.patients print p1.bed_num print p2.bed_num
import sys def sum_values(a,b,c): ''' adding parametes Parameters a (int) b (int) c (int) Returns sum (int): sum of above number based on condition ''' temp=[13,14,17,18,19] sum=a+b+c sum= sum-a if a in temp else sum sum= sum-b if b in temp else sum sum= sum-c if c in temp else sum return sum def main(a,b,c): '''check all argument value are interger type or not Parameters a (string) b (string) c (string) Returns sum (int): sum of above number based on condition ValueError : if all parameter are not type casted to int ''' try: a,b,c=map(int,[a,b,c]) except ValueError as es: return 'All inputs must be numeric' else: result=sum_values(a,b,c) return result if __name__=='__main__': try: _,a,b,c=sys.argv except ValueError as e: print('Exactly 3 numbers are required') else: result=main(a,b,c) print(result)
# WriteTweets Class # Programmed by: Jesse Smith # Course: CIS225E-HYB1 # Description: Write lists of tweets by ReadTweets class to files. # This removes usernames and creates anonymity of tweets from read import ReadTweets class WriteTweets(ReadTweets): def __init__(self, filename): ReadTweets.__init__(self, filename) def writetweets(self): usernames = super(WriteTweets, self).get_usernames() tweets = super(WriteTweets, self).get_tweets() dates = super(WriteTweets, self).get_dates() #Create username, twee, and date file usernameFile = open("username.txt", 'w') tweetFile = open("listtweets.txt", 'w') dateFile = open("dates.txt", 'w') #Write lists in different files for item in usernames: usernameFile.write(item.upper() + '\n') usernameFile.close() for item in tweets: tweetFile.write(item.upper() + '\n') tweetFile.close() for item in dates: dateFile.write(item + '\n') dateFile.close() return print("Usernames, tweets, and dates files have been written")
i=int(input()) j=int(input()) k=int(input()) if(i>=j and i>=k): print(i) elif(j>=i and j>=k): print(j) else: print(k)
def leapyear(year: int): if(year % 4 == 0): #divisible by 4 if(year % 100 != 0): #but not divisible by 100 return True elif(year % 400 == 0): #unless divisible by 400 return True return False
# -*- coding: utf-8 -*- """ Created on Mon May 6 12:46:20 2019 @author: mynam """ grid = list() for i in range(6): row = input().strip().split(' ') row = list(map(int, row)) grid.append(row) # start max_hourglass_sum at smallest possible hourglass hourglass_values = [] for i in range(1,5): for j in range(1, 5): hourglass = grid[i-1][j-1] + grid[i-1][j] +grid[i-1][j+1] + grid[i][j] + grid[i+1][j-1] + grid[i+1][j] +grid[i+1][j+1] hourglass_values.append(hourglass) print(max(hourglass_values))
#coding: utf-8 import math def d(x1,y1,x2,y2): d = math.sqrt(((x1-x2)**2) + ((y1-y2)**2)) return d if __name__ == "__main__": print("Entre com X1") x1 = eval(input()) print("Entre com Y1") y1 = eval(input()) print("Entre com X2") x2 = eval(input()) print("Entre com Y2") y2 = eval(input()) if d(x1,x2,y1,y2) >= 10: print("longe") else: print("perto")
# ************************************************ # Point.py # Define a classe Ponto # Autor: Márcio Sarroglia Pinho # pinho@pucrs.br # ************************************************ class Point: def __init__(self, x=0,y=0,z=0): self.x = x self.y = y self.z = z #print ("Objeto criado") def imprime(self): print (self.x, self.y, self.z) def set(self, x, y, z=0): self.x = x self.y = y self.z = z def multiplica(self, x, y, z): self.x *= x self.y *= y self.z *= z def isEqual(self, a): if self.x == a.x and self.y == a.y: return True else: return False #P = Point() #P.set(1,2) #P.imprime() #P.set(23,34,56) #P.imprime()
import math def _money(): money=int(input("You have an amount of: ")) return money def aplprc(): apl_price=int(input("An apple costs: ")) return apl_price def maxapls(): max_apls=int(money/apl_price) return max_apls def getTotal(): total=apl_price * max_apls return total def getChange(): change=money-total return change def display(max_apls, change): print(f"You can buy {max_apls} apples and your change is {change} pesos.") money=_money() apl_price=aplprc() max_apls=maxapls() total=getTotal() change=getChange() display(max_apls, change)
from random import random from random import randint import sys def main(): w = randint(int(sys.argv[1]), 2 * int(sys.argv[1])) print w a = randint(int(sys.argv[2]), int(sys.argv[2])) syllabus = [] for i in range(w): syllabus.append([]) for i in range(a): name = 'HW' + str(i) syllabus[randint(0, w - 1)].append(name) syllabus[randint(0, w - 1)].append(name) for week in syllabus: size = len(week) output = '' output += str(size) for name in week: output += ' ' + name print output if __name__ == '__main__': main()
n = int(input()) min_name = '' min_time = 10000000 for _ in range(n): time, name = input().split(' ', 1) if int(time) < min_time: min_time = int(time) min_name = name print(min_name)
#!/usr/env/python # _*_ coding: utf-8 _*_ """ 排序算法 reference-link: [1]-https://sites.fas.harvard.edu/~cscie119/lectures/sorting.pdf [2]-https://en.wikipedia.org/wiki/Shellsort [3]-https://en.wikipedia.org/wiki/Quicksort [4]-https://www.geeksforgeeks.org/hoares-vs-lomuto-partition-scheme-quicksort/ [5]-http://personal.kent.edu/%7Ermuhamma/Algorithms/MyAlgorithms/Sorting/countingSort.htm [6]-https://stackoverflow.com/questions/9755721/how-can-building-a-heap-be-on-time-complexity """ class Sort(object): @staticmethod def __compare__(left, right, descend_order=False): if descend_order: return left > right else: return left < right @staticmethod def __index_of_selection__(input_array, start, end, descend_order=False): if not input_array: raise ValueError("input array is empty.") if start < 0 \ or end < 0 \ or start > end \ or end >= len(input_array): raise AssertionError("invalid array index", start, end) select_index = start for i in range(start + 1, end + 1): if descend_order: # 降序排列时选择次大元素 if input_array[i] > input_array[select_index]: select_index = i elif input_array[i] < input_array[select_index]: select_index = i return select_index @staticmethod def __swap_element__(input_array, index_left, index_right): if not input_array: raise ValueError("input array is empty.") if index_left < 0 \ or index_right < 0 \ or index_left >= len(input_array) \ or index_right >= len(input_array): raise AssertionError("invalid array index", index_left, index_right) if index_left != index_right: input_array[index_left], input_array[index_right] = input_array[index_right], input_array[index_left] @staticmethod def selection_sort(input_array, descend_order=False): """ 选择排序 依次从[0,len-1]位置选择应该放在这个位置上的那个最小或者最大元素 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ for i in range(len(input_array) - 1): select_index = Sort.__index_of_selection__(input_array, i, len(input_array) - 1, descend_order) if i != select_index: Sort.__swap_element__(input_array, i, select_index) # print("after ", i + 1, " select: ", input_array) @staticmethod def insertion_sort(input_array, descend_order=False): """ 插入排序 依次将[1,len-1]位置元素插入在适当位置 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ for i in range(1, len(input_array)): to_insert = input_array[i] j = i if descend_order: while j > 0 and input_array[j - 1] < to_insert: # 降序排列时小于插入元素的部分后移 input_array[j] = input_array[j - 1] j -= 1 else: while j > 0 and input_array[j - 1] > to_insert: # 升序排列时大于插入元素的部分后移 input_array[j] = input_array[j - 1] j -= 1 if j != i: input_array[j] = to_insert print("after ", i, " insert: ", input_array) @staticmethod def shell_sort(input_array, descend_order=False): """ 希尔排序 对插入排序的改进 根据间隔序列(gap sequence)对子数组进行插入排序 间隔序列对排序效率有影响 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ gap_seq = [701, 301, 132, 57, 23, 10, 4, 1] # Using Marcin Ciura's gap sequence # gap_seq = [5, 3, 1] for gap in gap_seq: for i in range(gap, len(input_array)): to_insert = input_array[i] j = i if descend_order: while j >= gap and input_array[j - gap] < to_insert: # 降序排列时小于插入元素的部分后移 input_array[j] = input_array[j - gap] j -= gap else: while j >= gap and input_array[j - gap] > to_insert: # 升序排列时大于插入元素的部分后移 input_array[j] = input_array[j - gap] j -= gap if j != i: input_array[j] = to_insert print('after gap= ', gap, " array is: ", input_array) @staticmethod def bubble_sort(input_array, descend_order=False): """ 冒泡排序 进行len-1趟冒泡过程,每次将最大(或者最小元素)交换到最终位置 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ for j in range(len(input_array) - 1, 0, -1): for i in range(j): if descend_order: # 降序排列时 将最小元素交换到最终位置 if input_array[i] < input_array[i + 1]: Sort.__swap_element__(input_array, i, i + 1) else: # 升序排列时 将最大元素交换到最终位置 if input_array[i] > input_array[i + 1]: Sort.__swap_element__(input_array, i, i + 1) @staticmethod def lomuto_partition(input_array, low, high, descend_order=False): """ lomuto划分算法 :param input_array: 输入数组 :param low: 开始索引 :param high: 停止索引 :param descend_order: 是否降序排列 :return: pivot所在索引pos 划分区间为[low, pos-1] [ pos+1, high] """ if low < 0 \ or high < 0 \ or low >= len(input_array) \ or high >= len(input_array): raise AssertionError("invalid array index", low, high) pivot = input_array[high] # right most element as pivot print('lomuto partition choosing pivot= ', pivot) i = low - 1 # marker for element less than pivot for j in range(low, high): if descend_order: # 降序排列 大的元素在左 小的元素在右 if input_array[j] > pivot: i += 1 Sort.__swap_element__(input_array, i, j) else: # 升序排列 大的元素在右 小的元素在左 if input_array[j] < pivot: i += 1 Sort.__swap_element__(input_array, i, j) Sort.__swap_element__(input_array, i + 1, high) return i + 1 @staticmethod def hoare_partition(input_array, low, high, descend_order=False): if low < 0 \ or high < 0 \ or low >= len(input_array) \ or high >= len(input_array): raise AssertionError("invalid array index", low, high) pivot = input_array[(low + high) / 2] print('hoare partition choosing pivot= ', pivot) while True: if descend_order: # 降序排列 大的元素在左 小的元素在右 while low < high and input_array[low] > pivot: low += 1 while low < high and input_array[high] < pivot: high -= 1 else: # 升序排列 大的元素在右 小的元素在左 while low < high and input_array[low] < pivot: low += 1 while low < high and input_array[high] > pivot: high -= 1 if low < high: Sort.__swap_element__(input_array, low, high) low += 1 high -= 1 else: return high @staticmethod def quick_sort_lomuto(input_array, descend_order=False): """ 快速排序 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def quick_sort(in_array, low, high): pos = Sort.lomuto_partition(in_array, low, high, descend_order) if low < pos - 1: quick_sort(in_array, low, pos - 1) if pos + 1 < high: quick_sort(in_array, pos + 1, high) if input_array: quick_sort(input_array, 0, len(input_array) - 1) @staticmethod def quick_sort_hoare(input_array, descend_order=False): """ 快速排序 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def quick_sort(in_array, low, high): pos = Sort.hoare_partition(in_array, low, high, descend_order) if low < pos: quick_sort(in_array, low, pos) if pos + 1 < high: quick_sort(in_array, pos + 1, high) if input_array: quick_sort(input_array, 0, len(input_array) - 1) @staticmethod def merge_sort(input_array, descend_order=False): """ 归并排序 需要和数组大小等长的辅助空间 先划分数组然后合并子数组 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def merge_array(array, left_start, left_end, right_start, right_end, descend=False): result_array = [None for _ in range(right_end - left_start)] # 辅助空间 i, j, k = left_start, right_start, 0 while i <= left_end and j <= right_end: if Sort.__compare__(array[i], array[j], descend): result_array[k] = array[i] i += 1 else: result_array[k] = array[j] j += 1 k += 1 if i <= left_end: result_array[k:] = array[i:left_end + 1] if j <= right_end: result_array[k:] = array[j:right_end + 1] array[left_start:right_end + 1] = result_array def split_and_merge(array, start, end, desc_order=False): if end <= start: return mid = (start + end) / 2 left_start, left_end = start, mid right_start, right_end = mid + 1, end split_and_merge(array, left_start, left_end, descend_order) split_and_merge(array, right_start, right_end, descend_order) print("merge: ", array[left_start:left_end + 1], array[right_start:right_end + 1]) merge_array(array, left_start, left_end, right_start, right_end, desc_order) split_and_merge(input_array, 0, len(input_array) - 1, descend_order) @staticmethod def count_sort(input_array, descend_order=False): """ 计数排序 尚不支持负数排序 根据输入数据计算出一个max_num大小的辅助计数数组 升序时计数数组中位置i存放数值<=i的元素个数 根据元素的计数值 决定它在排序后数组中的位置 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def value_to_pos(value, max_value, desc_order=False): if desc_order: return max_value - value else: return value if not input_array: return max_num = max(input_array) count_array = [0 for _ in range(max_num+1)] out_array = [None for _ in range(len(input_array))] for x in input_array: pos = value_to_pos(x, max_num, desc_order=descend_order) count_array[pos] += 1 for i in range(1, len(count_array)): count_array[i] += count_array[i-1] for x in input_array: pos = value_to_pos(x, max_num, desc_order=descend_order) out_array[count_array[pos] - 1] = x count_array[pos] -= 1 for i in range(len(input_array)): input_array[i] = out_array[i] @staticmethod def radix_sort(input_array, descend_order=False): """ 基数排序 尚不支持负数排序 对元素的每个位进行基本排序(计数、快排等) 最后结果即有序 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def count_sort(array, exp, desc_order=False): def value_to_pos(value, max_value, des_order=False): if des_order: return max_value - (value / exp) % 10 # 利用exp计算对应位的数值 例如170 计算十位则为7 else: return (value / exp) % 10 if not array: return max_num = 9 count_array = [0 for _ in range(max_num + 1)] out_array = [None for _ in range(len(array))] for x in array: pos = value_to_pos(x, max_num, des_order=desc_order) count_array[pos] += 1 for i in range(1, len(count_array)): count_array[i] += count_array[i - 1] for i in range(len(array)-1, -1, -1): # 注意这里逆序填入辅助数组 保证原数组中先出现元素在小的索引位置 pos = value_to_pos(array[i], max_num, des_order=descend_order) out_array[count_array[pos] - 1] = array[i] count_array[pos] -= 1 for i in range(len(array)): array[i] = out_array[i] if not input_array: return exp_value = 1 # 用于计算数值对应位的数字 使用least significant digit(LSD)策略 max_number = max(input_array) while max_number / exp_value > 0: count_sort(input_array, exp_value, descend_order) print(("after sort by %d's digit: " % exp_value), input_array) exp_value *= 10 @staticmethod def heap_sort(input_array, descend_order=False): """ 堆排序 根据升序构造大顶堆(降序则小顶堆) 依次将堆顶元素输出到数组尾部则排序完成 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ class BinaryHeap(object): """ 二叉堆 """ def __init__(self, input_data, heap_type="max"): self.data = input_data if heap_type == "max": self.cmp_func = lambda x, y: x > y else: self.cmp_func = lambda x, y: x < y self.heapify() @staticmethod def get_parent_index(i): return (i - 1) / 2 @staticmethod def get_left_index(i): return 2 * i + 1 @staticmethod def get_right_index(i): return 2 * i + 2 def heapify(self): if not self.data: return start = (len(self.data) - 1) / 2 for i in range(start, -1, -1): self.sift_down(i, len(self.data) - 1) def sift_down(self, start, end): """ 将start开始的节点持续与[start, end]范围内孩子节点比较 如果违背堆性质则交换节点 否则算法停止 :param start: 开始元素索引 :param end: 停止元素索引 :return: None """ if start >= end: return left, right = BinaryHeap.get_left_index(start), BinaryHeap.get_right_index(start) while left <= end or right <= end: child_index = left if right <= end: if self.cmp_func(self.data[right], self.data[child_index]): child_index = right if self.cmp_func(self.data[child_index], self.data[start]): self.data[start], self.data[child_index] = self.data[child_index], self.data[start] start = child_index left, right = BinaryHeap.get_left_index(start), BinaryHeap.get_right_index(start) else: break def sort(self): for i in range(len(self.data)-1, 0, -1): self.data[i], self.data[0] = self.data[0], self.data[i] if i - 1 > 0: self.sift_down(0, i - 1) print(('after choose the %dth element: ' % i), self.data) if not input_array: return h_type = (descend_order and "min") or "max" binary_heap = BinaryHeap(input_array, heap_type=h_type) binary_heap.sort() @staticmethod def bucket_sort(input_array, descend_order=False): """ 桶排序 distribution sort 构造n个桶,将元素按照一定规则装入桶中;对每个桶里元素进行排序,最后将各个桶中元素汇总得到最终排序结果 :param input_array: 输入元素列表 :param descend_order: 是否降序排列 :return: None """ def value_to_bucket_index(value): return int(value * 10) # build the buckets buckets = [[] for _ in range(10)] for x in input_array: pos = value_to_bucket_index(x) buckets[pos].append(x) # sort the buckets for i in range(len(buckets)): Sort.selection_sort(buckets[i], descend_order) print(("the %dth bucket elements are: " % i), buckets[i]) # concatenate the buckets start = 0 concatenate_range = (descend_order and range(len(buckets)-1, -1, -1)) or range(len(buckets)) for i in concatenate_range: if not buckets: continue input_array[start:start + len(buckets[i])] = buckets[i] start += len(buckets[i]) def test_case_1(): input_array = [15, 6, 2, 12, 4] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.selection_sort(input_array) print(" selection sort by ascending order: ", input_array) Sort.selection_sort(array_copy, descend_order=True) print(" selection sort by descending order: ", array_copy) def test_case_2(): input_array = [12, 5, 2, 13, 18, 4] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.insertion_sort(input_array) print(" insertion sort by ascending order: ", input_array) Sort.insertion_sort(array_copy, descend_order=True) print(" insertion sort by descending order: ", array_copy) def test_case_3(): input_array = [62, 83, 18, 53, 07, 17, 95, 86, 47, 69, 25, 28] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.shell_sort(input_array) print(" shell sort by ascending order: ", input_array) Sort.shell_sort(array_copy, descend_order=True) print(" shell sort by descending order: ", array_copy) def test_case_4(): input_array = [28, 24, 27, 18] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.bubble_sort(input_array) print(" bubble sort by ascending order: ", input_array) Sort.bubble_sort(array_copy, descend_order=True) print(" bubble sort by descending order: ", array_copy) def test_case_5(): input_arrays = [[10, 80, 30, 90, 40, 50, 70], [7, 15, 4, 9, 6, 18, 9, 12]] for input_array in input_arrays: array_copy = [x for x in input_array] print("input array is: ", input_array) pos = Sort.lomuto_partition(input_array, 0, len(input_array) - 1) print(" lomuto partition by ascending order: ", input_array, "split= ", pos) pos = Sort.lomuto_partition(array_copy, 0, len(array_copy) - 1, descend_order=True) print(" lomuto partition by descending order: ", array_copy, "split= ", pos) print("\n") def test_case_6(): input_arrays = [[10, 80, 30, 90, 40, 50, 70], [7, 15, 4, 9, 6, 18, 9, 12]] for input_array in input_arrays: array_copy = [x for x in input_array] print("input array is: ", input_array) pos = Sort.hoare_partition(input_array, 0, len(input_array) - 1) print(" hoare partition by ascending order: ", input_array, "split= ", pos) pos = Sort.hoare_partition(array_copy, 0, len(array_copy) - 1, descend_order=True) print(" hoare partition by descending order: ", array_copy, "split= ", pos) print("\n") def test_case_7(): input_arrays = [[10, 80, 30, 90, 40, 50, 70], [7, 15, 4, 9, 6, 18, 9, 12]] for input_array in input_arrays: array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.quick_sort_lomuto(input_array) print(" quick sort lomuto partition by ascending order: ", input_array) Sort.quick_sort_lomuto(array_copy, descend_order=True) print(" quick sort lomuto partition by descending order: ", array_copy) print("\n") def test_case_8(): input_arrays = [[10, 80, 30, 90, 40, 50, 70], [7, 15, 4, 9, 6, 18, 9, 12]] for input_array in input_arrays: # array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.quick_sort_hoare(input_array) print(" quick sort hoare partition by ascending order: ", input_array) # Sort.quick_sort_hoare(array_copy, descend_order=True) # print(" quick sort hoare partition by descending order: ", array_copy) print("\n") def test_case_9(): input_array = [12, 8, 14, 4, 6, 33, 2, 27] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.merge_sort(input_array) print(" merge sort by ascending order: ", input_array) Sort.merge_sort(array_copy, descend_order=True) print(" merge sort by descending order: ", array_copy) def test_case_10(): input_array = [3, 6, 4, 1, 3, 4, 1, 4] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.count_sort(input_array) print(" count sort by ascending order: ", input_array) Sort.count_sort(array_copy, descend_order=True) print(" count sort by descending order: ", array_copy) def test_case_11(): input_array = [2, 24, 45, 66, 75, 90, 170, 802] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.radix_sort(input_array) print(" radix sort by ascending order: ", input_array) Sort.radix_sort(array_copy, descend_order=True) print(" radix sort by descending order: ", array_copy) def test_case_12(): input_array = [15, 19, 10, 7, 17, 16, 7, 10] array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.heap_sort(input_array) print(" heap sort by ascending order: ", input_array) Sort.heap_sort(array_copy, descend_order=True) print(" heap sort by descending order: ", array_copy) def test_case_13(): input_arrays = [[0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434], [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]] for input_array in input_arrays: array_copy = [x for x in input_array] print("input array is: ", input_array) Sort.bucket_sort(input_array) print(" bucket sort by ascending order: ", input_array) Sort.bucket_sort(array_copy, descend_order=True) print(" bucket sort by descending order: ", array_copy) print("\n") if __name__ == "__main__": test_case_13()
#!/usr/bin/python # -*- coding: UTF-8 -*- import GraphVisual from binaryTree import BinaryTree from binaryTree import TreeNode class BinarySearchTree(BinaryTree): """ 二叉搜索树 """ def __init__(self): self.root = None def __init__(self, data_array): if type(data_array) is not list: raise ValueError('init with data array only') self.root = None for x in data_array: self.add(x) def add(self, value): if not self.root: self.root = TreeNode(value) return True else: return BinarySearchTree.__add_value(self.root, value) @staticmethod def __add_value(node, value): if not node: return False if node.data == value: return False # duplicate elif value < node.data: if node.left: return BinarySearchTree.__add_value(node.left, value) else: node.left = TreeNode(value) else: if node.right: return BinarySearchTree.__add_value(node.right, value) else: node.right = TreeNode(value) return True def find(self, value): return BinarySearchTree.__find__(self.root, value) @staticmethod def __find__(node, value): if not node: return False if value == node.data: return True elif value < node.data: return BinarySearchTree.__find__(node.left, value) else: return BinarySearchTree.__find__(node.right, value) def remove_by_recursion(self, value): if not self.root: return False elif value == self.root.data: temp_root = TreeNode() # 创建一个临时节点 方便处理 temp_root.left = self.root ret = BinarySearchTree.__remove__(temp_root.left, temp_root, value) self.root = temp_root.left return ret elif value < self.root.data and self.root.left: return BinarySearchTree.__remove__(self.root.left, self.root, value) elif value > self.root.data and self.root.right: return BinarySearchTree.__remove__(self.root.right, self.root, value) return False @staticmethod def __remove__(node, parent_node, value): if not node or not parent_node: return False if value == node.data: if node.left and node.right: # case 被删除节点左右孩子都存在 min_node = node.right while min_node.left: min_node = min_node.left node.data = min_node.data BinarySearchTree.__remove__(node.right, node, node.data) else: # case 最多只有一个孩子存在 if node == parent_node.left: parent_node.left = node.left or node.right else: parent_node.right = node.left or node.right elif value < node.data and node.left: return BinarySearchTree.__remove__(node.left, node, value) elif value > node.data and node.right: return BinarySearchTree.__remove__(node.right, node, value) return False def remove_by_iterate(self, remove_key): if not self.root: return False node_to_remove, parent_node = self.root, None has_finished = False while not has_finished: while node_to_remove.data != remove_key: if remove_key < node_to_remove.data and node_to_remove.left: parent_node = node_to_remove node_to_remove = node_to_remove.left elif remove_key > node_to_remove.data and node_to_remove.right: parent_node = node_to_remove node_to_remove = node_to_remove.right else: return False if node_to_remove.left and node_to_remove.right: # case 被删除节点左右孩子都存在 min_node = node_to_remove.right while min_node.left: min_node = min_node.left node_to_remove.data = min_node.data remove_key = node_to_remove.data parent_node = node_to_remove node_to_remove = node_to_remove.right has_finished = False else: # case 最多只有一个孩子存在 if parent_node: if node_to_remove == parent_node.left: parent_node.left = node_to_remove.left or node_to_remove.right else: parent_node.right = node_to_remove.left or node_to_remove.right else: self.root = node_to_remove.left or node_to_remove.right has_finished = True return True if __name__ == "__main__": value_list = [5, 2, -4, 3, 12, 9, 21, 19, 25] bst = BinarySearchTree(value_list) print(bst.to_string("InOrder")) node_text_map, edges = bst.get_show_info() GraphVisual.GraphVisualization.show(node_text_map, edges, view_graph=True) print('has value 29 ?', bst.find(29)) print('has value 12 ?', bst.find(12)) print('has value 27 ?', bst.find(27)) print('remove 12 success ?', bst.remove_by_iterate(12)) print(bst.to_string("InOrder")) print('remove 21 success ?', bst.remove_by_iterate(21)) print(bst.to_string("InOrder")) print('remove -4 success ?', bst.remove_by_iterate(-4)) print(bst.to_string("InOrder"))
#!/usr/bin/python # -*- coding: UTF-8 -*- from binaryTree import BinaryTree from GraphVisual import GraphVisualization class BinaryHeap(object): """ 二叉堆 基于数组实现 堆元素索引从0开始 """ @staticmethod def compare_less(x, y): return x < y @staticmethod def compare_greater(x, y): return x > y MIN_COMPARE_FUNC = compare_less MAX_COMPARE_FUNC = compare_greater def __init__(self, heap_type="min", init_data=None): self.data = [] self.heap_type = heap_type if not init_data: return if type(init_data) is not list: raise ValueError("Init with list of data only.") self.data = init_data for adjust_index in range(len(self.data) / 2 - 1, -1, -1): BinaryHeap.__move__down(self.heap_type, self.data, adjust_index) def find_min(self): """ 获取最小元素 大顶堆不支持该操作 """ if self.heap_type != "min": raise NotImplementedError("unsupported operation, not a min heap") return (self.data and self.data[0]) or None def find_max(self): """ 获取最大元素 小顶堆不支持该操作 """ if self.heap_type != "max": raise NotImplementedError("unsupported operation, not a max heap") return (self.data and self.data[0]) or None def add(self, val): self.data.append(val) BinaryHeap.__move__up__(self.heap_type, self.data, len(self.data) - 1) @staticmethod def __move__up__(heap_type, data_array, start_index): """ 自底向上调整节点 1.Compare the added element with its parent; if they are in the correct order, stop. 2.If not, swap the element with its parent and return to the previous step. :param heap_type: 堆类型 :param data_array: 输入数组 :param start_index: 开始索引 :return: None """ if heap_type == "min": compare_func = BinaryHeap.MIN_COMPARE_FUNC else: compare_func = BinaryHeap.MAX_COMPARE_FUNC if start_index > len(data_array): raise KeyError(" index = " + str(start_index) + " exceed array index, with length= " + str(len(data_array))) cur_index = start_index parent_index = BinaryHeap.get_parent_index(cur_index) while cur_index > 0 and not compare_func(data_array[parent_index], data_array[cur_index]): data_array[parent_index], data_array[cur_index] = data_array[cur_index], data_array[parent_index] cur_index = parent_index parent_index = BinaryHeap.get_parent_index(cur_index) def remove_min(self): """ 移除最小元素 大顶堆不支持该操作 :return: 如果存在则返回最小元素 """ if self.heap_type != "min": raise NotImplementedError("unsupported operation, not a min heap.") return self.__remove_root__() def remove_max(self): """ 移除最大元素 小顶堆不支持该操作 :return: 如果存在则返回最大元素 """ if self.heap_type != "max": raise NotImplementedError("unsupported operation, not a max heap.") return self.__remove_root__() def __remove_root__(self): if self.is_empty(): return None if len(self.data) == 1: return self.data.pop(-1) min_data = self.data[0] self.data[0] = self.data.pop(-1) # 堆顶和最后一个元素交换 然后开始调整 BinaryHeap.__move__down(self.heap_type, self.data,0) return min_data @staticmethod def __move__down(heap_type, data_array, start_index, end_index=None): """ 自顶向下调整 1.Compare the new root with its children; if they are in the correct order, stop. 2.If not, swap the element with one of its children and return to the previous step. (Swap with its smaller child in a min-heap and its larger child in a max-heap.) :param heap_type: 堆类型 :param data_array: 输入数组 :param start_index: 开始索引 :return:None """ if not end_index: end_index = len(data_array) if heap_type == "min": compare_func = BinaryHeap.MIN_COMPARE_FUNC else: compare_func = BinaryHeap.MAX_COMPARE_FUNC cur_index = start_index left_child_index, right_child_index = \ BinaryHeap.get_left_child_index(cur_index), BinaryHeap.get_right_child_index(cur_index) while left_child_index < end_index: the_proper_index = left_child_index if right_child_index < end_index and compare_func( data_array[right_child_index], data_array[left_child_index]): the_proper_index = right_child_index if compare_func(data_array[cur_index], data_array[the_proper_index]): break data_array[cur_index], data_array[the_proper_index] = data_array[the_proper_index], data_array[cur_index] cur_index = the_proper_index left_child_index, right_child_index = \ BinaryHeap.get_left_child_index(cur_index), BinaryHeap.get_right_child_index(cur_index) @staticmethod def sort(data_array, order="Desc"): heap_type = (order == "Desc" and "min") or "max" # 建立堆方式1 从最后一个节点父节点开始 start_index = BinaryHeap.get_parent_index(len(data_array) - 1) for adjust_index in range(start_index, -1, -1): BinaryHeap.__move__down(heap_type, data_array, adjust_index) # 建立堆方式2 每个节点都向上调整 # for i in range(len(input_data)): # BinaryHeap.__move__up__(heap_type, input_data, i) bt = BinaryTree(data_array) node_text_map, edges = bt.get_show_info() GraphVisualization.show(node_text_map, edges, view_graph=True) # 依次与第i个元素交换 然后调整 for i in range(len(data_array)-1, 0, -1): data_array[i], data_array[0] = data_array[0], data_array[i] BinaryHeap.__move__down(heap_type, data_array, 0, i) return data_array def is_empty(self): return not self.data def __str__(self): ret_str = self.heap_type + " heap[" for x in self.data: ret_str += str(x) + "," ret_str += "]" return ret_str def __repr__(self): self.__str__() @staticmethod def get_left_child_index(cur_index): return cur_index * 2 + 1 @staticmethod def get_right_child_index(cur_index): return cur_index * 2 + 2 @staticmethod def get_parent_index(cur_index): return (cur_index - 1) / 2 def test_min_heap(): print('\ntest min heap' + '*'*20) input_data = [35, 33, 42, 10, 14, 19, 27, 44, 26, 31] print('input data:', input_data) bh = BinaryHeap("min", input_data) print('heap data', bh.data) print('heap min', bh.find_min()) bh.remove_min() print('after remove min', bh.data) bh.add(23) print('after insert element 23', bh.data) def test_max_heap(): print('\ntest max heap' + '*'*20) input_data = [35, 33, 42, 10, 14, 19, 27, 44, 26, 31] print('input data:', input_data) bh = BinaryHeap("max", input_data) print('heap data', bh.data) print('heap max', bh.find_max()) bh.remove_max() print('after remove max', bh.data) bh.add(23) print('after insert element 23', bh.data) def test_heap_sort(): print('\ntest heap sort' + '*'*20) input_data = [2, 8, 6, 1, 10, 15, 3, 12, 11, 49, 38, 65, 97, 76, 13, 27] print('before sort:', input_data) BinaryHeap.sort(input_data, order="Desc") print('after sort by Descend order: ', input_data) BinaryHeap.sort(input_data, order="Asce") print('after sort by Ascending order: ', input_data) if __name__ == "__main__": test_min_heap() test_max_heap() test_heap_sort()
#!/usr/env/python # _*_ coding: utf-8 _*_ """ 阶乘调用堆栈: factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) return 1 return 2*1 = 2 return 3*2 = 6 return 4*6 = 24 return 5*24 = 120 """ class Solution(object): @staticmethod def factorial(n): if n <= 1: return 1 else: return n * Solution.factorial(n-1) if __name__ == "__main__": print(Solution.factorial(5))
# -*- coding: utf-8 -*- """ Tarea 4, Problema 06 Brenda Paola García Rivas No cuenta: 316328021 Taller de Herramientas Computacionales """ #Calcular el promedio de 10 datos #No sé bien cómo hacerlo sin listas:( n1=int(input('Primer dato:')) n2=int(input('Segundo dato:')) n3=int(input('Tercer dato:')) n4=int(input('Cuarto dato:')) n5=int(input('Quinto dato:')) n6=int(input('Sexto dato:')) n7=int(input('Séptimo dato:')) n8=int(input('Octavo dato:')) n9=int(input('Noveno dato:')) n10=int(input('Décimo dato:')) suma=n1+n2+n3+n4+n5+n6+n7+n8+n9+n10 prom=suma/10
# -*- coding: utf-8 -*- """ Tarea 4, Problema 05 Brenda Paola García Rivas No cuenta: 316328021 Taller de Herramientas Computacionales """ #Culcular la suma de los primeros n enteros def sumar(n): return (n * (n+1)) / 2 #Fórmula n = int(input('Ingrese un número natural: ')) suma= sumar(n) print ('Resultado: ', suma)
# Comparision operators # <,>,>=,<=,==,!= # Can be used in chain comparision operations # Membership operator ### The IN statement checks if a variable is also found in another variable. # Boolean operators ### True. Numerical substitute is 1 ### False. Numerical substitute is 0 print(True) print(False) print(True==0) print(True==1) print(False==1) print(False==0) # Inverse Boolean ### The NOT statement can be used to create an inverse boolean output. print(not True) print(not False) print( True and True ) print( True and False) print( False and True ) print( False and False) print( True or True ) print( True or False) print( False or True ) print( False or False) print(10 == 10) print(10 != 10) print(10 != 2 ) print(50 == 2 ) print(10>1 and 1>10) print(10>1 and 4!=4) var1="house"; var2="cinema"; var3="temple" print("o" in var1 ) print("g" in var2 ) print("t" in var3 ) # chain Comparision operator print(24>=20>4==4 and 50<100>40 ) print(24>=20>4==4 and 50<100>40!=40) print("h" in var1 and "z" not in var3) print("h" in var1 and "z" not in var3 and 10>4!=50 and 4000<=5000) print("h" in var1 or "z" not in var3 and 10>4!=50 and 4000<=5000) print(var1,var2,var3)
import csv def get_file_contents(filename): "Get the file contents of a CSV. Return the entries and a list of fieldnames." with open(filename) as f: reader = csv.DictReader(f) entries = list(reader) fieldnames = reader.fieldnames return entries, fieldnames def anonymize(entries): "Anonymize the entries by mapping the IPs and worker IDs to integers." worker_ids = {e['_worker_id'] for e in entries} ip_addresses = {e['_ip'] for e in entries} ident_dict = {ident: i for i, ident in enumerate(worker_ids)} address_dict = {address: i for i, address in enumerate(ip_addresses)} for e in entries: worker_id = e['_worker_id'] ip_address = e['_ip'] e['_worker_id'] = ident_dict[worker_id] e['_ip'] = address_dict[ip_address] def process_file(infile, outfile): "Process a file and write the anonymized version to the disk." entries, fieldnames = get_file_contents(infile) anonymize(entries) with open(outfile, 'w') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(entries)
# Language translator # Rules: all vowels will be equal to (g) def translate(phrase): vowels = "aeiou" new_lang = "" for char in phrase: if char.lower() in vowels: if char.isupper(): char = "G" new_lang += char else: char = "g" new_lang += char else: new_lang += char return new_lang english_word = input("Please enter some sentences in English to translate to My language\n: ") print("My language: " + translate(english_word))
import time import pandas as pd import numpy as np import calendar from datetime import datetime CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while True: try: city= input("\nChoose a city to analyze; chicago, washington, new york city: \n") if city.lower() in list(CITY_DATA.keys()): print('Hello there,lets analyze '+city+' city data!!') break else: print("\nPlease enter any of the cities below:.\n") for city in list(CITY_DATA.keys()): print(city) except Exception as e: print("please enter the right city") while True: try: month=input("\nChoose month to filter the data by(January, February,March,April,May,June) or 'all' for no month filter:\n") if month != 'all': if month in calendar.month_name[1:7]: break else: print("please choose one of the months below") for k in calendar.month_name[:7]: print(k) else: break except Exception as e: print("please input the right month") while True: try: day=input("\nChoose A DAY to filter the data by(Monday,Tuesday,Wednesday,Thursday,Friday,Saturday, Sunday) or 'all' for no month filter:\n") if day != 'all': if day in calendar.day_name[:7]: break else: print("please choose one of the days below") for k in calendar.day_name[:7]: print(k) else: break except Exception as e: print("please enter the right day") print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df=pd.read_csv(CITY_DATA[city]) try: df['Start Time'] = pd.to_datetime(df['Start Time']) df['month']=df['Start Time'].dt.month df['day']=df['Start Time'].dt.weekday_name if month != 'all': month=calendar.month_name[:7].index(month) df=df[df['month']==month] if day != 'all': df = df[df['day'] == day.title()] return df except Exception as e: print("The load_data function has a problem...") def view_data_stats(df): """ Displays raw data from the dataframe and descriptive statistics """ try: while True: view_data = input('\nWould you like to view the raw data? Enter yes or no...\n') if view_data.lower() =='yes': print(df.head()) print(df.describe()) print(df.info()) else: break except Exception as e: print("The view_data_stats function has a problem...") def time_stats(df): """Displays statistics on the most frequent times of travel.""" try: print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month df['month']=df['Start Time'].dt.month common_month=df['month'].mode()[0] print("\nThe most common month was:\n") print(common_month) # display the most common day of week df['day']=df['Start Time'].dt.weekday_name common_day=df['day'].mode()[0] print("\nThe most common day was:\n") print(common_day) # display the most common start hour df['hour']=df['Start Time'].dt.hour common_hour=df['hour'].mode()[0] print("\nThe most common hour was:\n") print(common_hour) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) except Exception as e: print("The time_stats function has a problem..") def station_stats(df): """Displays statistics on the most popular stations and trip.""" try: print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station common_station=df['Start Station'].mode()[0] print("\nThe most common start station was:\n" + common_station) # display most commonly used end station common_end_station=df['End Station'].mode()[0] print("\nThe most common end station was:\n" + common_end_station) # display most frequent combination of start station and end station trip df['comb']=df['Start Station'] +' and '+ df['End Station'] common_comb=df['comb'].mode()[0] print("\nThe most frequent combination of start station and end station respectively:\n" + common_comb) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) except Exception as e: print("The station_statsfunction has a problem..") def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" try: print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time df['End Time']=pd.to_datetime(df['End Time']) df['time_diff']=df['End Time']-df['Start Time'] df['time_diff']=df['time_diff']/np.timedelta64(1,'s') total_travel_time=df['time_diff'].sum() print("\nThe total travel time in seconds was:\n") print(total_travel_time) # display mean travel time mean_travel_time=df['time_diff'].mean() print("\nThe mean travel time was:\n") print(mean_travel_time) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) except Exception as e: print("The trip_duration_stats function has a problem") def user_stats(df): """Displays statistics on bikeshare users.""" try: print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types count_user_type=df['User Type'].value_counts() print("\nBelow are the counts of user types:\n") print(count_user_type) # Display counts of gender if 'Gender' in df: count_gender =df['Gender'].value_counts() print("\nBelow are the gender counts:\n") print(count_gender) else: print("The dataframe has no gender column") # Display earliest, most recent, and most common year of birth if 'Birth Year' in df: common_birth_year =int(df['Birth Year'].mode()[0]) print("\nThe most common year of birth was:\n") print(common_birth_year) earliest_birth_year =int(df['Birth Year'].min()) print("\nThe earliest year of birth was:\n") print(earliest_birth_year) most_recent_birth_year = int(df['Birth Year'].max()) print("\nThe most recent year of birth was:\n") print(most_recent_birth_year) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) except Exception as e: print("The user_stats function has a problem..") def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) view_data_stats(df) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
hora_entrada = int(input('Digite aqui a hora de entrada: ')) minutos_entrada = int(input('Digite aqui os minutos de entrada: ')) hora_saida = int(input('Digite aqui a hora de saida: ')) minutos_saida = int(input('Digite aqui os minutos de saida: ')) minutos_total_entrada = (hora_entrada * 60) + minutos_entrada minutos_total_saida = (hora_saida * 60) + minutos_saida total = minutos_total_saida - minutos_total_entrada if total <= 60: print('Total a pagar R$1,00') elif 60 < total <= 120: print('Total a pagar R$2,OO') elif 120 < total <= 180: print('Total a pagar R$3,40') elif 180 < total <= 240: print('Total a pagar R$4,80') elif total > 240: calc = (total/60) * 2 print(f'Total a pagar R${calc:,.2f}')
# 4. SELECTING THE ROOM FOR THE MOVIE # 4.1 Showing the rooms # 4.2 Choosing a room # 4.3 Checking if that room has available sits # 4.4 If the room isn't available, choosing diff room # 4.3 Checking if that room has available sits # 4.4 If the room isn't available, choosing diff room def check(dic,room): if dic[room] < 25: print("There is room for you!") while dic[room] == 25: print("Get a room! Another room! ") diff_room_choice = input("Did they just knocked you out? We are here! ") upper_dif_room_choice = diff_room_choice.upper() if dic[upper_dif_room_choice] < 25: print("There is room for you! Pick your sit ") break
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # simple dict person = { 'frist_name': 'John', 'last_name': 'Doe', 'age': 30 } # Using constructor person = dict(first_name='John', last_name='Doe', age=30) # Access vaue print(person['first_name']) print(person.get('last_name')) # Add key/value person['phone'] = '555-555-555' # get the keys print(person.keys()) # get the values print(person.items()) # Make a copy person2 = person.copy() person2['city'] = 'Boston' print(person) # Remove Item del(person['age']) person.pop('phone') # clear the dictionary person.clear() # get length print(len(person2)) # List of dict people = [ {'name': 'Martha', 'age': 40}, {'name': 'Ahmed', 'age': 60} ] print(people) print(people[1]['name'])
import random guessed = False number = random.randint(1,20) print("I am thinking of a number between 1 and 20. Take a guess") while not guessed: guess = input() guess = int(guess) if guess > number: print("Guess is too high") if guess < number: print("Guess is too low") if guess == number: print("You guessed right") guessed = True
import os def get_file_path(file_path): filenames = [] sorted_path = os.listdir(file_path) sorted_path.sort() for filename in sorted_path: filename = os.path.join(file_path, filename) filenames.append(filename) return filenames def get_file_path_with_type(file_path, file_type): filenames = [] sorted_path = os.listdir(file_path) sorted_path.sort() for filename in sorted_path: if os.path.splitext(filename)[1] == file_type: filename = os.path.join(file_path, filename) filenames.append(filename) return filenames def check_path(path): if not os.path.isdir(path): os.makedirs(path) return path def get_file_name(file_path): file_full_name = os.path.basename(file_path) file_name, extension_name = os.path.splitext(file_full_name) if os.path.isfile(file_path): return file_name else: return False
import csv def write_to_csv_file(headers, dict_rows, delimiter=';'): with open('text.csv', 'w', encoding='utf-8') as f: writer = csv.DictWriter(f, headers, delimiter=delimiter) writer.writeheader() for key, value in dict_rows.items(): writer.writerow({headers[0]: key, headers[1]: value}) if __name__ == '__main__': headers = ['question', 'answer'] answers = {'Как дела?': 'хорошо', 'Как зовут?': 'Маша', 'Что ты делала сегодня?': 'ничего'} write_to_csv_file(headers, answers)
def ask_user(): expected_answer = "Хорошо" actual_answer = '' while actual_answer != expected_answer: actual_answer = input("Как дела\n") return actual_answer def get_answer(): expected_answer = "Пока" actual_answer = '' while actual_answer != expected_answer: actual_answer = ask_user() if __name__ == '__main__': get_answer()
from abc import ABCMeta, abstractmethod class IgnitionKey: def start_drive(self): pass class IgnitionButton: def start_drive(self): pass class Car(metaclass=ABCMeta): @abstractmethod def create_starter(self): raise NotImplementedError def drive(self): starter = self.create_starter() starter.start_drive() class Volvo(Car): name = 'Volvo' def __str__(self): return 'Volvo' def create_starter(self): return IgnitionButton() class Lada(Car): name = 'Lada' def __str__(self): return 'Lada' def create_starter(self): return IgnitionKey()
import numpy as np from timeit import Timer #We create an array li = list(range(500)) #The same but with np nump_arr = np.array(li) #Function to do the sum def python_for(): return [num + 1 for num in li] #Function to do the sum def numpy(): return nump_arr + 1 #Results print(min(Timer(python_for).repeat(10, 10))) print(min(Timer(numpy).repeat(10, 10))) """ https://realpython.com/numpy-array-programming/ https://www.it-swarm.dev/es/python/que-es-la-vectorizacion/834957754/ """
#Function to verify if the string is palindrome def palindrome(phrase): phrase=phrase.lower() phrase=phrase.replace(' ', '') #If it is a pa or ca, return True return phrase==phrase[::-1] s = input("Ingrese string: ") #We show our string print(s) #We pass the string print(palindrome(s)) #We are reading the file with open('palindrome.txt','a') as sentence: #Condition to write within our first file if(palindrome(s)==True): sentence.write(s) sentence.write('\n') with open('Nonpalindrome.txt','a') as Sentence: #Condition to write within our second file if(palindrome(s)==False): Sentence.write(s) Sentence.write('\n') #Message to verify that all ran well print("Task Done") """ Link where shows how to read and write in files: https://www.youtube.com/watch?v=W0h-8sXlRJQ&t=121s """
# shopping_list = ["milk", "eggs", "bacon"] # # for item in shopping_list: # print("My List:") # print(item) # # print("End of list") # # for x in range(1, 11): # print(x) counter = 0 while(counter < 10): print(counter) counter += 1
# def set_alarm(day): # day = day.lower() # if(day == "saturday" or day == "sunday"): # return None # else: # return "07:00" # # # def add(num1, num2): # return num1 + num2 # # answer = add(2,5) # print(answer) def say_hello(): name = 'Ali' print("Hi " + name) say_hello() print(name)
# Vertices are a point in space # There are 8 edges in a cube, so we first # specify all 8 coordinates as vertices DEFAULT_VERTICES = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) # Edges are a line between 2 points/vertices. # The number within the edge points to the index # of the vertices # E.G. (0,1) means its a line between vertex 0 and vertex 1 DEFAULT_EDGES = ( (0, 1), (0, 3), (0, 4), (2, 1), (2, 3), (2, 7), (6, 3), (6, 4), (6, 7), (5, 1), (5, 4), (5, 7) )
lnum = [23, 35, 35, 654, 46, 345] lnew = [] def randomize(randomlist): random = lnum[0] for x in lnum: if (x % 2 == 0): random = x return random while len(lnum) != 0: x = randomize(lnum) lnum.remove(x) lnew.append(x) print (lnew)
input_name= input('Enter a name') output_text= 'hello'+ input_name print(output_text)
def question_principal(): while True: user_answer = input( "\nWhat is the total value of the house you want to purchase. This is known as your principal. i.e. 500000 ") if user_answer.isdigit(): return int(user_answer) else: print("\nInvalid input. Please format like so 500000") def question_mortgage_type_length(): while True: user_answer = input("\n How long is the term of this mortgage? i.e. 15, 20, 30, 45") if user_answer.isdigit() and int(user_answer) > 0: return int(user_answer) else: print("\nNot a valid length") def question_mortgage_type(): while True: user_answer = input( """\nAre you dealing with a 1) fixed term mortgage or 2)adjustable rate mortgage Enter 1 or 2""") if int(user_answer) == 1: return question_mortgage_type_length() elif int(user_answer) == 2: print( "\nARM requires more specialized calculation please reference \"https://www.usbank.com/home-loans/mortgage/mortgage-calculators/arm-calculator.html\"") quit() else: print('\nPlease enter 1 or 2') def question_mortgage_rate(): while True: user_answer = input("\nWhat is the annual interest rate you will pay on your principal i.e. 5.375") if float(user_answer) > 10.0: print("\nYou're being robbed, try a different loan agent") elif float(user_answer) > 0: return float(user_answer) elif float(user_answer) <= 0: print("\nCan't have negative interest") else: print("\nInvalid input. Please format like so 1.2 ") def question_mortgage_downpayment(principal): while True: user_answer = input( "\nHow much downpayment are you going to put down? (This is the amount you pay to lower your principal i.e. 150000") if 0 <= int(user_answer) < principal: return int(user_answer) else: print("\nPlease adjust your downpayment amount to the format 150000 between 0 and your principal")