text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ The functions to visualize the result of dataSet spitting by Decision Tree Created on Fri Apr 21 15:13:35 2017 @author: Martin """ import matplotlib.pyplot as plt #node pattern decisionNode = dict(boxstyle="square", fc="0.75") leafNode = dict(boxstyle="round", fc="w") arrow_args = dict(arrowstyle="<|-",shrinkB=12) #get the number of leafs in the tree(dict strut) def getNumLeafs(tree): numLeafs = 0 #base case: empty tree if not tree: return 0 for key,value in tree.items(): if isinstance(value, dict): numLeafs+=getNumLeafs(value) else: numLeafs+=1 return numLeafs #get the depth of the tree(dict strut) def getTreeDepth(tree): maxDepth = 0 parentNode = list(tree.keys())[0] subTree = tree[parentNode] for key, value in subTree.items(): if isinstance(value, dict): currentDepth=1 + getTreeDepth(value) else: currentDepth=1 if currentDepth > maxDepth: maxDepth = currentDepth return maxDepth #plot the node on the figure def plotNode(nodeTxt, nodePt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=nodePt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args) #plot the node txt on the box def plotMidText(nodePt, parentPt, nodeTxt): xMid=(parentPt[0]-nodePt[0])/2.0 + nodePt[0] yMid=(parentPt[1]-nodePt[1])/2.0 + nodePt[1] createPlot.ax1.text(xMid, yMid, nodeTxt) #plot the tree on the figure def plotTree(tree, parentPt, nodeTxt): numLeafs = float(getNumLeafs(tree)) parentTxt = list(tree.keys())[0] nodePt = (plotTree.xOff + 0.5*(1.0 + numLeafs)/plotTree.totalW, plotTree.yOff) plotMidText(nodePt, parentPt, nodeTxt) plotNode(parentTxt, nodePt, parentPt, decisionNode) secondDict = tree[parentTxt] plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD for key, value in secondDict.items(): if isinstance(value, dict): plotTree(value,nodePt,str(key)) else: plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW plotMidText((plotTree.xOff, plotTree.yOff), nodePt, str(key)) plotNode(value, (plotTree.xOff, plotTree.yOff), nodePt, leafNode) plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD #the create function call from outside function def createPlot(tree): axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, **axprops,frameon=False) plotTree.totalW = float(getNumLeafs(tree)) plotTree.totalD = float(getTreeDepth(tree)) plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; plotTree(tree, (0.5,1.0), '') plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 21 13:54:36 2017 @author: KACHING """ #PriorityQueue for Graph class PriorityQueue: def __init__(self): self.items=[] self.size=0 def IsEmpty(self): return self.size==0 def BuildHeap(self,items): self.items=items self.size=len(self.items) i=self.size//2-1 for j in range(i,-1,-1): self.Percdown(j,self.size) def Percdown(self,i,n): tmp=self.items[i] child=2*i+1 while child<n: if child!=n-1 and self.items[child+1][0]<self.items[child][0]: child+=1 if self.items[child][0]<tmp[0]: self.items[i]=self.items[child] else: break i=child child=2*i+1 self.items[i]=tmp def DeleteMin(self): if self.size==1: Min=self.items.pop() self.size-=1 else: self.items[0],self.items[-1]=self.items[-1],self.items[0] Min=self.items.pop() self.size-=1 self.Percdown(0,self.size) return Min def Insert(self,element): self.items.append(element) self.size+=1 self.Percup(self.size) def Percup(self,n): i=n-1 parent=n//2-1 tmp=self.items[i] while i>=0: if self.items[parent][0]>tmp[0]: self.items[i]=self.items[parent] else: break i=parent parent=(i+1)//2-1 self.items[i]=tmp if __name__=='__main__': test=[(33,'a'), (27,'b'),(21,'c'), (19,'d')] PQ=PriorityQueue() PQ.BuildHeap([ x for x in test]) print(PQ.items) PQ.Insert((7,'e')) for i in range(0,5): a=PQ.DeleteMin() print(PQ.items)
r = 9.4 pi = 3.14 print("円周は{}cm".format(r * 2 * pi)) print("円の面積は{}cm^2".format(r ** 2 * pi)) print("球の体積は{}cm^3".format(4 / 3 * pi + r ** 3)) print("テスト")
#Write a function that takes in a string and for each character, returns #the distance to the nearest vowel. If the character is a vowel itself, return 0 #All input strings will contain at least one vowel. #Strings will be lowercased. #Vowels are: a, e, i, o, u def distance_to_nearest_vowel(string): string=string.lower() vowels=[ 'a', 'e', 'i', 'o', 'u'] a=[] v=[] #get the indices of vowels for inx, char in enumerate(string): if char in vowels: v.append(inx) for i in range(len(string[:-1])): if string[i] in vowels: a.append(0) elif string[i] not in vowels and string[i-1] in vowels and string[i+1] not in vowels: a.append(1) elif string[i] not in vowels and string[i - 1] not in vowels and string[i + 1] in vowels : a.append(1) elif string[i] not in vowels: #a.append("not v") m1=abs(i-min(v)) m2=abs(i-max(v)) if m1<m2: a.append(m1) else: a.append(m2) index_of_last=len(string)-1 if string[-1:] in vowels: a.append(0) elif string[len(string)-1] not in vowels and string[len(string)-2] in vowels: a.append(1) elif string[len(string)-1] not in vowels: m=max(v) dif=abs(index_of_last - m) a.append(dif) print(a) # print the result distance_to_nearest_vowel("aaaaa") #➞ [0, 0, 0, 0, 0] distance_to_nearest_vowel("babbb") #➞ [1, 0, 1, 2, 3] distance_to_nearest_vowel("abcdabcd") #➞ [0, 1, 2, 1, 0, 1, 2, 3] distance_to_nearest_vowel("shopper") #➞ [2, 1, 0, 1, 1, 0, 1] distance_to_nearest_vowel("table") #➞ [1,0,1,1,0] distance_to_nearest_vowel("wxyzobcdf") #➞ [4,3,2,1,0,1,2,3,4] #-------------------------------------------------------------------------------------------------- #by having an integer N we want to print it's palindromic triangle #for example if N=5 then it's palindromic tringle will be: #1 #121 #12321 #1234321 #123454321 a=[] b=[] n=5 for i in range(1,n+1): a.append(i) b.append(i) a=a[:-1] a.reverse() for i in a: b.append(i) for i in b: print(i,end="") #-------------------------------------------------------------------------------------------------- #pick only one element from each list ( we have k lists such that 1<= k <= 7 ) #then do this: ( add up square of each element) % M where 1<=M<=1000 #note that we want the maximum result #example: #2 5 4 #3 7 8 9 #5 5 7 8 9 10 #we choose 5 from first list #we choose 9 from second list #we choose 10 from third list #(25+81+100) % 1000 = 206 which is max value N=[[2,5,4],[3,7,8,9],[5,5,7,8,9,10]] arr=[] for i in N: arr.append(max(i)) #print(arr) x=[int(i)**2 for i in arr] #print(x) addd=sum(x) M=1000 #print(addd%M) #-------------------------------------------------------------------------------------------------- #Given a two list. Create a third list by picking an odd-index element from the first list #and even index elements from second. l1=[1,2,"A","B","C","W",0,7,8] l2=["D","E",3,4,5,6,"G","N",40] l3=[] odd_list_one=[ i for i in l1 if l1.index(i)%2!=0] even_list_two=[ i for i in l2 if l2.index(i)%2==0] for i in odd_list_one: l3.append(i) for i in even_list_two: l3.append(i) #print(l3) #-------------------------------------------------------------------------------------------------- #we have a function that has two arguments: a list and a number #we add 2 to odd numbers in the list and we subtract 2 from even numbers in the list #the number of the times that we do this is depend on number which was the second argument #for example: #([3, 4, 9], 3) means we add 2 three times to odd numbers i.e to 3 and 9 and we three times subtract 2 from 4 #result will be [9, -2, 15] and we output the result def even_odd(myList,N): odds=[i for i in myList if i%2!=0] evens=[i for i in myList if i%2==0] l=[] for i in myList: if i in odds: for j in range(N): i=i+2 else: for j in range(N): i=i-2 l.append(i) print(l) #even_odd([1,2,3],1) #even_odd([3,4,9],3) #even_odd([0,0,0],10) #-------------------------------------------------------------------------------------------------- #In each input list, every number repeats at least once, except for two. #Write a function that returns the two unique numbers. #example: #returnUnique([1, 9, 8, 8, 7, 6, 1, 6]) ➞ [9, 7] #returnUnique([5, 5, 2, 4, 4, 4, 9, 9, 9, 1]) ➞ [2, 1] #returnUnique([9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8]) ➞ [5, 6] def returnUnique(myList): arr=[] for i in myList: if myList.count(i)==1: arr.append(i) print(arr) #returnUnique([1, 9, 8, 8, 7, 6, 1, 6]) #returnUnique([5, 5, 2, 4, 4, 4, 9, 9, 9, 1]) #returnUnique([9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8]) #-------------------------------------------------------------------------------------------------- #Create a function that takes in a list and returns a list of the accumulating sum. #example: #accumulating_list([1, 2, 3, 4]) ➞ [1, 3, 6, 10] #[1, 3, 6, 10] can be written as [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4] #accumulating_list([1, 5, 7]) ➞ [1, 6, 13] #accumulating_list([1, 0, 1, 0, 1]) ➞ [1, 1, 2, 2, 3] #accumulating_list([]) ➞ [] def accumulating_list(myList): a=0 arr=[] for i in myList: a=a+i arr.append(a) print(arr) #accumulating_list([1, 5, 7]) #accumulating_list([1, 2, 3, 4]) #accumulating_list([1, 0, 1, 0, 1]) #accumulating_list([]) #-------------------------------------------------------------------------------------------------- #Create a function that tests whether or not an integer is a perfect number. #A perfect number is a number that can be written as the sum of its factors, excluding the number itself. #For example, 6 is a perfect number, since 1 + 2 + 3 = 6, where 1, 2, and 3 are all factors of 6. #Similarly, 28 is a perfect number, since 1 + 2 + 4 + 7 + 14 = 28. def check_perfect(num): arr=[] for i in range(1,num): if num%i==0: arr.append(i) if sum(arr)==num: print(True) # i.e yes it is a perfect number else: print(False) #check_perfect(6) # True #check_perfect(28) # True #check_perfect(496) # True #check_perfect(12) # False #check_perfect(97) # False #-------------------------------------------------------------------------------------------------- #Suppose you have a dictionary guest list of students and the country they are from, #stored as key-value pairs in a dictionary. #Write a function that takes in a name and returns a name tag, that should read: # "Hi! I'm [name], and I'm from [country]." #If the name is not in the dictionary, return: #"Hi! I'm a guest. def greeting(name): GUEST_LIST = { "Randy": "Germany", "Karla": "France", "Wendy": "Japan", "Norman": "England", "Sam": "Argentina" } for i in GUEST_LIST.keys(): if i==name: print("Hi! I am", name , "and I am from", GUEST_LIST[name] ) if name not in GUEST_LIST.keys(): print("Hi! I'm a guest.") #greeting("Randy") # "Hi! I'm Randy, and I'm from Germany." #greeting("Sam") # "Hi! I'm Sam, and I'm from Argentina." #greeting("Monti") # "Hi! I'm a guest." #-------------------------------------------------------------------------------------------------- #write a function that counts number of overlapping intervals with a given number #It takes two arguements: first parameter is list of intervals , second parameter is the number #example: #count_overlapping([[1, 2], [2, 3], [1, 3], [4, 5], [0, 1]], 2) ➞ 3 # Since [1, 2], [2, 3] and [1, 3] all overlap with point 2 arr=[] def count_overlapping(myList,number): for i in myList: if number in range(i[0],i[1]+1): arr.append(i) print(len(arr)) #count_overlapping([[1, 2], [2, 3], [3, 4]], 5) #0 #count_overlapping([[1, 2], [5, 6], [5, 7]], 5) #2 #count_overlapping([[1, 2], [5, 8], [6, 9]], 7) #2 #count_overlapping([[1, 2], [2, 3], [1, 3], [4, 5], [0, 1]], 2) #3 #--------------------------------------------------------------------------------------------------- #Create a function that takes an integer and outputs an n x n square solely consisting of the integer n #example: #square_patch(3) is: # [ # [3, 3, 3], # [3, 3, 3], # [3, 3, 3] # ] def square_patch(num): if num>0: a=num*(list([num])) x=[a for i in range(num)] for i in x: print(i) elif num==0: print("[]") else: print("number should be positive") #square_patch(3) #square_patch(5) #--------------------------------------------------------------------------------------------------- #Write a function that takes in a string and replaces all 'a's with 4, 'e's with 3, 'i's with 1, 'o's with 0, and 's's with 5. def change_string(myString): myString=myString.lower() for i in myString: if i=='a': myString=myString.replace(i,"4") elif i=='e': myString = myString.replace(i, "3") elif i=='i': myString = myString.replace(i, "1") elif i=='o': myString = myString.replace(i, "0") elif i=='s': myString = myString.replace(i, "5") print( myString) #change_string("javascript is cool") #"j4v45cr1pt 15 c00l" #change_string("programming is fun") #"pr0gr4mm1ng 15 fun" #change_string("become a coder") #"b3c0m3 4 c0d3r" #--------------------------------------------------------------------------------------------------- #Create a function that takes a string, checks if #it has the same number of x's and o's and returns either true or false. #It returns true if there aren't any x's or o's. #Must be case insensitive. def XO(string): x=[] o=[] for i in string: if i=="x" or i=="X": x.append(i) elif i=="o" or i=="O": o.append(i) if len(x)==len(o): print(True) else: print(False) #XO("ooxx") # true #XO("xooxx") #false #case sensitive #XO("ooxXm") # true # Returns true if no x and o. #XO("zpzpzpp") # true #XO("zzoo") # false #--------------------------------------------------------------------------------------------------- #Given a common phrase, return False if #any individual word in the phrase contains duplicate letters. Return True otherwise. #for example: keep has duplicate letter e def no_duplicate_letters(myPhrase): duplicates=[] non_duplicates=[] words=myPhrase.split() for i in words: for j in i: if i.count(j)>1: duplicates.append(j) if duplicates!=[]: print(False) else: print(True) #no_duplicate_letters("Fortune favours the bold.") # True #no_duplicate_letters("You can lead a horse to water, but you can't make him drink.") # True #no_duplicate_letters("Look before you leap.") # False #Duplicate letters in "Look" and "before". #no_duplicate_letters("An apple a day keeps the doctor away.") # False # Duplicate letters in "apple", "keeps", "doctor", and "away". #--------------------------------------------------------------------------------------------------- #You are given three inputs: a string, one letter, and a second letter. #Write a function that returns True if every instance of the first #letter occurs before every instance of the second letter. #All strings will be in lower case. #All strings will contain the first and second letters at least once. #All strings will be in lower case. #All strings will contain the first and second letters at least once. def first_before_second(mySentence, firstLetter, secondletter): mySentence=mySentence.lower() arr=[] x=[i for i, letter in enumerate(mySentence) if letter == firstLetter] w = [i for i, letter in enumerate(mySentence) if letter == secondletter] a=[] b=[] for i in x: for j in w: a.append(([i,j])) c=[i[0] <i[1] for i in a] if all(c)==True: print(True) else: print(False) #first_before_second("a rabbit jumps joyfully", "a", "j") # True #Every instance of "a" occurs before every instance of "j". #first_before_second("knaves knew about waterfalls", "k", "w") # True #first_before_second("happy birthday", "a", "y") # False # The "a" in "birthday" occurs after the "y" in "happy". #first_before_second("precarious kangaroos", "k", "a") # False #--------------------------------------------------------------------------------------------------- #Creata a function that flips a horizontal list into a vertical list, and a vertical list into a horizontal list def flip_list(myList): arr=[] for i in myList: for j in i: arr.append(j) print(arr) def flip_listt(myList): arr=[] for i in myList: arr.append([i]) print(arr) #flip_listt([1, 2, 3, 4]) #--> [[1], [2], [3], [4]] # Take a horizontal list and flip it vertical. #flip_list([[5], [6], [9]]) #--> [5, 6, 9] # Take a vertical list and flip it horizontal. #flip_list([]) #--> [] #-------------------------------------------------------------------------------------------------- #Create a function that returns True if two lines rhyme and False otherwise. #For the purposes of this exercise, two lines rhyme if the last word from each sentence contains the same vowels. #Case insensitive. #Here we are disregarding cases like "thyme" and "lime". #We are also disregarding cases like: #"away" and "today" (which technically rhyme, even though they contain different vowels). def does_rhyme(mySentence1,mySentence2): a=mySentence1.split() b=mySentence2.split() last1=a[len(a)-1] last2=b[len(b)-1] vowels=["a","o","e","u","i","A","O","E","U","I"] arr1=[] arr2=[] for i in last1: i=i.lower() if i in vowels: arr1.append(i) for i in last2: i=i.lower() if i in vowels: arr2.append(i) if arr1==arr2: print(True) else: print(False) #does_rhyme("Sam I am!" ,"Green eggs and ham.") # True #does_rhyme("Sam I am!","Green eggs and HAM.") # True #Capitalization and punctuation should not matter. #does_rhyme("You are off to the races", "a splendid day.") # False #does_rhyme("and frequently do?", "you gotta move.")# False #-------------------------------------------------------------------------------------------------- #Create a function that takes in n, a, b #and returns the number of values raised to the nth power lie in the range [a, b], inclusive. # Remember that the range is inclusive. # a < b will always be true. def power_ranger(n,a,b): arr=[] for i in range(1,100): if i**n in range(a,b+1): arr.append(i) print(len(arr)) #power_ranger(2, 49, 65) #➞ 2 # 2 squares (n^2) lie between 48 and 65, 49 (7^2) and 64 (8^2) #power_ranger(3, 1, 27) #➞ 3 # 3 cubes (n^3) lie between 1 and 27, 1 (1^3), 8 (2^3) and 27 (3^3) #power_ranger(10, 1, 5)# ➞ 1 # 1 value raised to the 10th power lies between 1 and 5, 1 (1^10) #power_ranger(5, 31, 33) #➞ 1 #power_ranger(4, 250, 1300) #➞ 3 #-------------------------------------------------------------------------------------------------- #Write a function that pairs the first number in an array with the last, the second number with the second to last, etc. #If the list has an odd length, repeat the middle element twice for the last pair. #Return an empty list if the input is an empty list def pairs(myArray): arr=[] arr2=[] if len(myArray)%2==0: # when length of array is even while myArray !=[]: first=myArray[0] l=len(myArray)-1 last=myArray[l] arr.append([first,last]) myArray.pop(0) myArray.pop() print(arr) else: middle_element_index=int(len(myArray)/2) middle_element=myArray[middle_element_index] myArray.pop(middle_element_index) while myArray!=[]: firstt = myArray[0] ll = len(myArray) - 1 lastt = myArray[ll] arr2.append([firstt,lastt]) myArray.pop(0) myArray.pop() arr2.append([middle_element,middle_element]) print(arr2) #pairs([1, 2, 3, 4, 5, 6, 7]) #➞ [[1, 7], [2, 6], [3, 5], [4, 4]] #pairs([1, 2, 3, 4, 5, 6]) #➞ [[1, 6], [2, 5], [3, 4]] #pairs([5, 9, 8, 1, 2]) #➞ [[5, 2], [9, 1], [8, 8]] #pairs([]) #➞ [] #-------------------------------------------------------------------------------------------------- #Write a function that moves all the zeroes to the end of a list. #Do this without returning a copy of the input list. #Keep the relative order of the non-zero elements the same. def zeroes_to_end(myList): arr=[] x=[i for i in myList if i!=0] for i in myList: if i==0: arr.append(i) for i in arr: x.append(i) print(x) #zeroes_to_end([1, 2, 0, 0, 4, 0, 5]) #➞ [1, 2, 4, 5, 0, 0, 0] #zeroes_to_end([0, 0, 2, 0, 5])# ➞ [2, 5, 0, 0, 0] #zeroes_to_end([4, 4, 5]) #➞ [4, 4, 5] #zeroes_to_end([0, 0]) #➞ [0, 0] #-------------------------------------------------------------------------------------------------- #Create a function that finds how many prime numbers there are, up to the given integer. def primeNumbers(num): arr=[] for i in range(2,num): isPrime=True for j in range(2,i): if i%j==0: isPrime=False if isPrime: arr.append(i) print(len(arr)) #primeNumbers(10) #➞ 4 #// 2, 3, 5 and 7 #primeNumbers(20) #➞ 8 #// 2, 3, 5, 7, 11, 13, 17 and 19 #primeNumbers(30) #➞ 10 #// 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29 #-------------------------------------------------------------------------------------------------- #Write a function to replace all instances of character x with character y and vice versa. def doubleSwap(myString,x,y): if x in myString and y in myString: s1 = myString.replace(x, "1") s2 = s1.replace(y, x) s3 = s2.replace("1", y) print(s3) #doubleSwap( "aabbccc", "a", "b")# ➞ "bbaaccc" #doubleSwap("random w#rds writt&n h&r&", "#", "&") #"random w&rds writt#n h#r#" #doubleSwap("128 895 556 788 999", "8", "9") #"129 985 556 799 888" #-------------------------------------------------------------------------------------------------- #Create a function that takes a string as an argument and returns True if each letter in the string is surrounded by a plus sign. #Return False otherwise. def plus_sign(myString): arr=[] a=[] if myString[0]!="+": print(False) else: for i in myString: if i.isalpha() == True: a.append(i) index_of_letter = myString.index(i) pre = index_of_letter - 1 after = index_of_letter + 1 if myString[pre]=="+" and myString[after]=="+": arr.append(i) if arr==a: print(True) else: print(False) #plus_sign("+f+d+c+#+f+") # True #plus_sign("+d+=3=+s+") # True #plus_sign("f++d+g+8+") # False #plus_sign("+s+7+fg+r+8+") # False #plus_sign("+w+u+x+1+2=k+")#False #plus_sign("+s+7=w") #-------------------------------------------------------------------------------------------------- #Create a function that takes in two words as input and returns a list of three elements, in the following order: #Shared letters between two words. #Letters unique to word 1. #Letters unique to word 2. #Each element should have unique letters, and have each letter be alphabetically sorted. #Both words will be in lower case. #You do not have to worry about punctuation, all words only have letters from [a-z]. #If an element contains no letters, return an empty string (see last example). def letters(first,second): first=first.lower() second=second.lower() arr1=[] for i in first: for j in second: if i==j: arr1.append(i) arr=[] for i in arr1: if i not in arr: arr.append(i) common=sorted(arr) C=''.join(common) #common letters between two words first_letters=[i for i in first] second_letters=[i for i in second] f=[] s=[] for i in first_letters: if i not in second_letters: f.append(i) ff=[] for i in f: if i not in ff: ff.append(i) for j in second_letters: if j not in first_letters: s.append(j) ss=[] for i in s: if i not in ss: ss.append(i) f_s=sorted(ff) s_s=sorted(ss) F=''.join(f_s) S=''.join(s_s) myArr=[] myArr.append([C,F,S]) print(str(myArr)[1:-1]) #letters("sharp", "soap") #➞ ["aps", "hr", "o"] #letters("board", "bored") #➞ ["bdor", "a", "e"] #letters("happiness", "envelope") #➞ ["enp", "ahis", "lov"] #letters("kerfuffle", "fluffy") #➞ ["flu", "ekr", "y"] # Even with multiple matching letters (e.g. 3 f's), there should # only exist a single "f" in your first element. #letters("match", "ham") #➞ ["ahm", "ct", ""] #"ham" does not contain any letters that are not found already #in "match". #------------------------------------------------------------------------------------------------- #Write a function that sorts the positive numbers in ascending order, #and keeps the negative numbers untouched def sort_pos(lst): sorted_pos = sorted([n for n in lst if n > 0]) new_list = [] for n in lst: if n > 0: new_list.append(sorted_pos.pop(0)) # remove one by one from beginning else: new_list.append(n) print(list(new_list)) #sort_pos([6, 3, -2, 5, -8, 2, -2]) #➞ [2, 3, -2, 5, -8, 6, -2] #sort_pos([6, 5, 4, -1, 3, 2, -1, 1]) #➞ [1, 2, 3, -1, 4, 5, -1, 6] #sort_pos([-5, -5, -5, -5, 7, -5]) #➞ [-5, -5, -5, -5, 7, -5] #sort_pos([])# ➞ [] #------------------------------------------------------------------------------------------------- #A 1 is unhappy if the digit to its left and the digit to its right are both 0s. A 0 is unhappy if the digit to its left and the digit to its right are both 1s. #If a number has only one neighbor, it is unhappy if its only neighbor is different. Otherwise, a number is happy. #Write a function that takes in a list of 0s and 1s and outputs the percentage of numbers which are happy. #The total percentage of numbers which are happy can be represented as: # % of happy 0s = (# happy 0s + # unhappy 0s) / # total 0s #% of happy 1s = (# happy 1s + # unhappy 1s) / # total 1s # %percentage of happy numbers = (% of happy 0s + % of happy 1s) / 2 #[0, 1, 0, 0, 0, 1, 1, 1, 0, 1] #The first element, a 0, and the last element, a 1 are both unhappy. #The second element, a 1 is unhappy. #The second-to-last element, a 0 is unhappy. #All other numbers in this list are happy. def percentage_happy(myArr): happy_zero=[] happy_one=[] sad_zero=[] sad_one=[] if myArr[0]==0: if myArr[1]==1: sad_zero.append(True) else: happy_zero.append(True) last=len(arr)-1 if myArr[last]==0: if myArr[last-1]==0: happy_zero.append(True) else: sad_zero.append(True) if myArr[0] == 1: if myArr[1] == 1: happy_one.append(True) else: sad_one.append(True) last = len(arr) - 1 if myArr[last] == 1: if myArr[last - 1] == 1: happy_one.append(True) else: sad_one.append(True) ArrOfNexts=[] ArrOfPre=[] for index, value in enumerate(myArr[:-1]): preVal = myArr[index - 1] ArrOfPre.append([value,preVal]) nextt = myArr[index + 1] ArrOfNexts.append([value,nextt]) ArrOfNexts.pop(0) ArrOfPre.pop(0) for i in range(len(ArrOfNexts)): if ArrOfNexts[i][0] ==ArrOfPre[i][0]== ArrOfNexts[i][1] == ArrOfPre[i][1] == 1: happy_one.append(True) elif ArrOfNexts[i][0] ==ArrOfPre[i][0]== ArrOfNexts[i][1] == ArrOfPre[i][1] == 0: happy_zero.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 0) and (ArrOfNexts[i][1] == ArrOfPre[i][1]==1): sad_zero.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 1) and (ArrOfNexts[i][1] == ArrOfPre[i][1] == 0): sad_one.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 1) and ArrOfNexts[i][1] == 1 and ArrOfPre[i][1] == 0: sad_one.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 1) and ArrOfNexts[i][1] == 0 and ArrOfPre[i][1] == 1: sad_one.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 0) and ArrOfNexts[i][1] == 1 and ArrOfPre[i][1] == 0: sad_zero.append(True) elif (ArrOfNexts[i][0] == ArrOfPre[i][0] == 0) and ArrOfNexts[i][1] == 0 and ArrOfPre[i][1] == 1: sad_zero.append(True) #print("happy Zero",happy_zero) #print("hapy one",happy_one) #print("sad one",sad_one) #print("sad zero",sad_zero) # % of happy 0s = (# happy 0s + # unhappy 0s) / # total 0s total_zero=[i for i in myArr if i==0] total_one=[i for i in myArr if i==1] number_of_happy_zero=len(happy_zero) number_of_happy_one = len(happy_one) number_of_sad_zero = len(sad_zero) number_of_sad_one = len(sad_one) #print("h1",number_of_happy_one) #print("s1:",number_of_sad_one) #print("h0",number_of_happy_zero) #print("s0",number_of_sad_zero) total_zeroo=len(total_zero) total_onee=len(total_one) #print("t1",total_onee) #print("t0",total_zeroo) happy_zero_Percentage=(number_of_happy_zero+number_of_sad_zero)/total_zeroo #print(happy_zero_Percentage) # % ofhappy1s = ( # happy 1s + # unhappy 1s) / # total 1s happy_one_Percentage = (number_of_happy_one + number_of_sad_one )/ total_onee #print(happy_one_Percentage) #% percentageofhappynumbers = (% of happy 0s + % of happy 1s) / 2 percentage_of_happynumbers = (happy_zero_Percentage + happy_one_Percentage) / 2 #print(percentage_of_happynumbers) #call the functions #percentage_happy([0, 1, 0, 1, 0])# ➞ 0 #percentage_happy([0, 1, 1, 0]) #➞ 0.5 #percentage_happy([0, 0, 0, 1, 1]) #➞ 1 #percentage_happy([1, 0, 0, 1, 1])# ➞ 0.8 #percentage_happy([1, 0, 1,0,0]) #-------------------------------------------------------------------------------------------------- #Create a function that determines whether each seat can "see" the front-stage. A number can "see" the front-stage if #it is strictly greater than the number before it. #Everyone can see the front-stage in the example below # FRONT STAGE # [[1, 2, 3, 2, 1, 1], # [2, 4, 4, 3, 2, 2], # [5, 5, 5, 5, 4, 4], # [6, 6, 7, 6, 5, 5]] # Starting from the left, the 6 > 5 > 2 > 1, so all numbers can see. # 6 > 5 > 4 > 2 - so all numbers can see, etc. # Not everyone can see the front-stage in the example below: # FRONT STAGE # [[1, 2, 3, 2, 1, 1], # [2, 4, 4, 3, 2, 2], # [5, 5, 5, 10, 4, 4], # [6, 6, 7, 6, 5, 5]] # The 10 is directly in front of the 6 and blocking its view. #The function should return True if every number can see the front-stage, and False if even a single number cannot. def can_see_stage(arr): arr=reversed(arr) #works for arrays of size 3 f, s,t = zip(*arr) x=list([f,s,t]) #print(x) c=[] for i in x: if i[0]>i[1]>i[2]: c.append(True) else: c.append(False) if all(c)==True: print(True) else: print(False) #can_see_stage([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) #➞ True #can_see_stage([[0, 0, 0],[1, 1, 1],[2, 2, 2]]) #➞ True #can_see_stage([[2, 0, 0],[1, 1, 1],[2, 2, 2]])# ➞ False #can_see_stage([[1, 0, 0],[1, 1, 1],[2, 2, 2]]) #➞ False #can_see_stage( [[1, 2, 2],[2, 4 , 3],[5, 5 , 10],[6, 6, 6]])#-> False #------------------------------------------------------------------------------------------------- #Start your counter at 0, and increment by 1 each time you encounter a new character. #Identical characters should share the same number. def character_mapping(string): counter=0 arr=[0] for i in range(len(string[:-1])): if string[i]!=string[i+1]: counter+=1 arr.append(counter) elif string[i]==string[i+1]: arr.append(counter) else: arr.append(counter) print(arr) #character_mapping("abcd") #➞ [0, 1, 2, 3] #character_mapping("abb") #➞ [0, 1, 1] #character_mapping("hmmmmm")# ➞ [0, 1, 1, 1, 1, 1] #------------------------------------------------------------------------------------------------- #Create a function that returns a list containing the prime factors of whatever integer is passed to it. from math import sqrt; from itertools import count, islice from functools import reduce def isPrime(n): return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1))) def prime_factors(num): arr=[] the_primes=[] for i in range(2, num+1): if num % i == 0: arr.append(i) z=[] for i in arr: if isPrime(i): the_primes.append(i) a=reduce(lambda x, y: x * y, the_primes) s=num/a s=int(s) if isPrime(s): the_primes.append(s) else: for i in range(2,s+1): if isPrime(i) and s%i==0: the_primes.append(i) print(sorted(the_primes)) #prime_factors(20) #➞ [2, 2, 5] #prime_factors(100) #➞ [2, 2, 5, 5] #prime_factors(8912234)# ➞ [2, 47, 94811] #-------------------------------------------------------------------------------------------------- #Create a function that takes a string and replaces every letter with the letter following it in the alphabet #i.e "c" becomes "d", "z" becomes "a", "b" becomes "c", etc #Then capitalize every vowel (a, e, i, o, u) and return the new modified string. #If a letter is already uppercase, return it as uppercase (regardless of being a vowel). def replace_with_next(myString): alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a"] alphabet2=[i.upper() for i in alphabet] vowels=["a","o","u","e","i"] a=[] for i in myString: if i.isalpha() and i.islower(): index_of_i=alphabet.index(i) index_of_following_letter=index_of_i+1 myString=myString.replace(i,alphabet[index_of_following_letter]) if i.isalpha() and i .isupper(): index_of_i=alphabet2.index(i) index_of_following_letter=index_of_i+1 myString=myString.replace(i,alphabet2[index_of_following_letter]) for i in myString: if i in vowels: myString=myString.replace(i,i.upper()) print(myString) replace_with_next("fun times!") #➞ "gvO Ujnft!" replace_with_next("eGG")# ➞ "FHH" replace_with_next("OMega") #➞ "PNfhb" #-------------------------------------------------------------------------------------------------- #Create a function that takes a list of numbers or strings and returns a list with the items from the original list stored into sublists. #Items of the same value should be in the same sublist. def advanced_sort(arr): x=[] for i in arr: for j in arr: if i==j and arr.count(i)>1: x.append([i,j]) elif arr.count(i)==1: x.append([i]) z=[] for i in x: if i not in z: z.append(i) print(z) #advanced_sort([2, 1, 2, 1]) #➞ [[2, 2], [1, 1]] #advanced_sort(["b", "a", "b", "a", "c"]) #➞ [["b", "b"], ["a", "a"], ["c"]] #-------------------------------------------------------------------------------------------------- #Write two functions: #One that returns the maximum product of three numbers in a list. #One that returns the minimum product of three numbers in a list. def max_product(arr): s=[] for i in arr: for j in arr: for k in arr: if i!=j and i!=k and j!=k: s.append(i*k*j) print(max(s)) def min_product(arr): s=[] for i in arr: for j in arr: for k in arr: if i!=j and i!=k and j!=k: s.append(i*k*j) print(min(s)) #max_product([-8, -9, 1, 2, 7]) #➞ 504 #max_product([-8, 1, 2, 7, 9]) #➞ 126 #min_product([-5, -3, -1, 0, -4]) #➞ -60 #min_product([-5, -3, -1, 0, 4]) #➞ -15 #-------------------------------------------------------------------------------------------------- #Sexy primes are primes that differ by 6. #For example, (5, 11) comprise a sexy prime pair, while (5, 11, 17) comprise a set of sexy prime triplets. #Create a function that takes two numbers as argument, the set length n (2 for pairs, 3 for triplets), and #the limit. Return a list of sorted tuples of sexy primes up to (but excluding) the limit. from math import sqrt; from itertools import count, islice from functools import reduce def isPrime(n): return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1))) def sexy_primes(count,limit): arr=[] for i in range(2,limit): if isPrime(i): arr.append(i) result = tuple(arr[x:x + count] for x in range(0, len(arr), count)) print(result) #sexy_primes(2, 100) #➞ [(5, 11), (7, 13), (11, 17), (13, 19), (17, 23), (23, 29), (31, 37), (37, 43), (41, 47), (47, 53), (53, 59), (61, 67), (67, 73), (73, 79), (83, 89)] #sexy_primes(3, 100) #➞ [(5, 11, 17), (7, 13, 19), (11, 17, 23), (17, 23, 29), (31, 37, 43), (41, 47, 53), (47, 53, 59), (61, 67, 73), (67, 73, 79)] #sexy_primes(3, 250) #➞ [(5, 11, 17), (7, 13, 19), (11, 17, 23), (17, 23, 29), (31, 37, 43), (41, 47, 53), (47, 53, 59), (61, 67, 73), (67, 73, 79), (97, 103, 109), (101, 107, 113), (151, 157, 163), (167, 173, 179), (227, 233, 239)] #-------------------------------------------------------------------------------------------------- #Write a function that repeats the shorter string until it is equal to the length of the longer string. #Both strings will differ in length. #Both strings will contain at least one character. def lengthen(s1,s2): s11=[i for i in s1] s22=[i for i in s2] if len(s11)<len(s22): for i in s11: s11.append(i) if len(s11)==len(s22): print(''.join(s11)) break else: for i in s22: s22.append(i) if len(s22)==len(s11): print(''.join(s22)) break #lengthen("abcdefg", "ab") #➞ "abababa" #lengthen("ingenius", "forest") #➞ "forestfo" #lengthen("clap", "skipping") #➞ "clapclap" #--------------------------------------------------------------------------------------------------- #An emirp = is a prime number that when we reverse its digits it is also prime 13 is a prime, and so is 31. Both are therefore emirps. #A bemirp is a prime which is an emirp but additionally, makes another prime when flipped upside down i.e 9 is upside down of 6 and 6 is upside down of 9 #So Bemirps consist only of digits 0, 1, 6, 8, and 9. it is emirp and upside dwon #For example: 11061811, reversed = 11816011, upside-down = 11091811, upside-down reversed = 11819011. All four are primes. #Create a function that takes a number and returns : #"B" if it’s a bemirp, #"E" if it's emirp, #"P" if it's a prime, and is not bemirp and is not emirp #"C" if it is not a prime from math import sqrt; from itertools import count, islice from functools import reduce def isPrime(n): return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1))) def recognize_prime(num): num=str(num) re=num[::-1] reversee=int(re) x = ['0', '1', '6', '8', '9'] emirp=isPrime(int(num)) and isPrime(int(reversee)) if emirp: print("E : it is emirp") arr=[] nineToSix=[] sixtoNine=[] w=[] for i in range(len(num)): if num[i] in x: arr.append(True) else: arr.append(False) for i in num: if i=='9': num=num.replace(i,'6') if isPrime(int(num)): nineToSix.append(True) else: nineToSix.append(False) elif i=='6': num=num.replace(i,'9') if isPrime(int(num)): sixtoNine.append(True) else: sixtoNine.append(False) w.append(nineToSix) w.append(sixtoNine) a=[] for i in w: if all(i)==True: a.append(True) #all elements of num are in x Bimirp= len(arr)==len(num) and all(arr)==True and emirp and a!=[] if Bimirp: print("B: bimirp") primee= isPrime(int(num)) if primee: print("p: it is prime") if not primee and not Bimirp and not emirp: print("c: it is not prime") #recognize_prime(13) #recognize_prime(101) #➞ "P" #recognize_prime(1011) #➞ "C" #recognize_prime(1069) #➞ "E" #recognize_prime(1061) #➞ "B" #-------------------------------------------------------------------------------------------------- #Given an array of strings and an original string, #write a function to output an array of boolean values - True if the word can be formed from the original word by swapping two letters only once and False otherwise. #Original string will consist of unique characters. from itertools import permutations def validate(element,string): aa=[] w=element #element w=list(w) s=string #string for k in range(len(w)): for j in range(len(w)): w=element w = list(w) w[j],w[k]=w[k],w[j] z=''.join(w) aa.append(z) x=[] for i in aa: if i not in x: x.append(i) m=[] if s in x: m.append('True') else: m.append('False') return m def validate_swaps(arr,string): a=[] for i in arr: m=validate(i,string) a.append(m) s=[''.join(i) for i in a] print(s) #validate_swaps(["BACDE", "EBCDA", "BCDEA", "ACBED"], "ABCDE") #➞ [True, True, False, False] # Swap "A" and "B" from "ABCDE" to get "BACDE". # Swap "A" and "E" from "ABCDE" to get "EBCDA". # Both "BCDEA" and "ACBED" cannot be formed from "ABCDE" using only a single swap. #validate_swaps(["32145", "12354", "15342", "12543"], "12345") #➞ [True, True, True, True] #validate_swaps(["9786", "9788", "97865", "7689"], "9768") #➞ [True, False, False, False] #-------------------------------------------------------------------------------------------------- #We can assign a value to each character in a word, based on their position in the alphabet (a = 1, b = 2, ... , z = 26). A #balanced word is one where the sum of values on the left-hand side of the word equals the sum of values on the right-hand side. #For odd length words, the middle character (balance point) is ignored. #Write a function that returns True if the word is balanced, and False if it's not. #All words will be lowercase, and have a minimum of 2 characters alphabet=['0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def balanced(string): string=string.lower() string=list(string) arr=[] aa=[] b=[] first_half_of_even=[] second_half_of_even=[] if len(string)%2==0: a=int(len(string)/2) arr.append(string[:a]) aa.append(string[a:]) for i in (arr): for j in i: first_half_of_even.append(alphabet.index(j)) for i in (aa): for j in i: second_half_of_even.append(alphabet.index(j)) x=sum(first_half_of_even) y=sum(second_half_of_even) if x==y: print(True) else: print(False) else: a = int(len(string) / 2) string=''.join(string) string=string.replace(string[a],'') #remove middle element arr.append(string[:a]) aa.append(string[a:]) for i in (arr): for j in i: first_half_of_even.append(alphabet.index(j)) for i in (aa): for j in i: second_half_of_even.append(alphabet.index(j)) x = sum(first_half_of_even) y = sum(second_half_of_even) if x == y: print(True) else: print(False) #balanced("zips") #balanced("brake") #--------------------------------------------------------------------------------------------------- #Write a Python class to get all possible unique subsets from a set of distinct integers. #Input : [4, 5, 6] #Output : [[],[4], [5], [6], [5, 6], [4, 6], [4, 5], [4, 5, 6]] from itertools import chain, combinations class subset: def __init__(self,string): self.string=string def sub(self): return chain.from_iterable(combinations(list(self.string), i) for i in range(len(list(self.string)) + 1)) a="456" s=subset(a) x=list(s.sub()) #print(x) #--------------------------------------------------------------------------------------------------- #Write a function to find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number #Input: numbers= [90,20,10,40,50,60,70], target=50 #Output: 2,3 def cal(arr,target): for i in arr: for j in arr: if i!=j: if i+j==target: print(arr.index(i),arr.index(j)) numbers= [90,20,10,40,50,60,70] target=50 #cal(numbers,target) #--------------------------------------------------------------------------------------------------- #Create all possible strings by using 'a', 'e', 'i', 'o', 'u'.Use the charactors exactly once import itertools s=['a', 'e', 'i', 'o', 'u'] x=list(itertools.permutations(s)) #for i in x: #print(''.join(i)) #--------------------------------------------------------------------------------------------------- #Write a Python program to find common divisors between two numbers in a given pair def find_divisor(arr): f=[] s=[] c=[] for i in range(1,arr[0]+1): if arr[0]%i==0: f.append(i) for i in range(1, arr[1] + 1): if arr[1] % i == 0: s.append(i) for i in f: if i in s: c.append(i) print(f,s,c) print("number of common divisors is:",len(c)) #find_divisor([2,4]) #find_divisor([2,8]) #find_divisor([12,24]) #-----------------------------------------------------------Dictionaries------------------------------------------------------ #Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). #sample Dictionary (n = 5) : #expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} def dic(n): d={} for i in range(1,n+1): d[i]=i*i print(d) #dic(5) #-------------------------------------------- #Write a Python program to multiply all the values together in a dictionary my_dict = {'data1':2,'data2':4,'data3':8} x=1 for i in my_dict.values(): x=x*i #print(x) #-------------------------------------------- #Write a Python program to map two lists into a dictionary. keys = [1, 2, 3] values = ['green','red', 'blue'] d={} for i in keys: for j in values: d[i]=j values.remove(j) break #print(d) #------------------------------------------- #Write a Python program to sort a dictionary by key. d = {4: 10, 3: 20, 2: 30, 6: 40, 5: 50, 1: 60} d=sorted(d.items()) x={x:y for x,y in d} #print(x) #------------------------------------------- #Write a Python program to combine two dictionary adding values for common keys d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} d={} #Sample output: {'a': 400, 'b': 400, 'c': 300, 'd':400} for i in d1.keys(): for j in d1.values(): for l in d2.keys(): for k in d2.values(): if i not in d2.keys(): d[i]=j d[l]=k else: x=d1[i]+d2[l] d[i]=x #print(d) #--------------------------------------------- #Write a Python program to find the highest 3 values in a dictionary. my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5873, 'f': 20} arr=[] keys_of_top_three=[] w=[] for i in my_dict.values(): arr.append(i) x=sorted(arr) top_three=x[-3:] x=[i for i in reversed(top_three)] #print(x) for i in x: for j in my_dict.keys(): if my_dict[j]==i: keys_of_top_three.append(j) for i in keys_of_top_three: if i not in w: w.append(i) #print(w) #-------------------------------------------- #Write a Python program to create a dictionary from a string. #Note: Track the count of the letters from the string. #string = "programming" #Expected output: {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1} def makeDicFromStr(string): arr=[] for i in string: arr.append([i,string.count(i)]) x = {x: y for x, y in arr} print(x) #makeDicFromStr("programming") #---------------------------------------------- #Write a Python program to sort in descending order by value. my_dictionaryy={'Math':81, 'Physics':83, 'Chemistry':87} #Expected data: [('Chemistry', 87), ('Physics', 83), ('Math', 81)] arr=[] for i in my_dictionaryy.values(): arr.append(i) arr=sorted(arr) arr=reversed(arr) w=[] for i in arr: for j in my_dictionaryy.keys(): if my_dictionaryy[j]==i: w.append([j,i]) #print(w) #---------------------------------------------- #Write a Python program to replace dictionary values with their sum. my_dict={'Math':2, 'Physics':3, 'Chemistry':1} x=sum(my_dict.values()) for i in my_dict.keys(): my_dict[i]=x #print(my_dict) #--------------------------------------------- #Write a Python function to check whether a number is perfect or not. #a perfect number is a positive integer that is equal to the sum of its proper positive divisors, #that is, the sum of its positive divisors excluding the number itself #Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). #Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. #Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. #The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128. def perfect(num): arr=[] for i in range(1,num): if num%i==0 : arr.append(i) if sum(arr)==num: print(True) else: print(False) #perfect(6) #perfect(28) #perfect(496)
# Imported the necessary modules import pandas as pd from psql import dbCon as psql import numpy as np from datetime import * import warnings import matplotlib as matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Defined the visual class class visual(): """The visual class is used to generate visualisations for book borrow and return statistics. There are three visualisations generated: 1. The first visualisation consists of two vertical bar graphs which depict the number of books being borrowed and returned per day. 2. The second visualisation consists of two vertical bar graphs which depict the number of books being borrowed and returned per week. 3. The third visualisation is a horizontal bar graph which depicts the three most popular books in the library.""" # Suppress all warnings warnings.simplefilter(action='ignore') # Function to create psql object def object_declare(self): """This function creates an object of the psql class and then return it. Returns: connection -- Object of the psql class. """ obj = psql() return obj # Function to come up with week range def calc_week_range(self, year, week): """This function comes up with the week range based on a week number and a year. First, the first date of the year is stored in a variable. Then, the number of days are calculated based on the week number. The number of days and six plus the number of days are then seperately added to the variable to come up with the week range. Arguments: year {int} -- The year of the week range. week {int} -- The week which is used to come up with the week range. Returns: string -- The week range based on week number and year. """ # Calculates and returns week range based on week number and year firstdate = date(year,1,1) rangedate = timedelta(days = (week-1)*7) return str(firstdate + rangedate) + " " + "-" + " " + str(firstdate + rangedate + timedelta(days=6)) # Function to create day-wise borrow and return visualisation def create_day_graph(self): """This function creates two vertical bar graphs with trend lines as subplots and combines them into one main plot. The first bar graph depicts the number of books borrowed from the library day-wise and the second one depicts the number of books being returned to the library day-wise.""" # Creates psql object and creates connection to cloud db obj = self.object_declare() conn = obj.createCon() # Retrieves bookborrowed date from cloud db data = pd.read_sql_query('''SELECT * FROM BOOKBORROWED''', conn) data['borroweddate'] = pd.to_datetime(data.borroweddate).dt.date # Gets number of books being borrowed day-wise and converts to dataframe counts = data['borroweddate'].value_counts().sort_index() borrowed_counts_df = counts.rename_axis('borroweddate').reset_index(name='counts') # Gets number of books being returned day-wise and converts to dataframe returned_counts_df = pd.read_sql_query('''select returneddate, count(returneddate) from bookborrowed group by returneddate order by returneddate;''', conn) returned_counts_df = returned_counts_df[returned_counts_df['returneddate'].notnull()] # Creates main plot fig = plt.figure() # Creates first subplot axis1 = fig.add_subplot(211) # Creates vertical bar graph depicting number of books borrowed day-wise borrowed_counts_df.plot(ax=axis1, color=['black']) borrowed_counts_df.plot.bar(rot=0, ax=axis1, color=['red']) axis1.set_xticklabels(borrowed_counts_df['borroweddate'], fontsize=5) axis1.set_xlabel("Book borrow date") axis1.set_ylabel("Number of books borrowed") axis1.set_title("Number of books borrowed day-wise") axis1.get_legend().remove() # Creates second subplot axis2 = fig.add_subplot(212) # Creates vertical bar graph depicting number of books returned day-wise returned_counts_df.plot(ax=axis2, color=['black']) returned_counts_df.plot.bar(rot=0, ax=axis2, color=['green']) axis2.set_xticklabels(returned_counts_df['returneddate'], fontsize=5) axis2.set_xlabel("Book return date") axis2.set_ylabel("Number of books returned") axis2.set_title("Number of books returned day-wise") axis2.get_legend().remove() fig.tight_layout() # Generates pdf containing both vertical bar graphs as a single plot fig.savefig('static/day_wise.pdf') # Close the cloud db connection obj.closeCon(conn) # Function to create week-wise borrow and return visualisation def create_week_graph(self): """This function creates two vertical bar graphs with trend lines as subplots and combines them into one main plot. The first bar graph depicts the number of books borrowed from the library week-wise and the second one depicts the number of books being returned to the library week-wise.""" # Creates psql object and creates connection to cloud db obj = self.object_declare() conn = obj.createCon() # Retrieves bookborrowed date from cloud db data = pd.read_sql_query('''SELECT * FROM BOOKBORROWED''', conn) # Divides data dataframe into two based on borrowed date and returned date borrowed_data = data.loc[:, data.columns != 'returneddate'] returned_data = data.loc[:, data.columns != 'borroweddate'] returned_data = returned_data[returned_data['returneddate'].notnull()] returned_data = returned_data.reset_index(drop=True) borrowed_data['borroweddate'] = pd.to_datetime(borrowed_data.borroweddate).dt.date returned_data['returneddate'] = pd.to_datetime(returned_data.returneddate).dt.date # Creates week column for both borrowed_data and returned_data dataframes borrowed_data['week_borrowed'] = pd.to_datetime(borrowed_data.borroweddate).dt.week returned_data['week_returned'] = pd.to_datetime(returned_data.returneddate).dt.week # Creates week_range column for both borrowed_data and returned_data dataframes borrowed_data['week_range_borrowed'] = np.nan returned_data['week_range_returned'] = np.nan # Goes through length of borrowed_data df and calculates week range for each borrow week for i in range(0, len(borrowed_data)): borrowed_data['week_range_borrowed'][i] = self.calc_week_range(datetime.now().year, int(borrowed_data['week_borrowed'][i])) # Goes through length of returned_data df and calculates week range for each return week for i in range(0, len(returned_data)): returned_data['week_range_returned'][i] = self.calc_week_range(datetime.now().year, int(returned_data['week_returned'][i])) # Gets number of books being borrowed week-wise and converts to dataframe borrowed_counts = borrowed_data['week_range_borrowed'].value_counts().sort_index() borrowed_counts_df = borrowed_counts.rename_axis('week range').reset_index(name='borrowed_counts') # Gets number of books being returned week-wise and converts to dataframe returned_counts = returned_data['week_range_returned'].value_counts().sort_index() returned_counts_df = returned_counts.rename_axis('week range').reset_index(name='returned_counts') # Creates vertical bar graph depicting number of books borrowed week-wise fig = plt.figure() axis1 = fig.add_subplot(211) borrowed_counts_df.plot(ax=axis1, color=['black']) borrowed_counts_df.plot.bar(rot=0, ax=axis1, color=['red']) axis1.set_xticklabels(borrowed_counts_df['week range'], fontsize=5) axis1.set_xlabel("Book borrow week") axis1.set_ylabel("Number of books borrowed") axis1.set_title("Number of books borrowed week-wise") axis1.get_legend().remove() # Creates vertical bar graph depicting number of books returned week-wise axis2 = fig.add_subplot(212) returned_counts_df.plot(ax=axis2, color=['black']) returned_counts_df.plot.bar(rot=0, ax=axis2, color=['green']) axis2.set_xticklabels(returned_counts_df['week range'], fontsize=5) axis2.set_xlabel("Book return week") axis2.set_ylabel("Number of books returned") axis2.set_title("Number of books returned week-wise") axis2.get_legend().remove() fig.tight_layout() # Generates pdf containing both vertical bar graphs as a single plot fig.savefig('static/week_wise.pdf') # Close the cloud db connection obj.closeCon(conn) # Function to create visualisation depicting three most popular books def create_popularbook_graph(self): """This function creates a horizontal grouped bar graph which depicts the three most popular books based on the number of times it has been borrowed. The number of borrows and returns for each of the three books are depicted as horizontal stacked bars.""" # Creates psql object and creates connection to cloud db obj = self.object_declare() conn = obj.createCon() # Retrieves data for three most popular books in library data = pd.read_sql_query('''select title,count(borroweddate), count(returneddate) from book, bookborrowed where book.bookid = bookborrowed.bookid group by title order by COUNT(borroweddate) DESC limit 3;''', conn) # Creates horizontal grouped bar graph depicting three most popular books fig, ax = plt.subplots() graph3 = data.plot.barh(rot=90, ax=ax, color=['blue','maroon']) ax.set_yticklabels(data.title) ax.set_xlabel("Number of times borrowed/returned") ax.set_ylabel("Book name") ax.set_title("Three most popular books in the library") ax.legend(["borrowed", "returned"]) # Generates pdf containing the horizontal grouped bar graph plt.savefig("static/popularbooks.pdf") # Close the cloud db connection obj.closeCon(conn) # Creates visual class object and calls all functions vis = visual() vis.create_day_graph() vis.create_week_graph() vis.create_popularbook_graph()
import timeit import time class CodeTimer: def __init__(self, name=None): self.name = " '" + name + "'" if name else '' def __enter__(self): self.start = timeit.default_timer() def __exit__(self, exc_type, exc_value, traceback): self.took = (timeit.default_timer() - self.start) * 1000.0 print(f'\x1b[6;30;42m {self.name} Code block total time: {self.took} ms \x1b[0m') def getUserInput(options): print("Enter your option:") for idx, element in enumerate(options): print("{}) {}".format(idx+1,element)) i = input("Enter number: ") try: if 0 < int(i) <= len(options): return int(i) except: pass return None
n1 = float(input('Insira um numero:')) n2 = float(input('Insira um numero:')) n3 = float(input('Insira um numero:')) if n1 > n2 > n3 and n1 > n3: print(n1) print(n2) print(n3) elif n1 > n2 and n1 > n3 > n2: print(n1) print(n3) print(n2) elif n2 > n1 > n3 and n2 > n3: print(n2) print(n1) print(n3) elif n2 > n1 and n2 > n3 > n1: print(n2) print(n3) print(n1) elif n3 > n1 > n2 and n3 > n2: print(n3) print(n1) print(n2) else: print(n3) print(n2) print(n1)
raio = float(input('Digite o raio da circunferencia:')) print((raio**2)*3.14)
import sys #loading a default module, sys #(sys allows you to pass in file instead of coding the file name into the script) import csv #loads default module, csv; allows Python to read .csv files import glob import os.path import os import dicttocsv_csvtolist_v2 as conv def get_name_and_area_from_gcms(csv_filename): """ reads in processed gcms data from utf8-encoded csv file name passed in; returns a list of chemicals and their areas for that sample """ name_and_area_doubles = [] areas = [float(item) for item in conv.read_unicode_csv_col_to_list(csv_filename, 2)] names = conv.read_unicode_csv_col_to_list(csv_filename, 3 ) for i in range(0, len(areas)): name_and_area_doubles.append([names[i], areas[i]]) return name_and_area_doubles def get_names_and_name_to_area(gcms_filepath): """ make a list of unique chemical names in each processed sample file, and a dictionary one that pairs names with abundance/area; if the flower does not have that particular chemical, then it is added to each the list and the dictionary; if we ID two peaks as the same chemical (they may be closely related compounds), then we add together the values for all of those peaks for the final area in the dictionary.""" name_and_area_doubles = get_name_and_area_from_gcms(gcms_filepath) list_of_names = [] name_to_area = {} for name, area in name_and_area_doubles: if name not in list_of_names: list_of_names.append(name) name_to_area[name] = area else: old_area = name_to_area[name] area_sum = old_area + area name_to_area[name] = area_sum return list_of_names, name_to_area def make_list_of_names_and_name_to_area_dictionary_for_all_csvs(directory): """ for all csv files in a directory,generates a macro dictionary that uses filenames as keys, and returns the smaller dictionaries for individual files; also generates as separate list with all unique chemical names across all files""" csv_files = glob.glob(directory + "*.csv") filepath_to_name_to_area_dictionaries_dictionary = {} master_list_of_names = [] for csv_file in csv_files: list_of_names, name_to_area = get_names_and_name_to_area(csv_file) for name in list_of_names: if name not in master_list_of_names: master_list_of_names.append(name) filepath_to_name_to_area_dictionaries_dictionary[csv_file] = name_to_area return filepath_to_name_to_area_dictionaries_dictionary, master_list_of_names def get_dictionary_of_names_and_list_of_areas_in_order(filepath_to_name_to_area_dictionaries_dictionary, master_list_of_names, list_of_filenames): """ outputs a dictionary with rt as the key and a list of area values that correspond to the order of flower samples in of the list of filenames ({rt -> [value of the area for that rt in file 1 in list of filenames, in file 2 in list of filenames, etc]}""" table = {} for name in master_list_of_names: all_areas = [] for filename in list_of_filenames: name_to_area_dictionary = filepath_to_name_to_area_dictionaries_dictionary[filename] area = name_to_area_dictionary.get(name, 0) all_areas.append(area) table[name] = all_areas return table def make_csv_of_name_area(csv_filename, name_to_areas_dictionary, master_list_of_names, list_of_filepaths): """ outputs a .csv file with header of filenames, row.names as rts, and areas/ abundances filling in the cells""" header = ["Chemical_Name"] filenames = [] for filepath in list_of_filepaths: filename = filepath.rstrip(os.sep) #retain just file name, not full path all_slash_indices = [i for i, char in enumerate(filename) if char == "/"] last_slash_index = all_slash_indices[-1] filename = filename[(last_slash_index + 1):] extension_index = filename.index(".csv") filename = filename[:extension_index] filenames.append(filename) header.extend(filenames) rows = [] for name in master_list_of_names: row = [name] areas = [] for area in name_to_areas_dictionary[name]: areas.append(unicode(int(area))) row.extend(areas) rows.append(row) conv.write_unicode_lists_into_csv_listsasrows(csv_filename, rows, header) def integrate_csvs_to_one_by_name(csv_output_file, directory_containing_csv_files): print "start" filepath_to_name_to_area_dictionaries_dictionary, master_list_of_names = make_list_of_names_and_name_to_area_dictionary_for_all_csvs(directory_containing_csv_files) list_of_filenames = filepath_to_name_to_area_dictionaries_dictionary.keys() table = get_dictionary_of_names_and_list_of_areas_in_order(filepath_to_name_to_area_dictionaries_dictionary, master_list_of_names, list_of_filenames) make_csv_of_name_area(csv_output_file, table, master_list_of_names, list_of_filenames) print "done"
class Employee: """ Employee Class contains firstname,lastname,ssn and salary properties and giveRaise method.Include also magic methods """ def __init__(self, firstname, lastname, ssn, salary=0.0): """ class constructor """ self.firstname = firstname self.lastname = lastname self.ssn= ssn self.salary = salary def __str__(self): """ class as string """ return 'First name: ' + self.firstname + '\nLast name: ' + self.lastname + '\nSocial Security Number: ' + self.ssn + '\nSalary: ' + str(self.salary) + '\n' def giveRaise(self, percentRaise): """ give raise in salary by accepting raising percentage """ self.salary = self.salary + (self.salary*percentRaise/100.0) def __lt__(self,other): """ less than comparison magic method """ if self.lastname.lower() < other.lastname.lower(): return True elif self.lastname.lower() == other.lastname.lower(): if self.firstname.lower() < other.firstname.lower(): return True else: return False else: return False def __eq__(self,other): """ Equal comparison magic method """ if self.firstname.lower() == other.firstname.lower() and self.lastname.lower() == other.lastname.lower(): return True else: return False class Manager(employee.Employee): """ Manager class inherits Employee. Have extra title property Includes constructor and string method """ def __init__(self, firstname, lastname, ssn, salary, title): """ class constructor. Also calls super class constructor """ super().__init__(firstname, lastname, ssn, salary) self.title = title def __str__(self): """ string method. Calls super class string method """ super().__str__() return super().__str__() + 'Title: ' + self.title + '\n' listOfObjects = [] # create Employee object emp = employee.Employee('John', 'Doe', '456-22-9834', 9000) listOfObjects.append(emp) # create Manager object man = manager.Manager('Jane', 'Aoe', '123-98-6665', 15000, 'Senior Manager') listOfObjects.append(man) emp2 = employee.Employee('vohn', 'Foe', '456-22-9834', 9000) listOfObjects.append(emp2) # create Manager object man2 = manager.Manager('Zane', 'Foe', '123-98-6665', 15000, 'Senior Manager') listOfObjects.append(man2) listOfObjects.sort() for p in listOfObjects: print ('\nBefore Raise:') print (p.__str__()) p.giveRaise(5) print ('\nAfter giving Raise:') print(p.__str__()) print(man==emp) print(man<emp) print(emp<man)
#inserire la parola nella variabile message (linea 46) #insert the word in the variable: message (line 46) #INSERIRE LA PAROLA IN MAIUSCOLO #INSERT THE WORD IN CAPS ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZ" letter_to_index=dict(zip(ALPHABET, range(len(ALPHABET)))) index_to_letter=dict(zip(range(len(ALPHABET)), ALPHABET)) def encrypt(message, shift): cipher="" for letter in message: if letter== " ": shifted_letter=letter else: index=(letter_to_index[letter]+shift)%len(ALPHABET) shifted_letter=index_to_letter[index] cipher+=shifted_letter return cipher def decrypt(ciphered_text, shift): decrypted="" for letter in ciphered_text: if letter== " ": shifted_letter=letter else: index=(letter_to_index[letter]-shift)%len(ALPHABET) shifted_letter=index_to_letter[index] decrypted+=shifted_letter return decrypted def main(): #INSERIRE LA PAROLA IN MAIUSCOLO #INSERT THE WORD IN CAPS message="WORD" scelta=input("Scrivere <criptare> o <decriptare> per selezionare la modalità di esecuzione del programma: ") if scelta=="criptare": encrypted_message=encrypt(message, 5) print(encrypted_message) elif scelta=="decriptare": decrypted_message=decrypt(message, 2) print(decrypted_message) main()
a=[[0]*3 for x in range(3)] b=[[0]*3 for x in range(3)] c=[[0]*3 for x in range(3)] for x in range(len(a)): for y in range(len(a[x])): a[x][y]=int(input('')) for x in range(3): for y in range(3): b[x][y]=int(input('')) c[x][y]=a[x][y]+b[x][y] print(c)
def IsPointInCircle(x, y, xc, yc, r): return((x-xc)**2+(y-yc)**2<=r**2) x=float(input()) y=float(input()) xc=float(input()) yc=float(input()) r=float(input()) if IsPointInCircle(x, y, xc, yc, r): print('YES') else: print('NO')
"""a=int(input()) b=int(input()) for i in range (a, b+1, 2): e=i%2+i print(e, end=" ")""" a=int(input()) b=int(input()) for i in range(a+a%2,b+1,2): print(i,end=" ")
a=list(input().split()) a.reverse() [print(i, end=" ") for i in a]
#Raphael Dela Cruz 2/26/21 #Method that runs all functions. NOTE: This program does not count letters if they do not appear, in my file the letter "z" does not appear so it does not show that it appears 0 times. def main(): #Remember to include file type. For example, to read a txt file called lorem, do lorem.txt userInput = input("Enter the file name you would like to read: ") countDictionary = countLetter(getText(userInput)) for k,v in countDictionary.items(): print("The letter {} appears {} times.".format(k, v)) #Function that counts letters in a sentence (or in this case, a file of text), then returns a list def countLetter(sentence): #Create empty dictionary dictionary = {} #Iterates through each letter, checks if it is a letter in the alphabet and adds it to dictionary for i in sentence: if(i.isalpha()): dictionary[i.lower()] = dictionary.get(i.lower(),0) + 1 #Sorts the dictionary so that the number of occurences for a is the very first key value. sortedDict = sorted(dictionary.items()) return dict(sortedDict) #Opens text file to obtain string value, then returns the string. def getText(fileName): fileOpen = open(fileName) return fileOpen.read() main()
import random # Read in all the words in one go with open("input.txt") as f: words = f.read() # split into words split_words = words.split() # TODO: analyze which words can follow other words # Your code here dataset = {} for i in range(len(split_words) - 1): word = split_words[i] next_word = split_words[i + 1] if word not in dataset: dataset[word] = [next_word] else: dataset[word].append(next_word) print(dataset) # TODO: construct 5 random sentences # Your code here # Make a list ofstart words # If first/second character is capitalized put into list # loop over our split words and put any start word in the list start_words = [] for key in dataset.keys(): if key[0].isupper() or len(key) > 1 and key[1].isupper(): start_words.append(key) word = random.choice(start_words) stopped = False stop_signs = "?.!" while not stopped: # print the word print(word) # if it 's a stop word stop if word[-1] in stop_signs or len(word) and word[-2] in stop_signs: stopped = True # choose random start word following_words = dataset[word] word = random.choice(following_words)
#problem statement can be found at #https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/0000000000088231 #I/O: python3 solution.py < input_file.txt > output_file.txt # input() reads a string with a line of input, stripping the ' ' (newline) at the end. # This is all you need for most Code Jam problems. def divsum(n): #math library having problems. maybe something deleted from interpreter if n%2 == 0: up=n else: up=(n//2) + 1 for i in range(1,up+1): if(notfour(str(i),str(n-i))): return (int(i),int(n-i)) def notfour(num1,num2): confirmation = True for i in num1+num2: if i=="4": confirmation = False return confirmation if __name__=="__main__": t = int(input()) # read a line with a single integer if t<1 or t>100: exit(0) for i in range(1, t + 1): #n = [int(s) for s in input().split(" ")] # read a list of integers, 2 in this case n=int(input()) if n<1: pass else: ans1 = divsum(n) print("Case #{}: {} {}".format(i, ans1[0],ans1[1]))
import datetime year=int(input("Enter year: ")) month=int(input("Enter month: ")) day=int(input("Enter day: ")) print("week number: ",datetime.date(year, month, day).isocalendar()[1])
import re def abbreviate(words): ac = "" words = re.sub(r'[\'_]', '', words) words = re.sub(r'[^\w]', ' ', words) for i in words.split(): ac += i[0] return ac.upper()
#___GLOBAL VARIABLES __doc__ #game board board = ["-","-","-", "-","-","-", "-","-","-",] #if game still going game_still_going = True #who won or tie winner = None #whose turn is it current_player = "X" def display_board(): print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " + board[7] + " | " + board[8]) def play_game(): display_board() while game_still_going: handle_turn(current_player) check_if_game_over() #flip to other player flip_player() #the game has ended if winner == "X" or winner == "O": print(winner + " won.") elif winner == None: print("Tie.") def handle_turn(player): print(player +) position = input("Choose a position from 1-9: ") position = int(position) - 1 board[position] = player display_board() def check_if_game_over(): check_for_winner() check_if_tie() def check_rows(): global game_still_going row_1 = board[0] == board[1] == board[2] != "-" row_2 = board[3] == board[4] == board[5] != "-" row_3 = board[6] == board[7] == board[8] != "-" if row_1 or row_2 or row_3: game_still_going = False if row_1: return board[0] elif row_2: return board[3] elif row_3: return board[6] return def check_columns(): global game_still_going col_1 = board[0] == board[3] == board[6] != "-" col_2 = board[1] == board[4] == board[7] != "-" col_3 = board[2] == board[5] == board[8] != "-" if col_1 or col_2 or col_3: game_still_going = False if col_1: return board[0] elif col_2: return board[1] elif col_3: return board[2] return def check_diagonals(): global game_still_going dia_1 = board[0] == board[4] == board[8] != "-" dia_2 = board[2] == board[4] == board[6] != "-" if dia_1 or dia_2: game_still_going = False if dia_1: return board[0] elif dia_2: return board[2] return def check_for_winner(): #check rows row_winner = check_rows() #check columns column_winner = check_columns() #check diagonals diagonal_winner = check_diagonals if row_winner: winner = row_winner elif column_winner: winner = column_winner elif diagonal_winner: winner = diagonal_winner else: winner = None return def check_if_tie(): global game_still_going if "-" not in board: game_still_going = False return def flip_player(): global current_player if current_player == "X": current_player = "O" elif current_player == "O": current_player = "X" return play_game() #board #display board #play game #handle a turn #check win #check rows #check columns #check diagonals #check tie #flip player
width = int(input()) height = int(input()) passengers = int(input()) border = ("|" + ("-" * (width * 2 + 1)) + "|") print(border) for row in range(height): print("|", end="") for col in range(width): print(".X" if passengers > 0 else ".O", end="") passengers -= 1 print(".|") print(border) print("v" + (" " * (width * 2 + 1)) + "v")
def workday(x): return {"banana": 2.5, "apple": 1.2, "orange": .85, "grapefruit": 1.45, "kiwi": 2.7, "pineapple": 5.5, "grapes": 3.85 }.get(x, -1.0) def weekend(x): return {"banana": 2.7, "apple": 1.25, "orange": .9, "grapefruit": 1.6, "kiwi": 3.0, "pineapple": 5.6, "grapes": 4.2 }.get(x, -1.0) fruit = input().lower() dayOfWeek = input().lower() quantity = float(input()) price = -1.0 isWeekend = (dayOfWeek == "saturday" or dayOfWeek == "sunday") isWorkDay = (dayOfWeek == "monday" or dayOfWeek == "tuesday" or dayOfWeek == "wednesday" or dayOfWeek == "thursday" or dayOfWeek == "friday") if isWeekend: price = quantity * weekend(fruit) elif isWorkDay: price = quantity * workday(fruit) if price >= 0: print("{:.2f}".format(price)) else: print("Error")
amount = float(input()) fromCurrency = input() toCurrency = input() if fromCurrency == "USD": amount *= 1.79549 elif fromCurrency == "EUR": amount *= 1.95583 elif fromCurrency == "GBP": amount *= 2.53405 if toCurrency == "USD": amount /= 1.79549 elif toCurrency == "EUR": amount /= 1.95583 elif toCurrency == "GBP": amount /= 2.53405 print("{0:.2f} {1}".format(amount, toCurrency))
import sys n = int(input()) minNumber = sys.maxsize for i in range(0, n): currentNumber = int(input()) if currentNumber < minNumber: minNumber = currentNumber print(minNumber)
n = int(input()) odd = "*" * (n - 2) even = "-" * (n - 2) for i in range(1, n - 1): if i % 2 == 1: print(odd + "\\ /" + odd) else: print(even + "\\ /" + even) print(" " * (n - 1) + "@") for i in range(1, n - 1): if i % 2 == 1: print(odd + "/ \\" + odd) else: print(even + "/ \\" + even)
bitcoin = int(input()) juan = float(input()) commission = float(input()) bitcoinToLev = bitcoin * 1168 juanToDollar = juan * 0.15 dollarToLev = juanToDollar * 1.76 euro = (bitcoinToLev + dollarToLev) / 1.95 euro -= euro * commission / 100 print("{0:.2f}".format(euro))
while True: print("Enter even number: ", end="") try: n = int(input()) if n % 2 == 1: print("The number is not even.") else: print("Even number entered: {}".format(n)) break except: print("Invalid number!")
x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) sideA = abs(x1 - x2) sideB = abs(y1 - y2) perimeter = 2 * (sideA + sideB) area = sideA * sideB print(area) print(perimeter)
"""Tardigrade is a module for experimenting with composable models for simulations. The idea is that multiple people can define a model and they will work together well. It also has ideas from deep uncertainty, in that it can easily represent uncertainty between models as well. """ import math import abc import random class Distribution(metaclass=abc.ABCMeta): """This is the Distribuion abstract base class. A Distribution is used by a random variable to reprsent the range and type of randomness that occurs""" @abc.abstractmethod def sample(self): """Sample picks a value from the distribution""" ... def set_num_samples(self, samples): """Set_num_samples sets the number of samples to be expect during the run This is usefull for coverage strategies, so that the samples can be evenly spaced. """ self.num_samples = samples def __init__(self): self.num_samples = None class UniformDistribution(Distribution): """UnifomDistribution selects a number in the range betweeen *upper* and *lower* with equal probability. There are two strategies that can be used when sampling. Random samples at random, coverage is used when yuu want to make sure you have even coverage over a space. Use this if you are only doing a few runs. """ def sample(self): "Sample picks a value from the distribution" sample_val = None if self.strategy == "random": sample_val = random.uniform(self.lower, self.upper) elif self.strategy == "coverage": step = (self.upper - self.lower) / self.num_samples sample_val = (step * self.samples_taken) + self.lower self.samples_taken += 1 return sample_val def __init__(self, upper, lower, strategy): super().__init__().__init__() self.upper = upper self.lower = lower self.strategy = strategy self.samples_taken = 0 self.last_sample = None class BernoulliDistribution(Distribution): """BernoulliDistrbution picks 0 with probability of p and 1 with probability p-1""" def sample(self): "Sample picks a value from the distribution" sample_val = None if self.strategy == "random": val = random.uniform(0, 1) if val < self.p_val: sample_val = 0 else: sample_val = 1 elif self.strategy == "coverage": num_zero_samples = self.p_val * self.num_samples if self.samples_taken < num_zero_samples: sample_val = 0 else: sample_val = 1 else: pass return sample_val def __init__(self, p_val, strategy): super().__init__() self.p_val = p_val self.samples_taken = 0 self.strategy = strategy class EquiProbableDistribution(Distribution): """EquiprobableDistribution picks from a number of different values, equally likely. Like a dice roll.""" def sample(self): "Sample picks a value from the distribution" sample_val = None if self.strategy == "random": sample_val = random.choice(self.vals) elif self.strategy == "coverage": num_per_value = self.num_samples / self.vals.length val_num = self.samples_taken / num_per_value self.samples_taken += 1 sample_val = self.vals[math.floor(val_num)] else: pass return sample_val def __init__(self, vals, strategy): super().__init__() self.vals = vals self.samples_taken = 0 self.strategy = strategy class SampleFrequency(metaclass=abc.ABCMeta): """Sample frequency is the frequency at which a random variable is re-rolled This is the abstract base class""" @abc.abstractmethod def should_resample(self, world: World): """should_resample is called by the RandomVariable to determie if it is the right time to resample the variable""" ... def __init__(self): self.force_resample = False class Once(SampleFrequency): """Once samples once during the run""" def should_resample(self, world: World): """should_resample is called by the RandomVariable to determie if it is the right time to resample the variable""" if self.force_resample: self.force_resample = False return True return False class Nticks(SampleFrequency): """Nticks resamples the random variable once every n-ticks of the clock""" def should_resample(self, world: World): """should_resample is called by the RandomVariable to determine if it is the right time to resample the variable""" if world.tick > (self.ticks_per_sample + self.last_tick): self.last_tick = world.tick return True return False def __init__(self, ticks_per_sample): super().__init__() self.last_tick = 0 self.ticks_per_sample = ticks_per_sample class Model: """Models are what defines the next state. They take a function that is expected to take the world, the current state, the current time and the difference in time from the last world""" def __init__(self, state: Any, func: Callable[[World, Any, Int, Int], Any]): self.state = state self.func = func def run(self, world, state, time, time_diff): """Run runs the func with the variables""" return self.func(world, state, time, time_diff) class RandomVariable: """RandomVariable brings together he frequency and distribution in order It also maintains knowledge of the current state of the random variable""" def __init__( self, name: str, variable_type: str, frequency: SampleFrequency, distribution: Distribution, ): self.name = name self.variable_type = variable_type self.frequency = frequency self.distribution = distribution self.value = None def get_value(self, world: World): """get_value gets the current value of the random variable. Sampling it if required""" if self.frequency.should_resample(world) or self.value is None: self.value = self.distribution.sample() return self.value def set_num_samples(self, samples: int) -> None: """Sets the number of samples for the run""" self.distribution.set_num_samples(samples) class UncertainModel: """Uncertain Model has a number of different models for tbe behaviour. It uses a random variable to determine which one to add.""" def __init__(self): self.model_list = [] self.random_variable = None def add_model(self, model: Model) -> None: """Adds a new model to the possible models""" self.model_list.append(model) def add_random_variable(self, variable: RandomVariable) -> None: """Adds a new variable to control which model is picked""" self.random_variable = variable def run(self, world: World, state: Any, time: int, time_diff: int) -> Any: """Runs the model based on the random variable""" if self.random_varibale is None: Raise( Exception( "Undefined random variable for uncertain model ", self.model_list[0].name, ) ) return self.model_list[self.random_variable.get_value(world)].run( world, state, time, time_diff ) class State: """State holds the state""" def __init__(self, name, state_type, val): self.name = name self.type = state_type self.val = val def get_val(self) -> Any: """Gets the value of the state""" return self.val class World: """World is the entire context for the simulation""" def next(self, state: State, func: Callable[[World, Any, Int, Int], Any]) -> None: """Next defines the function that updates the particular state over time""" model = Model(state, func) if state in self.model_map: # Add random model here ... else: self.model_map[state] = model def add_state(self, name, state_type, val): """Add state creates a new state of the world""" self.state_map[name] = State(name, state_type, val) def get_state(self, name): """Get state gets the current state""" return self.state_map[name].get_val() def add_variable(self, name, variable_type, distribution, sample_frequency): """Adds a random variable""" self.variable_map[name] = RandomVariable( name, variable_type, frequency, distribution ) def copy_state_and_models(self, world): """Copies state and models from one world to another""" self.state_map.update(world.state_map) # TODO Need to do work in here if there are two models # with the same name to make an uncertain one self.model_map.update(world.model_map) def __init__(self): self.state_map = {} self.model_map = {} self.variable_map = {} self.history = [] def sample(self, num_samples): ... def probabilistic_model(self, state_name, distrubution, sample_frequency): ... def simulate(self, steps): for var_name, var_obj in self.variable_map.items(): # We aren't sampling over lots of worlds var_obj.set_num_samples(1) for x in range(steps): for state_name, state_obj in self.state_map.items(): next_state_value = self.model_map[state_name].run( self, state_obj.val, x, 1.0 ) state_obj.val = next_state_value print(state_name, next_state_value) world1 = World() world1.add_state("light", "boolean", True) world1.next("light", lambda world, val, t, dt: True if t < 450 else False) world2 = World() world2.add_state("light", "boolean", True) world2.add_state("carpos", "int", 0.0) world2.next( "carpos", lambda world, val, t, dt: val + (dt / 6.0) if world.get_state("light") else val, ) world3 = World() world3.copy_state_and_models(world2) world3.copy_state_and_models(world1) world3.simulate(452) print(world3.get_state("light"))
class Solution: def countPrimes(self, n: int) -> int: if n < 3: return 0 primes = [True] * n primes[0] = False primes[1] = False for i in range(2, int(n**0.5+1)): if not primes[i]: continue t = i+i while t < n: primes[t] = False t += i return sum(primes)
# 42. Trapping Rain Water # https://leetcode.com/problems/trapping-rain-water/ class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ stack=[] s=0 h=0 for i, v in enumerate(height): #print i, v, stack, s if v>0: while stack: if stack[-1][0]<=v: vv, ni=stack.pop() #print '@', (i-ni-1)*(vv-h) s+=(i-ni-1)*(vv-h) h=vv else: vv, ni=stack[-1] #print (i-ni-1)*(v-h) s+=(i-ni-1)*(v-h) break h=0 stack.append((v, i)) return s
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: ok = True for i in range(len(flowerbed)): if flowerbed[i] == 0: if ok and (i==len(flowerbed)-1 or flowerbed[i+1]==0): n-=1 ok = False else: ok = True else: ok = False if n > 0: return False return True
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ if n == 0: return elif m == 0: for i in range(n): nums1[i] = nums2[i] #print(nums1) return i1 = m - 1 i2 = n - 1 i = m + n -1 while i1 >= 0 and i2 >= 0: if nums1[i1] >= nums2[i2]: nums1[i] = nums1[i1] i1 -= 1 else: nums1[i] = nums2[i2] i2 -= 1 i -= 1 print(nums1) print(nums2) while i2 >= 0: nums1[i] = nums2[i2] i2 -= 1 i -= 1 return
class Solution: def diff(self, w1, w2): return sum([1 for i in range(len(w1)) if w1[i] != w2[i]]) def diff1(self, w1): res_set = set() for i in range(len(w1)): s = w1[:i] + '-' + w1[i+1:] if s in self.str_dict: res_set = res_set | self.str_dict[s] self.str_dict[s].add(w1) else: self.str_dict[s] = set([w1]) return res_set def bfs(self, beginWord, endWord): word_set = set() word_queue = [beginWord] word_set.add(beginWord) h = 1 while word_queue: h += 1 new_queue = [] for w1 in word_queue: for w2 in self.word_dict[w1]: if w2 == endWord: return h if w2 not in word_set: new_queue.append(w2) word_set.add(w2) word_queue = new_queue return 0 def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: wordList += [beginWord] self.word_dict = {} self.str_dict = {} for i in range(len(wordList)): w1 = wordList[i] self.word_dict[w1] = set() diff_words = self.diff1(w1) self.word_dict[w1] = diff_words for w2 in diff_words: self.word_dict[w2].add(w1) #for j in range(i): # w2 = wordList[j] # if self.diff(w1, w2) <2: # self.word_dict[w1].add(w2) # self.word_dict[w2].add(w1) return self.bfs(beginWord, endWord)
#--- Exercício 3 - Funções #--- Escreva uma função para listar pessoas cadastradas: #--- a função deve exibir todas as pessoas cadastradas na função do ex1 #--- Escreva uma função para exibi uma pessoa específica: # a função deve exibir uma pessoa cadastrada na função do ex1 filtrando por id from Exercicio1 import lista_cadastro def listar_pessoas(lista_cadastro): for pessoa in lista_cadastro: for ch, val in pessoa.items(): print(ch, ' : ', val) print('Esses foram os dados presente no banco de dados.\n') def listar_pessoa(ID): for pessoa in lista_cadastro: for val in pessoa.items(): if val == pessoa['ID']: print('Nome', ' : ', pessoa['Nome']) print('Sobrenome', ' : ', pessoa['Sobrenome']) print('Idade', ' : ', pessoa['Idade']) print('Esses foram os dados vinculados a esse ID no banco de dados.\n')
'''Diseña un programa que, dado un número entero, muestre por pantalla el mensaje «El número es par» cuando el número sea par y el mensaje «El numero es impar» cuando sea impar.''' a = int(input('Ingresa un numero: ')) if (a % 2) == 0: print('\nEl numero es par') if (a % 2) != 0: print('\nEl numero es impar')
from random import randrange from turtle import Screen, Turtle from time import sleep CeldaCerrada = 0 CeldaAbierta = 1 CeldaTemporalmenteAbierta = 2 def crea_matriz(filas, columnas): matriz = [] for i in range(filas): matriz.append([None] * columnas) return matriz def inicializa_tablero(tablero): for i in range(len(tablero)): for j in range(len(tablero[0])): tablero[i][j] = CeldaCerrada def rellena_simbolos(simbolo): numsimbolo = 0 for i in range(len(simbolo)): for j in range(len(simbolo[0])): simbolo[i][j] = chr(ord('a') + numsimbolo // 2) numsimbolo += 1 for i in range(1000): [f1, c1] = [randrange(len(simbolo)), randrange(len(simbolo[0]))] [f2, c2] = [randrange(len(simbolo)), randrange(len(simbolo[0]))] tmp = simbolo[f1][c1] simbolo[f1][c1] = simbolo[f2][c2] simbolo[f2][c2] = tmp def dibuja_celda(baldosa, simbolo, i, j): global tortuga tortuga.penup() tortuga.goto(j + .5, i) tortuga.begin_fill() if baldosa[i][j] == CeldaCerrada: tortuga.fillcolor('blue') tortuga.circle(.5) tortuga.goto(j + .5, i + .25) tortuga.write(simbolo[i][j]) elif baldosa[i][j] == CeldaAbierta: tortuga.fillcolor('white') tortuga.circle(.5) tortuga.goto(j + .5, i + .25) tortuga.write(simbolo[i][j]) else: tortuga.fillcolor('yellow') tortuga.circle(.5) tortuga.goto(j + .5, i + .25) tortuga.write(simbolo[i][j]) tortuga.end_fill() tortuga.pendown() def dibuja_tablero(tablero, simbolo): for i in range(len(simbolo)): for j in range(len(simbolo[0])): dibuja_celda(tablero, simbolo, i, j) def clic(x, y): global pantalla, tablero, simbolo, temporal1, temporal2 pantalla.onclick(None) [j, i] = [int(x), int(y)] if 0 <= i < len(tablero) and 0 <= j <= len(tablero[0]): if tablero[i][j] == CeldaCerrada: if temporal1 == None: temporal1 = [i, j] tablero[i][j] = CeldaTemporalmenteAbierta else: temporal2 = [i, j] tablero[i][j] = CeldaTemporalmenteAbierta dibuja_celda(tablero, simbolo, i, j) if temporal2 != None: if simbolo[temporal1[0]][temporal1[1]] == simbolo[temporal2[0]][temporal2[1]]: tablero[temporal1[0]][temporal1[1]] = CeldaAbierta tablero[temporal2[0]][temporal2[1]] = CeldaAbierta else: sleep(0.5) tablero[temporal1[0]][temporal1[1]] = CeldaCerrada tablero[temporal2[0]][temporal2[1]] = CeldaCerrada dibuja_celda(tablero, simbolo, temporal1[0], temporal1[1]) dibuja_celda(tablero, simbolo, temporal2[0], temporal2[1]) temporal1 = None temporal2 = None dibuja_celda(tablero, simbolo, i, j) if todas_abiertas(tablero): pantalla.bye() else: pantalla.onclick(clic) def todas_abiertas(tablero): for i in range(len(tablero)): for j in range(len(tablero[0])): if tablero[i][j] == CeldaCerrada: return False return True def menu(): opc = 0 while opc > 3 or opc <= 0: print('Selecciona tu nivel de dificultad: ') print('1) Facil') print('2) Normal') print('3) Dificil') opc = int(input('¿Dificultad 1, 2, ó 3?: ')) if opc == 1: return [3, 4] elif opc == 2: return [4, 6] else: return [6, 8] # Programa principal [filas, columnas] = menu() pantalla = Screen() pantalla.setup(columnas * 50, filas * 50) pantalla.screensize(columnas * 50, filas * 50) pantalla.setworldcoordinates(-.5, -.5, columnas + .5, filas + .5) pantalla.delay(0) tortuga = Turtle() tortuga.hideturtle() simbolo = crea_matriz(filas, columnas) tablero = crea_matriz(filas, columnas) temporal1 = None temporal2 = None inicializa_tablero(tablero) rellena_simbolos(simbolo) dibuja_tablero(tablero, simbolo) pantalla.onclick(clic) pantalla.mainloop()
#Diseña un programa que, dados dos números enteros, muestre por pantalla uno de estos mensajes: # «El segundo es el cuadrado del primero», «El segundo es menor que el cuadrado del primero » # o bien «El segundo es mayor que el cuadrado del primero », dependiendo de la verificación de la condición # correspondiente al significado de cada mensaje. primero = int(input('Ingresa el primero numero: ')) segundo = int(input('Ingresa el segundo numero: ')) if segundo == (primero ** 2): print('El segundo es el cuadrado del primero') if segundo <= (primero ** 2): print('El segundo es menor que el cuadrado del primero') if segundo >= (primero ** 2): print('El segundo es mayor que el cuadrado del primero')
from turtle import Screen, Turtle pantalla = Screen() pantalla.setup(425, 225) pantalla.screensize(400, 200) # Diseña un programa que dibuje un triángulo equilátero con la tortuga. # El trazo del triángulo debe tener un grosor de 10 píxeles. tortuga = Turtle() tortuga.pensize(10) tortuga.forward(100) tortuga.left(120) tortuga.forward(100) tortuga.left(120) tortuga.forward(100) # No uses los métodos left o right. tortuga.setheading(0) tortuga.pensize(2) tortuga.color('white') tortuga.forward(100) tortuga.setheading(120) tortuga.forward(100) tortuga.setheading(240) tortuga.forward(100) pantalla.exitonclick()
from turtle import Screen, Turtle # El método speed permite controlar la velocidad con la que se desplaza la tortuga: su argumento es un número entre 0 y 10, # donde 1 es la mínima velocidad y 10 es la máxima. # Calificaciones ingresadas predefinidas #suspensos = 10 #aprobados = 20 #notables = 40 #sobresalientes = 30 # Modifica el programa para que sea el usuario quien proporcione, mediante el teclado, # el valor del porcentaje de suspensos, aprobados, notables y sobresalientes. #suspensos = int(input("Ingresa el porcentaje de suspensos: ")) #aprobados = int(input("Ingresa el porcentaje de aprobados: ")) #notables = int(input("Ingresa el porcentaje de notables: ")) #sobresalientes = int(input("Ingresa el porcentaje de sobresalientes: ")) # Modifica el programa para que sea el usuario quien proporcione, mediante el teclado, # el número de suspensos, aprobados, notables y sobresalientes. (Antes de dibujar el gráfico de # pastel debes convertir esas cantidades en porcentajes). suspensos = int(input("Ingresa el numero de suspensos: ")) aprobados = int(input("Ingresa el numero de aprobados: ")) notables = int(input("Ingresa el numero de notables: ")) sobresalientes = int(input("Ingresa el numero de sobresalientes: ")) total = suspensos + aprobados + notables + sobresalientes suspensos = (suspensos * 100) / total aprobados = (aprobados * 100) / total notables = (notables * 100) / total sobresalientes = (sobresalientes * 100) / total #Radio del círculo radio = 300 #Inicialización pantalla = Screen() tortuga = Turtle() tortuga.speed(0) #Esconder la tortuga tortuga.hideturtle() #Dibujo del círculo exterior. tortuga.penup() tortuga.goto(0, -radio) tortuga.pendown() tortuga.circle(radio) tortuga.penup() tortuga.home() tortuga.pendown() #Dibujo de la línea para los suspensos. angulo = 360 * suspensos / 100 tortuga.left(angulo) tortuga.forward(radio) tortuga.backward(radio) #Escribir el texto para los suspensos tortuga.penup() tortuga.right(angulo / 2) tortuga.forward(radio / 2) tortuga.write('suspensos') tortuga.backward(radio / 2) tortuga.left(angulo / 2) tortuga.pendown() #Dibujo de la línea para los aprobados. angulo = 360 * aprobados / 100 tortuga.left(angulo) tortuga.forward(radio) tortuga.backward(radio) #Escribir el texto para los aprobados tortuga.penup() tortuga.right(angulo / 2) tortuga.forward(radio / 2) tortuga.write('aprobados') tortuga.backward(radio / 2) tortuga.left(angulo / 2) tortuga.pendown() #Dibujo de la línea para los notables. angulo = 360 * notables / 100 tortuga.left(angulo) tortuga.forward(radio) tortuga.backward(radio) #Escribir el texto para los notables tortuga.penup() tortuga.right(angulo / 2) tortuga.forward(radio / 2) tortuga.write('notables') tortuga.backward(radio / 2) tortuga.left(angulo / 2) tortuga.pendown() #Dibujo de la línea para los sobresalientes. angulo = 360 * sobresalientes / 100 tortuga.left(angulo) tortuga.forward(radio) tortuga.backward(radio) #Escribir el texto para los sobresalientes tortuga.penup() tortuga.right(angulo / 2) tortuga.forward(radio / 2) tortuga.write('sobresalientes') tortuga.backward(radio / 2) tortuga.left(angulo / 2) tortuga.pendown() #Salir cuando se pulse el botón en la ventana pantalla.exitonclick()
def min(a, b): if a < b: return a else: return b def max(a, b): if a > b: return a else: return b def mcd(m, n): menor = min(m, n) mayor = max(m, n) resto = mayor % menor if resto == 0: return menor else: return mcd(menor, resto)
#Realiza un programa que proporcione el desglose en billetes y monedas de una #cantidad entera de euros. Recuerda que hay billetes de 500, 200, 100, 50, 20, 10 y 5 pesos y #monedas de 2 y 1 pesos. Debes «recorrer» los valores de billete y moneda disponibles con uno o #más bucles for in dinero = int(input('Dime cuanto dinero tienes: ')) for pesos in [500, 200, 100, 50, 20, 10, 5, 2, 1]: billete = dinero//pesos if billete != 0: if pesos > 10: print('Tienes {0} billetes de {1}'.format(billete, pesos)) else: print('Tienes {0} monedas de {1}'.format(billete, pesos)) dinero = dinero % pesos
#lists mylist = [1,2,4] mylist = ['test',12,43.4,True,[1,2,3]] print(mylist) print(len(mylist)) mylist.append("newItem") print(mylist) mylist.append(['x','y','z']) print(mylist) mylist.extend(['x','y','z']) print(mylist) #remove end of the list mylist.pop() print(mylist) #remove item by index index = 0 mylist.pop(index) print(mylist) #list comprehensions matrix = [[1,2,3],[4,5,6],[7,8,9]] col1 = [row[0] for row in matrix] print(col1)
import pandas from bokeh.plotting import figure, output_file, show #prepare some data from excel df = pandas.read_excel("verlegenhuken.xlsx") #df=pandas.read_excel("http://pythonhow.com/data/verlegenhuken.xlsx", sheet_name=0) df["Temperature"]=df["Temperature"]/10 df["Pressure"]=df["Pressure"]/10 p=figure(plot_width=500,plot_height=400, tools='pan') p.title.text="Temperature and Air Pressure" p.title.text_color="Gray" p.title.text_font="arial" p.title.text_font_style="bold" p.xaxis.minor_tick_line_color=None p.yaxis.minor_tick_line_color=None p.xaxis.axis_label="Temperature (°C)" p.yaxis.axis_label="Pressure (hPa)" #p.circle(x,y) p.circle(df["Temperature"],df["Pressure"],size=0.5) #Prepare the output file output_file("WeatherData.html") show(p)
from binary_trees.binary_tree_node import BinaryTreeNode class BinaryTree: def __init__(self): self.__head = None def add(self, data): new_node = BinaryTreeNode(data) if self.__head is None: # if tree empty self.__head = new_node else: self.__add_new_node(self.__head, new_node) def __add_new_node(self, current_node, new_node): compare = current_node.compare(new_node) direction = 'left' if compare == 'less' else 'right' child_node = current_node.get_node(direction) if child_node is None: current_node.set_node(new_node, direction) else: self.__add_new_node(child_node, new_node) def remove(self, value): current, parent = self.__find_with_parent(value) if current is None: return False current_right = current.get_node('right') current_left = current.get_node('left') # Case 1: If current has no right child, current's left replaces current. if current_right is None: if parent is None: self.__head = current_left else: compare = parent.compare(current.value) direction = 'left' if compare == 'less' else 'right' parent.set_node(current_left, direction) # Case 2: If current 's right child has no left child, # current's right child replaces current. elif current_right.get_node('left') is None: current_right.set_node(current_left, 'left') if parent is None: self.__head = current_right else: compare = parent.compare(current.value) direction = 'left' if compare == 'less' else 'right' parent.set_node(current_right, direction) # Case 3: If current's right child has a left child, # replace current with current's right child's left-most child. else: leftmost_parent = current_right leftmost = current_right.get_node('left') while leftmost.get_node('left') is not None: leftmost_parent = leftmost leftmost = leftmost.get_node('left') # The parent's left subtree becomes the leftmost's right subtree. leftmost_right = leftmost.get_node('right') leftmost_parent.set_node(leftmost_right, 'left') # Assign leftmost's left and right to current's left and right children. leftmost.set_node(current_left, 'left') leftmost.set_node(current_right, 'right') if parent is None: self.__head = leftmost else: compare = parent.compare(current.value) direction = 'left' if compare == 'less' else 'right' parent.set_node(leftmost, direction) return True def __find_with_parent(self, remove_value): current = self.__head parent = None while current is not None: compare = current.compare(remove_value) if compare == 'equal': break direction = 'left' if compare == 'less' else 'right' parent = current current = current.get_node(direction) return current, parent def print(self): pass
import math import numpy as np def globe_distance(origin, destination): """ Return distance in km. https://gist.github.com/rochacbruno/2883505 Haversine formula example in Python Author: Wayne Dyck """ lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km # dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c # return d def average_positions(longs, lats): assert len(longs) == len(lats) n = len(lats) sum_x = 0 sum_y = 0 sum_z = 0 longs = [math.radians(l) for l in longs] longs = [(math.sin(l), math.cos(l)) for l in longs] lats = [math.radians(l) for l in lats] lats = [(math.sin(l), math.cos(l)) for l in lats] # x += Math.Cos(latitude) * Math.Cos(longitude); # y += Math.Cos(latitude) * Math.Sin(longitude); # z += Math.Sin(latitude); sum_x = sum([lats[i][1] * longs[i][1] for i in xrange(n)]) sum_y = sum([lats[i][1] * longs[i][0] for i in xrange(n)]) sum_z = sum([lats[i][0] for i in xrange(n)]) # x = x / total; # y = y / total; # z = z / total; sum_x /= n sum_y /= n sum_z /= n # var centralLongitude = Math.Atan2(y, x); # var centralSquareRoot = Math.Sqrt(x * x + y * y); # var centralLatitude = Math.Atan2(z, centralSquareRoot); result = math.atan2(sum_y, sum_x), math.atan2(sum_z, math.sqrt(sum_x**2 + sum_y**2)) return math.degrees(result[0]), math.degrees(result[1]) def to_3d_representation(longs, lats): longs = math.radians(longs) lats = math.radians(lats) long_coses = np.cos(longs) lat_coses = np.cos(lats) long_sines = np.sin(longs) lat_sines = np.sin(lats) x = lat_coses * long_coses y = lat_coses * long_sines z = lat_sines return (x, y, z) def to_long_lat(x, y, z): longitude = math.atan2(y, x) latitude = math.atan2(z, math.sqrt(x**2 + y**2)) return math.degrees(longitude), math.degrees(latitude)
# Defining Function def f(x): return 2*x**3 - 4*x**2 - 24 # Implementing Bisection Method def bisection(x0,x1,e): step = 1 print('\n\n*** BISECTION METHOD IMPLEMENTATION ***') condition = True while condition: x2 = (x0 + x1)/2 print('Iteration-%d, x2 = %0.5f and f(x2) = %0.5f' % (step, x2, f(x2))) if f(x0) * f(x2) < 0: x1 = x2 else: x0 = x2 step = step + 1 condition = abs(f(x2)) > e print('\nAkar Penyelesaian : %0.5f' % x2) # Input Section x0 = input('Dugaan awal: ') x1 = input('Duganaan akhir: ') e = input('Toleransi Eror: ') # Converting input to float x0 = float(x0) x1 = float(x1) e = float(e) #Note: You can combine above two section like this # x0 = float(input('dugaan awal: ')) # x1 = float(input('dugaan akhir: ')) # e = float(input('Toleransi Error: ')) # Checking Correctness of initial guess values and bisecting if f(x0) * f(x1) > 0.0: print('Given guess values do not bracket the root.') print('Try Again with different guess values.') else: bisection(x0,x1,e)
# Import `random` so we can generate random numbers. # The `string` module gives us access to string-related utilities, # like a list of lowercase characters. import random import string print('ROBOT MISSILE') print() print('Type the correct code letter (A-Z) to defuse the missile.') print('You have 8 chances.') print() # Choose, at random, a lowercase ascii character code = random.choice(string.ascii_lowercase) # Loop until we get a match, or we've tried 8 times guesses = 0 success = False while not success and guesses < 8: # Read a character from the user, and convert it to lower case guess = input('What is your guess? ').lower() guesses += 1 # Check to see if the guess is correct. If it is, flag the success; # otherwise, print an error message hinting towards the final answer. if guess == code: success = True elif guess < code: print('The code is later than %s in the alphabet' % guess) elif guess > code: print('The code is earlier than %s in the alphabet' % guess) # The loop has exited. Let the user know if they succeeded or not. if success: print('TICK... FIZZ... CLICK...') print('You did it!') else: print('BOOOOOOOOMMM...') print('You blew it!') print() print("The correct code was '%s'." % code) print('You did it%s!' % (' (just)' if guesses == 8 else ''))
from typing import DefaultDict, Dict, Iterable, List, Set, Tuple from advent_utils import input_to_list def twoSum(l: List[int], sum: int) -> Tuple[int, int]: store: Set[int] = set() for i in l: if i in store: return (i, sum-i) else: store.add(sum-i) raise Exception("not all were ints") assert(twoSum([-2, 8, 3, 4, 5], 6) == (8,-2)) x1, x2 = twoSum(input_to_list('./input.txt'), 2020) answer = x1 * x2 print("first answer") print(answer) def threeSum(l: List[int], sum: int = 2020) -> Tuple[int, int, int]: d: Dict[int, List[int]] = DefaultDict(lambda: []) for idx,val in enumerate(l): d[sum-val].append(idx) for i in range(len(l)-1): for j in range(i+1, len(l)): x, y = l[i], l[j] z = x+y if z in d: if any([k not in [i,j] for k in d[z]]): return (x, y, sum-z) raise Exception("no three sum found") assert(sum(threeSum([3, 4, 5, 8, -9, 4, 5], 4))==4) a1, a2, a3 = threeSum(input_to_list('./input.txt'), 2020) print("second answer") print(a1*a2*a3)
import pymysql import os db = pymysql.connect( host="localhost", user="root", password="", database="pythoncrud" ) def insert_data(db): try: print("\n\t" , 5* "==", "INSERT DATA MAHASISWA" , 5*"==") nim = int(input("\n\t Masukan nim mahasiswa\t\t: ")) nama = input("\n\t Masukan nama mahasiswa\t\t: ") jurusan = input("\n\t Masukan jurusan mahasiswa\t: ") gender = input("\n\t Masukan gender\t\t\t: ") except ValueError: print("\n\t Anda memasukan variable , silakan input ulang kembali!!") else: value = (nim, nama, jurusan, gender) cursor = db.cursor() sql = "INSERT INTO mahasiswa (`nim`, `nama`, `jurusan`, `gender`) VALUES (%s, %s, %s, %s)" cursor.execute(sql, value) db.commit() print("\n\t", "{} Data berhasil disimpan".format(cursor.rowcount)) finally: cursor.close() def show_data(db): cursor = db.cursor() cursor.execute("SELECT * FROM mahasiswa") rows = cursor.fetchall() no = 1 for row in rows: print("\n\t" , 5*"===", "DATA MAHASISWA KE-",no, 5*"===") print("\n\t ID \t\t: ", +row[0]) print("\t NIM \t\t: ", + row[1]) print("\t NAMA \t\t: ", row[2]) print("\t JURUSAN \t: ",row[3]) print("\t GENDER \t: ", row[4]) print("\n\t", 9*"======") no += 1 print("\n\t Jumblah banyaknya mahasiswa : ", no-1) cursor.close() def update_data(db): try: print("\n\t",5*"=====", "UPDATE DATA MAHASISWA", 5 * "=====") id = int(input("\n\t Masukan id mahasiswa yang ingin diupdate\t: ")) jurusan = input("\n\t Masukan jurusan mahasiswa yang baru\t\t: ") except ValueError: print("anda memasukan variable!!") except ZeroDivisionError: print("anda memasukan angka 0!!") else: cursor = db.cursor() sql = "UPDATE mahasiswa SET jurusan = %s WHERE id = %s" val = (jurusan, id) cursor.execute(sql, val) db.commit() print("\n\t", "{} Data berhasil disimpan".format(cursor.rowcount)) finally: cursor.close() def delete_data(db): try: print("\n\t", 5 * "===", "UPDATE DATA MAHASISWA", 5 * "===") id = int(input("\n\tMasukan id mahasiswa yang ingin didelete\t: ")) nim = input("\n\tMasukan delete nim mahasiswa\t\t: ") except ValueError: print("anda memasukan variable!!") except ZeroDivisionError: print("anda memasukan angka 0!!") else: cursor = db.cursor() sql = "DELETE FROM mahasiswa WHERE id = %s AND nim = %s" val = (id, nim) cursor.execute(sql, val) db.commit() print("{} data diubah".format(cursor.rowcount)) finally: cursor.close() def many_data(db): try: id1 = int(input("delete data dari id ke : ")) id2 = int(input("samapai id ke : ")) except ValueError: print("anda memasukan variable!!") except ZeroDivisionError: print("anda memasukan angka 0!!") else: cursor = db.cursor() sql = "DELETE FROM mahasiswa WHERE id BETWEEN %s AND %s" val = (id1, id2) cursor.execute(sql, val) db.commit() print("{} data diubah".format(cursor.rowcount)) finally: cursor.close() def search_data(db): try: id = int(input("\n\tMasukan id mahasiswa yang ingin dicari\t: ")) except ValueError: print("anda memasukan variable!!") except ZeroDivisionError: print("anda memasukan angka 0!!") else: cursor = db.cursor() sql = "SELECT * FROM mahasiswa WHERE id = %s" cursor.execute(sql, id) rows = cursor.fetchall() record = cursor.fetchall() for row in record: print("Id = ", row[0], ) print("Name = ", row[1]) print("Join Date = ", row[2]) print("Salary = ", row[3], "\n") no = 1 for row in rows: print("\n\t" , 5*"===", "DATA MAHASISWA KE-",no, 5*"===") print("\n\t ID \t\t: ", +row[0]) print("\t NIM \t\t: ", + row[1]) print("\t NAMA \t\t: ", row[2]) print("\t JURUSAN \t: ",row[3]) print("\t GENDER \t: ", row[4]) print("\n\t", 9*"======") no += 1 cursor.close() def reset_increment(db): cursor = db.cursor() cursor.execute( "SET @num = 0;") cursor.execute("UPDATE mahasiswa SET id = @num := (@num+1);") cursor.execute("ALTER TABLE mahasiswa AUTO_INCREMENT =1;") def jumblah_data(db): cursor = db.cursor() cursor.execute("SELECT COUNT(id) FROM mahasiswa;") print("{} banyak data : ".format(cursor.rowcount)) def show_menu(db): print("\n\t=== APLIKASI DATABASE PYTHON ===") print("\n\t1. Insert Data") print("\t2. Tampilkan Data") print("\t3. Update Data") print("\t4. Hapus Data") print("\t5. Cari Data") print("\t6. Delete Many Data") print("\t7. Reset Auto Increment") print("\t0. Keluar") print("\n\t------------------") menu = input("\n\tPilih menu> ") os.system("cls") if menu == "1": insert_data(db) elif menu == "2": show_data(db) elif menu == "3": update_data(db) elif menu == "4": delete_data(db) elif menu == "5": search_data(db) elif menu == "6": many_data(db) elif menu == "7": reset_increment(db) elif menu == "8": jumblah_data(db) elif menu == "0": exit() else: print("Menu salah!") if __name__ == "__main__": while(True): show_menu(db)
from nltk.tokenize import sent_tokenize, word_tokenize #metni kelimelerine ayırmak => tokenleştirme text = "Alan Turing, İngiliz matematikçi, bilgisayar bilimcisi ve kriptolog. Bilgisayar biliminin kurucusu sayılır. Geliştirmiş olduğu Turing testi ile makinelerin ve bilgisayarların düşünme yetisine sahip olup olamayacakları konusunda bir kriter öne sürmüştür." """ print(text.split()) print("\n") print(word_tokenize(text)) #noktalama işaretlerini de bir kelime olarak kabul ediyor. print("\n") print(sent_tokenize(text)) #cümleler tokenleştirildi """ for token in word_tokenize(text): print(token)
from nltk.stem import WordNetLemmatizer #farklı bir kök bulma yöntemi lem = WordNetLemmatizer() words = ['eat', 'eating', 'eater', 'eats', 'ate', 'dogs', 'women', 'children'] for word in words: print(lem.lemmatize(word)) """ lemmatizing ile kelimenin sözlükteki anlamına inilir ve çoğullar tekilleştirilebilir. stemming de children ve women aynı kalmıştı çünkü sözlük anlamına değil sondaki ekine odaklanır. =lemmatize= dogs -> dog women -> woman children -> child """ #eğer kelimenin fiil olduğunu belirtirsek, lemmatizing işleminde kelimenin kökünü bu şekilde bulabilir. # 'v' => verb print(lem.lemmatize('eating','v')) print(lem.lemmatize('ate', 'v'))
#Program to find whether the given input is numeric n=int(input()) a=type(n) if a==int: print("Yes")
num = float(input("Enter a number: ")) if num<=0: print("Invalid") elif (num % 2) == 0: print("Even") else: print("Odd")
""" Parse a string that has phone ids and their quantities. IDs can be either for Android or IPhone. Android format is A + 4 characters. IPhone format is I + 3 characters. """ import re from itertools import takewhile, dropwhile, izip EXAMPLE = "Aa1133Iab2Aa112Iac3" def tokens(s): pattern = r'A\w{3}|I\w{2}|\d+' return (g.group() for g in re.finditer(pattern, s)) def tokens_to_pairs(tokens): i = iter(tokens) return ((ident, int(quant)) for (ident, quant) in izip(i, i)) def parse_into_map(s): d = {} for (k, v) in tokens_to_pairs(tokens(s)): d.update({k: d.get(k, 0) + v}) return d print parse_into_map(EXAMPLE)
# Facebook interview sample "Look and Say" # Implement a function that outputs the Look and Say sequence: # # 1 # 11 # 21 # 1211 # 111221 # 312211 # 13112221 # 1113213211 # 31131211131221 # 13211311123113112211 from itertools import groupby, chain, islice def next(n): return ''.join( chain.from_iterable( str(len(list(g))) + k for (k, g) in groupby(n) ) ) def look_and_say(): current = '1' while True: yield current current = next(current) def print_look_and_say(n): for s in islice(look_and_say(), n): print(s)
from itertools import product DIGITS_TO_CHARS = { '0': '0', '1': '1', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } def phone_number_to_words(s): tuples = product(*(DIGITS_TO_CHARS[c] for c in s)) result = sorted(''.join(list(t)) for t in tuples) return ','.join(result) print(phone_number_to_words('2453270'))
# Facebook Sample Interview Question "Edit Distance" # # Write a function that returns whether two words are exactly "one edit" away # using the following signature: # # bool OneEditApart(string s1, string s2); # # An edit is: # # Inserting one character anywhere in the word (including at the beginning and end) # Removing one character # Replacing one character # # Examples: # # OneEditApart("cat", "dog") = false # OneEditApart("cat", "cats") = true # OneEditApart("cat", "cut") = true # OneEditApart("cat", "cast") = true # OneEditApart("cat", "at") = true # OneEditApart("cat", "act") = false def one_edit_apart(s1, s2): if abs(len(s1) - len(s2)) > 1: return False if not s1 or not s2: return True if s1[0] == s2[0]: return one_edit_apart(s1[1:], s2[1:]) if len(s1) > len(s2): return s1[1:] == s2 if len(s2) > len(s1): return s2[1:] == s1 return s1[1:] == s2[1:]
# Current thread is MainThread which the Python interpretor creates at runtime. Below is the code to check. import threading print('Current thread:', threading.currentThread().getName()) # This will give you the current thread # To compare it wilth main Thread without getting the name - used to check when using multiple threading if threading.currentThread() == threading.main_thread(): print('Main thread') else: print('Some other thread')
# This program will create the file client, send the name of the file it wants the server to read and displaying the contents on the console import socket s = socket.socket() # Creating an object s.connect(('localhost',6767)) # Prompt the user to enter filename filename = input('Enter a file name: ') s.send(filename.encode()) content = s.recv(1024) print(content.decode()) s.close()
#Funtion to calculate factorial ofa given number def factorial(n): if n==0: return 1 else: return n*factorial(n-1) print(factorial(10))
import socket # Defining IP protocol -Internet Explorer 4 in socket, TCP?IP communication s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Thi sreturns are socket # Binding the socket s.bind(('localhost',4000)) print('Server listening on port', 4000) s.listen(1) #Number of connections the server will accept c,addr = s.accept() # Reading the data that comes in msg_from_client = c.recv(1024) '''while msg_from_client: msg_from_client = c.recv(1024)''' c.send(msg_from_client) c.send(encrypt(msg_from_client.decode(),3)) c.send(b'Message from server') # send a message to the client the code in binary c.send('\nbye'.encode()) c.close() #A python program to illustrate Caesar Cipher Technique def encrypt(text,s): result = "" # traverse text for i in range(len(text)): char = text[i] # Encrypt uppercase characters if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) elif(str(char) == ' '): result += ' ' # Encrypt lowercase characters else: result += chr((ord(char) + s - 97) % 26 + 97) return print(result.encode())
#Decorator is a function that takes a funtion as input and returns another function after performing some additional processing # to the funtion taken as input i.e. decorates it # Inside the funtion that is returned from the decorator, there is logic that will invoke the input funtion, # takes the result of it and performs additional logic on it # Create a decoartor funtion that will return the double the number returned by another funtion ''' Steps to create a Decor function 1. Create a function decor() which takes another funtion fun() as a parameter 2. Define another funtion, inner() which will invoke the input funtion fun(), perform and return the logic to double it 3. Close the decor funtion by returning the inner funtion() 4. Define the funtion that will be decorated 5. Invoke the decore function ''' ''' def decor(fun): def inner(): result = fun() #Invoking the fun() function return result*2 #Performing the logic on fun() return inner #Close the decor funtion by returning the inner funtion def num(): return 5 resultfun = decor(num) #We are passing the num funtion (which will be decorated) as a paramaetre to the decorator print(resultfun()) #to get the final result in resultfun ''' # In order to directly apply a funtion to decorator use @decor on top of the respective funtion # This way we can directly print the reult by invoking the funtion to be decorated ''' def decor(fun): def inner(): result = fun() #Invoking the fun() function return result*2 #Performing the logic on fun() return inner #Close the decor funtion by returning the inner funtion @decor #Used to indicate that this funtion will ALWAYS be used to the decorator def num(): return 5 print(num()) #Directly invoke num() ''' # String decorators # Create a funtion hello() that will take the name and return 'Hello' + name # Create a decorator that will decoarte the Hello funtion and return hello() + 'How are you' def decor(fun): def inner(n): result = fun(n) result = result + ' How are you?' return result return inner @decor def hello(name): return 'Hello ' +name name=input('Enter your name: ') print(hello(name))
# Socket programming - to establish communication between server and client using the TCP/IP protocol # 1. Create server by opening up a socket # 2. Bind to a machine and port number # 3. Machine starts listening on the port on that machine and then the client can connect to it # 4. Once connectionn is established, messages are sent and received # 5. Connection is closed # This program will create a TCP/IP server, listen to the messages sent by client and send back a message in binary import socket host = 'localhost' port = 4000 # Defining IP protocol -Internet Explorer 4 in socket, TCP?IP communication s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Thi sreturns are socket # Binding the socket s.bind((host,port)) print('Server listening on port', port) s.listen(1) #Number of connections the server will accept c,addr = s.accept() #Accept() methods returns the connection and client address when the client sends a message print('Connection from', str(addr)) c.send(b'Hello, how are you') # send a message to the client the code in binary #or c.send('bye'.encode()) c.close()
# Poly means multi and morphism means behavior i.e. different types of behavior based on data or objects that the functions are dealing with. # # Different ways to implement # 1. Duct typing # 2. Duct typing to do depency injection # 3. + operator for overloading to perform multiple operations. # Method overriding - run time polymorphism # #Duck typing - It is the dynamic nature of the object passed in a method or funtion # For eg, if two different classes - Duck and Human have a method - talk(), then an object from another method can be dynamically used to call # the talk() method from any class. Depending on what object is being passed, the function can do different/multiple things class Duck: def talk(self): print('Quack Quack') class Human: def talk(self): print('Hello') def callTalk(obj): obj.talk() d = Duck() #Behaves as a method of class Duck when object of class Duck is passed callTalk(d) h = Human() #Behaves as a method of class Humanh when object of class Human is passed callTalk(h)
class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + last + '@company.com' def fullname(self): return print(self.first + ' ' + self.last) emp1 = Employee('Corey','Schafer',50000) emp2 = Employee('Ted','Mosbey',60000) emp1.fullname() print(Employee.fullname(emp1)) emp2.fullname()
#Write an assertion statement for even numbers ''' num = int(input('Enter a number- ')) assert num%2==0, 'You have entered an odd number' #This message is displayed when the condition is not met ''' # The code after assert statement is not displayed and so we can use a try catch block # Also, printing the assertion error makes it user-friendly try: num = int(input('Enter a number- ')) assert num%2==0, 'You have entered an odd number' except AssertionError as obj: print(obj) print('After the assertion')
#!/usr/bin/env python3 # coding: utf-8 print("Baшeгo героя окружила огромная армия троллей.") print("Смрадными зелеными трупами врагов устланы все окрестные поля.") print("Одинокий герой достает меч из ножен . готовясь к последней битве в своей жиз­ни.\n") health = 10 trolls = 0 damage = 3 while health > 0: trolls += 1 health = health - damage print("Взмахнув мечом.ваш герой истребляет злобного тролля." \ "но сам получает повреждений на", damage, "очков .") print( "Ваш герой доблестно сражался и убил", trolls, "троллей.") print("Ho увы! Он пал на поле боя . ")
#!/usr/bin/env python3 # coding: utf-8 IPS = 254 d_name = "moduli.ru" d_block = "195.151.31." #d_name = str(input("Домен: ")) #d_block = str(input("ИП: ")) name = d_name.replace(' ','') block = d_block.replace(' ','') if name == "": name = str("example.org") else: pass if block == "": block = str("192.168.0.") else: pass for ip in range(IPS): resolv_ip = (block + str(ip)) print("s" + str(ip), resolv_ip) #print(str(ip), "PTR", resolv_ip) #for ip in range(IPS): # #resolv_ip = (block + str(ip)) # resolv_ip = (str(ip) + " PTR") # resolv_name = ("s" + str(ip) + "." + name) # print(resolv_ip, resolv_name) #EOF
GarisJudul = 48 * "-" BarisBaru = "\n" Judul1 = "Inisialisasi Variabel A & B (Sebelum Pertukaran)" Judul2 = "Hasil Variabel A & B (Setelah Pertukaran)" Judul3 = "Inisialisasi Variabel Awal" Judul4 = "Hasil Pertukaran Nilai" #Inisialisasi (Assignment) Awal a = 10 b = 20 # CARA 1 (Tidak Disarankan) print(GarisJudul) print("Cara I (Tidak Disarankan)") print(GarisJudul, BarisBaru) print(Judul1) print(f'=> A: {a}') print(f'=> B: {b}', BarisBaru) c = a a = b b = c print(Judul2) print(f'=> A: {a}') print(f'=> B: {b}', 3 * BarisBaru) # CARA 2 (Disarankan) print(GarisJudul) print("Cara II (Disarankan)") print(GarisJudul, BarisBaru) print(Judul1) print(f'=> A: {a}') print(f'=> B: {b}', BarisBaru) a, b = b, a print(Judul2) print(f'=> A: {a}') print(f'=> B: {b}', 3 * BarisBaru) #Contoh Pertukaran Nilai Dengan Banyak Variabel print(GarisJudul) print("Pertukaran Nilai Dengan Banyak Variabel") print(GarisJudul, BarisBaru) a, b, c, d, e, f, g = 1, 2, 3, 4, 5, 6, 7 print(Judul3) print(f'A: {a}, B: {b}, C: {c}, D: {d}, E: {e}, F: {f}, G: {g}', BarisBaru) a, b, c, d, e, f, g = d, f, b, g, c, a, e print(Judul4) print(f'A: {a}, B: {b}, C: {c}, D: {d}, E: {e}, F: {f}, G: {g}', 6 * BarisBaru)
def jumps(list): counter = 1 index = 0 while True: max_value =0 for i in range(index, list[index]+index, 1): if i >= len(list)-1: return counter if list[i] > max_value: max_value = list[i] index = max_value + index if list[index] == 0: return -1 counter = counter + 1 sub_liste = [] testcase = -1 liste = [] while int(testcase) < 0: testcase = input("Testcases") for i in range(0, int(testcase), 1): length = input("length") for x in range(0, int(length), 1): sub_liste.append(int(input("enter number"))) liste.append(sub_liste) for j in liste: print(jumps(j))
#!/usr/bin/python3 import sys,time import webbrowser # to deal with web browser # take inline input from user or URL data=sys.argv[1:] print(data) # searching object for i in data: # write code here to google search print(i) time.sleep(2) webbrowser.open_new_tab("https://www.google.com/search?q="+i)
#This is a program made by Steven Kolln #This program demonstrates basic usage of the AWS service SNS import boto; def queueInfo(): sqs=boto.connect_sqs(); queue1=raw_input("Input the name of a queue here and press enter: "); print "" raw_input("Here is some info about the queue:"); q1=sqs.get_queue_attributes(sqs.get_queue(queue1)); for x,y in q1.items(): print x,y print "" def main(): sqs=boto.connect_sqs(); raw_input("I am now going to create two queues."); sqs.create_queue("test"); sqs.create_queue("test2"); raw_input("Two queues were made. I am now going to list all queues I own."); for x in sqs.get_all_queues(): print x queueInfo(); queueInfo(); raw_input("I am now going to delete queue 2. \n"); sqs.delete_queue(sqs.get_queue("test2")); raw_input("Queue deleted. Here are the queues that are left."); print sqs.lookup("test"); print sqs.lookup("test2"); raw_input("I am now going to add 3 message to the queue. Test1 2 and 3."); for x in range(1,4): sqs.get_queue("test").write(sqs.get_queue("test").new_message("This is a Test"+str(x))); q1=sqs.get_queue_attributes(sqs.get_queue("test")); for x,y in q1.items(): if x=="ApproximateNumberOfMessages": print x,y print "" raw_input("I am now going to dequeue the queue one by one then delete the queue"); print str(sqs.get_queue("test").read().get_body()) raw_input("First message dequeued. Here are the next two."); print sqs.get_queue("test").read().get_body() print sqs.get_queue("test").read().get_body() raw_input("Queue empty. Now deleting the queue"); sqs.delete_queue(sqs.get_queue("test")); print sqs.lookup("test"); print sqs.lookup("test2"); if __name__=="__main__": main();
#Tuple is a collection which is ordered and unchangeable. Allows duplicate members. #Tuples are lists that cannot be changed #they share attributes like (len, max, min, indexing, slicing and other basics) with lists a = (3,) #comma is required for a single item to be a Tuple x = ("Diana", 32, "New York") print(a) #x[1] = 'Orange' -> Returns error. Tuples are unchangeable print(x) #Once a tuple is created, you cannot add or remove items. Tuples are unchangeable. #you can use tuples to assign multiple variables at once name,age,country = x print(country) #append to tuple x = (3,4,5,6) x = x + (1,2,3) print(x) print(len(x)) print(max(x)) print(min(x)) tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5]) # Following action is not valid for tuples # tup1[0] = 100 tup3 = tup1 + tup2 #add tuples print(tup3[::-1]) #reverse del tup3 #-> for deleting tuples #difference with lists list_num = [1,2,3,4] tup_num = (1,2,3,4) print(list_num) print(tup_num) print(type(list_num)) print(type(tup_num)) print('list_num=',list_num.__sizeof__()) print('tup_num=',tup_num.__sizeof__()) #low size, faster than lists #list <-> tuple newlist = list(tup_num) newtuple = tuple(list_num) ''' Why use a tuple instead of a list? Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification. There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be. 1.The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [] . 2.Lists has variable length, tuple has fixed length. 3.List has mutable nature, tuple has immutable nature. 4.List has more functionality than the tuple. '''
#Serialization => json #Python provides built-in JSON libraries to encode and decode JSON. #Encoding import json json_string = json.dumps([1, 2, 3, "a", "b", "c"]) print(json_string) #dumps() method converts dictionary object of python into JSON string data format. x = { "name": "Ken", "age": 45, "married": True, "children": ("Alice","Bob"), "pets": ['Dog'], "cars": [ {"model": "Audi A1", "mpg": 15.1}, {"model": "Zeep Compass", "mpg": 18.1} ] } # sorting result in asscending order by keys: sorted_string = json.dumps(x, indent=4, sort_keys=True) print(sorted_string) #'marshal' and 'pickle' external modules of Python maintain a version of JSON library. #Python supports a Python proprietary data serialization method called pickle (and a faster alternative called cPickle). import pickle pickled_string = pickle.dumps([1, 2, 3, "a", "b", "c"]) print(pickle.loads(pickled_string)) ''' dumps() encoding to JSON objects dump() encoded string writing on file loads() Decode the JSON string load() Decode while JSON file read ''' person_data = {"person": {"name": "Kenn", "sex": "male", "age": 28}} # here we create new data_file.json file with write mode using file i/o operation with open('json_file.json', "w") as file_write: # write json data into file json.dump(person_data, file_write) #Decoding # json data string person_data = '{ "person": { "name": "Kenn", "sex": "male", "age": 28}}' # Decoding or converting JSON format in dictionary using loads() dict_obj = json.loads(person_data) print(dict_obj) # check type of dict_obj print("Type of dict_obj", type(dict_obj)) # get human object details print("Person......", dict_obj.get('person')) with open('json_file.json') as file_object: # store file data in object data = json.load(file_object) print(data) ''' Encode default(o) – Implemented in the subclass and return serialize object for o object. encode(o) – Same as json.dumps() method return JSON string of Python data structure. iterencode(o) – Represent string one by one and encode object o. Decode default(o) – Implemented in the subclass and return deserialized object o object. decode(o) – Same as json.loads() method return Python data structure of JSON string or data. raw_decode(o) – Represent Python dictionary one by one and decode object o. ''' #Decoding JSON data from URL: Real Life Example import json import requests # get JSON string data from CityBike NYC using web requests library json_response= requests.get("https://feeds.citibikenyc.com/stations/stations.json") # check type of json_response object print(type(json_response.text)) # load data in loads() function of json library bike_dict = json.loads(json_response.text) #check type of news_dict print(type(bike_dict)) # now get stationBeanList key data from dict print(bike_dict['stationBeanList'][0]) #example import json # fix this function, so it adds the given name # and salary pair to salaries_json, and return it def add_employee(salaries_json, name, salary): salaries = json.loads(salaries_json) salaries[name] = salary return json.dumps(salaries) # test code salaries = '{"Alfred" : 300, "Jane" : 400 }' new_salaries = add_employee(salaries, "Me", 800) decoded_salaries = json.loads(new_salaries) print(decoded_salaries["Alfred"]) print(decoded_salaries["Jane"]) print(decoded_salaries["Me"])
""" Database will be introduced in the next section, in this Section we will introduce flask restful and authentication. """ from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) items = [] class Item(Resource): def get(self, name): for item in items: if item["name"] == name: return item return {"item": None}, 404 def post(self, name): item = {"name": name, "price": 12.00} items.append(item) return item, 201 class Items(Resource): def get(self): return {"items": items} api.add_resource(Item, "/item/<string:name>") api.add_resource(Items, "/items") app.run(port=5000)
""" How does these two stars work? 1) They can be used in a function to collect named arguments into a dictionary. 2) Or they can be used in a function call to unpack a dictionary into keyword arguments. *args -> positional arguments **kwargs -> named arguments This sintax is used to accep an unlimited number of arguments.Example: def post(url, data=None, json=None, **kwargs): return request("post", url, data=data, json=json, **kwargs) """ def named(**kwargs): print(kwargs) def print_nicely(**kwargs): named(**kwargs) for arg, value in kwargs.items(): print(f"{arg}:{value}") details = {"name": "Bob", "age": 25} print(details) # **details means unpacked, f(**details) == f(name="Bob", age=25) named(**details) print_nicely(**details)
""" JWT stands for JSON Web Token, and all it is, is an obfuscation of data. And that is we're going to be encoding some data, and that's a JSON Web Token. So a user is going to be an entity that has a unique identifying number and a username and a password. The user is going to send us a username and a password, and we're going to send them, the client really, a JWT and that JWT is going to be the user ID. When the client has the JWT, they can send it to us with any request they make, and when they do that it's going to tell us that they have previously authenticated, and that means they are logged in. """ from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) app.secret_key = "jose" api = Api(app) items = [] class Item(Resource): def get(self, name): item = next(filter(lambda x: x["name"] == name, items), None) return {"item": item}, 200 if item is not None else 404 def post(self, name): if next(filter(lambda x: x["name"] == name, items), None) is not None: return {"message": f"An item with name {name} already exists."}, 400 posted_data = request.get_json(silent=True) new_item = {"name": name, "price": posted_data["price"]} items.append(new_item) return new_item, 201 class ItemList(Resource): def get(self): return {"items": items} api.add_resource(Item, "/item/<string:name>") api.add_resource(ItemList, "/items") # For good error messages debug=True app.run(port=5000, debug=True)
def collatz(number): if number % 2 == 0: return number // 2 else: return 3 * number + 1 print("Please type a number: ") userInt = int(input()) newInt = collatz(userInt) print(collatz(userInt)) while collatz(newInt) > 1: newInt = collatz(newInt) print(collatz(newInt))
# -*- coding: utf-8 -*- """Softmax.""" scores = [3.0, 1.0, 0.2] import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" soft_ret = []; for i in range(len(x)): soft_ret.append(np.exp(x)[i] / sum(np.exp(x))) return np.array(soft_ret) print(softmax(scores)) # Plot softmax curves import matplotlib.pyplot as plt x = np.arange(-2.0, 6.0, 0.1) # it creates a range with scores not only one array scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) plt.plot(x, softmax(scores).T, linewidth=2) plt.show()
import sqlite3 from sqlite3 import Error class DatabaseManager: def __init__(self, directory='./'): """ Initializes the DatabaseManager with a connection and Keystones table """ if directory[-1] != '/': directory += '/' try: self.conn = sqlite3.connect(f'{directory}keystones.db') create_table_sql = ''' CREATE TABLE IF NOT EXISTS Keystones ( userID TEXT, characterName TEXT COLLATE NOCASE, dungeonID INT NOT NULL, level INT NOT NULL, PRIMARY KEY (userID, characterName) ); ''' self.create_table(create_table_sql) except Error as e: print(e) def create_table(self, create_table_sql): """Creates a table within the current connection""" try: c = self.conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def add_keystone(self, insert_values): """ Inserts or updates a row in the Keystones table This method insert a row into the Keystones table. If a row already exists with the passed userID and characterName, then that row will be updated instead. :param insert_values: (tuple) a tuple containing the userID, characterName, dungeonID, and level to be added (in that order) :return: (bool) True if the transaction was successful """ sql_statement = ''' INSERT OR REPLACE INTO Keystones(userID, characterName, dungeonID, level) VALUES (?, ?, ?, ?); ''' try: cur = self.conn.cursor() cur.execute(sql_statement, insert_values) self.conn.commit() except Error as e: print(e) return False else: return True def get_keystones_single(self, user_id): """ Gets the keystones for a single user A user can be associated with multiple keystones if they have multiple characters :param user_id: (str) the id for a user :return: list of tuples containing character name (str), dungeon id (integer), and level (integer) """ id_tuple = (user_id,) # Needs to be passed as a tuple sql_statement = ''' SELECT characterName, dungeonID, level FROM Keystones WHERE userID=?; ''' try: cur = self.conn.cursor() cur.execute(sql_statement, id_tuple) return cur.fetchall() except Error as e: print(e) return None def get_keystones_many(self, user_ids): """ Gets the keystones for multiple users A user can be associated with multiple keystones if they have multiple characters :param user_ids: (sequence of str) the user ids to get keys of :return: dictionary mapping user ids (str) to a list of tuples containing character name (str), dungeon id (integer), and level (integer) """ query_result = {} sql_statement = ''' SELECT characterName, dungeonID, level FROM Keystones WHERE userID=?; ''' try: cur = self.conn.cursor() for user_id in user_ids: id_tuple = (user_id,) cur.execute(sql_statement, id_tuple) query_result[user_id] = cur.fetchall() except Error as e: print(e) return None else: return query_result def close_connection(self): """ Closes the database connection This method should only be used after being completely finished using the database (ie the program has stopped running). :return: (None) """ try: self.conn.close() except Error as e: print(e) def main(): db_manager = DatabaseManager() db_manager.add_keystone(('123456', 'hovsep', 35, 10)) db_manager.add_keystone(('123456', 'hop', 890, 1)) db_manager.add_keystone(('123456', 'hosep', 5, 180)) db_manager.add_keystone(('567', 'jon', 7, 100)) db_manager.add_keystone(('567', '', 7, 100)) db_manager.add_keystone(('567', 'jak', 7, 100)) db_manager.add_keystone(('567', 'jaK', 8, '99')) db_manager.add_keystone(('567', 'jaKe', 8, '+9')) print(db_manager.get_keystones_many(['5678'])) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Fri Oct 7 15:22:26 2016 @author: skotiang """ from math import sqrt # importing the math formular def Fibonacci_nums(n): sequence = list() X = (1 + sqrt(5))/2 Y = (1 - sqrt(5))/2 for index in xrange(n): term = int((X**index - Y**index)/sqrt(5)) # Fibonacci recursive algorithm sequence.append(term) # append the nth term to the sequence print sequence
#!/usr/bin/python # class to calculate time to wait until some point in the future # 5/3/18 # updated 8/12/18 import sys import logging from time import sleep from datetime import datetime, timedelta class Wait: ''' class to handle sleeping until some point in the future. it uses time.sleep(), and therefore is blocking. there is one public method in this class, wait_til(). read its docstring for details on how it's used. ''' def __init__(self): self.logger = self._init_logger() self.format = '%m:%d:%y:%H:%M:%S' def _init_logger(self): logger = logging.getLogger('wait') logger.info('wait logger instantiated') return logger def _check_len(self, next_time): ''' utility method to return # of fields separated by ':' in next_time. returns 1 if there is no ':' in next_time. ''' return len(next_time.split(':')) def _parse(self, next_time): ''' if next_time is already a datetime object, pass it on through. if next_time is a single field, treat it as an int representing seconds from now til some point in the future. attempt to add it to datetime.now() and return it. if next_time is 3 fields separated by ':', prepend it with the current date. otherwise leave it as is. either way attempt to convert it to datetime object. both int(next_time) and datetime.strptime(next_time, self.format) will throw ValueError if they fail due to bad arguments. ''' if type(next_time) == datetime: return next_time else: next_time = str(next_time) check = self._check_len(next_time) try: if check == 1: return datetime.now() + timedelta(seconds=int(next_time)) elif check == 3: today = datetime.today().strftime('%m:%d:%y') next_time = ':'.join([today, next_time]) return datetime.strptime(next_time, self.format) except ValueError: self.logger.error('improperly formatted input, cannot convert to datetime object') return None def _is_future(self, next_time): '''check that next_time is in the future''' if next_time > datetime.now(): return next_time else: self.logger.error('input time is not in the future') return None def _validate_time(self, next_time): ''' if seemingly valid input is received, attempt to parse it and convert it to a datetime object in the future; if input is invalid or this process fails somehow, return none ''' next_time = self._parse(next_time) return self._is_future(next_time) if next_time else None def _calculate_wait(self, future): '''calculate total # of seconds between now and future for time.sleep()''' return (future - datetime.now()).total_seconds() def wait_til(self, next_time): ''' next_time should be a string formatted in one of two ways, where each field is a zero padded decimal number assuming a 24-hour clock: 1. 'month:day:year:hour:minute:second' i.e. '01:15:20:23:59:00' is Jan 15, 2020 at 11:59PM. 2. 'hour:minute:second' omitting the first three fields will automatically set the date to the current date i.e. '23:59:00' is today's date at 11:59PM. alternatively pass in an int or a string representing the amount of seconds to pause. i.e. 20 will pause for 20 seconds, '120' will pause for 2 minutes, etc. ''' valid_time = self._validate_time(next_time) if valid_time: sleeps = self._calculate_wait(valid_time) self.logger.info('pausing until {}, or {} seconds from now'.format(valid_time, sleeps)) sleep(sleeps) else: self.logger.error('invalid input, unable to calculate wait time') self.logger.error('exiting...') sys.exit() # self.logger.warning('sleeping for 30 seconds instead') # self.wait_til(30)
""" [5,4,9] tamaño : 3 indice a cambiar: 0 elemento del indice a cambiar: 5 hacer comparaciones ara intercambiar los valores nuevo indice : 1 nuevo elemento de ese indic: 4 [4,5,9] """ array = [10,7,3,13,2,50,3,10,2,1,7,0] # array con elemntos númericos print(f'Array inicial {array}') # tomar un elemento a la vez y compararlo para intercambiarlo con un nuevo menor for i in range(0,len(array)): minValue = array[i] # elemento seleccionado a itercambiar para compararlo si es que no existe un valor mas pequeño minIndex = i # la posicion donde esta ubicado el elemento a intercambiar #for j,el in enumerate(array) for j in range(minIndex+1,len(array)): if array[j] < minValue: minValue = array[j] minIndex = j temp = array[i] # 10 array[i] = minValue # [2,7,3,13,2] i= 0 minValue = 2 temp = 10 array[minIndex] = temp # minIndex = 4 temp = 10 #[2,7,3,13,10] print(f'Array final {array}')
""" # 2_sums.py # Program retruns the sum and the sum of the cubes of the first n natural numbers # User provides value of n Created by: temikelani on: 1/30/20 """ def sumNatural(n): sum = 0 for i in range(1, n + 1): sum += i return sum def sumCubeNatural(n): sum = 0 for i in range(1, n + 1): sum += (i**3) return sum def main(): print("This program finds the sum and the sum of the cubes of the first n natural numbers: ") # asks user for input n = int(input("Please enter value for n: ")) print("The sum of the first", n, "numbers is:", sumNatural(n)) print("The sum of the cubes of the first", n, "numbers is:", sumCubeNatural(n)) main()
""" # 9_caesar_cipher.py # This program builds a caesar cipher that shifts each letter by a key # For example, if the key value is 2, the word "Sourpuss" would be encoded as "Uqwtrwuu." # A true Caesar cipher does the shifting in a circular fashion where the next character after "z" is "a." # assuming all letters are lowercase, and phrase only consists of letters and phrases Created by: temiKelani on: 1/28/20 """ def main(): print("This program encodes & decodes a phrase using a key(max 1-26)", "\n (only lowercase letters and spaces, no characters) : ") print("E.g. if the key value is 2, the word 'Sourpuss' would be encoded as 'Uqwtrwuu'") # user provides phrase and key: phrase = input("Please enter phrase: ") key = int(input("Please enter key: ")) lcase_name = phrase.lower() # ensures all characters are in lower case # the position of each letter represents it's value (1-26) and (27-52) # a dummy value "dummy is use to hold the position 0. # alphabet is repeated to create circular effect of going from z to a and back. max value of key is 26 letter_value = ["dummy", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] # ENCRYPTION encrypted_phrase = "" # holds encrypted string # from ASCII, a=97 and z=122 >>> to make a = 1 as required by letter_value[index] # we use (ASCII(a) - 96) and do the same for all letters after applying the key for i in lcase_name: encrypted_phrase += letter_value[(ord(i) + key) - 96] print("\n The encrypted phrase is :", encrypted_phrase) # DECRYPTION decrypted_phrase = "" # holds decrypted string for i in encrypted_phrase: decrypted_phrase += letter_value[(ord(i) - key) - 96] print("\n The encrypted phrase is :", decrypted_phrase) main()
""" # 5_assign_grade.py # A professor gives 100-point exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, 60-69:D, <60:F. # Write a program that accepts an exam score as input and prints out the corresponding grade. Created by: temikelani on: 1/28/20 """ def main(): # generate list of grades. each representing # 0-9,10-19,20-29,30-39,40-49,50-59,60-69,70-79,80-89,90-99,100 grades = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A", "A"] # collect score from user score = int(input("Please enter your score here (1-100): ")) # grade is calculated using integer division # if score is 10, then 10//10 is 1 which is assign to grades[1] print("Your grade is:", str(grades[score // 10]) + ".") main()
""" # 2_print_month.py # A program to print the abbreviation of a month, given its number without any decision structures Created by: temikelani on: 1/27/20 """ def print_month(): print("This program will print the abbreviation of a month, given its number \n") # collect month num from user num = int(input("Please enter the month number here: ")) # set the var months to be a string of all the months (3-letter) abbreviations concatenated together # each new moth will hold a positions +3 places from previous one 0 = Jan, 3 = Feb etc. months = "JanFebMarAprMayJunJulAugSepOctNovDec" # this var converts number entered to position of string. 1 = 0, 2 = 3, 3 = 6 etc... position = (num - 1) * 3 # print the abbreviatiosn print("That month is: ", months[position:position+3]) print_month()
#! /usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # # Pre-processing script, stores songs text from the given csv file # Delimited every song with the word NewSongNow # # Name: Shivalika Sharma, Komal Arora # # ============================================================================= import csv import sys def process(): f= open("temp.txt","w+") #opening a text file to write for row in csv.reader(iter(sys.stdin.readline, '')): #reading line by line from sys.stdin f.write(row[3].replace("\n","")) #removing all new lines f.write("NewSongNow") #adding the NewSongNow string at the end of every song to differentiate two songs process() #calling process function
def even_odd(number): if number % 2 == 0: return "Number is even" else: return "Number is odd" print("To exit the program press x") while True: number = input("Enter the number.") if number == 'x': break else: print(even_odd(int(number)))
import re def is_ISBN(id_number): pattern = "\d{1}-\d{3}-\d{5}-\d{1}" if re.search(pattern, id_number): print("ISBN", id_number, "is valid.") else: print("ISBN", id_number, "is not valid.") is_ISBN("3-598-21508-2") is_ISBN("3-598-215048-2")
import string import random def generate_password(): alfabet = string.ascii_letters + string.digits + str("!@#$%^&*") pass_len = random.randint(8,16) return "".join(random.choice(alfabet) for i in range(pass_len)) if __name__ == "__main__": ans = input("Do you want generate a new password?\n") while(ans.lower() in ["y", "yes"]): print(generate_password()) ans = input("Do you want generate a new password?\n")
from math import sin, cos, sqrt, atan2, radians if __name__ == '__main__': R = 6373.0 lat1 = int(input("Please give first point latitude :")) lon1 = int(input("Please give first point longitude :")) lat2 = int(input("Please give second point latitude :")) lon2 = int(input("Please give second point longitude :")) dlon = latitude2 - latitude1 dlat = longitude2 - longitude1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c print("Distance:", distance)
import calendar import re ### Q1 def print_prime(limit): for num in range(2, limit+1): is_prime = True for i in range(2,num): if (num % i) == 0: is_prime = False break if is_prime: print(num, end= " ") print("Q1") print_prime(15) ### Q2 def check_leap_year(year): if calendar.isleap(year): print(year, " is a leap year.") else: print(year, " is not a leap year.") print("\nQ2") check_leap_year(1990) check_leap_year(2000) ### Q3 def is_ISBN(id_number): pattern = "\d{1}-\d{3}-\d{5}-\d{1}" if re.search(pattern, id_number): print("ISBN", id_number, "is valid.") else: print("ISBN", id_number, "is not valid.") print("Q3") is_ISBN("3-598-21508-2") is_ISBN("3-598-215048-2") ### Q4 def check_list(num_list): if num_list[0] == num_list[-1]: return True else: return False print("Q4") print("[1,2]:", check_list([1,2])) print("[3]:", check_list([3])) print("[3,5,3]:", check_list([3,4,3]))
class Hero: # class variabel jumlah = 0 # __init__ metode yang dipanggil saat kita membuat sebuah objek. def __init__(self, inputName, inputHealth, inputPower, inputArmor): # instance variabel self.name = inputName self.health = inputHealth self.power = inputPower self.armor = inputArmor Hero.jumlah += 1 print("membuat hero dengan nama " + inputName) hero1 = Hero('Sniper', 100, 10, 4) print(Hero.jumlah) hero2 = Hero('Mirana', 100, 20, 1) print(Hero.jumlah) hero3 = Hero('Ucup', 10000, 200, 0) print(Hero.jumlah) # NB """ Maka class variable akan nempel/kepunyaan class Hero sedangkan instance variable akan nempel/kepunyaan object hero1, hero2 dll """
"""Rosalind problem: FIB""" import sys def fib(n, k): """Calculate fibonacci number.""" if n == 0: return 0 elif n < 2: return 1 else: return fib(n - 1, k) + (k * fib(n - 2, k)) def main() : """Main program""" for line in sys.stdin: n, k = map(int, line.strip().split()) print(fib(n, k)) if __name__ == '__main__': main()
import os import platform def clear(): if (platform.system() == 'Windows'): os.system('cls') else: os.system('clear') return def howTo(): clear() print("Countdown is a game where we start off with 10 \ \nand subtract 1, 2, or 3. The objective is to force\ \nthe other player to land on 0. Have fun!\n \n ") return userCharacter = 'y' print("Welcome to Countdown!\n") while ( userCharacter == 'y'): gameNumber = 10 while ( gameNumber > 0): howTo() userNumber = 0 print "Current Number: ", gameNumber #Error checking while loop, makes sure input is either 1,2, or 3 while ( userNumber == 0): userNumber = int(input("Enter a 1,2,3: ")) if userNumber <= 0 or userNumber > 3: print("Invalid number, please try again") userNumber = 0 gameNumber -= userNumber if (gameNumber <= 0): print("You Lost") userCharacter = raw_input("To play again, enter 'y': ")
def pig_latin(phrase): piggy = str() for word in phrase.split(): piggy += word[1:] + "-" + word[0] + "ay " return piggy print pig_latin("test mctesty face")
def reverse(word): return word[::-1] def recursive_reverse(word): if len(word) <= 1: return word return recursive_reverse(word[1:]) + word[0] print reverse("test") print recursive_reverse("test")