text
stringlengths
37
1.41M
''' Given a string, return the first recurring character in it, or null if there is no recurring character. For example, given the string "acbbac", return "b". Given the string "abcdef", return null. ''' import unittest def solution(string): str_set = set() for c in string: if c not in str_set: str_set.add(c) else: return c return None class DailyCodingProblemTest(unittest.TestCase): def test_case_1(self): test = 'acbbac' self.assertEqual(solution(test), 'b') def test_case_2(self): test = 'acbdefg' self.assertEqual(solution(test), None) def test_case_3(self): test = '' self.assertEqual(solution(test), None) if __name__ == '__main__': unittest.main()
'''This problem was asked by Google. Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. ''' import math def pow(x,y): if y == 0: return 1 newY = math.floor(y/2) val = pow(x,newY) if y % 2 == 0: return val * val else: return x * val * val print('Test 2^10: ', pow(2,10)) print('Test 5^2: ', pow(5,2)) print('Test 3^3: ', pow(3,3))
''' Given a real number n, find the square root of n. For example, given n = 9, return 3. ''' TOLERANCE_VAL = 10 ** -5 def tol(n1, n2): return abs(n1-n2) < TOLERANCE_VAL def square_root(n): if not n: return n if n < 0: print('Can not square root a negative number') return return sqrt_helper(n, 0, n) def sqrt_helper(num, start, end): mid = start + ((end-start)/2) guess = mid * mid if tol(guess, num): return mid if (guess > num): return sqrt_helper(num, start, mid) else: return sqrt_helper(num, mid, end) print('Square root 9: ', square_root(9)) print('Square root 10: ', square_root(10)) print('Square root 25: ', square_root(25)) print('Square root 38: ', square_root(38)) print('Square root 49: ', square_root(49)) print('Square root 2: ', square_root(2)) print('Square root 100: ', square_root(100)) print('Square root 225: ',square_root(225)) print('Square root 300: ', square_root(300)) print('Square root 10000: ', square_root(10000))
''' Given an array of elements, return the length of the longest subarray where all its elements are distinct. For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1]. ''' import unittest def distinct_subarray(nums): if not nums or len(nums) == 0: return 0 def distinct_helper(array, seen=set()): if not array or len(array) == 0: return len(seen) if array[0] in seen: return len(seen) set_copy = seen.copy() set_copy.add(array[0]) with_num = distinct_helper(array[1:], set_copy) not_with_num = distinct_helper(array[1:], set()) return max(with_num, not_with_num) return distinct_helper(nums, set()) class DailyCodingProblemTest(unittest.TestCase): def test_case_1(self): test = [5, 1, 3, 5, 2, 3, 4, 1] self.assertEqual(distinct_subarray(test), 5) def test_case_2(self): test = [] self.assertEqual(distinct_subarray(test), 0) def test_case_3(self): test = [5, 1, 3, 5] self.assertEqual(distinct_subarray(test), 3) if __name__ == '__main__': unittest.main()
import unittest import math ''' We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions it has. Do this faster than O(N^2) time. You may assume each element in the array is distinct. For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. ''' def count_inversions(arr): temp = [0] * len(arr) return mergeSort(arr, temp, 0, len(arr)-1); def mergeSort(arr, temp, l, r): inv_count = 0 if r > l: mid = math.floor((r + l) / 2); inv_count = mergeSort(arr, temp, l, mid) inv_count += mergeSort(arr, temp, mid + 1, r) inv_count += merge(arr, temp, l, mid + 1, r) return inv_count def merge(arr, temp, l, mid, r): i = l j = mid k = l inv_count = 0 while(i <= mid-1 and j <= r): if (arr[i] > arr[j]): temp[k] = arr[j] inv_count += mid - i k += 1 j += 1 else: temp[k] = arr[i] k += 1 i += 1 while (i <= mid - 1): temp[k] = arr[i] k += 1 i += 1 while (j <= r): temp[k] = arr[j] k += 1 j += 1 i = l while(i <= r): arr[i] = temp[i] i += 1 return inv_count; def countInversions(arr): inv_count = 0 if len(arr) >1: mid = len(arr)//2 #Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves countInversions(L) # Sorting the first half countInversions(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+=1 else: arr[k] = R[j] j+=1 inv_count += mid - i k+=1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+=1 k+=1 while j < len(R): arr[k] = R[j] j+=1 k+=1 return inv_count class Count_Inversions_Test(unittest.TestCase): def test_case_1(self): test_case = [1,2,3,4,5] result = 0 self.assertEqual(countInversions(test_case), result) def test_case_2(self): test_case = [2, 4, 1, 3, 5] result = 3 self.assertEqual(countInversions(test_case), result) def test_case_3(self): test_case = [5,4,3,2,1] result = 10 self.assertEqual(countInversions(test_case), result) if __name__ == '__main__': unittest.main()
''' This problem was asked by Amazon. Implement a bit array. A bit array is a space efficient array that holds a value of 1 or 0 at each index. init(size): initialize the array with size set(i, val): updates index at i with val where val is either 1 or 0. get(i): gets the value at index i. ''' class BitArray(object): def __init__(self, size): self.bit_array = [0]*size self.size = size def set(self, i, val): if i >= self.size: raise LookupError("Invalid Index") self.bit_array[self.size - i - 1] = val def get(self, i): if i >= self.size: raise LookupError("Invalid Index") return int(self.bit_array[self.size - i - 1]) def str_rep(self): return ''.join([str(b) for b in self.bit_array]) bit_arr = BitArray(8) assert bit_arr.get(0) == 0 bit_arr.set(0, 1) assert bit_arr.get(0) == 1 assert bit_arr.str_rep() == '00000001' bit_arr.set(7, 1) bit_arr.set(5, 1) bit_arr.set(0, 0) assert bit_arr.str_rep() == '10100000' try: bit_arr.set(10, 1) except LookupError as le: print(le)
''' What will this code print out? def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(): print(i) flist.append(print_i) return flist functions = make_functions() for f in functions: f() How can we make it print out what we apparently want? ''' # This function will print out the number '3' 3 times def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(x): print(x) flist.append(print_i(i)) return flist functions = make_functions() for f in functions: f # or we can do it this way: def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(x): print(x) flist.append((print_i, i)) return flist functions = make_functions() for f, arg in functions: f(arg) #
''' You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle: 1 2 3 1 5 1 We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries. Write a program that returns the weight of the maximum weight path. ''' import unittest def max_triangle_path(triangle): def path_helper(triangle, level, index, cur_path, cur_sum): if level == len(triangle) - 1: return cur_path, cur_sum left_path, left_sum = path_helper(triangle, level + 1, index, \ cur_path + [triangle[level + 1][index]], cur_sum + triangle[level + 1][index]) right_path, right_sum = path_helper(triangle, level + 1, index + 1, \ cur_path + [triangle[level + 1][index + 1]], cur_sum + triangle[level + 1][index + 1]) if left_sum > right_sum: return left_path, left_sum else: return right_path, right_sum max_path, max_sum = path_helper(triangle, 0, 0, [triangle[0][0]], triangle[0][0]) return max_path class DailyCodingProblemTest(unittest.TestCase): def test_case_1(self): test = [[1], [2, 3], [1, 5, 1]] result = [1, 3, 5] self.assertEqual(max_triangle_path(test), result) def test_case_2(self): test = [[1], [3, 5], [7, 4, 3]] result= [1, 3, 7] self.assertEqual(max_triangle_path(test), result) if __name__ == '__main__': unittest.main()
''' Given a string which we can delete at most k, return whether you can make a palindrome. For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'. ''' import unittest def lcs(a, b): DP = [[0]*(len(a)+1) for _ in range(len(b)+1)] for i in range(len(DP)): for j in range(len(DP[0])): if not i or not j: DP[i][j] = 0 elif a[i-1] == b[j-1]: DP[i][j] = DP[i-1][j-1] + 1 else: DP[i][j] = max(DP[i][j-1], DP[i-1][j]) return DP[len(a)][len(a)] def k_palindrome(str, k): rev = str[::-1] return (len(str) - lcs(str, rev)) <= k class Daily_Coding_Problem_Test(unittest.TestCase): def test_case_1(self): test = 'waterrfetawx' k = 2 expected = True self.assertEqual(k_palindrome(test, k), expected) def test_case_2(self): test = '' k = 2 expected = True self.assertEqual(k_palindrome(test, k), expected) def test_case_3(self): test = 'abca' k = 1 expected = True self.assertEqual(k_palindrome(test, k), expected) def test_case_4(self): test = 'abc' k = 1 expected = False self.assertEqual(k_palindrome(test, k), expected) if __name__ == '__main__': unittest.main()
''' Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. A solution will always exist. See Goldbach’s conjecture. Example: Input: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the lexicographically smaller solution. If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then [a, b] < [c, d] If a < c OR a==c AND b < d. ''' def prime_sum(n): prime_arr = sieve_primes(n) for i in range(n): if (prime_arr[i] and prime_arr[n-i]): return (i, n-i) def sieve_primes(n): prime_arr = [True]*n prime_arr[0] = False prime_arr[1] = False p = 2 while(p*p <= n): i = p*p while(i < n): prime_arr[i] = False i += p p += 1 return prime_arr print("prime sum of 82: ", prime_sum(82)) print("prime sum of 14: ", prime_sum(14)) print("prime sum of 4: ", prime_sum(4)) print("prime sum of 764: ", prime_sum(764))
import os from random import shuffle def menu(): print("---------------------------") print("| PYRE IT UP! QUIZ GAME |") print("---------------------------\n") print("[1] START Quiz") print("[2] View High Scores") print("[3] Reset High Scores") print("[0] Exit") choice = int(input("\nChoice: ")) return choice def category_menu(): print("---------------------------") print("| SELECT CATEGORY |") print("---------------------------\n") print("[1] Ultimate Frisbee") print("[2] League of Legends") print("[3] KPOP") print("[0] Exit\n") category_choice = int(input("Choice: ")) return category_choice def difficulty_menu(): print("---------------------------") print("| SELECT DIFFICULTY |") print("---------------------------\n") print("[1] Kindle\t(EASY)") print("[2] Flamin'\t(MEDIUM)") print("[3] Scorched\t(HARD)") print("[0] Exit\n") difficulty_choice = int(input("Choice: ")) return difficulty_choice def instructions(scoring): inst="Each round consists of 10 random questions from each category.\nChoose the letter of the correct answer."+"\nEach correct answer is worth "+str(scoring)+" point/s."+"\nGood luck!\n" return inst def quizgame(question_file,points): instpoint=points fileReader=open(question_file,"r") question_roster=[] for line in fileReader: list1=line[:-1].split(",") question_roster.append(list1) fileReader.close() score=0 name=input("Enter name: ") name=name.capitalize() print("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("| QUIZ STARTS |") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") inst=instructions(instpoint) print(inst) shuffle(question_roster) displayed_questions=0 while displayed_questions != 10: correctAns=question_roster[displayed_questions][0] ques=question_roster[displayed_questions][1] choiA=question_roster[displayed_questions][2] choiB=question_roster[displayed_questions][3] choiC=question_roster[displayed_questions][4] print(ques) print() print("[A]",choiA) print("[B]",choiB) print("[C]",choiC) userAns=input("\nAnswer: ") print() userAns=userAns.upper() if userAns==correctAns: score=score+points print("\tCorrect!\n") else: print("\tThe correct answer is",correctAns,"\n") #increment displayed_questions=displayed_questions+1 return name,score def selection_sort(x): for i in range(len(x)): minimum= i for j in range (i+1,len(x)): if x[minimum][1] < x[j][1]: minimum=j temp= x[minimum] x[minimum]=x[i] x[i]=temp return x def name_check(mainList,username,userscore): inTheList=False for i in mainList: if username==i[0]: inTheList=True break if inTheList: i[1]=i[1]+userscore # print(i) else: newInput=[name,score] mainList.append(newInput) return mainList #MAIN PROGRAM choice = None highscore_list=[] #Auto Load High Score fileDisplay=open("highscore_roster.txt","r") for line in fileDisplay: list1=line[:-1].split(",") list1[1]=int(list1[1]) if highscore_list==[]: highscore_list.append(list1) elif list1 in highscore_list: continue else: highscore_list.append(list1) fileDisplay.close() while choice!=0: choice = menu() un = os.system('cls') if choice==1: difficulty_choice=None while difficulty_choice!=0: difficulty_choice=difficulty_menu() if difficulty_choice ==1: print("\nYou have chosen EASY\nPlease choose a category\n") category_choice=None while category_choice != 0: category_choice=category_menu() if category_choice==1: un = os.system('cls') print("\nEASY:Ultimate Frisbee\n") name,score=quizgame("easy_frisbee.txt",1) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==2: un = os.system('cls') print("\nEASY:League of Legends\n") name,score=quizgame("easy_league.txt",1) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==3: un = os.system('cls') print("\nEASY:KPOP\n") name,score=quizgame("easy_kpop.txt",1) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==0: print("\nRETURNING TO MAIN MENU\n") difficulty_choice=0 else: print("\nInvalid Choice!!\n") elif difficulty_choice ==2: print("\nYou have chosen MEDIUM\nPlease choose a category\n") category_choice=None while category_choice != 0: category_choice=category_menu() if category_choice==1: un = os.system('cls') print("\nMEDIUM:Ultimate Frisbee\n") name,score=quizgame("medium_frisbee.txt",3) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==2: un = os.system('cls') print("\nMEDIUM:League of Legends\n") name,score=quizgame("medium_league.txt",3) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==3: un = os.system('cls') print("\nMEDIUM:KPOP\n") name,score=quizgame("medium_kpop.txt",3) print() print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==0: print("\nRETURNING TO MAIN MENU\n") difficulty_choice=0 else: print("\nInvalid Choice!!\n") elif difficulty_choice ==3: print("\nYou have chosen HARD\nPlease choose a category\n") category_choice=None while category_choice != 0: category_choice=category_menu() if category_choice==1: un = os.system('cls') print("\nHARD:Ultimate Frisbee\n") name,score=quizgame("hard_ultimate.txt",5) print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==2: un = os.system('cls') print("\nHARD:League of Legends\n") name,score=quizgame("hard_league.txt",5) print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==3: un = os.system('cls') print("\nHARD:KPOP\n") name,score=quizgame("hard_kpop.txt",5) print(name,"scored:",score) print() checked_list=name_check(highscore_list,name,score) highscore_list=selection_sort(checked_list) category_choice=0 difficulty_choice=0 elif category_choice==0: print("\nRETURNING TO MAIN MENU\n") difficulty_choice=0 else: print("\nInvalid Choice!!\n") elif difficulty_choice==0: print("\nRETURNING TO MAIN MENU\n") else: print("\nInvalid Choice!!\n") #View High Scores (File open and read mode) elif choice==2: print("---------------------------") print("| TOP 10 HIGHSCORES |") print("---------------------------\n") highscore_list=selection_sort(highscore_list) if highscore_list==[[]]: print("\n - - - - - EMPTY - - - - - \n") elif highscore_list==[]: print("\n - - - - - EMPTY - - - - - \n") else: highscore_list=selection_sort(highscore_list) display=0 if len(highscore_list)<10: while display!=len(highscore_list): print(highscore_list[display][0],highscore_list[display][1]) display=display+1 else: while display !=10: print(highscore_list[display][0],highscore_list[display][1]) display=display+1 print() elif choice==3: print("\nReset High Scores") highscore_list=[] fileSaver=open("highscore_roster.txt","w") fileSaver.write("") fileSaver.close() print("\nScores have been reset!!") print("\n- - HIGH SCORES NOW EMPTY - -\n") elif choice==0: fileSaver=open("highscore_roster.txt","w") for e in highscore_list: fileSaver.write(e[0]+","+str(e[1])+"\n") fileSaver.close() print("__________________________") print("| |") print("| THANK YOU FOR PLAYING! |") print("|________________________|\n") else: print("\n\nInvalid choice or Function not available!\n")
word = input("Please type ten lettered word.") print(word[0], word[9]) for i in range(11): print(word[0:i:1]) from random import shuffle word = list(word) shuffle(word) print(''.join(word))
#1 # def display_message(): # print("I'm learning python") # display_message() #2 # def favourite_book(title): # print(f"My favourite books is {title}") # favourite_book("Harry Potter") # #3 help # def make_shirt(text="I love python",size="large"): # print(f"Your shirt will say {text} and be size {size} ") # make_shirt(input("text"), input("size")) # #4 # m_names = ["Harry", "Ron", "Hermione", "Dumbledore"] # def show_magicians(names): # print(names) # show_magicians(m_names) # def make_great(name): # return (f"The Great {name}") # m_names = [item for item in map(make_great, m_names)] # show_magicians(m_names) #5 # def discribe_city(city="none",country="nonewhereville"): # print(f"This {city} is in {country}") # discribe_city("Toronto", "Canada") # discribe_city("Miami", "Florida") # discribe_city() #6 # from datetime import date # def get_age(year, month, day): # today = date.today() # return today.year - year - ((today.month, today.day) < (month, day)) # def can_retire(gender, date_of_birth): # bday = date_of_birth.split('/') # year = int(bday[0]) # month = int(bday[1]) # day = int(bday[2]) # age = get_age(year, month, day) # gender = gender.lower() # if gender == "female": # if age > 61: # print("You may retire") # else: # print("You man not retire") # elif gender == "male": # if age > 66: # print("You may retire") # else: # print("You man not retire") # gender = input("Are you male of female?") # bdate = input('enter your bday ex: year/month/day') # can_retire(gender, bdate) #7 from faker import Faker users = [] def add_users(**kwargs): user2 = users.append(kwargs) return user2 for i in range(10): fake = Faker() kwargs = {'name': fake.name(), 'address': fake.address(), 'langage':fake.language_name()} all_users = add_users(kwargs) print(all_users)
import re test_cases = ['''Date 1 : 12/11/18 Date 2: 01/01/19'''] # Create a dictionary to convert from month names to numbers (e.g. Jan = 01) month_dict = dict(jan='01', feb='02', mar='03', apr='04', may='05', jun='06', jul='07', aug='08', sep='09', oct='10', nov='11', dec='12') def word_to_num(string): """ This function converts a string to lowercase and only accepts the first three letter. This is to prepare a string for month_dict Example: word_to_num('January') -> jan """ s = string.lower()[:3] return(month_dict[s]) def date_converter(line): """ This function extracts dates in every format from text and converts them to YYYYMMDD. Example: date_converter("It was the May 1st, 2009") -> 20090501 """ results = [] day = '01' month = '01' year = '1900' # If format is MM/DD/YYYY or M/D/YY or some combination regex = re.search('([0]?\d|[1][0-2])[/-]([0-3]?\d)[/-]([1-2]\d{3}|\d{2})', line) # If format is DD Month YYYY or D Mon YY or some combination, also matches if no day given month_regex = re.search( '([0-3]?\d)\s*(Jan(?:uary)?(?:aury)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(' '?:ust)?|Sept?(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?(?:emeber)?).?,?\s([1-2]\d{3})', line) # If format is Month/DD/YYYY or Mon/D/YY or or Month DDth, YYYY or some combination rev_month_regex = re.search( '(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(?:ember)?|Oct(' '?:ober)?|Nov(?:ember)?|Dec(?:ember)?).?[-\s]([0-3]?\d)(?:st|nd|rd|th)?[-,\s]\s*([1-2]\d{3})', line) rev_th_regex = re.search( '([0-3]?\d)(?:st|nd|rd|th)? (Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(?:ember)?|Oct(' '?:ober)?|Nov(?:ember)?|Dec(?:ember)?).?[-,\s]\s*([1-2]\d{3})', line) # If format is any combination of just Month or Mon and YY or YYYY no_day_regex = re.search( '(Jan(?:uary)?(?:aury)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(' '?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?(?:emeber)?).?,?[\s]([1-2]\d{3}|\d{2})', line) # If format is MM/YYYY or M YYYY or some combination no_day_digits_regex = re.search('([0]?\d|[1][0-2])[/\s]([1-2]\d{3})', line) # If format only contains a year. If year is written alone it must be in form YYYY year_only_regex = re.search('([1-2]\d{3})', line) if regex: return(regex) elif month_regex: return(month_regex) elif rev_month_regex: return(rev_month_regex) elif rev_th_regex: return(rev_th_regex) elif no_day_regex: return(no_day_regex) elif no_day_digits_regex: return(no_day_digits_regex) elif year_only_regex: return(year_only_regex) # Make sure all variables have correct number, add zeros if necessary test_run = [date_converter(w) for w in test_cases] print(test_run)
# Make a function that an take any non-negative integer as an argument and return it with its digits in descendin order # def descending_order(num): # numbr = str(num) # first_list = list(numbr) # first_list.sort(reverse = True) # newstr = ''.join([str(i) for i in first_list]) # newstr = int(newstr) # return newstr # Return the number (count) of vowels in the given string. # We will consider a, e, i, o, u as vowels for this Kata (but not y). # The input string will only consist of lower case letters and/or spaces. # def get_count(input_str): # num_vowels = 0 # vowels = ['a', 'e', 'i', 'o', 'u'] # char_list = list(input_str) # for i in char_list: # for j in vowels: # if i == j: # num_vowels += 1 # else: # num_vowels += 0 # return num_vowels # Square every digit of a number and concatenate them. For example, # if we run 9119 through the function, 811181 will come out, because # 9 squared is 81 and 1 squared is 1. # def square_digits(num): # num = str(num) #turn integer into string # new_list = list(num) #put every integer into a list # final_list = [] #initialize empty list # for i in new_list: # i = int(i) #turn item in list into an integer # squared = i*i #square int # final_list.append(squared) #add new num to empty list # final_int = int(''.join([str(j) for j in final_list])) #make string out of final list and convert to int type # return final_int # Friday 13th or Black Friday is considered as unlucky day. # Calculate how many unlucky days are in the given year. # Find the number of Friday 13th in the given year. # input: integer # output: integer import datetime def unlucky_days(year): #initialize count of friday 13ths fridays = 0 #set start of the year first = datetime.date(year, 1, 1) #set end date last = datetime.date(year, 12, 31) #set time to be changed by delta = datetime.timedelta(days = 1) while first <= last: if first.weekday() == 4 and first.day ==13: fridays += 1 first += delta return fridays
""" Write a Python program to find if a given string starts with a given character using Lambda. """ word = 'python' string = lambda char : True if char == word[0] else False print(string('p')) print(string('P'))
""" Write a Python program to change a given string to a new string where the first and last chars have been exchanged. """ string = 'deal_madrir' def func(word): return word[-1] + word[1:-1] + word[0] print(func(string))
""" Write a Python function that takes a number as a parameter and check the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. """ def func(nums): if nums < 100: for i in range(2 , nums): if nums % i == 0: return f'{nums} is not a prime number !!!' else: for i in range(2 , (nums // 2)): if nums % i == 0: return f'{nums} is not a prime number !!!' return f'{nums} is a prime number !!!' print(func(0)) print(func(2)) print(func(7)) print(func(10)) print(func(13))
""" Write a Python program to count the occurrences of each word in a given sentence. """ sentences = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod,tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor reprehenderit voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt culpa qui officia deserunt mollit anim id est laborum' def func(words): listOfWord = words.split(' ') countTheWord = {} for word in listOfWord: count = 0 for test_word in listOfWord: if test_word == word: count = count + 1 countTheWord[word] = count return countTheWord print(func(sentences))
""" Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] """ givenTuples = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] def func(list): lengthlist= len(list) for index in range(lengthlist): for num in range(lengthlist): if list[index][1] < list[num][1]: tmp = list[num] list[num] = list[index] list[index] = tmp return list print(func(givenTuples))
""" Write a Python program to filter a list of integers using Lambda. """ lists = [2,3,4,5,7,9,10,16,25,36,50,53,74,100,108] items = list(filter(lambda x:x % 3 != 0 , lists)) print(items)
""" Write a Python program to sum all the items in a list. """ items = [34,67,89,354,15,7,78] def func(lists): sum = 0 for list in lists: sum = sum + list return sum print(func(items))
""" Write a Python program to slice a tuple. """ lists = ['Python','is', 'a','programming','language','!!!'] sliced = lists[:5] print(sliced)
#!/usr/bin/python2.7 class Movie: def __init__(self, decade=None, genre=None, title=None, rating=-1): self.decade = decade self.genre = genre self.title = title self.rating = rating def update(self, fields): self.decade = fields[0] self.genre = fields[1] new_rating = float(fields[3]) if self.rating < new_rating: # if the new film has higher rating self.rating = new_rating # update the max rating self.title = fields[2] # and the corresponding title # NOTE: there is no need to check for rating == new_rating # since this reducer receives the movie names in lexicographical order # and so this will always yield the first movie alphabetically def is_same(self, fields): return self.decade == fields[0] and self.genre == fields[1] def _print(self): # print result if movie info is present if self.title: print("%s|%s|%s" % (self.decade, self.genre, self.title)) def parse_line(self, line): fields = line.strip().strip("|").split("|") if self.is_same(fields): # same decade and genre self.update(fields) else: # new decade or new genre self._print() self.__init__() self.update(fields)
import math import numpy # Create a class to hold a city location. Call the class "City". It should have # fields for name, latitude, and longitude. class City: def __init__(self, name, state, county, latitude, longitude, population, density, timezone, zips): self.name = name self.state = state self.county = county self.latitude = latitude self.longitude = longitude self.population = population self.density = density self.timezone = timezone self.zips = zips pass # We have a collection of US cities with population over 750,000 stored in the # file "cities.csv". (CSV stands for "comma-separated values".) # # Use Python's built-in "csv" module to read this file so that each record is # imported into a City instance. (You're free to add more attributes to the City # class if you wish, but this is not necessary.) Google "python 3 csv" for # references and use your Google-fu for other examples. # # Store the instances in the "cities" list, below. # # Note that the first line of the CSV is header that describes the fields--this # should not be loaded into a City object. cities = [] import csv with open('cities.csv') as csvfile: csv_read = csv.reader(csvfile, delimiter=',') csv_read.next() # exclude first row for row in csv_read: cities.append(City(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8])) # Print the list of cities (name, lat, lon), 1 record per line. # for city in cities: # print(city.name, city.latitude, city.longitude) # *** STRETCH GOAL! *** # # Allow the user to input two points, each specified by latitude and longitude. # These points form the corners of a lat/lon square. Output the cities that fall # within this square. # # Be aware that the user could specify either a lower-left/upper-right pair of # coordinates, or an upper-left/lower-right pair of coordinates. Hint: normalize # the input data so that it's always one or the other (what is latMin, latMax?) # then search for cities. print('We will now attempt to find all the cities within a rectangular area defined by two sets of coordinates:') print() print('Please input a pair of coordinates: ') lat1 = int(input('- latitude: ')) lon1 = int(input('- longitude: ')) print('Please input a pair of coordinates: ') lat2 = int(input('- latitude: ')) lon2 = int(input('- longitude: ')) # if 3 in numpy.arange(math.floor(min(lat1, lat2)), math.ceil(max(lat1, lat2))): # print('pass') for city in cities: if int(float(city.latitude)) in numpy.arange(math.floor(min(lat1, lat2)), math.ceil(max(lat1, lat2))): if int(float(city.longitude)) in numpy.arange(math.floor(min(lon1, lon2)), math.ceil(max(lon1, lon2))): print(city.name + ': (' + city.latitude + ',' + city.longitude +')') # # Example I/O: # # Enter lat1,lon1: 45,-100 # Enter lat2,lon2: 32,-120 # Albuquerque: (35.1055,-106.6476) # Riverside: (33.9382,-117.3949) # San Diego: (32.8312,-117.1225) # Los Angeles: (34.114,-118.4068) # Las Vegas: (36.2288,-115.2603) # Denver: (39.7621,-104.8759) # Phoenix: (33.5722,-112.0891) # Tucson: (32.1558,-110.8777) # Salt Lake City: (40.7774,-111.9301) #
result = 0 for i in range (1, 51): if(i % 5 == 0): continue elif(i % 3 == 0): result += i print("결과 = ", result)
num = int(input("1부터 10사이의 숫자를 하나 입력하세요 :")) if num>0 and num<=10: if num%2==0: print(num, ": 짝수") else: print(num, ": 홀수") else: print("1부터 10사이의 값이 아닙니다")
#실습 2 color_name=input("색상값을 입력하시오") if color_name == 'red': print("#ff0000") else: print("#000000")
while True: word = input("문자열을 입력하시오 :") wordlength = len(word) if wordlength == 0: break elif wordlength >= 5 and wordlength < 9: continue elif wordlength < 5: print("유효한 입력 결과:", "*", word, "*") elif wordlength > 8: print("유효한 입력 결과:", "$", word, "$")
def get_book_title(): return "파이썬 정복" def get_book_publisher(): return "한빛미디어" name = get_book_title() for i in range(0, 2): print(name) print(get_book_publisher())
''' Jiale Shi Statistical Computing for Scientists and Engineers Homework 1 5b Fall 2018 University of Notre Dame ''' import numpy as np import matplotlib.pyplot as plt import scipy.stats import errno import os.path def readCSV(fileDir='.'): ''' Reads in .csv data file @args: fileDir = path to file ''' file_path = os.path.join("/Users/shijiale1995/Downloads", 'camera.csv') if(os.path.exists(file_path)): return np.genfromtxt(file_path, delimiter=',',skip_header=2) else: raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path) def mleGuassian(x): ''' Does MLE for a single deminsional guassian @args: x = training data @returns: mu, sigma = mean and std of trained guassian ''' N = x.shape[0] mu = 0 sig2 = 0 print (N) for i in range(0,N): mu = mu+x[i] mu= mu/N for i in range(0,N): sig2 = sig2+pow(x[i]-mu,2) sig2 = sig2/N return mu, np.sqrt(sig2) if __name__== "__main__": # Start by reading in the camera data data = readCSV() # Create histogram max_res = np.histogram((data[:,2]-2491.7618497109806)/752.5256308818603, bins=20) # Get x/y training points (for x we take the center of the bins) x0 = 0.5*(max_res[1][:-1]+max_res[1][1:]) y0 = max_res[0] # Set up observations x_data = [] for i, val in enumerate(x0): x_data.append(np.repeat(val, y0[i])) x_data = np.concatenate(x_data,axis=0) # MLE mu, sigma = mleGuassian(x_data) print (x_data) print (mu,sigma) print('Plotting Figure') f1 = plt.figure(1) # Plot Normalized Histogram bins = max_res[1][:] y_norm = np.sum((bins[1:]-bins[:-1])*y0) # Finite Integral plt.bar(x0, y0/y_norm, align='center',width=200/752.5256308818603, edgecolor="k",label="Histogram") # Plot MLE Guassian x = np.linspace(mu - 4*sigma, mu + 4*sigma,200) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma),'r',label="MLE Guassian") plt.title('Camera Max Resolution') plt.xlabel('Camera Max Resolution (Pixels)') plt.legend() # f1.savefig('Hm1-P5a-Res.png', bbox_inches='tight') plt.show()
a = int(input('Informe o 1 valor:')) b = int(input('Informe o 2 valor :')) c = int(input('Informe o 3 valor')) if a > b and a > c: if b > c: print(f'Ordem crescente {a} {b} {c}') if c > b: print(f'Ordem crescente {a} {c} {b}') elif b > a and b > c: if a > c: print(f'Ordem crescente {b} {a} {c}') if c > a: print(f'Ordem crescente {b} {c} {a}') elif c > a and c > b: if a > b: print(f'Ordem crescente {c} {a} {b}') if b > a: print(f'Ordem crescente {c} {b} {a}')
import re stack = [] top = -1 max_size = 5 def Empty(S): if top == -1: return True else: return False def Full(S): if top == max_size - 1: return True else: return False def Push(S, ITEM): global top S.append(ITEM) top += 1 def Pop(S): global top top -= 1 return S.pop() def getNumber(expr): expr += ' ' number = 0 I = 0 while(expr[I] != ' ' and expr[I] != None): number = 10 * number + ord(expr[I]) - ord('0'); I += 1 return number def applyOperator(operator): global stack result = 0 if Empty(stack) == False: op2 = Pop(stack) if Empty(stack) == False: error = False op1 = Pop(stack) if operator == '+': result = op1 + op2 elif operator == '-': result = op1 - op2 elif operator == '*': result = op1 * op2 elif operator == '/': if op2 == 0: error = True print "Divide by Zero!" else: result = op1 / op2 if error == False: Push(stack, result) else: print "Stack underflow: only one argument" else: print "Stack underflow: no arguments" expr = '44 45 +' operand = '' sign = 1; length = len(expr) for i in range(length): curr = expr[i] if i+1 == length: next = ' ' else: next = expr[i+1] if re.search('^[\d]$', curr) != None: operand += str(curr) if next == ' ': Push(stack, sign * getNumber(operand)) sign = 1 operand = '' elif curr == '-' and re.search('^[\d]$', next) != None: sign = -1 elif re.search('^[+-/*]$', curr) != None: applyOperator(curr) print stack
import pandas as pd import sqlite3 df = pd.read_csv('buddymove_holidayiq.csv') conn = sqlite3.connect("buddymove_holidayiq.sqlite3") cursor = conn.cursor() df.to_sql("buddymove_holidayiq.sqlite3", conn) query = "SELECT * FROM 'buddymove_holidayiq.sqlite3'" cursor.execute(query).fetchall() print('Table size:_', df.shape) query2 = ''' SELECT COUNT (*) FROM 'buddymove_holidayiq.sqlite3' WHERE "Nature" >= 100 AND "Shopping" >= 100 ''' print(f"How many reviewed at least 100 in Nature and Shopping? : {cursor.execute(query2).fetchall()[0][0]} users")
import sys def inputNumber(inputMessage, verify = None, verifyFail = None): while True: answer = input(inputMessage) # input() in python 2 evaluates the input! if not answer.isnumeric(): print('Answer must be numeric') else: if not verify: # if we don't have a verify function return answer if verify(int(answer)): # we have a function return answer # and it passed else: # else it failed. print(verifyFail or "Invalid number provided") # That's called a short circuit; a valid string evaluates to True so the second # part of the statement is ignored. if sys.version_info < (3,): sys.exit('Python 3 only please') # result = inputNumber('Please enter any number: ') # print('You entered ' + result) result = inputNumber('Please enter any number less than 100: ', lambda x: x < 100) print('You entered ' + result) result = inputNumber('Please enter any number less than 10: ', lambda x: x < 10, 'Number must be less than 10') print('You entered ' + result) result = inputNumber('Please enter 42: ', lambda x: x == 42, 'Number must be 42') print('You entered ' + result)
from collections import defaultdict def create_graph(n , arr , graph): i = 0 while i < 2 * e : graph[arr[i]].append(arr[i + 1]) i += 2 def cycle_util(graph, vertex, visited, rec_stack): visited[vertex] = True rec_stack[vertex] = True for neighbor in graph[vertex]: if visited[neighbor] == False: if cycle_util(graph, neighbor, visited, rec_stack) == True: return True elif rec_stack[neighbor] == True: return True print("vertex", vertex) print(rec_stack) rec_stack[vertex] = False return False def isCyclic(n, graph): # Code here rec_stack = [False] * n visited = [False] * n for i in range(n): print("i :", i) if visited[i] == False: if cycle_util(graph, i, visited, rec_stack) == True: return True return False if __name__ == "__main__": t = int(input()) for i in range(t): n,e = list(map(int, input().strip().split())) arr = list(map(int, input().strip().split())) graph = defaultdict(list) create_graph(e, arr, graph) result = isCyclic(n, graph) print("result ", result)
"""Project 1: Choose your Own Adventure.""" __author__ = "730401304" player: str = "" points: int = 0 def main() -> None: """The programs entrypoint.""" greet() global points points = points + 1 print(f"Well welcome to the crew {player}!!!") x: int = 0 while x != 3: print("Where would you like to go next sailor? You have 3 options. Option 1, you can be captain on the Black Pearl and choose how to deal with trouble over the horizon while gaining Adventure Points. Option 2, you can wager your Adventure Points for double or nothing on a coin toss against Davy Jones. And option 3, you can end the experience right now and walk away with your adventure points. ") x: int = int(input("Pick an option by typing either 1, 2 or 3. ")) if x == 3: print(f"Goodbye {player}, you have earned {points} Adventure Points! Safe Travels.") return else: if x == 1: option_1() else: if x == 2: option_2(x) def greet() -> None: """General greeting for player.""" print("Ahoy matey, you have stumbled across the Pirates of the Carribean adventure story!!! In this experience you will sail the 7 seas and experience a variety of pit stops, where your actions will either make you a legendary pirate or leave you in Davy Jones' Locker. As the story progresses, you will gain adventure points depending on your choices. The more action points you have, the closer you become to being a legendary pirate like Jack Sparrow! All hands to deck!!!") global player player = input("Now before we begin, what might ye name be sailor? ") def option_1() -> None: """Option used to gain points through story.""" print(f"Youve been promoted to captain aboard the Black Pearl, {player}!") def option_2(x: int) -> int: print(f"so you chose to gamble your points for double or nothing against Davy Jones eh {player}? Best of luck to ye. ") from random import randint global points print("You will pick a side of the golden Aztec coin.") side: int = int(input("Enter 1 for Heads or 2 for Tails. ")) coin: int = randint(1, 2) if side == coin: points *= 2 print(f"Congrats, you doubled your points captain. {player}, you now have {points} Adventure Points! Davy Jones wants to double down again, this time he is sure you will be walking away with nothing.") z: int = int(input("Do you want to bet again? Enter 1 for Yes or 2 for No. ")) if z == 1: side_2: int = int(input("Feeling lucky are ye? Well enter 1 for Heads or 2 for Tails. ")) if side_2 == coin: points *= 2 print("Well you are one of the luckiest pirates on the seven seas, good job captain!") else: None else: None else: points = 0 print(points) return points if __name__ == '__main__': main()
# Name: Mayuri Patel #this function convert the list to dictionary def converse(months): lstTo_dict = {} for i in months: month = i[0] num_days = i[1] #building the dictionary lstTo_dict[month] = num_days return lstTo_dict #exit the function and return the dictionary #this function reverse the dictionary key:values def reverse(lstTo_dict): # reversed dictionary is stored daysMonths = {} for month in lstTo_dict.keys(): days = lstTo_dict[month] if days in daysMonths.keys(): daysMonths[days].append(month) else: daysMonths[days] = [month] return daysMonths #exit the function and return the dictionary #this main function holds flow of code def main(): # a list of months and dates is given months = [["January", 31], ["February", 28],["March", 31],["April", 30],["May", 31],["June", 30],["July", 31],["August", 31],["September", 30],["October", 31],["November", 30],["December", 31]] lstTo_dict = converse(months) #calling the function print(lstTo_dict) daysMonths = reverse(lstTo_dict) #calling the function print(daysMonths) if __name__ == "__main__": main()
# Problem # Alice and Bob take turns playing a game, with Alice starting first. # # Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: # # Choosing any x with 0 < x < N and N % x == 0. # Replacing the number N on the chalkboard with N - x. # Also, if a player cannot make a move, they lose the game. # # Return True if and only if Alice wins the game, assuming both players play optimally. # # # # Example 1: # # Input: 2 # Output: true # Explanation: Alice chooses 1, and Bob has no more moves. # Example 2: # # Input: 3 # Output: false # Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. # Solution from leetcode.test import Test class Solution: # If the number is even, Alice selects 1 and makes the number odd. After that, # whatever Bob chooses, Alice will always finish turn 1. The situation is symmetric with an odd number. # You can't divide an odd number by an even number. # When subtracting from an odd number - odd, we get an even number def divisorGame(self, N: int) -> bool: return not bool(N % 2) # Tests cases = [ {"input": 2, "output": True}, {"input": 3, "output": False}, ] Test(Solution().divisorGame, cases, True).test()
# Problem # The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, # such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, # # F(0) = 0, F(1) = 1 # F(N) = F(N - 1) + F(N - 2), for N > 1. # Given N, calculate F(N). # # # # Example 1: # # Input: 2 # Output: 1 # Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. # Example 2: # # Input: 3 # Output: 2 # Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. # Example 3: # # Input: 4 # Output: 3 # Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. # # # Note: # # 0 ≤ N ≤ 30. # Solution from leetcode.test import Test class Solution: # Solution with cycle def fib(self, N: int) -> int: f_n_2 = 1 f_n_1 = 0 i = 2 while i <= N: f_n_i = f_n_2 + f_n_1 f_n_1 = f_n_2 f_n_2 = f_n_i i += 1 return f_n_2 if N else 0 class Solution_1: # Recursion solution def fib(self, N: int) -> int: if N > 1: return self.fib(N-1) + self.fib(N-2) elif N == 1: return 1 else: return 0 # Tests cases = [ {"input": 2, "output": 1}, {"input": 3, "output": 2}, {"input": 4, "output": 3}, ] Test(Solution().fib, cases, True).test() Test(Solution_1().fib, cases, True).test()
# Problem # We are to write the letters of a given string S, from left to right into lines. # Each line has maximum width 100 units, and if writing a letter would cause the # width of the line to exceed 100 units, it is written on the next line. We are given an array widths, # an array where widths[0] is the width of 'a', widths[1] is the width of 'b', ..., and widths[25] is the width of 'z'. # # Now answer two questions: how many lines have at least one character from S, # and what is the width used by the last such line? Return your answer as an integer list of length 2. # # # # Example : # Input: # widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] # S = "abcdefghijklmnopqrstuvwxyz" # Output: [3, 60] # Explanation: # All letters have the same length of 10. To write all 26 letters, # we need two full lines and one line with 60 units. # Example : # Input: # widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] # S = "bbbcccdddaaa" # Output: [2, 4] # Explanation: # All letters except 'a' have the same length of 10, and # "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units. # For the last 'a', it is written on the second line because # there is only 2 units left in the first line. # So the answer is 2 lines, plus 4 units in the second line. # # # Note: # # The length of S will be in the range [1, 1000]. # S will only contain lowercase letters. # widths is an array of length 26. # widths[i] will be in the range of [2, 10]. # Solution from typing import List from leetcode.test import Test class Solution: def numberOfLines(self, widths: List[int], S: str) -> List[int]: l, w = 1, 0 a_offset = 97 for c in S: char_w = widths[ord(c) - a_offset] w += char_w if w > 100: l += 1 w = char_w return [l, w] # Tests cases = [ { "input": [ [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10], "abcdefghijklmnopqrstuvwxyz"], "output": [3, 60]}, { "input": [ [4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10], "bbbcccdddaaa"], "output": [2, 4]}, ] Test(Solution().numberOfLines, cases, False).test()
# Problem # Given a string S of lowercase letters, a duplicate removal consists of # choosing two adjacent and equal letters, and removing them. # # We repeatedly make duplicate removals on S until we no longer can. # # Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. # # # # Example 1: # # Input: "abbaca" # Output: "ca" # Explanation: # For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, # and this is the only possible move. The result of this move is that the string is "aaca", # of which only "aa" is possible, so the final string is "ca". # Solution from leetcode.test import Test class Solution: def removeDuplicates(self, S: str) -> str: ans = [] for i in S: if ans and ans[-1] == i: ans.pop() else: ans.append(i) return "".join(ans) # Tests cases = [ {"input": "abbaca", "output": "ca"}, ] Test(Solution().removeDuplicates, cases, True).test()
# Problem # Given a n-ary tree, find its maximum depth. # # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # # Nary-Tree input serialization is represented in their level order traversal, each group of children is # separated by the null value (See examples). # # # # Example 1: # # # # Input: root = [1,null,3,2,4,null,5,6] # Output: 3 # Example 2: # # # # Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] # Output: 5 # # # Constraints: # # The depth of the n-ary tree is less than or equal to 1000. # The total number of nodes is between [0, 10^4]. # Solution # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: # Solution with recursion def maxDepth(self, root: 'Node') -> int: self.max_depth = 0 if not root: return 0 for c in root.children: self.max_depth = max(self.max_depth, self.maxDepth(c)) return self.max_depth + 1 class Solution_1: # Solution with cycle def maxDepth(self, root: 'Node') -> int: resp = 0 childrens = [(root, 1)] if root else [] depth = 0 while childrens: root, depth = childrens.pop(0) if root.children: for c in root.children: childrens.append((c, depth + 1)) return depth
# Problem # Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), # return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest. # # A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, # or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, # that is, always ones may appear first and then zeros. # # # # Example 1: # # Input: mat = # [[1,1,0,0,0], # [1,1,1,1,0], # [1,0,0,0,0], # [1,1,0,0,0], # [1,1,1,1,1]], # k = 3 # Output: [2,0,3] # Explanation: # The number of soldiers for each row is: # row 0 -> 2 # row 1 -> 4 # row 2 -> 1 # row 3 -> 2 # row 4 -> 5 # Rows ordered from the weakest to the strongest are [2,0,3,1,4] # Example 2: # # Input: mat = # [[1,0,0,0], # [1,1,1,1], # [1,0,0,0], # [1,0,0,0]], # k = 2 # Output: [0,2] # Explanation: # The number of soldiers for each row is: # row 0 -> 1 # row 1 -> 4 # row 2 -> 1 # row 3 -> 1 # Rows ordered from the weakest to the strongest are [0,2,3,1] # # # Constraints: # # m == mat.length # n == mat[i].length # 2 <= n, m <= 100 # 1 <= k <= m # matrix[i][j] is either 0 or 1. # Solution from typing import List from leetcode.test import Test class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: counted_matrix = {} for i in range(len(mat)): counted_matrix[i] = mat[i].count(0) res = [] while k: min_pair = list(counted_matrix.items())[0] for key, value in counted_matrix.items(): if value > min_pair[1] or (value == min_pair[1] and key < min_pair[0]): min_pair = (key, value) res.append(min_pair[0]) counted_matrix.pop(min_pair[0]) k -= 1 return res # Tests cases = [ { "input": [ [ [1, 1, 0, 0, 0], [1, 1, 1, 1, 0], [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1]], 3], "output": [2, 0, 3]}, {"input": [ [ [1, 0, 0, 0], [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0]], 2], "output": [0, 2]}, ] Test(Solution().kWeakestRows, cases, False).test()
#---------------------------------------------------------------------------------------------------------------------- #encoding: UTF-8 # Autor: Sebastian Morales Martin, A01376228 # Descripcion: cálculo de coordenadas cartesianas a coordenadas polares # A partir de aquí escribe tu programa # Análisis #Entrada: coordenadas # Salida: valor de la magnitud, valor del ángulo de la magnitud en grados # Relación E/S: fórmula para la magnitud (teorema de pitágoras), magnitud (tangente ivertida) y grados (conversion de Radianes a Grados) #---------------------------------------------------------------------------------------------------------------------- import math print("-----------------------------------------------") print("") x = input("Introduzca el valor de X: ") xNum = int(x) y = input("Introduzca el valor de Y: ") yNum = int(y) print("") print("-----------------------------------------------") print("") r = xNum**2 + yNum**2 rRaiz = math.sqrt(r) rad = math.atan2(yNum,xNum) grad = (rad) * (180/3.1416) print("1. Valor de r:", rRaiz) print("") print("2. Grados totales:", grad)
""" Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. """ class Solution: def romanToInt(self, s: str) -> int: dictr = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } ans = 0 for i in range(len(s)): ans += dictr[s[i]] if i == 0: continue elif dictr[s[i]] > dictr[s[i-1]]: ans -= dictr[s[i-1]]*2 return ans
# -*- coding: utf-8 -*- __author__ = 'ivanvallesperez' import os def make_sure_do_not_replace(path): """ This function has been created for those cases when a file has to be generated and we want to be sure that we don't replace any previous file. It generates a different filename if a file already exists with the same name :param path: path to be checked and adapted (str or unicode) :return: path (str or unicode) """ base, fileName = os.path.split(path) file_name, file_ext = os.path.splitext(fileName) i = 1 while os.path.exists(path): path = os.path.join(base, file_name + "_copy%s" % i + file_ext) i += 1 return path
import argparse import re def reduce_asterisks(pattern): reduced = '' asterisk_now = False for i in pattern: if not asterisk_now and i == '*': reduced += i asterisk_now = True elif i != '*': reduced += i asterisk_now = False return reduced def check_sameness(str1, str2): str2 = re.escape(reduce_asterisks(str2)) str2 = str2.replace('\*', '.*') return bool(re.match(str2, str1)) parser = argparse.ArgumentParser() parser.add_argument('str1', type=str) parser.add_argument('str2', type=str) args = parser.parse_args() if check_sameness(args.str1, args.str2): print('OK') else: print('KO')
import numpy as np m = np.array([[1,2,3], [4,5,6]]) print(m) """< [[1 2 3] [4 5 6]] >""" v = m.flatten() print(v) """< [1 2 3 4 5 6] >"""
import numpy as np m = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(m) """< [[1 2 3] [4 5 6] [7 8 9]] >""" v = np.diagonal(m) print(v) """< [1 5 9] >"""
import sys import math # FUNCIO QUE LLEGEIX L'ARXIU PASSAT COM A PARAMETRE def readfile(): filename = sys.argv[1] variables = [] for line in open(filename): variables.append([int(i) for i in line.strip().split(' ')]) points = [] i = 0 while i < variables[0][0]: points.append(variables[i + 1]) i += 1 variables[0].append(points) return variables[0] # FUNCIO QUE PRINTA "impossible" I SURT DEL PROGRAMA def impossible(): print("impossible") exit() # FUNCIO QUE COMPROVA UN POSSIBLE PONT O AQUEDUCTE NO VÀLID def wrong_cases(points_rec, radius, span_point): if radius > h: impossible() i = 0 while i < 2: if points_rec[i][1] > span_point[1] and math.dist(span_point, points_rec[i]) >= radius: impossible() i += 1 # FUNCIO QUE CALCULA EL COST MITJANÇANT LA FORMULA PROPOSADA def cost(height, x): return alpha * height + beta * x # FUNCIO PRINCIPAL QUE COMPROVA TOT L'ANTERIOR DE FORMA RECURSIVA FINS QUE ARRIBA A L'ULTIM PUNT def recursive(points_rec, sum_costs): dist_x = points_rec[1][0] - points_rec[0][0] radius = dist_x / 2 span_point = [radius + points_rec[0][0], h - radius] wrong_cases(points_rec, radius, span_point) if len(points_rec) == 2: return cost(sum_costs[0] + h * 2 - (points_rec[1][1] + points_rec[0][1]), sum_costs[1] + dist_x ** 2) total_cost = [sum_costs[0] + h - points_rec[0][1], sum_costs[1] + dist_x ** 2] return recursive(points_rec[1:], total_cost) # Recolliment de variables n, h, alpha, beta, points = readfile() # Segons la llargaria de "points" fa augmentar el limit de recursio (inicial:1000) sys.setrecursionlimit(len(points) + 100) # S'escriu directament el resultat print(recursive(points, [0, 0]))
#!/usr/bin/env python3 import random N = 64 MAX_WORDS = 256 MAX_EXPONENT_WORDS = 8 for _ in range(N): x_words = random.randint(1, MAX_WORDS) y_words = random.randint(1, MAX_EXPONENT_WORDS) m_words = random.randint(1, MAX_WORDS) x = 0 y = 0 m = 0 for _ in range(x_words): x <<= 32 x |= random.getrandbits(32) for _ in range(y_words): y <<= 32 y |= random.getrandbits(32) for _ in range(m_words): m <<= 32 m |= random.getrandbits(32) m |= 1 result = pow(x, y, m) print(f"{x:x} {y:x} {m:x} {result:x}")
def zuixiaozhi(arr,type=1): min=arr[0] for i in range(1,len(arr)): if type==1: if min>arr[i]: min=arr[i] else: if min<arr[i]: min=arr[i] return min arr=[3,12,1,34] print(zuixiaozhi(arr,2))
# Ask the user for a password, and then make sure that the password follow those criterias: # - At least 1 lower case letter between. # - At least 1 number. # - At least 1 upper case letter. # - At least one exclamation mark. # - Minimum length of transaction password: 6. # - Maximum length of transaction password: 12. password = input("Please input your password: ") check = 0 if password.isupper() == True: # This means that all the letters in password are uppercased letters print("Your password needs to contain at least one lowercased letter") check = 1 if password.isalpha() == True: print("Your password needs to contain at least one number") check = 1 if password.lower() == password: # This will check if the original password is equal to his lowercased version print("Your password needs to contain at least one uppercased letter") check = 1 if "!" not in password: print("your password needs to contain an exclamation mark") check = 1 if len(password) <= 6: print("Your password needs to have more than 6 characters") check = 1 if len(password) >= 12: print("Your password needs to have less than 12 characters") check = 1 if check == 0: print("Your password is OK")
age = input("How old are you ? ") age = int(age) # _________________________________________ #/ Convert it to an int because the result \ #\ of input() is always a string. / # ----------------------------------------- # \ ^__^ # \ (oo)\_______ # (__)\ )\/\ # ||----w | # || || if age > 18: print("You can buy alcohol") else: print("Sorry, drink water")
### Exercise (medium) # #Make a function that receives a list and print: #- The number of elements in the list #- The minimum element in the list #- The maximum element in the list #- The sum of all the numbers in the list # ### def list_describer(l): print("Number of elements in this list:", len(l)) print("Minimum element of this list:", min(l)) print("Maximum element of this list:", max(l)) print("All the elements of this list sum to:",sum(l)) list_describer([1,3,312,51234,31234,151,5715,262,341,4572,3452435,])
class VendingMachine: def __init__(self): self.earnt_money = 0 self.products = [] # self.products will be a list of dictionnaries that represent a product # name/price/quantity def stock_article(self, product_dict): # Check if the dictionnary is valid keys = ['name', 'price', 'quantity'] for key in keys: if key not in product_dict.keys(): print("Invalid product format") return False # Check if the article already exist --> update the quantity for ix, product in enumerate(self.products): if product['name'] == product_dict['name']: self.products[ix]['quantity'] += product_dict['quantity'] return True self.products.append(product_dict) def buy_article(self, product_name): """ This function gets the name of a product (str) and simulate the sell of this product. Returns True or False --> Success of the transaction """ # Retrieve product dictionnary for ix, product_dict in enumerate(self.products): if product_dict['name'].lower() == product_name.lower(): product_ix = ix # Check availability if self.products[product_ix]['quantity'] == 0: print("Sorry, this product isn't available.") return False # Display the price price = self.products[product_ix]['price'] print("This product cost ${}".format(price)) buyit = input("Do you want this {}?[Y/n]\n> ".format(product_name)) if buyit.lower() == 'n': return False print("Enjoy your {} !!".format(product_name)) # Sell it.. self.products[product_ix]['quantity'] -= 1 if self.products[product_ix]['quantity'] < 0: self.products[product_ix]['quantity'] = 0 machine1 = VendingMachine() print("Hello and welcome to the Python Vending Machine") print("What would you like to do:") while True: print("1 - Buy an article") print("2 - Stock an article") print("Press x to exit") choice = input('> ') if choice == '1': print("Here is a list of the articles:") for product in machine1.products: print("{} - ${}".format(product['name'], product['price'])) chosen_product = input("Which article would you like to buy?\n> ") machine1.buy_article(chosen_product) elif choice == '2': name = input("What's the name of the product you want to stock?\n> ") price = input("What's the price of the product you want to stock?\n> ") quantity = input("What's the quantity of the product you want to stock?\n> ") price = int(price) quantity = int(quantity) product_dict = { 'name': name, 'price': price, 'quantity': quantity } machine1.stock_article(product_dict) elif choice == 'x': break else: print("Invalid choice") print("\n\n")
# Define name and age variables my_name = "Eyal" my_age = 20 # Incrementing my_age my_age += 1 my_age = my_age + 1 # Print presentation sentence out print("Hello my name is", my_name, "and I am", my_age, "years old") # Using the format() function print("Hello my name is {} and I am {} years old".format(my_name, my_age)) print(f"Hello my name is {my_name} and I am {my_age} years old") # ____________________ # < I am commented out > # -------------------- # \ ^__^ # \ (oo)\_______ # (__)\ )\/\ # ||----w | # || ||
# FrogRiverOne def solution(X, A): leaves = set() for i, j in enumerate(A): if j <= X: leaves.add(j) if len(leaves) == X: return i return -1 def solution2(A): leaves = set() if __name__ == "__main__": print(solution(5, [1, 3, 1, 4, 2, 3, 5, 4]))
import copy import sys class Point: x = -1 y = -1 class Node: 'the main node class' depth = 0 alpha = -9999 beta = 9999 value = -9999 x = -1 y = -1 nextX = -1 nextY = -1 board = [['*' for x in range(8)] for y in range(8)] flag=False def printRef(): for i in range(0,8): for j in range(0,8): print "(",i,",",j,")", print "\t", print return def pr(x,y): y = x + 1 x = y #print x,y,"in pr" if y == 0 : print "root", elif y==-1 or x==-2: print "pass", else: if x == 0: print "a", elif x == 1: print "b", elif x == 2: print "c", elif x == 3: print "d", elif x == 4: print "e", elif x == 5: print "f", elif x == 6: print "g", elif x == 7: print "h", print "%d" % y, print ",", return def printLine1(node): #f = open("output.txt",'a') y = node.x + 1 x = node.y if y == 0 or x == -1: print "root", elif y==-1 or x==-2: print "pass", else: if x == 0: print "a", elif x == 1: print "b", elif x == 2: print "c", elif x == 3: print "d", elif x == 4: print "e", elif x == 5: print "f", elif x == 6: print "g", elif x == 7: print "h", print "%d" % y, print ",", print "%d" %node.depth, print ",", if node.value == 9999: print "Infinity", elif node.value == -9999: print "-Infinity", else: print "%d" % node.value, print ",", if node.alpha == 9999: print "Infinity", elif node.alpha == -9999: print "-Infinity", else: print "%d" % node.alpha, print ",", if node.beta == 9999: print "Infinity" elif node.beta == -9999: print "-Infinity" else: print "%d" % node.beta return def printLine(node): f = open("output.txt",'a') y = node.x + 1 x = node.y if y == 0 or x == 0: f.write("root") elif y==-1 or x==-2: f.write("pass") else: if x == 0: f.write("a") elif x == 1: f.write("b") elif x == 2: f.write("c") elif x == 3: f.write("d") elif x == 4: f.write("e") elif x == 5: f.write("f") elif x == 6: f.write("g") elif x == 7: f.write("h") f.write("%d" % y) f.write(",") f.write("%d" %node.depth) f.write(",") if node.value == 9999: f.write("Infinity") elif node.value == -9999: f.write("-Infinity") else: f.write("%d" % node.value) f.write(",") if node.alpha == 9999: f.write("Infinity") elif node.alpha == -9999: f.write("-Infinity") else: f.write("%d" % node.alpha) f.write(",") if node.beta == 9999: f.write("Infinity") elif node.beta == -9999: f.write("-Infinity") else: f.write("%d" % node.beta) f.write("\n") f.close(); return def printBoard(board): for i in range(0,8): for j in range(0,8): print board[i][j], print "\t", print return def numberOfX(board): count = 0 for i in range(0,8): for j in range(0,8): if board[i][j] == 'X': count = count + 1 return count def numberOfO(board): count = 0 for i in range(0,8): for j in range(0,8): if board[i][j] == 'O': count = count + 1 return count def isValidMove(board, x, y, turn): kas = copy.copy(board) noofX = numberOfX(board) noofO = numberOfO(board) board[x][y] = turn if turn == 'X': for i in range(x+1,8): if board[i][y] == '*': break; elif board[i][y] == 'X': for kk in range(x+1,i): board[kk][y] = 'X' break for i in range(y+1,8): if board[x][i] == '*': break; elif board[x][i] == 'X': for kk in range(y+1,i): board[x][kk] = 'X' break for i in range(y-1,0,-1): if board[x][i] == '*': break; elif board[x][i] == 'X': for kk in range(y-1,i,-1): board[x][kk] = 'X' break for i in range(x-1,0,-1): if board[i][y] == '*': break; elif board[i][y] == 'X': for kk in range(x-1,i,-1): board[kk][y] = 'X' break j = y for i in range(x+1,8): j = j + 1 if j == 8: break if board[i][j] == '*': break elif board[i][j] == 'X': j = y for kk in range(x+1,i): j = j + 1 board[kk][j] = 'X' break j = y for i in range(x+1,8): j = j - 1 if j == -1: break if board[i][j] == '*': break elif board[i][j] == 'X': j = y for kk in range(x+1,i): j = j - 1 board[kk][j] = 'X' break j = y for i in range(x-1,0,-1): j = j - 1 if j == -1: break if board[i][j] == '*': break; elif board[i][j] == 'X': j = y for kk in range(x-1,i,-1): j = j - 1 board[kk][j] = 'X' break j = y for i in range(x-1,0,-1): j = j + 1 if j == 8: break if board[i][j] == '*': break; elif board[i][j] == 'X': j = y for kk in range(x-1,i,-1): j = j + 1 board[kk][j] = 'X' break #printBoard(board) elif turn == 'O': for i in range(x+1,8): if board[i][y] == '*': break; elif board[i][y] == 'O': for kk in range(x+1,i): board[kk][y] = 'O' break for i in range(y+1,8): if board[x][i] == '*': break; elif board[x][i] == 'O': for kk in range(y+1,i): board[x][kk] = 'O' break for i in range(y-1,0,-1): if board[x][i] == '*': break; elif board[x][i] == 'O': for kk in range(y-1,i,-1): board[x][kk] = 'O' break for i in range(x-1,0,-1): if board[i][y] == '*': break; elif board[i][y] == 'O': for kk in range(x-1,i,-1): board[kk][y] = 'O' break j = y for i in range(x+1,8): j = j + 1 if j == 8: break if board[i][j] == '*': break elif board[i][j] == 'O': j = y for kk in range(x+1,i): j = j + 1 board[kk][j] = 'O' break j = y for i in range(x+1,8): j = j - 1 if j == -1: break if board[i][j] == '*': break elif board[i][j] == 'O': j = y for kk in range(x+1,i): j = j - 1 board[kk][j] = 'O' break j = y for i in range(x-1,0,-1): j = j - 1 if j == -1: break if board[i][j] == '*': break; elif board[i][j] == 'O': j = y for kk in range(x-1,i,-1): j = j - 1 board[kk][j] = 'O' break j = y for i in range(x-1,0,-1): j = j + 1 if j == 8: break if board[i][j] == '*': break; elif board[i][j] == 'O': j = y for kk in range(x-1,i,-1): j = j + 1 board[kk][j] = 'O' break if noofX == numberOfX(board): board=copy.copy(kas) return False if noofO == numberOfO(board): board=copy.copy(kas) return False board=copy.copy(kas) return True def numberOfChances(board1, turn): count = 0 initScore = calcScore(board1, turn, 8, 8) for i in range(0, 8): for j in range(0, 8): if board1[i][j] != '*': continue else: kast = copy.deepcopy(board1) if isValidMove(kast, i, j, turn): count=count+1 #print count,"anything" #print turn,"ntng" p = [] for i in range(0, 8): for j in range(0, 8): if board1[i][j] != '*': continue kst = copy.deepcopy(board1) if isValidMove(kst, i, j, turn): # print i," ******************************* ",j pp = Point() if len(p) == 0: p = [Point()] pp.x = i pp.y = j p[0] = pp else: pp.x = i pp.y = j p.append(pp) return p def calcScore(board1, turn, n, m): scrboard = [[0 for x in range(8)] for y in range(8)] scrboard[0][0] = 99 scrboard[0][1] = -8 scrboard[0][2] = 8 scrboard[0][3] = 6 scrboard[1][0] = -8 scrboard[1][1] = -24 scrboard[1][2] = -4 scrboard[1][3] = -3 scrboard[2][0] = 8 scrboard[2][1] = -4 scrboard[2][2] = 7 scrboard[2][3] = 4 scrboard[3][0] = 6 scrboard[3][1] = -3 scrboard[3][2] = 4 scrboard[3][3] = 0 for x in range(4, 8): for y in range(0, 4): scrboard[x][y] = scrboard[7 - x][y] for x in range(4, 8): for y in range(4, 8): scrboard[x][y] = scrboard[7 - x][7 - y] for x in range(0, 4): for y in range(4, 8): scrboard[x][y] = scrboard[x][7 - y] finscore = 0 i = 0 j = 0 if turn == 'X': for i in range(0, n): for j in range(0, m): if board1[i][j] == 'X': finscore = finscore + scrboard[i][j] elif board1[i][j] == 'O': finscore = finscore - scrboard[i][j] elif turn == 'O': for i in range(0, n): for j in range(0, m): if board1[i][j] == 'O': finscore = finscore + scrboard[i][j] elif board1[i][j] == 'X': finscore = finscore - scrboard[i][j] return finscore def modifyX(board, x, y): if x==-1 or y == -1: return board[x][y] = 'X' for i in range(x+1,8): if board[i][y] == '*': break; elif board[i][y] == 'X': for kk in range(x+1,i): board[kk][y] = 'X' break for i in range(y+1,8): if board[x][i] == '*': break; elif board[x][i] == 'X': for kk in range(y+1,i): board[x][kk] = 'X' break for i in range(y-1,0,-1): if board[x][i] == '*': break; elif board[x][i] == 'X': for kk in range(y-1,i,-1): board[x][kk] = 'X' break for i in range(x-1,0,-1): if board[i][y] == '*': break; elif board[i][y] == 'X': for kk in range(x-1,i,-1): board[kk][y] = 'X' break j = y for i in range(x+1,8): j = j + 1 if j == 8: break if board[i][j] == '*': break elif board[i][j] == 'X': j = y for kk in range(x+1,i): j = j + 1 board[kk][j] = 'X' break j = y for i in range(x+1,8): j = j - 1 if j == -1: break if board[i][j] == '*': break elif board[i][j] == 'X': j = y for kk in range(x+1,i): j = j - 1 board[kk][j] = 'X' break j = y for i in range(x-1,0,-1): j = j - 1 if j == -1: break if board[i][j] == '*': break; elif board[i][j] == 'X': j = y for kk in range(x-1,i,-1): j = j - 1 board[kk][j] = 'X' break j = y for i in range(x-1,0,-1): j = j + 1 if j == 8: break if board[i][j] == '*': break; elif board[i][j] == 'X': j = y for kk in range(x-1,i,-1): j = j + 1 board[kk][j] = 'X' break return def modifyY(board, x, y): if x==-1 or y == -1: return board[x][y] = 'O' for i in range(x+1,8): if board[i][y] == '*': break; elif board[i][y] == 'O': for kk in range(x+1,i): board[kk][y] = 'O' break for i in range(y+1,8): if board[x][i] == '*': break; elif board[x][i] == 'O': for kk in range(y+1,i): board[x][kk] = 'O' break for i in range(y-1,0,-1): if board[x][i] == '*': break; elif board[x][i] == 'O': for kk in range(y-1,i,-1): board[x][kk] = 'O' break for i in range(x-1,0,-1): if board[i][y] == '*': break; elif board[i][y] == 'O': for kk in range(x-1,i,-1): board[kk][y] = 'O' break j = y for i in range(x+1,8): j = j + 1 if j == 8: break if board[i][j] == '*': break elif board[i][j] == 'O': j = y for kk in range(x+1,i): j = j + 1 board[kk][j] = 'O' break j = y for i in range(x+1,8): j = j - 1 if j == -1: break if board[i][j] == '*': break elif board[i][j] == 'O': j = y for kk in range(x+1,i): j = j - 1 board[kk][j] = 'O' break j = y for i in range(x-1,0,-1): j = j - 1 if j == -1: break if board[i][j] == '*': break; elif board[i][j] == 'O': j = y for kk in range(x-1,i,-1): j = j - 1 board[kk][j] = 'O' break j = y for i in range(x-1,0,-1): j = j + 1 if j == 8: break if board[i][j] == '*': break; elif board[i][j] == 'O': j = y for kk in range(x-1,i,-1): j = j + 1 board[kk][j] = 'O' break return def boardtostring(board): bts = "" for i in range(0,8): for j in range(0,8): bts=bts+"%c" % board[i][j] bts = bts + "\n" return bts SIZE = 8 board = [['*' for x in range(SIZE)] for y in range(SIZE)] f = open("input1.txt",'r') #print f.read() turn = f.readline()[0] if turn == 'X': turn1 = 'O' else: turn1 = 'X' findepth = ord(f.readline()[0]) - ord("0") for i in range(0,8): line = f.readline() for j in range(0,8): board[i][j] = line[j] f.close() node = Node() node.board = copy.deepcopy(board) node.depth = 0 node.x = -1 node.y = -1 def ALPHA_BETA(node): node.nextX = -1 node.nextY = -1 f = open("output.txt",'w') f.write("Node,Depth,Value,Alpha,Beta\n") f.close() node=MAX_VALUE(node) if turn == 'X': modifyX(node.board,node.nextX,node.nextY) else: modifyY(node.board, node.nextX, node.nextY) f = open("output.txt",'r') datainfile = f.read() f.close() f = open("output.txt",'w') f.write(boardtostring(node.board)) f.write(datainfile) f.close() return def MAX_VALUE(node): if node.depth>findepth: node.value=calcScore(node.board,turn,8,8) return node if len(numberOfChances(node.board,turn))==0: #print "pass ",node.depth,node.value,node.alpha,node.beta printLine(node) #print " i called printline" #print "608" child=Node() child.flag=True tempBoard = copy.deepcopy(node.board) child.board=tempBoard child.depth=node.depth+1 child.x=-2 child.y=-2 if node.flag==True: child.value=calcScore(child.board,turn,8,8) #print "i calculated score ",child.value child.x=-2 child.y=-2 printLine(child) node.value=child.value node.alpha=child.value printLine(node) return child #printLine(node) child=MIN_VALUE(child) node.alpha=child.value node.value=child.value #print "sodhi" printLine(node) return child points=numberOfChances(node.board,turn) #print len(points),"ariiiiiiiiiiiiiiiiiiiii" dummy_value=-9999 for p in points: child=Node() tempBoard = copy.deepcopy(node.board) if turn =='X': modifyX(tempBoard,p.x,p.y) else: modifyY(tempBoard,p.x,p.y) child.x=p.x child.y=p.y #print p.x,p.y,"lalalal" #printBoard(tempBoard) child.board=tempBoard child.depth=node.depth+1 #print "in for loop ,max: 641" printLine(node) #print child.depth,child.value,child.alpha,child.beta,"this is to be delteted" #printLine(child) child.value = node.beta dummy_value=max(dummy_value,MIN_VALUE(child).value) #print "in for loop max, 644" #print dummy_value,"in max" node.alpha=dummy_value if node.alpha <= child.value: if child.depth == 1: node.nextX = child.x node.nextY = child.y node.value=dummy_value printLine(node) if dummy_value>=node.beta: return node if node.alpha < child.value: node.alpha = child.value if child.depth == 1: node.nextX = child.x node.nextY = child.y return node def MIN_VALUE(node): if node.depth>findepth: node.value=calcScore(node.board,turn1,8,8) return node #print len(numberOfChances(node.board, turn1)), "-----------------------" if len(numberOfChances(node.board,turn1))==0: #print "pass ",node.depth,node.value,node.alpha,node.beta #node.value = 9999 printLine(node) #print "Min 0" #print "idiot" #print "i dont have moves in min,661" child=Node() child.flag=True child.depth=node.depth+1 child.x=-2 child.y=-2 tempBoard = copy.deepcopy(node.board) child.board=tempBoard if node.flag==True: child.value=calcScore(child.board,turn1,8,8) child.x=-2 child.y=-2 printLine(child) #print "Min 1" node.value=child.value node.beta=child.beta printLine(node) #print "Min 2" return child #printLine(node) #print "in min, 675" child=MAX_VALUE(child) node.beta=child.value node.value=child.value #print "koottu" printLine(node) #print "Min 3" return child points=numberOfChances(node.board,turn1) #print len(points),"yedho oka sodhi" dummy_value=9999 for p in points: child=Node() tempBoard = copy.deepcopy(node.board) if turn1 =='X': modifyX(tempBoard,p.x,p.y) else: modifyY(tempBoard,p.x,p.y) child.x=p.x child.y=p.y #print child.x,child.y #pr(child.x,child.y) child.board=tempBoard #printBoard(child.board) child.depth=node.depth+1 printLine(node) #printLine(child) dummy_value=min(dummy_value,MAX_VALUE(child).value) #print dummy_value,"in min" node.value=dummy_value node.beta=dummy_value printLine(node) if dummy_value<=node.alpha: return node node.beta=min(node.beta,node.value) return node ALPHA_BETA(node)
""" A module can define a class with the desired functionality, and then at the end, replace itself in sys.modules with an instance of that class (or with the class, if you insist, but that's generally less useful). import callable_module print(callable_module.bar('lindsay')) """ import sys class Foo: def bar(self, name): return name sys.modules[__name__] = Foo()
""" A deque (pronounced "deck") implementation in Python A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection. What makes a deque different is the unrestrictive nature of adding and removing items. New items can be added at either the front or the rear. Likewise, existing items can be removed from either end. In a sense, this hybrid linear structure provides all the capabilities of stacks and queues in a single data structure. It is important to note that even though the deque can assume many of the characteristics of stacks and queues, it does not require the LIFO and FIFO orderings that are enforced by those data structures. It is up to you to make consistent use of the addition and removal operations. The deque operations are given below. - Deque() creates a new deque that is empty. It needs no parameters and returns an empty deque. - add_front(item) adds a new item to the front of the deque. It needs the item and returns nothing. - add_rear(item) adds a new item to the rear of the deque. It needs the item and returns nothing. - remove_front() removes the front item from the deque. It needs no parameters and returns the item. The deque is modified. - remove_rear() removes the rear item from the deque. It needs no parameters and returns the item. The deque is modified. - is_empty() tests to see whether the deque is empty. It needs no parameters and returns a boolean value. - size() returns the number of items in the deque. It needs no parameters and returns an integer. Lists vs. Deques Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation. You can't use slice/index operations on a deque, but you can use popleft/appendleft, which are operations deque is optimized for. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead. Python lists are much better for random-access and fixed-length operations, including slicing, While deques are much more useful for pushing and popping things off the ends, with indexing (but not slicing, interestingly) being possible but slower than with lists. """ class Deque(object): def __init__(self): self.items = [] def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0,item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) @property def is_empty(self): return self.size == 0 @property def size(self): return len(self.items)
# coding: utf-8 """ Some easy questions to ask an interviewer from Joel Spolsky: 1) Write a function that determines if a string starts with an upper-case letter A-Z 2) Write a function that determines the area of a circle given the radius 3) Add up all the values in an array """ import re def starts_with_uppercase(s): # XXX: s[0] ile daha mı hızlı olur? # XXX: regex haricinde daha hızlı bir yöntem var mı? if not isinstance(s, (basestring, buffer)): return False return bool(re.match(r'^[A-Z]', s)) if __name__ == '__main__': test_strings = (1212, 'berker', 'Peksag', '_foo', '12berker',) for _str in test_strings: print _str, starts_with_uppercase(_str)
""" A decorator factory is a function that returns a decorator. Decorator factories are used when you want to pass additional argument to the decorator, and they are commonly implemented by nesting 3 functions. The outer function is the decorator factory, the middle one is the decorator, and the inner one is the function that will replace the decorated function. """ import functools def repeat_for(times): def deco(func): @functools.wraps(func) def inner(): for x in range(times): func() return inner return deco @repeat_for(3) def hello(): print("hello") @repeat_for(2) def bye(): print("bye") # same as bye = repeat_for(2)(bye) hello() bye() def tags(tag_name): def tags_decorator(func): @functools.wraps(func) def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): """Return some text.""" return "Hello {}".format(name) def get_text_not_decorated(name): """Return some text.""" return "Hello {}".format(name) print(get_text("Lindsay")) print(tags("p")(get_text_not_decorated)("Lindsay"))
""" Simple cache implementation --------------------------- The following is a simple cache implementation, which is suitable for relatively small caches (up to a few hundred items), and where it’s relatively costly to create or reload objects after a cache miss (e.g. a few milliseconds or more per object.) Usage:: cache = Cache() try: item = cache.get(key) except KeyError: item = item_factory() cache.set(key, item) print(len(cache)) TODO items: * Add cache.get(key, default) * Use collections.MutableMapping """ import unittest class Cache: def __init__(self, *, maxsize=100): self.cache = {} self.order = [] # least recently used first self.maxsize = maxsize def get(self, key): item = self.cache[key] # KeyError if not present self.order.remove(key) self.order.append(key) return item def set(self, key, value): if key in self.cache: self.order.remove(key) elif len(self.cache) >= self.maxsize: # discard least recently used item del self.cache[self.order.pop(0)] self.cache[key] = value self.order.append(key) def __len__(self): return len(self.cache) class CacheTestCase(unittest.TestCase): def setUp(self): self.cache = Cache() def test_get(self): self.assertRaises(KeyError, self.cache.get, 'foo') self.cache.set('foo', 'bar') self.assertEqual(self.cache.get('foo'), 'bar') def test_set(self): self.cache.set('foo', 'foo') self.assertEqual(self.cache.get('foo'), 'foo') self.cache.set('foo', 'bar') self.assertEqual(self.cache.get('foo'), 'bar') def test_len(self): self.assertEqual(len(self.cache), 0) self.cache.set('bar', 'baz') self.assertEqual(len(self.cache), 1) self.cache.set('key', 'value') self.assertEqual(len(self.cache), 2) def test_maxsize(self): self.assertEqual(self.cache.maxsize, 100) cache = Cache(maxsize=42) self.assertEqual(cache.maxsize, 42) if __name__ == '__main__': unittest.main(verbosity=2)
# Program to check student attendance. #If attendance>75%, student can sit for attendance. #If attendance<75%, he cannot class Student_attendance: def att(self,attendance): if(attendance>75): print("Student can sit for unit test") else: print("Student cannot sit for unit test.") attendance = int(input("Enter percentage attendance of student")) ob=Student_attendance() ob.att(attendance)
# This question is about AdaBoost algorithm. # You should implement it using library function (DecisionTreeClassifier) as a base classifier # Don't do any additional imports, everything is already there # # There are two functions you need to implement: # (a) fit # (b) predict from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier import numpy as np import pandas as pd class BoostingTreeClassifier: def __init__(self, random_state): self.random_state = random_state self.classifiers = [] self.tree_weights = [] self.sample_weights = [] #TO DO ---- 10 POINTS ---------- Implement the fit function --------------------- def fit(self, X, y, n_trees): """Trains n_trees classifiers based on AdaBoost algorithm - i.e. applying same model on samples while changing their weights. You should only use library function DecisionTreeClassifier as a base classifier, the boosting algorithm itself should be written from scratch. Store trained tree classifiers in self.classifiers. Calculate tree weight for each classifier and store them in self.tree_weights. Initialise DecisionTreeClassifier with self.random_state :param X: train data :param y: train labels :param n_trees: number of trees to train :return: doesn't return anything """ self.sample_weights = [] N = len(X) self.sample_weights.append([]) self.tree_weights = [1.0] for i in range(N): self.sample_weights[0].append(1 / N) for tree_ind in range(n_trees): self.classifiers.append(DecisionTreeClassifier(random_state=rand_state)) self.classifiers[-1].fit(X, y) y_pred = self.classifiers[-1].predict(X) weighted_error = self.get_weighted_error(self.sample_weights[-1], y, y_pred) tree_weight = self.calculate_tree_weight(weighted_error) self.tree_weights.append(tree_weight) new_sample_weights = self.calculate_sample_weights(tree_weight, y, y_pred, self.sample_weights[-1]) new_sample_weights = self.normalize_weights(new_sample_weights) self.sample_weights.append(new_sample_weights) # weight update = 1/2 ln((1-weighted error(f))/weighted error(f)) # sample update = alpha(-w) if correct, alpha(w) if incorrect # initial sample weights = 1/m # NORMALIZE #TO DO ---- 5 POINTS ---------- Implement the predict function --------------------- def predict(self, X): """Makes final predictions aggregating predictions of trained classifiers :param X: test data (arrays) :return: predictions """ predictions = [] cl_predictions = [] for classifier in self.classifiers: cl_predictions.append(classifier.predict(X)) for index in range(len(cl_predictions[0])): pred = {-1: 0.0, 1: 0.0} for cl in range(len(cl_predictions)): # if cl == 3: # continue pred[cl_predictions[cl][index]] += self.tree_weights[cl] if pred[-1] > pred[1]: predictions.append(-1) else: predictions.append(1) return predictions def calculate_sample_weights(self, tree_weight, y, y_pred, sample_weights): s_ws = [] for i in range(len(y)): if y[i] != y_pred[i]: s_ws.append(sample_weights[i] ** (tree_weight)) else: s_ws.append(sample_weights[i] ** (-tree_weight)) return s_ws def get_weighted_error(self, sample_weights, y, y_pred): error = 0 for i in range(len(y)): if y[i] != y_pred[i]: error += sample_weights[i] # print("error equals = {}".format(error)) return error # Should I divide ny N? def calculate_tree_weight(self, error): print(error) if error == 0: return 1.0 / 2 a = (1 - error) / error return 1.0/2 * np.log(a) def normalize_weights(self, weights): copied = [] w_sum = sum(weights) for w in weights: copied.append(w / w_sum) return copied # loading and pre-processing titanic data set titanic = pd.read_csv('datasets/titanic_modified.csv').dropna() data = titanic[['Pclass', 'Age', 'SibSp', 'Parch']].values labels = titanic.iloc[:, 6].values # changing labels so that we can apply boosting labels[np.argwhere(labels == 0)] = -1 # splitting into train and test set X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.3, random_state=0) # setting constants rand_state = 3 T = 10 # number of trees # measuring accuracy using one decision tree tree = DecisionTreeClassifier(random_state=rand_state) tree.fit(X_train, y_train) print('One tree accuracy:', accuracy_score(tree.predict(X_test), y_test)) # # measuring accuracy using an ensemble based on boosting ensemble = BoostingTreeClassifier(random_state=rand_state) ensemble.fit(X_train, y_train, T) print('Ensemble accuracy:', accuracy_score(ensemble.predict(X_test), y_test)) # My ensemble trains a lot and becomes error-less on train set... print(X_train) print(X_train.shape)
import random import json import datetime class Result(): # class def __init__(self, player_name, score): self.date = datetime.datetime.now() self.player_name = player_name self.score = score def play_game(player_name, level): secret = random.randint(1, 30) score = 0 while True: guess = int(input("Please guess the secret number between 1 and 30")) score += 1 result_list = get_score() result = Result(player_name, score) # das Objekt result_list.append({player_name, datetime.datetime.now(), score}) with open("result.txt", "w") as result_file: # das Objekt wird in eine json Datei gespeichert json.dump(result.__dict__, result_file, default=str, indent=3) # json string if guess == secret: print("You have guessed it {}!".format(player_name)) break elif guess > secret: if level.lower() == "easy": print("Your guess is not correct ... try something smaller:") else: print("Try something else:") elif guess < secret: if level.lower() == "easy": print("Your guess is not correct ... try something bigger:") else: print("Try something else:") return score def get_score(): with open("result.txt", "r")as read_file: score = json.load(read_file) return score def print_score(): result_list = get_score() print(result_list) def user_input(): player_name = str(input("What's your name?")) while True: selection = input("Would you like to play a new game? a), would you like to see the score? b) quit? c)") if selection.lower() == "a": difficulty = str(input("Please select the difficulty: easy/hard")) score = play_game(player_name, difficulty) # score wird als variable ausgeführt elif selection.lower() == "b": print(result) else: print("goodbye!") break if __name__ == "__main__": user_input()
def diffWaysToCompute(input): """ :type input: str :rtype: List[int] """ n = [] symbol = [] p = 0 i = 0 for c in input: if c.isdigit(): p = p * 10 + int(c) else: i += 1 n.append(p) n.append(c) symbol.append(i) i += 1 p = 0 n.append(p) print(n) print(symbol) table = {} return compute(n, symbol, 0, len(n) - 1, table) def compute(n, symbol, i, j, table): if i == j: table[(i, j)] = [n[i]] return [n[i]] if (i, j) in table: return table[(i, j)] r = [] for s in symbol: if i < s < j: for val1 in compute(n, symbol, i, s - 1, table): for val2 in compute(n, symbol, s + 1, j, table): if n[s] == '+': r.append(val1 + val2) elif n[s] == '-': r.append(val1 - val2) elif n[s] == '*': r.append(val1 * val2) else: r.append(val1 / val2) table[(i, j)] = r return r def t(x): r = [1] x.append(r) return r def main(): # s = '2-3+1' # t = diffWaysToCompute(s) # print(t) x = [] print(t(x)) print(x) if __name__ == '__main__': main()
from enum import Enum class Region(Enum): WEST = 1 EAST = 2 NORTH = 3 SOUTH = 4 print(Region.NORTH.name) print(Region.NORTH.value) print(Region(3)) print(Region['NORTH']) print(Region(4))
from ListNode import * def rearrange(head): if head != None: pre = None p = head while p != None: if p.val >= 0: pre = p p = p.next else: pre.next = p.next p.next = head head = p p = pre.next return head def main(): head = createList([0, -1]) head = rearrange(head) printList(head) if __name__ == '__main__': main()
# https://leetcode.com/problems/construct-string-from-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def tree2str(self, t: TreeNode) -> str: if not t: return "" left = "" if not t.left else self.tree2str(t.left) right = "" if not t.right else self.tree2str(t.right) if len(left) > 0 and len(right) > 0: return f"{t.val}({left})({right})" if len(left) > 0: return f"{t.val}({left})" if len(right) > 0: return f"{t.val}({left})({right})" else: return f"{t.val}"
# https://leetcode.com/problems/design-add-and-search-words-data-structure/ class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.words: Dict[int, Set[str]] = {} def addWord(self, word: str) -> None: """ Adds a word into the data structure. """ len_w = len(word) value = self.words.get(len_w, set()) value.add(word) self.words[len_w] = value def search(self, word: str) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ len_w = len(word) to_find = self.words.get(len_w, set()) if word in to_find: return True for it_word in to_find: is_equal = True for i in range(len_w): if it_word[i] != word[i] and word[i] != '.': is_equal = False if not is_equal: break if is_equal: return True return False # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
# https://projecteuler.net/problem=3 import math # def get_primes(max_val: int) -> set[int]: def get_primes(max_val: int) -> list: crive = [True] * (max_val + 1) crive[0] = crive[1] = False for x in range(2, max_val + 1): if crive[x]: temp = x x += temp while x <= max_val: crive[x] = False x += temp # return {x for x in range(max_val) if crive[x]} return [x for x in range(max_val) if crive[x]] if __name__ == "__main__": value = 600851475143 primes = sorted(get_primes(int(math.sqrt(value))), reverse=True) for prime in primes: if value % prime == 0: print(f"The biggest prime factor of {value} is {prime}") break
#!/bin/python3 import math import os import random import re import sys # Complete the checkMagazine function below. def checkMagazine(magazine, note): magazine_dit = dict() for x in magazine: magazine_dit[x] = magazine_dit.get(x, 0) + 1 for x in note: if x not in magazine_dit or magazine_dit[x] == 0: return 'No' else: magazine_dit[x] -= 1 return 'Yes' if __name__ == '__main__': mn = input().split() m = int(mn[0]) n = int(mn[1]) magazine = input().rstrip().split() note = input().rstrip().split() print(checkMagazine(magazine, note)) # print(checkMagazine(['give', 'me', 'one', 'grand', 'today', 'night'], ['give', 'one', 'grand', 'today'])) # print(checkMagazine(['two times three is not four'], ['two times two is four'])) # print(checkMagazine(['ive', 'got', 'a', 'lovely', 'bunch', 'of', 'coconuts'], ['ive', 'got', 'some', 'coconuts']))
# https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ class Solution: def is_sorted(self, nums: List[int]) -> bool: # print(f"is_sorted({nums})") lenn = len(nums) for i in range(lenn - 1): if nums[i + 1] < nums[i]: return False return True def check(self, nums: List[int]) -> bool: break_point = -1 lenn = len(nums) for i in range(lenn - 1): if nums[i + 1] < nums[i]: if break_point >= 0: return False else: break_point = i # print(f"bp: {break_point}") return break_point == -1 or self.is_sorted(nums[break_point + 1:] + nums[:break_point + 1])
#!/bin/python import math import os import random import re import sys numberName = ["o' clock", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twoelve", "thirteen", "fourteen", "quarter", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"] numberName += ["twenty" + " " + numberName[i] for i in xrange(1, 10)] numberName += ["half"] # Complete the timeInWords function below. def timeInWords(h, m): minutes = "minute{} ".format("s" if 1 < m < 59 else "") if m not in [15, 30, 45] else "" if m == 0: return "{} {}".format(numberName[h], numberName[m]) elif m <= 30: return "{} {}past {}".format(numberName[m], minutes, numberName[h]) else: return "{} {}to {}".format(numberName[60 - m], minutes, numberName[h + 1]) if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') h = int(raw_input()) m = int(raw_input()) result = timeInWords(h, m) print result # fptr.write(result + '\n') # fptr.close()
def LongestWord(sen): palavras = sen.split(' ') maior = "" for palavra in palavras: atual = "" for letra in palavra: if letra.isalpha(): atual += letra if len(atual) > len(maior): maior = atual return maior # keep this function call here print LongestWord(raw_input())
print("Hello (^_^)") exi = True while exi == True: print("----MENU----\n1.Register\n2.Login\n3.Exit") menu = int(input()) if menu==1: print("--REGISTER--") userR = str(input("USERNAME:")) plassR = str(input("PLASSWORD:")) print("Register successfuly") elif menu==2: print("--LOGIN--") userL = str(input("USERNAME:")) plassL = str(input("PLASSWORD:")) if userL==userR and plassL==plassR: print("Login successfuly") exi = False else: print("Try it again") elif menu==3: print("END") exi = False else: print("ERROR\nplease try it again")
velocidade = int(input('Digite a velocidade do veículo: ')) if velocidade > 80: print('Você foi multado!') multa = (velocidade - 80) * 7 print('O valor da multa é de R${}.'.format(multa)) else: print('Tenha um bom dia e dirija com segurança')
idade_maior = 0 nome_maior = '' soma_idade = 0 count_mulheres = 0 media = 0 for counter in range(1, 5): print('--------- {}° PESSOA ---------'.format(counter)) nome = str(input('Nome: ')) idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).upper() soma_idade += idade media = soma_idade / counter if idade > idade_maior and sexo == 'M': nome_maior = nome idade_maior = idade if idade < 20 and sexo == 'F': count_mulheres += 1 print('A média de idade do grupo é de {} anos.'.format(media)) print('O homem mais velho se chama {} e tem {} anos.'.format(nome_maior, idade_maior)) print('No grupo tem {} mulheres com menos de 20 anos.'.format(count_mulheres))
print('-='*27) valor_casa = float(input('Digite o valor da casa que deseja comprar: R$ ')) salario = float(input('Digite o salário que você recebe: R$ ')) anos = int(input('Digite em quantos anos deseja parcelar: R$ ')) print('-='*27) prestacao = (valor_casa / anos) / 12 minimo = salario * 0.3 if prestacao <= minimo: print('Empréstimo aprovado!') print('Prestação: R$ {:.2f}'.format(prestacao)) else : print('Empréstimo negado!')
a = float(input('Digite o lado a do triangulo: ')) b = float(input('Digite o lado b do triangulo: ')) c = float(input('Digite o lado c do triangulo: ')) if a < b + c and b < a + c and c < a + b: print('As retas podem formar um triangulo') if a == b and a == c: print('Formará um triângulo equiátero.') elif a != b and a != c: print('Formará um triângulo escaleno.') else: print('Formará um triangulo isóceles.') else: print('As retas não podem formar um triangulo')
""" Example usage of replot to output replottable plots with Pyplot. """ import numpy as np from replot import plot # Code the does the actual plotting # You can also put this in a separate .py file and specify the path to it plotting_code = """\ import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt from replot import get_data # Read in the input data data = get_data() values = data["values"] # Plot the data fig = plt.figure() ax = fig.add_subplot(111) bars = ax.bar(list(range(len(values))), values) ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off' ) # Output the plot plt.savefig("plot.pdf") """ # Now generate some data to plot values = np.random.randint(0, 10, 10) # Put the data in a dictionary # In this case, it's just the values, but we might have other data structures too data = {"values": values} # Output the plotting code, data and the plot itself plot(".", plotting_code, data) # Now we've output the plot to plot.pdf # but you can also edit the plotting code afterwards in plot.py and re-run # the plotting by just calling that script!
import sys, random print("Welcome to the Psych 'Sidekick Name Picker.'\n") print("A name just like Sean would pick for Gus:\n\n") first = ('Baby Oil','Bad News', 'Big Burps', "Bill, 'Beenie-Weenie'") last = ('Appleyart','Bigmeat','Littlemeat','Bloominshine','Boogerbottom','Clutterbuck','Cocktoasten', 'Jefferson','Jingley-Schmidt') while True: firstName = random.choice(first) lastName = random.choice(last) print("\n\n") print("{} {}".format(firstName, lastName), file=sys.stderr) print("\n\n") try_again = input("\n\nTry again? (Press Enter else n to quit)\n ") if try_again.lower() == "n": break input("\nPress Enter to Exit.")
#Escribe un programa que lea las dimensiones (base y altura) de dos rectángulos y que calcule e imprima el perímetro y área #de cada uno. def calcularArea1(base1, altura1): area = base1*altura1 return area def calcularArea2(base2, altura2): area = base2*altura2 return area def calcularPerimetro1(base1, altura1): p = (base1*2)+(altura1*2) return p def calcularPerimetro2(base2, altura2): p = (base2*2)+(altura2*2) return p def compararAreas(area1, area2): if area1>area2: x = "El área del primer rectángulo es mayor que el segundo." elif area2>area1: x = "El área del segundo rectángulo es mayor que el primero." elif area1==area2: x = "El área de los rectángulos es la misma." return x def main(): base1 = int(input("Teclea el largo del rectángulo1: ")) altura1 = int(input("Teclea la altura del rectángulo1: ")) base2 = int(input("Teclea el largo del rectángulo2: ")) altura2 = int(input("Teclea la altura del rectángulo2: ")) area1 = calcularArea1(base1, altura1) area2 = calcularArea2(base2, altura2) perimetro1 = calcularPerimetro1(base1, altura1) perimetro2 = calcularPerimetro2(base2, altura2) comparacion = compararAreas(area1, area2) print(comparacion) main()
import sys def read_ints(): """Read integers from underlying buffer until we hit EOF.""" numb, sign = 0, 1 res = [] s = sys.stdin.read() for i in range(len(s)): if s[i] >= '0': numb = 10 * numb + ord(s[i]) - 48 else: if s[i] == '-': sign = -1 else: res.append(sign * numb) numb, sign = 0, 1 if s[-1] >= '0': res.append(sign * numb) return res
def gen(A, b, n): if b == n-1: print A else: A[b+1] = 0 gen(A, b+1, n) A[b+1] = 1 gen(A, b+1, n) if __name__ == '__main__': n = 15 Arr = [] for i in range(n): Arr.append(0) gen(Arr, 0, n)
# -*- coding: utf-8 -*- """ program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh Created on Fri Jun 16 16:03:10 2017 @author: mtrem """ # String of letters in alphabetical order alphabet = 'abcdefghijklmnopqrstuvwxyz' # input string s = 'fwguvsabmbussybnqfd' # Counter to keep track of characters in input string counter = 0 # intialize the longest substring longString = '' # Keep track of previously found substring prevString = '' # Scan each letter in the Input string # if the next letter is alphabetically higher order than last letter in substring then # append the string , else update the longString with current letter # Compare newly found substring with the previous one # In the case of ties, print the first substring, For example, if s = 'abcbcd', ans. abc # repeat until the end of the input string while (counter < len(s)): if (longString == ''): longString = s[counter] else: newString = longString[len(longString)-1] if (alphabet.find(newString) <= alphabet.find(s[counter])) : longString += s[counter] else: if (len(prevString) < len(longString)): prevString = longString longString = s[counter] counter += 1 if (len(prevString) == len(longString) or len(prevString) > len(longString)): print("Longest substring in alphabetical order is: " + prevString) else: print("Longest substring in alphabetical order is: " + longString)
# -*- coding: utf-8 -*- """ Python function, evalQuadratic(a, b, c, x), that returns the value of the quadratic a⋅x2+b⋅x+c. Created on Mon Jun 19 15:28:29 2017 @author: mtrem """ def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' return (a * (x ** 2)) + (b * x) + c print(evalQuadratic(2, 3, 4, 7))
print("what's your favorite sport?") sport = input ().title() if sport == "Skiing": print ("That's my favorite too!") elif sport == "Golf": print ("I'm decent, but I'm practing.") elif sport == "Wrestling": print ("I love wrestling") else: print (sport + " sounds fun.") print("What's your favorite TY show?") show = input().title() if show == "The Flash": print ("I love the show!") elif show == "Aressted Devolpment": print ("I've made a hige mistake.") else: print ("I haven't watched" + show) print ("What's your favorite color") color = input().title() if color == "Green": ("Mine Too!") elif color == "Blue": print ("Thats my second favorite.") mymovies = ["Anchorman, Anchorman2, Deadpool, Fast and Furious, Space Balls, 21 jump street, 22 jump street, Cars, Any Marvle Movie"] print(" what is your favorite movie") movie = input() if movie in mymovies: print ("I love watching" + movie)
""" 读取JSON数据 """ import json; import csv2; json_str = '{"name":"wendy", "age": 22, "title": "老师"}'; result = json.loads(json_str); print(result); print(type(result)); print(result['name']); print(result['age']); # 把转换得到的字典作为关键字参数传入Teacher的构造器 teacher = csv2.Teacher(**result); print(teacher); print(teacher.name); print(teacher.age); print(teacher.title);
from nltk.tokenize import sent_tokenize def lines(a, b): """Return lines in both a and b""" # split each string into lines linesa = a.splitlines() linesb = b.splitlines() # instantiate results list lines = [] # compare lines for a_line in linesa: for b_line in linesb: # if both lines match append to results if a_line == b_line: lines.append(a_line) # convert to set to remove duplicates uniquelines = set(lines) return uniquelines def sentences(a, b): """Return sentences in both a and b""" # TODO # split each string into sentences sentences_a = sent_tokenize(a) sentences_b = sent_tokenize(b) sentences = [] # compare lines for a_sentence in sentences_a: for b_sentence in sentences_b: # if both lines match append to results if a_sentence == b_sentence: sentences.append(a_sentence) # convert to set to remove duplicates unique_sentences = set(sentences) return unique_sentences def get_substrings(string, n): subs = [] for i in range(len(string) - n + 1): subs.append(string[i:i+n]) return subs def substrings(a, b, n): """Return substrings of length n in both a and b""" # generate all substrings of length n sub_a = get_substrings(a, n) sub_b = get_substrings(b, n) substrings = [] # compare substrings for a_sub in sub_a: for b_sub in sub_b: # if both substrings match append to results if a_sub == b_sub: substrings.append(a_sub) # convert to set to remove duplicates unique_substrings = set(substrings) return unique_substrings
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" alphabetLength = alphabet.__len__() def run_caesar(): stringToEncrypt = input("Please enter a message to encrypt") shiftMessage = "Please enter a whole number from -%d to %d to be your key" % (alphabetLength-1, alphabetLength-1) intKey = int(input(shiftMessage)) encrypted = caesar_cipher(stringToEncrypt, intKey) print("Your encrypted message is", encrypted) def caesar_cipher(clearText, shiftAmount): """ caesar_cipher: Use the caesar cipher to encrypt clearText using shiftAmount Parameters ---------- clearText: the text string to encrypt shiftAmount: the integer shift amount Return: the encrypted string """ clearText = clearText.upper() encryptedString = "" for currentCharacter in clearText: position = alphabet.find(currentCharacter) newPosition = (position + shiftAmount) % alphabetLength if currentCharacter in alphabet: encryptedString = encryptedString + alphabet[newPosition] else: encryptedString = encryptedString + currentCharacter return encryptedString run_caesar()
#!/usr/bin/python from __future__ import print_function import random print("You are in a dark room in a mysterious castle") print("In front of you are three doors. You must choose one.") playerChoice = raw_input("Choose 1, 2, 3 or 4. . . ") if playerChoice == "1": print ("You find a room full of treasure. You're rich!") print ("GAME OVER, YOU WIN!"); elif playerChoice == "2": print("The door opens and an angry ogre hits you with his club.") print("GAME OVER, YOU LOSE") elif playerChoice == "3": print("You go into a room full of gold and find a sleeping dragon.") print("You can either:") print("1) Try to steal some of the dragon's gold.") print("2) Try to sneak around the dragon and exit.") dragonChoice = raw_input("Type 1 or 2...") if dragonChoice == "1": dragonWakes = random.randint(0,1) if dragonWakes == 1: print("The dragon wakes up and eats you! You are delicious!") print("GAME OVER, YOU LOSE") else: print("You are able take some gold and escape the waking dragon!") print("Beware next time, the dragon is now awake!") print("GAME OVER, YOU WIN (for now)") elif dragonChoice == "2": print("You sneak around the dragon and escape the castle") print("GAME OVER, YOU WIN") else: print("The dragon wakes up because you entered an incorrect chose!") print("He and eats you! You are delicious!") print("GAME OVER, YOU LOSE") elif playerChoice == "4": print("You enter a room with a sphinx.") print("It asks you to guess what number it is thinking of, between 1 and 10.") number = int(raw_input("What number do you choose? ")) sphinxNumber = random.randint(1,10) if number == sphinxNumber: print("The sphinx hisses in disapprovement. You guessed correctly.") print("She must lets you go free.") print ("GAME OVER, YOU WIN!"); else: print("The sphinx tells you that your guess was incorrect.") print("The sphinx was thinking of ", sphinxNumber) print("GAME OVER, YOU LOSE") else: print("Sorry you didn't enter 1, 2 or 3!") print("Run the game and try again")
import random low = 0 high = 24 random_index = random.randint(low, high) primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] number = primes[random_index] for i in range(low, high): if number == primes[i]: print("Found {} in {} try(s)".format(number, i+1)) break
def sayHello(): myName = input("What is your name? ") print("hello", myName) sayHello()
def sayHello(name): print("hello", name) myName = input("What is your name? ") sayHello(myName)
print('________________________________________') print('CIRCONFERENZA DEL CERCHIO DATO IL RAGGIO') raggio = input('Inserire il raggio: ') r = float(raggio) print('Diametro' , r*2) print('Circonferenza' , r*2 * 3.14) print('Area' , r**2 * 3.14) print('ho ragione, lo so') print('Autore: Luca Gamerro' , 'Linguaggio di programmazione: Python')
# FUNCTIONS # A function is like a mini-program within a program. def hello(): print('Howdy!') print('Howdy!!!') print('Hello there.') # Can you run the function hello()? def hello_friend(name): print('Howdy, ' + name) # Can you say Howdy to your code buddy? ### Exercise: Can you write a function that: # Takes in your name and the language you are learning # Prints out an Introduction for yourself # Bonus -- if you are learning 'python', then it prints out 'Cool!' # Hint - google python 'if' statement ### Learn More About Functions # https://automatetheboringstuff.com/chapter3/