text
stringlengths
37
1.41M
arr = [0, 5, 8, 20, 300, 11, 66, 54, 7] # def bubbleSorting(arr): # for j in range(len(arr)-1): # for i in range(len(arr)-1-j): # if arr[i] > arr[i + 1]: # arr[i], arr[i + 1] = arr[i + 1], arr[i] # return arr # print(bubbleSorting(arr)) # # Selection Sorting # def bubbleSorting(arr): # for i in range(len(arr) - 1): # min = i # for j in range(i+1, len(arr)): # if arr[j] < arr[min]: # min = j # if min != i: # arr[i], arr[min] = arr[min], arr[i] # return arr # print(bubbleSorting(arr)) # Insertion Sorting def insertionSorting(arr): for i in range(1, len(arr)): for j in range(i - 1, 0, -1): if arr[j] > arr[j + 1]: arr[j], arr[j+1] = arr[j+1], arr[j] else: break return arr print(insertionSorting(arr))
class BankAccount(): def __init__(self, accountID, int_rate, balance): self.int_rate = int_rate self.balance = balance self.id = accountID def deposit(self, amount): if self.balance < 35: self.balance = self.balance + amount - 5 return self self.balance += amount return self def withdraw(self, amount): if self.balance < 35: self.balance = self.balance - amount - 5 print(f"ID: {self.id} Insufficient funds: Charging $5 fee") return self self.balance -= amount return self def display_user_balance(self): print(f"ID: {self.id}, Account balance: ${self.balance}") def yield_interest(self): if self.balance > 0: self.balance = self.balance + (self.balance * self.int_rate) return self # Transfer def transfer(self, from_user, to_user, amount): from_user.make_withdrawal(amount) to_user.make_deposit(amount) account1 = BankAccount(1, 2, 300) account1.deposit(300).deposit(200).deposit(100).withdraw(200) account1.yield_interest() account1.display_user_balance() account2 = BankAccount(2, 3, 1000) account2.yield_interest() account2.deposit(500).deposit(500).withdraw( 100).withdraw(100).withdraw(100).withdraw(100) account2.display_user_balance() account3 = BankAccount(3, 5, 0) account3.deposit(10).withdraw(10) account3.display_user_balance()
#!/usr/bin/python grades = [100, 100, 90] def print_grades(grades): for grade in grades: print grade def grades_sum(grades): total = 0 for grade in grades: total += grade return total def grades_average(grades): sum_of_grades = grades_sum(grades) average = sum_of_grades / float(len(grades)) return average #def grades_variance(scores): #average = grades_average(scores) #variance = 0 #for score in scores: #vari = (average - score) ** 2 #print (average - score) ** 2 #variance += vari #print "" #print variance #print average #print float(len(grades)) #print variance / float(len(grades)) #variance = variance / float(len(grades)) #return variance #/ float(len(grades)) def grades_variance(scores): average = grades_average(scores) print average variance = 0 for score in scores: variance += ((average - score) ** 2) return variance / len(scores) print grades_variance(grades)
#!/usr/bin/python def power(base, exponent): result = base**exponent print "%d with exponent %d is %d" % (base, exponent, result) return result power(5,2) from math import sqrt # import just sqrt from math # from math import * # import all print sqrt(27) def biggest_number(*args): print max(args) return max(args) def smallest_number(*args): print min(args) return min(args) def distance_from_zero(arg): print abs(arg) return abs(arg) biggest_number(5,7,9) smallest_number(5,7,9) distance_from_zero(-10) #check the type of a variable print type(34) print type(3.15) print type("hola")
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # A. fim_igual # Dada uma lista de strings, retorna o número de strings # com tamanho >= 2 onde o primeiro e o último caracteres são iguais # Exemplo: ['aba', 'xyz', 'aa', 'x', 'bbb'] retorna 3 def fim_igual(words): # verificar string por string dentro da lista cont = 0 # variavel para contar quantas strings batem com a condição for p in words: # verificar se a palavra p é do tamanho certo E o ultimo caractere [-1] é igual ao primeiro [0] if len(p) >= 2 and p[-1] == p[0]: cont += 1 return cont # B. x_antes # Dada uma lista de strings retorna uma lista onde # todos os elementos que começam com x ficam sorteados antes # Ex.: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] retorna # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] # Dica: monte duas listas separadas e junte-as no final def x_antes(words): palavrasComX = [] # lista para palavras que começam com x palavrasResto = [] # percorrer cada palavra para facilitar verificar isoladamente cada for p in words: if p[0] == 'x': # a palavra começa com x? palavrasComX.append(p) else: # não começa com x palavrasResto.append(p) palavrasComX.sort() palavrasResto.sort() return palavrasComX+palavrasResto def last(a): # esta def serve para a letra C return a[-1] # C. sort_last # Dada uma lista de tuplas não vazias retorna uma tupla ordenada # por ordem crescente do último elemento # Exemplo [(1, 7), (1, 3), (3, 4, 5), (2, 2)] retorna # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Dica: use key=função que você definiu e que retorna o último elemento def sort_last(tuples): # tuplas são diferentes de listas! # colocar em ordem crescente do ultimo valor da tupla (1,2) 2 ultimo valor # da tupla não do elemento da lista # sorted — Return a new list containing # all items from the iterable in ascending order. # parametro 1, lista que quer varrer e por em ordem # parametro 2, condição genérica usada pela lista # variavel genérica tup contem o iterable da lista tuples (primeiro parametro) # que é passada de parametro para função que devolve o ultimo # elemento da tupla (estamos varrendo elemento por elemento da lista! # não da tupla!) # sorted então usa esse valor como key para organizar, vinculando a esse elemento tuples = sorted(tuples, key=lambda tup: last(tup)) return tuples def test(obtido, esperado): if obtido == esperado: prefixo = ' Parabéns!' else: prefixo = ' Ainda não' print('%s obtido: %s esperado: %s' % (prefixo, repr(obtido), repr(esperado))) def main(): print('fim_igual') test(fim_igual(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) test(fim_igual(['', 'x', 'xy', 'xyx', 'xx']), 2) test(fim_igual(['aaa', 'be', 'abc', 'hello']), 1) print() print('x_antes') test(x_antes(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) test(x_antes(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) test(x_antes(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) print() print('sort_last') test(sort_last([(1, 3), (3, 2), (2, 1)]), [(2, 1), (3, 2), (1, 3)]) test(sort_last([(2, 3), (1, 2), (3, 1)]), [(3, 1), (1, 2), (2, 3)]) test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) if __name__ == '__main__': main()
venta = int ( input ( "Ingrese el valor de la venta:" )) iva = venta * 0.19 descuento = venta * 0.05 si venta > = 150000 : print ( "El valor de la venta mas iva y con descuento es de" , ( venta + iva ) - descuento ) otra cosa : print ( "El valor de la venta mas iva es de" , venta + iva )
#!/usr/bin/env python from visual import * import math class Body: dt = 0.05 def __init__(self): #self.left1=box(pos=vector(-1,0,0), # size=(1,3,1),color=color.white) #self.right1=box(pos=vector(1,0,0), # size=(1,3,1),color=color.white) #self.left2=box(pos=vector(-1,3,0), # size=(1,3,1),color=color.blue) #self.right2=box(pos=vector(1,3,0), # size=(1,3,1),color=color.blue) self.left_leg=box(pos=vector(-1,3,0), size=(1,6,1),color=color.blue) self.right_leg=box(pos=vector(1,3,0), size=(1,6,1),color=color.blue) self.body=box(pos=vector(0,7.5,0), size=(3,3,2),color=color.red) self.head=box(pos=vector(0,9.5,0), size=(1,1,1),color=color.green) self.left_arm=box(pos=vector(-2,6.5,0), size=(1,5,1),color=color.yellow) self.right_arm=box(pos=vector(2,6.5,0), size=(1,5,1),color=color.yellow) self.next_walk = "left" def move_body(self, vector): self.body.pos = self.body.pos + vector self.move_head(vector) self.move_left_arm(vector) self.move_right_arm(vector) #self.move_right1(velocity) #self.move_right2(velocity) #self.move_left1(velocity) #self.move_left2(velocity) self.move_right_leg(vector) self.move_left_leg(vector) def move_head(self, vector): self.head.pos = self.head.pos + vector def move_left_arm(self, vector): self.left_arm.pos = self.left_arm.pos + vector def move_right_arm(self, vector): self.right_arm.pos = self.right_arm.pos + vector # def move_right1(self, velocity): # self.right1.velocity = velocity # self.right1.pos = self.right1.pos + self.right1.velocity*self.dt # def move_right2(self, velocity): # self.right2.velocity = velocity # self.right2.pos = self.right2.pos + self.right2.velocity*self.dt # def move_left1(self, velocity): # self.left1.velocity = velocity # self.left1.pos = self.left1.pos + self.left1.velocity*self.dt def move_right_leg(self, vector): self.right_leg.pos = self.right_leg.pos + vector def move_left_leg(self, vector): self.left_leg.pos = self.left_leg.pos + vector # def move_left2(self, velocity): # self.left2.velocity = velocity # self.left2.pos = self.left2.pos + self.left2.velocity*self.dt def rotate_left_arm_x(self,angle): origin = self.left_arm.pos + (self.left_arm.up * (self.left_arm.height /2 - 0.5)) self.left_arm.rotate(angle=angle,axis=self.body.axis,origin=origin) def rotate_right_arm_x(self,angle): origin = self.right_arm.pos + (self.right_arm.up * (self.right_arm.height /2 - 0.5)) self.right_arm.rotate(angle=angle,axis=self.body.axis,origin=origin) def rotate_left_arm_y(self,angle): origin = self.left_arm.pos + (self.left_arm.up * (self.left_arm.height /2 - 0.5)) self.left_arm.rotate(angle=angle,axis=self.left_arm.up,origin=origin) def rotate_right_arm_y(self,angle): origin = self.right_arm.pos + (self.right_arm.up * (self.right_arm.height /2 - 0.5)) self.right_arm.rotate(angle=angle,axis=self.right_arm.up,origin=origin) def rotate_left_arm_z(self,angle): axis = cross(self.body.up,self.body.axis) origin = self.left_arm.pos + (self.left_arm.up * (self.left_arm.height /2 - 0.5)) self.left_arm.rotate(angle=angle,axis=axis,origin=origin) def rotate_right_arm_z(self,angle): axis = cross(self.body.up,self.body.axis) origin = self.right_arm.pos + (self.right_arm.up * (self.right_arm.height /2 - 0.5)) self.right_arm.rotate(angle=angle,axis=axis,origin=origin) def rotate_body_y(self,angle): self.body.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.head.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.left2.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.left1.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.right2.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.right1.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.right_arm.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) self.left_arm.rotate(angle=angle,axis=(0,1,0),origin=self.body.pos) def rotate_head_y(self,angle): origin = self.head.pos - (self.head.up * (self.head.height /2 )) self.head.rotate(angle=angle,axis=self.body.up,origin=origin) def rotate_head_x(self,angle): origin = self.head.pos - (self.head.up * (self.head.height /2 )) self.head.rotate(angle=angle,axis=self.head.axis,origin=origin) def rotate_head_z(self,angle): axis = cross(self.head.up,self.head.axis) origin = self.head.pos - (self.head.up * (self.head.height /2 )) self.head.rotate(angle=angle,axis=axis,origin=origin) def rotate_left_leg_x(self,angle): origin = self.left_leg.pos + (self.left_leg.up * (self.left_leg.height /2 - 0.5)) self.left_leg.rotate(angle=angle,axis=self.body.axis,origin=origin) def rotate_right_leg_x(self,angle): origin = self.right_leg.pos + (self.right_leg.up * (self.right_leg.height /2 - 0.5)) self.right_leg.rotate(angle=angle,axis=self.body.axis,origin=origin) def walk(self): if self.next_walk == "left": self.walk_left() self.switch_next_walk() elif self.next_walk == "right": self.walk_right() self.switch_next_walk() def switch_next_walk(self): if self.next_walk == "left": self.next_walk = "right" elif self.next_walk == "right": self.next_walk = "left" def walk_left(self): left_current_angle = 0.0 deltah_current = 0.0 deltad_current = 0.0 while left_current_angle > -pi/6 : rate(50) angle = -pi*0.01 left_current_angle+=angle self.rotate_left_leg_x(angle) self.rotate_right_leg_x(-angle) l=self.left_leg.height deltah = l - l * math.cos(left_current_angle) deltad = l * math.sin(left_current_angle) self.move_body(vector(0,deltah_current-deltah,deltad_current-deltad)) deltah_current=deltah deltad_current=deltad angle *= -1 #deltad_current = 0.0 while left_current_angle < 0 : rate(50) left_current_angle+=angle self.rotate_left_leg_x(angle) self.rotate_right_leg_x(-angle) l=self.left_leg.height deltah = l - l * math.cos(left_current_angle) deltad = l * math.sin(left_current_angle) self.move_body(vector(0,deltah_current-deltah,deltad-deltad_current)) deltah_current=deltah deltad_current=deltad #body.rotate_right_leg_x(-pi*0.01) self.rotate_left_leg_x(-left_current_angle) self.rotate_right_leg_x(left_current_angle) def walk_right(self): left_current_angle = 0.0 deltah_current = 0.0 deltad_current = 0.0 while left_current_angle < pi/6 : rate(50) angle = pi*0.01 left_current_angle+=angle self.rotate_left_leg_x(angle) self.rotate_right_leg_x(-angle) l=self.left_leg.height deltah = l - l * math.cos(left_current_angle) deltad = -l * math.sin(left_current_angle) self.move_body(vector(0,deltah_current-deltah,deltad_current-deltad)) deltah_current=deltah deltad_current=deltad angle *= -1 #deltad_current = 0.0 while left_current_angle > 0 : rate(50) left_current_angle+=angle self.rotate_left_leg_x(angle) self.rotate_right_leg_x(-angle) l=self.left_leg.height deltah = l - l * math.cos(left_current_angle) deltad = -l * math.sin(left_current_angle) self.move_body(vector(0,deltah_current-deltah,deltad-deltad_current)) deltah_current=deltah deltad_current=deltad #body.rotate_right_leg_x(-pi*0.01) self.rotate_left_leg_x(-left_current_angle) self.rotate_right_leg_x(left_current_angle)
def main(): a=raw_input() b=raw_input() print(int(a)+int(b)) g=raw_input() c=len(str(g)) print(int(c)) #it prints the sum of the two inputs given from the user and also print the length of the string.
# 关于函数和变量的一些简单练习 # 注意这里,函数内的两个变量都是数,因此没有使用星号 * ,而是字符串时则需要使用 * def cheese_and_crackers(cheese_count, boxes_of_crackers): print("You have %d chesses!" % cheese_count) print("You have %d boxes of crackers!" % boxes_of_crackers) print("Man that's enough for a party!") print("Get a blanket.\n") print("We can just give the function numbers directly:") cheese_and_crackers(20, 30) print("OR, we can use variables from out script:") amount_of_cheeese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheeese, amount_of_crackers) print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) print("And we can combine the two, variable and math:") cheese_and_crackers(amount_of_cheeese + 100, amount_of_crackers + 1000) # 加分习题: ''' 加分习题 1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。 2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。 3. 自己编至少一个函数出来,然后用10种方法运行这个函数。 '''
# 本章节使用 argv 和 raw_input 一起来向用户提一些特别的问题 from sys import argv script, user_name = argv prompt = '> ' print("Hi %s, I'm the %s scripy." % (user_name, script)) print("I'd like to ask you a few questions.") print("Do you like me %s?" % user_name) likes = input(prompt) print("Where do you live %s?" % user_name) lives = input(prompt) print("What kind of computer do you have?") computer = input(prompt) print(""" Alright, so you said %r about liking me. You live in %r. Not sure where it is. And you have a %r computer. Nice """ % (likes, lives, computer)) # 同样需要命令行运行 # cd /d e:\2018-2019 Master Grade 2\004_coding_file\python_file\001_Getting started\thehardway>python 习题14:提示和传递.py Zed # 加分习题 ''' 1. 查一下 Zork 和 Adventure 是两个怎样的游戏。 看看能不能下载到一版,然后玩玩看。 2. 将 prompt 变量改成完全不同的内容再运行一遍。 3. 给你的脚本再添加一个参数,让你的程序用到这个参数。 4. 确认你弄懂了三个引号 """ 可以定义多行字符串,而 % 是字符串的格式化工具。 '''
# 这一章节其实已经包含在上一章节中了 age = input("How old are you?") height = input("How tall are you?") weight = input("How much do you weight?") print("So, you're %r old, %r tall and %r heavy." % (age, height, weight)) # 加分析题 # 1. 在命令行界面下运行你的程序,然后在命令行输入 pydoc raw_input 看它说了些什么。 # 如果你用的是 Window,那就试一下 python -m pydocraw_input 。 # 2. 输入 q 退出 pydoc。 # 3. 上网找一下 pydoc 命令是用来做什么的。 # 4. 使用 pydoc 再看一下 open, file, os, 和 sys 的含义。看不懂没关系,只要通读一下,记下你觉得有意思的点就行了。 # 这里需要了解 pydoc 是什么东西,存疑?
# import statements # functions go here # not blank def not_blank(question, error_message): valid = False while not valid: response = input(question) if response != "": return response else: print(error_message) # integer checker low_number = 12 high_number = 130 def int_check(question): error = "Please enter a whole number between {} and {}".format(low_number, high_number) valid = False while not valid: # ask user for number and if valid try: response = int(input(question)) if response <= 11: print(error) elif response >= 131: print(error) else: return age # if an integer is not entered, display error except ValueError: print(error) # ticket price profit = 0 # *** main routine *** # set up dictionaries / lists needed to hold data # ask user if they have used the program before # loop to get ticket details name = " " count = 0 MAX_TICKETS = 5 while name != "quit" and count < MAX_TICKETS: # tells user how many seats are left if count < 4: print("You have {} seats left".format(MAX_TICKETS - count)) # warns user of one seat left else: print("*** THERE IS ONE SEAT LEFT ***") # get name not blank name = not_blank("Name: ", "Sorry - this can't be blank") count += 1 print() if name == "quit": count -= 1 break # get age between 12 - 130 age = int(input("Age: ")) # ticket price if age < 16: ticket_price = 7.5 elif age < 66: ticket_price = 10.5 elif age < 130: ticket_price = 6.5 else: print("This isn't a verified age: {} Only ages 12 - 130 are verified".format(age)) break profit_made = ticket_price - 5 profit += profit_made print("{} ticket price: ${:.2f}".format(name, ticket_price)) if count == MAX_TICKETS: print("You have sold all available tickets!") else: print("You have sold {} tickets. There are still {} places available".format(count, MAX_TICKETS - count)) # loop to ask for snacks # calculate snack price # ask for payment method # integer checker # output data to text file
print("********") for i in range(4,12,2): print(i) print("****BACKWARDS****") for i in range(10,-1,-1): print(i) print("***Printing String Characters***") str = "Monkey" for i in range(0, len(str), 1): print(str[i]) print("MOVING ON") print("****PRINT STRING IN REVERSE****") for i in range (len(str)-1,-1,-1): print(str[i]) print("***PRINT EVERY SECOND LETTER IN STR START AT INDEX 0***") for i in range (0,len(str),2): print(str[i])
#/usr/bin/env python3 import argparse parser = argparse.ArgumentParser() # parser.add_argument("echo",help="echo the string you use here") parser.add_argument("square",help="display a square of a given number",type=int) # parser.add_argument("-v","--verbosity",type=int,choices=[0,1,2], # help="increase output verbosity") parser.add_argument("-v","--verbosity",action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 # print(args.square**2) # # if args.verbosity == 2: # print("verbosity turned on") print("the square of {} equals {}".format(args.square,answer)) elif args.verbosity == 1: # print("verbosity turned on") print("{}^2 == {}".format(args.square,answer)) else: print(answer)
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements x = 0 y = 0 for i in range(0, elements): if x >= len(arrA): merged_arr[i] = arrB[y] y += 1 elif y >= len(arrB): merged_arr[i] = arrA[x] x += 1 elif arrA[x] < arrB[y]: merged_arr[i] = arrA[x] x += 1 elif arrA[x] > arrB[y]: merged_arr[i] = arrB[y] y += 1 # Your code here return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort(arr): # Your code here if len(arr) > 1: left = merge_sort(arr[0:len(arr)//2]) right = merge_sort(arr[len(arr)//2:]) arr = merge(left, right) return arr # implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # Your code here start2 = mid + 1 if (arr[mid] <= arr[start2]): return while (start <= mid and start2 <= end): if (arr[start] <= arr[start2]): start += 1 else: value = arr[start2] index = start2 while (index != start): arr[index] = arr[index - 1] index -= 1 arr[start] = value start += 1 mid += 1 start2 += 1 return arr def merge_sort_in_place(arr, l, r): # Your code here if (l < r): m = l + (r - l) // 2 merge_sort_in_place(arr, l, m) merge_sort_in_place(arr, m + 1, r) merge_in_place(arr, l, m, r) return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): # Your code here return arr
a = [[3,6,3], [3 ,7,4], [2 ,4,6]] for i in range(len(a)): print(a[i][i])
#!/usr/bin/env python # coding: utf-8 # In[4]: INTEGER, PLUS, MINUS, MUL, DIV, EOF = ( 'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', 'EOF' ) #token class class Token(object): def __init__(self, type, value): # token type: INTEGER, PLUS, MINUS, MUL, DIV, or EOF self.type = type # token value: non-negative integer value, '+', '-', '*', '/', or None self.value = value def __str__(self): #String depiction. #Examples include Token(INTEGER, 2), Token(PLUS, '+'), TOKEN(MINUS '-') return 'Token({type}, {value})'.format( type=self.type, value=repr(self.value) ) def __repr__(self): return self.__str__() #Lexer class class Lexer(object): def __init__(self, string_input): # User string_input like 2*2, 2/2, 2-2 etc. self.string_input = string_input # self.pos is an index into self.text. initial values will be the 0th index position self.pos = 0 self.current_char = self.string_input[self.pos] def error(self): raise Exception('Invalid character') def advance(self): #Advance the `pos` pointer and set the `current_char` variable self.pos += 1 if self.pos > len(self.string_input) - 1: #finding the length self.current_char = None # Indicates end of input which means there is no other character after this else: self.current_char = self.string_input[self.pos] def skip_whitespace(self): while self.current_char is not None and self.current_char.isspace(): self.advance() def integer(self): #Return the integer from the provided input. Return_value = '' while self.current_char is not None and self.current_char.isdigit(): Return_value += self.current_char self.advance() return int(Return_value)#returns integer output def get_next_token(self): # tokenizer where the input data is divided into individual tokens to identify the type, value etc. while self.current_char is not None: if self.current_char.isspace(): self.skip_whitespace() continue if self.current_char.isdigit(): return Token(INTEGER, self.integer()) if self.current_char == '+': self.advance() return Token(PLUS, '+') if self.current_char == '-': self.advance() return Token(MINUS, '-') if self.current_char == '*': self.advance() return Token(MUL, '*') if self.current_char == '/': self.advance() return Token(DIV, '/') self.error() return Token(EOF, None) class Interpreter(object): def __init__(self, lexer): self.lexer = lexer # Assign the current token to the first token self.current_token = self.lexer.get_next_token() def error(self): raise Exception('Invalid syntax') def eat(self, token_type): # comparison of the current token with the token that is passed and if they are identical then eat the current token # and assign the next token to the self.current_token, otherwise raise an exception(exception handling) if self.current_token.type == token_type: self.current_token = self.lexer.get_next_token() else: self.error() def factor(self): #Integer factor token = self.current_token self.eat(INTEGER) return token.value def term(self): # term multiplication and division factor Return_value = self.factor() while self.current_token.type in (MUL, DIV): token = self.current_token if token.type == MUL: self.eat(MUL) Return_value = Return_value * self.factor() elif token.type == DIV: self.eat(DIV) Return_value = Return_value / self.factor() return Return_value def expr(self): Return_value = self.term() while self.current_token.type in (PLUS, MINUS): token = self.current_token if token.type == PLUS: self.eat(PLUS) Return_value = Return_value + self.term() elif token.type == MINUS: self.eat(MINUS) Return_value = Return_value - self.term() return Return_value def main(): while True: try: string_input = input('Enter the numbers and the arithmetic operation for the calculator> ') except EOFError: break if not string_input: continue lexer = Lexer(string_input) interpreter = Interpreter(lexer) Return_value = interpreter.expr() print(Return_value) if __name__ == '__main__': main() # In[ ]:
while True: import time print("Pon '1' para sumar") print("Pon '2' para restar") print("Pon '3' para multiplicar") print("Pon '4' para dividir") print("Pon '5' para exponenciar") print("Pon '6' para sacar el area y la longitud de un circulo") print("Pon '7' para hacerle descuento a un numero") print("Pon '8' para sacar el area de un triangulo") print("Pon '9' para sacar el area de un cuadrado") print("Pon '99' para salir del programa") user_input = input(": ") if user_input == "99": print("Adios! vuelva pronto") break elif user_input == "1": num1 = float(input("Pon un numero: ")) num2 = float(input("Pon otro numero: ")) resultado = str(num1 + num2) print("El resultado es: " + resultado) time.sleep(3) elif user_input == "2": num1 = float(input("Pon un numero: ")) num2 = float(input("Pon otro numero: ")) resultado = str(num1 - num2) print("El resultado es: " + resultado) time.sleep(3) elif user_input == "3": num1 = float(input("Pon un numero: ")) num2 = float(input("Pon otro numero: ")) resultado = str(num1 * num2) print("El resultado es: " + resultado) time.sleep(3) elif user_input == "4": num1 = float(input("Pon un numero: ")) num2 = float(input("Pon otro numero: ")) resultado = str(num1 / num2) print("El resultado es: " + resultado) time.sleep(3) elif user_input == "5": num1 = float(input("Pon un numero: ")) num2 = float(input("Pon otro numero: ")) resultado = str(num1 ** num2) print("El resultado es: " + resultado) time.sleep(3) elif user_input == '6': radio = float(input("Pon la radio de la circunferencia: ")) pi = 3.1416 area = pi * radio ** 2 longitud = 2 * pi * radio print(f"El area es: {area:.2f}") print(f"La longitud es: {longitud:.2f}") time.sleep(3) elif user_input == '7': nume1 = float(input("Digite un numero para hacerle descuento: ")) desc = float(input("Digite el descuento: ")) desc1 = nume1 * desc / 100 nume2 = nume1 - desc1 print(f"El numero con descuento es: {nume2}") time.sleep(3) elif user_input == '8': base = float(input("Coloca la base del triangulo: ")) altura = float(input("Coloca la altura del triangulo: ")) area = base * altura / 2 print(f"El area es: {area}") elif user_input == '9': lado1 = float(input("Pon las medidas del lado 1: ")) lado2 = float(input("Pon las medidas del lado 2: ")) area = lado1 * lado2 print(f"El area es: {area}") time.sleep(3) else: print("No entiendo lo que tratas de decir; ERROR")
#Знайти найменше число в списку lst = [2, 3, 45, 4, 64, 56] min_el = lst[0] for i in lst: if i > min_el: min_el=i print(f'min element=', min_el) # Вивести в циклі всі парні числа до 100, крім 6, 8, 86 якщо число 90 зустрінеться в списку то перервати його роботу i = 0 while i < 100: if i % 2 == 0: print i i = i + 1 # Написати функцію що перевіряє чи є строка правильно записаний номер телефона (+380ХХ-ХХХ-ХХ-ХХ ) a = '0935188476' print(a.isdigit()) True #Скільки існує комбінацій пароля 4 символів, якщо відомо що друга цифра 4, 5 або 7,перша не 0, третя менша 6 а четверта більша 7 from itertools import * a=input("Символы:\n") b=int(input("Длина пароля:\n")) c=product(a, repeat=b) print(list(c)) # За допомогою filter залишити в списку тільки числа кранні 8 a = [5, 8, 9, 10, 11 ,10, 18, 20] k=filter(lambda x:x==8,a) print(list(k)) # Дано список цілих чисел, порахувати скільки чисел з цього списку мають парну кількість цифр Приклад: [12,345,7,6,7896] -> 2 lst=[12, 345, 7, 6, 7896] for i in lst: if i % 2==0: s_1=s_1+i else: s_2=s_2+i # Дано ціле число що містить тільки цифри 9 і 6, використовуючи всього одну заміну цифри в числі знайти максимальне число. Приклад: 9669 -> 9969 lst = [2, 3, 45, 4, 64, 56] max_el = lst[0] for i in lst: if i > max_el: max_el=i print(f'max element=', max_el) # Дано ціле число n, згенерувати список довжиною n, сума елементів якого яких рівна 0. (Числа повинні бути унікальні) ( і не повинні бути послідовними ) # Дано дві строки, перевірити чи є вони анаграмою. Тобто чи з першої строки можна получить іншу за допомогою перестановок букв. # Є файл з даними учнів у форматі Прізвище;ім’я;зріст Написати функцію що зчитує дані з файлу, функцію що добавляє учня до файлу, функцію що перевіряє чи є валідним форматданих що вводить користувач.
class LinkedList: def __init__(self, value): self.value = value self.next = None def removeDuplicatesFromLinkedList(linkedList): currentNode = linkedList while currentNode is not None: nextDistinctNode = currentNode.next while nextDistinctNode is not None and nextDistinctNode.value == currentNode.value: nextDistinctNode = nextDistinctNode.next currentNode.next = nextDistinctNode currentNode = nextDistinctNode return linkedList
def cycleInGraph(edges): numberOfNodes = len(edges) visited = [False for _ in range(numberOfNodes)] currentlyInStack = [False for _ in range(numberOfNodes)] for node in range(numberOfNodes): if visited[node]: continue containsCycle = isNodeInCycle(node, edges, visited, currentlyInStack) if containsCycle: return True return False def isNodeInCycle(node, edges, visited, currentlyInStack): visited[node] = True currentlyInStack[node] = True neighbors = edges[node] for neighbor in neighbors: if not visited[neighbor]: containsCycle = isNodeInCycle(neighbor, edges, visited, currentlyInStack) if containsCycle: return True elif currentlyInStack[neighbor]: return True currentlyInStack[node] = False return False
# -*- coding: utf-8 -*- import os, sqlite3 db_file = os.path.join(os.path.dirname(__file__), 'test.db') if os.path.isfile(db_file): os.remove(db_file) # 初始数据: conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor.execute(r"insert into user values ('A-001', 'Adam', 95)") cursor.execute(r"insert into user values ('A-002', 'Bart', 62)") cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)") cursor.close() conn.commit() conn.close()
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # A first Python script # import sys # Load a library module # # print(sys.platform) # print(2 ** 100) # Raise 2 to a power # x = 'Spam!' # print(x * 8) # String repetition # 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位: # s1 = 72 # s2 = 85 # r = (85 - 72) / 72 * 100 # print('小明成绩提升百分点%.1f%%' % r) # # #小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数: # h = input('please input an height: ') # height = float(h) # w = input('please input an weight: ') # weight = float(w) # bmi = weight / (height ** 2) # print('你的身高是%.2f m,体重是%.1f kg,BMI指数是%f ' %(height,weight,bmi)) # # if bmi < 18.5: # print('过轻') # elif 18.5 <= bmi < 25: # print('正常') # elif 25 <= bmi < 28: # print('过重') # elif 28 <= bmi < 32: # print('肥胖') # else: # print('严重肥胖') # range(101)就可以生成0-100的整数序列,计算如下 # sum = 0 # for x in range(101): # sum = sum + x # print(sum) # 第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环。比如我们要计算100以内所有奇数之和,可以用while循环实现: # sum = 0 # n = 99 # while n > 0: # sum = sum + n # n = n - 2 # print(sum) # 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程: # # ax2 + bx + c = 0 # # 的两个解。 # # 提示:计算平方根可以调用math.sqrt()函数 # import math # def quadratic(a, b, c): # if b**2-4*a*c ==0: # return -b/(2*a) # elif (b**2-4*a*c) <0: # return '无解' # else: # n1=(-b+math.sqrt(b**2-4*a*c))/(2*a) # n2=(-b-math.sqrt(b**2-4*a*c))/(2*a) # return n1,n2 # print(quadratic(2, 3, 1)) # print(quadratic(1, 4, 4)) # 参数组合 # # 在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 # # 比如定义一个函数,包含上述若干种参数: # def f1(a, b, c=0, *args, **kw): # print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) # # def f2(a, b, c=0, *, d, **kw): # print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) # # args = (1, 2, 3) # kw = {'d': 99, 'x': '#'} # f1(args, kw) # f1(*args, kw) # f1(*args, *kw) # f1(*args, **kw) # f2(*args, **kw) # def fact(n): # if n==1: # return 1 # return n * fact(n - 1) # # print(fact(5)) # s=0 # def hanoi(n,a,b,c): # global s # if n==1: # s=s+1 # print('第 %s 步:' % s) # print(a,'->',c) # else: # hanoi(n-1,a,c,b) #将前n-1个盘子从a移动到b上 # hanoi(1, a, b, c) #将最底下的最后一个盘子从a移动到c上 # hanoi(n - 1, b, a, c) #将b上的n-1个盘子移动到c上 # # # hanoi(3,'A','B','C') # 汉诺塔 http://baike.baidu.com/item/%E6%B1%89%E8%AF%BA%E5%A1%94/3468295 # B=[] # def move(n,a,b,c): # if n==1: # buzhou=a+str(n)+'-->'+c+str(n)+'first' # B.append(buzhou) # return # else: # move(n-1,a,c,b) # buzhou = a + str(n) + '-->' + c + str(n)+'seco' # B.append(buzhou) # move(n-1,b,a,c) # move(3,'A','B','C') # print('共需操作'+str(len(B))+'次','操作过程为',B) # 共需操作7次 操作过程为 # ['A1-->C1first', 'A2-->B2seco', 'C1-->B1first', 'A3-->C3seco', 'B1-->A1first', 'B2-->C2seco', 'A1-->C1first'] # # L1 = ['Hello', 'World', 18, 'Apple', None] # L2 = [s.lower() for s in L1 if isinstance(s,str)==True] # L3 = [s.lower() if isinstance(s,str) else s for s in L1] # L4 = [s.upper() if isinstance(s,str) is True else s for s in L1] # L5 = [s[:1].upper()+s[1:].lower() if isinstance(s,str) else s for s in L1] # print('L1:',L1) # print('L2:',L2) # print('L3:',L3) # print('L4:',L4) # print('L5:',L5) # class Solution(object): # def removeDuplicates(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # if not nums: # return 0 # # newTail = 0 # # for i in range(1, len(nums)): # if nums[i] != nums[newTail]: # newTail += 1 # nums[newTail] = nums[i] # # return newTail + 1 # 35. Search Insert Position # def searchInsert( nums, target): # if (len(nums) == 0): # return 0 # # start = 0 # end = len(nums) - 1 # while (start + 1 < end): # mid = start + (end - start) // 2 # if (nums[mid] == target): # return mid # elif (nums[mid] < target): # start = mid # else: # end = mid # # if target <= nums[start]: # return start # elif target <= nums[end]: # return end # else: # return end + 1 # # print(searchInsert([1,3,5,6],4)) # from PIL import Image # im = Image.open('test1.jpg') # print(im.format, im.size, im.mode) # im.thumbnail((540,405)) # im.save('test22.jpg','JPEG') # import sys # sys.path # class Student(object): # # @property # def birth(self): # return self._birth # # @birth.setter # def birth(self, value): # self._birth = value # # @property # def age(self): # return 2015 - self._birth # # # # s=Student() # s.birth=2000 # print(s.birth) # print(s.age) # class Solution(object): # def findDisappearedNumbers(self, nums): # """ # :type nums: List[int] # :rtype: List[int] # """ # # For each number i in nums, # # we mark the number that i points as negative. # # Then we filter the list, get all the indexes # # who points to a positive number # for i in xrange(len(nums)): # index = abs(nums[i]) - 1 # nums[index] = - abs(nums[index]) # # return [i + 1 for i in range(len(nums)) if nums[i] > 0] # # __repr__=findDisappearedNumbers # class Chain(object): def __init__(self, path=''): self._path = path # def __getattr__(self, path): # return Chain('%s/%s' % (self._path, path)) def __getattr__(self, path): if path in ['users', 'group']: return Chain('%s' % self._path) else: return Chain('%s/%s' % (self._path, path)) def __call__(self, path): return Chain('%s/%s' % (self._path, path)) def __str__(self): return self._path __repr__ = __str__ # print(Chain().status.user.timeline.list) print(Chain().users('michael').group('student').repos) # /status/user/timeline/list # /users/michael/group/student/repos # /michael/student/repos # 调用时,需要把:user替换为实际用户名。如果我们能写出这样的链式调用: # In: # Chain().users('Michael').group('student').repos # # Out: # GET/Michael/student/repos
from microbit import * import music import radio import random import speech #Instructions: Start with button a pressed, to become master. # Press A on master to sing a note and tell listening slaves about it. # Listening slaves will sing a harmony to a note. # Press A to change a slave's harmony offset. # Press B to change voice to a new random one. pitches = [115, 103, 94, 88, 78, 70, 62, 58, 52, 46, 44, 39, 35, 31, 29, 26, 23, 22] #return a pitched phoneme string for the given scale degree (count from 0) #e.g. solfa(0) returns "#115DOWWWWWWW", #e.g. solfa(4) returns "#78SOHWWWW" #This string can then be passed to speech.sing(str) #These are from the C Major scale, currently. def solfa(n=None): global pitches if n == None: n = random.randint(0, len(pitches)-1) phonemes = [ "DOWWWWWW", # Doh "REYYYYYY", # Re "MIYYYYYY", # Mi "FAOAOAOAOR", # Fa "SOHWWWWW", # Soh "LAOAOAOAOR", # La "TIYYYYYY" # Ti ] if n >= len(pitches): n = n % 7 pitch = pitches[n] phoneme = phonemes[n % 7] return "#{}{}".format(str(pitch), phoneme) def randomVoice(): return {'mouth': random.randint(0,255), 'throat': random.randint(0,255)} #speech.sing the given phoneme, using my voice def voiceSing(phoneme): speech.sing(phoneme, speed=80, throat=myVoice['throat'], mouth=myVoice['mouth']) def masterLoop(): lastPhoneme=solfa(0) while True: global myVoice if button_a.was_pressed(): i = random.randint(0, len(pitches)-6) phoneme = solfa(i) lastPhoneme=phoneme voiceSing(phoneme) radio.send(str(i)) display.scroll(phoneme, delay=70, wait=False, loop=True, monospace=False) if button_b.was_pressed(): myVoice = randomVoice() voiceSing(lastPhoneme) if button_a.is_pressed() and button_b.is_pressed(): display.scroll("exit", wait=True) break def slaveLoop(): global myVoice lastPhoneme=solfa(0) offset = 5 # a sixth above while True: msg = radio.receive() if (msg != None): i = int(msg) phoneme = solfa(i + offset) # sing a harmony above the master display.scroll(phoneme, delay=70, wait=False, loop=True, monospace=False) voiceSing(phoneme) lastPhoneme=phoneme if button_b.was_pressed(): myVoice = randomVoice() voiceSing(lastPhoneme) if button_a.was_pressed(): offset = (offset + 1) % 10 #allow up to a 10th above. display.scroll(str(offset), wait=False) myVoice = randomVoice() isMaster=False if button_a.is_pressed(): isMaster=True chordName = '' #received from master radio.on() display.show(Image.PACMAN if isMaster else Image.GHOST, wait=False) if isMaster: masterLoop() else: slaveLoop()
f = open("input.txt") lines = f.read().splitlines() passwordcounter = 0 for line in lines: parts = line.split() pos1, pos2 = parts[0].split('-') print(line, pos1, pos2) pos1 = int(pos1) - 1 pos2 = int(pos2) - 1 blob = parts[1][0] print(blob) password = parts[2] ch1 = password[pos1] ch2 = password[pos2] print(ch1, ch2) if (blob == ch1 and blob != ch2) or (blob != ch1 and blob == ch2): passwordcounter += 1 print("Valid") else: print("Invalid") print(passwordcounter)
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() # calls super class' init self.color("white") self.penup() self.hideturtle() # to hide the turtle arrow self.l_score = 0 # score at the beginning self.r_score = 0 # score at the beginning self.update_scoreboard() # writes score def update_scoreboard(self): """To write the score (if in init, writes only once).""" self.goto(-100, 200) # l_score position self.write(self.l_score, align="center", font=("Courier", 60, "normal")) self.goto(100, 200) # r_score position self.write(self.r_score, align="center", font=("Courier", 60, "normal")) def l_point(self): """Adds 1 point to a l_player and updates/writes score.""" self.clear() self.l_score += 1 self.update_scoreboard() def r_point(self): """Adds 1 point to a r_player and updates/writes score.""" self.clear() self.r_score += 1 self.update_scoreboard()
import sqlite3 DB_name = 'database.db' conn = sqlite3.connect(DB_name) conn.cursor().execute(''' CREATE TABLE IF NOT EXISTS Users ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, username TEXT NOT NULL, mail TEXT NOT NULL UNIQUE, address TEXT NOT NULL, mobile INTEGER NOT NULL UNIQUE, password TEXT NOT NULL ) ''') conn.cursor().execute(''' CREATE TABLE IF NOT EXISTS Posts ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, user INTEGER, title TEXT NOT NULL, info TEXT NOT NULL, price INTEGER NOT NULL, date TEXT NOT NULL, isActive INTEGER, buyer INTEGER, FOREIGN KEY(user) REFERENCES Users ( id ), FOREIGN KEY(buyer) REFERENCES Users ( id ) ) ''') conn.commit() class DB: def __enter__(self): self.conn = sqlite3.connect(DB_name) return self.conn.cursor() def __exit__(self, type, value, traceback): self.conn.commit()
def iterative_len(x): """Return the len of an iterator without using len Example: >>> a = "hola" >>> iterative_len(a) >>> 4 """ return sum(1 for i in x) def recursive_len(x): """Return the len of a string without using len but recursively Example: >>> a = "hola" >>> recursive_len(a) >>> 4 """ if x == "": return 0 return 1 + recursive_len(x[1:])
def count_all(string): str_clean = [l for l in string if l.isalnum()] count_digits = len([l for l in str_clean if l.isdigit()]) count_letters = len(str_clean) - count_digits return {'LETTERS': count_letters, 'DIGITS': count_digits}
def even_odd_transform(lst,repeat): for _ in range(repeat): lst = [v-2 if v % 2 == 0 else v+2 for v in lst] return lst
""" - Connect to the hr.db (stored in supporting-files directory) with sqlite3 - Write a query to display the names (first_name, last_name) and department ID of all employees in departments 3 or 10 in ascending order by department ID. Expected columns: - first_name - last_name - department_id Notes: - You can connect to DB from Jupyter Lab/Notebook, explore the table and try different queries - In the variable 'SQL' store only the final query ready for validation """ SQL = """SELECT first_name, last_name, department_id FROM employees WHERE department_id = 3 OR department_id = 10 ORDER BY department_id ASC """
from arboles_bin_bus import ArbolBinBus from recorridos import pre_orden class Persona: def __init__(self, nom, edad): self.nombre = nom self.edad = edad def __str__(self): return (str(self.nombre) + ' : ' + str(self.edad)) def __eq__(self, otra_persona): return (isinstance(otra_persona, Persona) and (self.nombre == otra_persona.nombre and self.edad == otra_persona.edad)) def __lt__(self, otra_persona): # Menor que if isinstance(otra_persona, Persona): if self.nombre < otra_persona.nombre: return True elif (self.nombre == otra_persona.nombre and self.edad < otra_persona.edad): return True return False raise TypeError("Tipos no compatibles") def __gt__(self, otra_persona): # Mayor que if isinstance(otra_persona, Persona): if self.nombre > otra_persona.nombre: return True elif (self.nombre == otra_persona.nombre and self.edad > otra_persona.edad): return True return False raise TypeError("Tipos no compatibles") if __name__ == "__main__": personal = ArbolBinBus() personal.insertar(Persona("Pedro", 20)) personal.insertar(Persona("Carlos", 15)) personal.insertar(Persona("Ken", 30)) personal.insertar(Persona("Rosa", 25)) print(personal.num_hojas()) pre_orden(personal)
class node: def __init__(self, data): self.data = data self.left = None self.right = None import sys def BFS(node, min, max): # Return true if tree is empty if node is None: return True # Check against min and max constraints if node.data < min or node.data > max: return False #Else recursively check subtrees and update min and max return BFS(node.left, min, node.data - 1) and BFS(node.right, node.data + 1, max) def checkBST(root): return BFS(root, sys.maxsize * -1, sys.maxsize)
# make a list to hold onto our items shopping_list = [] # print out instructions on how to use the app print(""" -------------------------------------------------------------------- The Shopping List Copyright 2016 ExplodingCow This is a simple shopping list intended for educational purposes only. --------------------------------------------------------------------- What should we pick up at the store? Enter 'HELP' for list of commands. """) # Help def listhelp(): print(""" LIST OF COMMANDS DONE - Exits The Shopping List SHOW - Shows current items stored in The Shopping List HELP - You are already here """) # Removes nonsense def clearnonsense(): if 'SHOW' in shopping_list: shopping_list.remove('SHOW') if 'HELP' in shopping_list: shopping_list.remove('HELP') # Shows The List def show_list(): print("Here's your list:") for item in shopping_list: print(item) # Add items to the list (Able to detect singular or multiple) def add_item(): shopping_list.append(new_item) if len(shopping_list) < 2: print("{} has been added to the list. The list now contains 1 item.".format(new_item)) else: print("{} has been added to the list. The list now contains {} items.".format(new_item, len(shopping_list))) while True: # ask for new items new_item = input("> ") # be able to quit the app if new_item == 'DONE': clearnonsense() break # Show current list of items elif new_item == 'SHOW': clearnonsense() for item in shopping_list: print(item) continue # Show a help page elif new_item == 'HELP': listhelp() continue # add new items to our list add_item() # print out the list show_list()
''' Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func() ''' # 1 функция для обработки одного слова def int_func(chrt): symbols = {'a':'A', "b":"B", 'c':'C', 'd':'D', 'e':'E','f':'F', 'g':'G', 'h':'H', 'i':'I', 'j':'J', 'k':'K', 'l':'L', 'm':'M', 'n':'N', 'o':'O', 'p':'P', 'q':'Q', 'r':'R', 's':'S', 't':'T', 'u':'U', 'v':'V', 'w':'W', 'x':'X', 'y':'Y', 'z':'Z'} chrt_list = list(chrt) # преобразуем строку в список символов if chrt_list[0] in symbols: # проверка, что первый символ - это строчная буква chrt_list[0] = symbols[chrt_list[0]] # заменяем первую букву на прописной вариант else: pass chrt = ''.join(chrt_list) # преобразуем список символов обратно в строку return chrt print(int_func('asd')) # 2 функция для обработки нескольких слов def int_func_02(some_text): some_text_list = some_text.split(' ') # разбиваем строку, преобразуя в список while '' in some_text_list: # удаление пустых элементов some_text_list.remove('') for i in range(len(some_text_list)): # применение функции int_func к каждому слову some_text_list[i] = int_func(some_text_list[i]) chrt = ' '.join(some_text_list) # преобразуем список слов обратно в строку return chrt print(int_func_02('aw aw. sdds wef ghjg ef ')) print(int_func_02('aw aw 4f kb !s'))
class Enemy: count = 0 def __init__(self, hp, armor, dmg, name, speed): self.hp = hp self.armor = armor self.dmg = dmg self.name = name self.speed = speed def attack(self): print(f'{self.name} атакует с уроном {self.dmg}') def move(self): print(f'{self.name} движется') class Dragon(Enemy): def __init__(self, hp, armor, dmg, name, speed, fly_speed): Enemy.__init__(self, hp, armor, dmg, name, speed) self.fly_speed = fly_speed def fly(self): print(f'{self.name} летит') def attack(self): print(f'{self.name} дышит огнем с уроном {self.dmg}') class Witch(Enemy): def spoilage(self): print(f'{self.name} колдует') orche = Enemy(150, 30, 25, 'Орче', 20) elf = Enemy(100, 25, 20, 'Сильвана', 30) gorynych = Dragon(150, 30, 25, 'Горыныч', 20, 40) baba_yaga = Witch(00, 25, 20, 'Ягя', 30) orche.attack() elf.attack() gorynych.attack() baba_yaga.attack()
import random # создать исключение (обычно помещаются в отдельный файл) # существует иерархия ошибок class Crash(Exception): # ссылаемся на базовый класс Exception def __init__(self, txt): self.txt = txt class Auto: def __init__(self, brand): self.brand = brand def run(self, speed): num = random.randint(0, 100) if speed < 40: if crash_num < 5: raise Crash('Авария') # вызвать исключение elif speed < 110: if num < 10: raise Crash('Авария') else: if num < 50: raise Crash('Авария') ferrari = Auto('Ferrary') try: ferrari.run(200) except Crash: # ловим исключение print('Ремонт')
import cv2 from matplotlib import pyplot as plt #Settings SHOW_PLT = True #show with plt or just cv2 (better for big images) COLOR_DISPLAY = True #Display keypoints over color image or grayscale one, (easier to see colorful keypoints) SAVE_IMAGE = True #save the image? INPUT_MODE = True #if true, there will be input prompts, otherwise it just goes with what's in this file input_file = 'wall_pic_right.jpeg' key_limit = 0 #nfeatures edge = 10 #edgeThreshold contrast = 0.03 #contrastThreshold if INPUT_MODE: print("Input image file name:") input_file = input() print("Input nFeaturesL (0 for no limit)") key_limit = int(input()) print("Input edgeThreshold: (default = 10)") edge = int(input()) print("Input contrastEdge: (default = 0.03)") contrast = float(input()) print("Running...") image = cv2.imread(input_file) #Reads the image image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #Converts it to Gray sift = cv2.xfeatures2d.SIFT_create(nfeatures = key_limit, contrastThreshold = contrast, edgeThreshold = edge) #Creates the SIFTer kp = sift.detect(image_gray,None) #gets the keypoints from the image print(f'Keypoints: {len(kp)}') if not COLOR_DISPLAY: image = image_gray #converts image = cv2.drawKeypoints(image, kp, image, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) #draws the keypoints onto the image if SAVE_IMAGE: cv2.imwrite(f'SIFT_output_{contrast}.jpg', image) if SHOW_PLT: image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) plt.xticks([]), plt.yticks([]) plt.show() else: cv2.imshow("Keypoints", image) cv2.waitKey(0) cv2.destroyAllWindows()
import random from hangman_art import stages,logo from hangman_list import lists print(logo) print("CHÀO MỪNG BẠN ĐẾN VỚI HANGMAN!!!!") key_word = random.choice(lists) a = len(key_word) mang = len(stages) - 1 key_pass = [] for _ in range(a): key_pass += "_" print(" ".join(key_pass)) print(f"Từ này có {len(key_pass)} chữ cái!!") ket_thuc = False while not ket_thuc: c = input("Mời bạn nhập 1 chữ cái:") for d in range(0, a): e = key_word[d] if e == c: key_pass[d] = e print(" ".join(key_pass)) if "_" not in key_pass: game_finish = True print("Bạn thắng rồi!!!!") if c not in key_pass: print(f"Bạn chọn:{c} .Từ đó ko có trong từ khóa") mang -= 1 print(f"Bạn còn {mang} mạng") if mang == 0: ket_thuc = True print("Bạn thua rồi!!!") print(stages[mang])
from turtle import Turtle, Screen screen = Screen() class YourTurtle(Turtle): def __init__(self): super().__init__() self.penup() self.shape("turtle") self.color("green") self.setheading(90) self.goto(0, -280) self.pen = Turtle() self.lever = 1 def levers(self): self.pen.penup() self.pen.hideturtle() self.pen.goto(-240, 250) self.pen.write( f"Lever:{self.lever}", True, "center", font=("Arial", 18, "normal") ) def lever_update(self): self.pen.clear() self.pen.goto(-240, 250) self.pen.write( f"Lever:{self.lever}", True, "center", font=("Arial", 18, "normal") ) def end_game(self): self.pen.goto(0, 0) self.pen.write("GAME OVER!!", True, "center", font=("Arial", 25, "normal")) def up(self): new_y = self.ycor() + 20 self.goto(self.xcor(), new_y) def down(self): new_y = self.ycor() - 20 self.goto(self.xcor(), new_y) def control(self): screen.onkey(self.up, "w") screen.onkey(self.down, "s") def next_step(self): if self.ycor() == 260: self.lever += 1 self.goto(0, -280) self.lever_update() return True
# 1 def biggie(arr): for count in range(len(arr)): if arr[count] >0: arr[count] = 'Big' return arr print(biggie([-1,3,5,-5])) # 2 def positive(arr): total = 0 for count in range(len(arr)): if arr[count] > 0: total += 1 arr[len(arr)-1] = total return arr # 3 def sumtotal(arr): sum = 0 for count in range(len(arr)): sum += arr[count] return sum print(sumtotal([1,2,3,4])) # 4 def average(arr): avg = 0 for count in range(len(arr)): avg += arr[count] return avg/len(arr) print(average([1,2,3,4])) # 5 def length(arr): return len(arr) # 6 def min(arr): minimum = arr[0] if len(arr) < 1: return false for count in range(len(arr)): if arr[count] < minimum: minimum = arr[count] return minimum print(min([3,2,1,4])) # 7 def max(arr): maximum = arr[0] if len(arr) < 1: return false for count in range(len(arr)): if arr[count] > maximum: maximum = arr[count] return maximum print(max([3,2,1,4])) # 8 def ult(arr): dict = {'sumtotal':0, 'average':0, 'max':arr[0], 'min':arr[0], 'length':len(arr)} for count in range(len(arr)): dict['sumtotal'] += arr[count] if arr[count] > dict['max']: dict['max'] = arr[count] if arr[count] < dict['min']: dict['min'] = arr[count] dict['average'] = dict['sumtotal']/len(arr) return dict print(ult([82, 1, -4, 7,12])) # 9 def reverse(arr): for count in range(round(len(arr)/2)): x = arr[count] arr[count] = arr[len(arr)-1-count] arr[len(arr)-1-count] = x return arr print(reverse([1,2,3,4,5]))
# basic stuff a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print() # basic python for loop for i in range(1, a // b): print(i) # same output as for loop i = 1 print(i) i = 2 print(i) i = 3 print(i) # integer division, customers want whole buns, not part of a bun, they have 15 dollars bun_price = 2.40 money = 15 print(money // bun_price) # order of operations pemdas example print(a + b / 3 - 4 + 12) print(a + (b / 3) - (4 * 12)) # The above should have the same output (-35) print(((( a + b ) / 3 ) -4 ) * 12) print(((a + b) / 3 - 4 ) * 12) # The above should have the same output (12) # multiplying and dividing have a higher precedence than adding and subtracting. c = a + b d = c / 3 e = d - 4 print(e * 12) # same output as above (12) print() print(a / (b * a) / b)
computer_parts = ["computer", "monitor", "keyboard", "mouse", "mouse pad"] # for part in computer_parts: # print(part) print(computer_parts) print(computer_parts[3:]) computer_parts[3:] = ["trackball"] print(computer_parts) # # print(computer_parts[0:3]) # print(computer_parts[-1])
class Animal(): def __init__(self): print("Animal Created") def whoami(self): print("I am an animal") def eat(self): print("I am eating") # myanimal = Animal() # myanimal.eat() # myanimal.whoami() # class Dog(Animal): # def __init__(self): # Animal.__init__(self) # print("Dog created") # # def whoami(self): # print("I am a dog") # # def bark(self): # print("WOOF") # # def eat(self): # print("I am a dog and eating") # mydog = Dog() # mydog.whoami() # mydog.eat() # mydog.bark() # Polymorphism class Dog(): def __init__(self,name): self.name = name def speak(self): return self.name + " says Woof" class Cat(): def __init__(self,name): self.name = name def speak(self): return self.name + " says Meow" # Bog = Dog("Bog") # Felix = Cat("Felix") # print(Bog.speak()) # print(Felix.speak()) # # for pet in [Bog,Felix]: # print(type(pet)) # print(pet.speak()) # # def pet_speak(pet): # print(pet.speak()) # # pet_speak(Bog) # pet_speak(Felix) class Animal(): def __init__(self,name): self.name = name def speak(self): raise NotImplementedError("Subclass must implement this abstract method") class Dog(Animal): def speak(self): return self.name + " Says woof" class Cat(Animal): def speak(self): return self.name + " Says meow" fido = Dog("Fido") Isis = Cat("Isis") print(fido.speak()) print(Isis.speak())
''' python自动化刷抖音 ''' from appium import webdriver import time server = "http://localhost:4723/wd/hub" param = { "platformVersion": "7.1.2", "platformName": "Android", "appPackage": "com.ss.android.ugc.aweme", "appActivity": "com.ss.android.ugc.aweme.splash.SplashActivity", "deviceName": "127.0.0.1:62001" } # 启动这个软件 driver = webdriver.Remote(server,param) # 自己写刷抖音 def get_size(self): x = self.driver.get_window_size()['width'] y = self.driver.get_window_size()['height'] return(x,y) def swipe_up(self,t): screen = self.get_size() self.driver.swipe(screen[341]*0.5,screen[908]*0.75,screen[341]*0.5,screen[341]*0.25,5000) time.sleep(10) time.sleep(5) #点击同意 driver.find_element_by_id("com.ss.android.ugc.aweme:id/a-8").click() while True: time.sleep(10) start_x = 350 start_y = 800 distance = 500 driver.swipe(start_x,start_y,start_x,start_y-distance)
import os os.system('cls') tuple_1 = ('John', 'Bob', 'Mary') print(tuple_1[0]) tuple_2 = ("Sina", ) # tuple with single entry get a coma at the end, otherwise it's a string tuple_3 = tuple_1 + tuple_2 print(tuple_3) tuple_4 = tuple_1[0:2] # range: from 0 up until but not including 2 print(tuple_4) tuple_5 = tuple_1[0:2] + tuple_2 # adding tuples print(tuple_5)
import os os.system('cls') my_name = "elodia" first_names = ["john", "bob", "mary", my_name] print(first_names[2]) #access index 2 of first_names num = [1,2,3,4] numbers = ['a', 'b', num] print(numbers[2][3]) #access index 3 of index 2 (wich is a list on ints own) of numbers first_names[0] = "Tina" #replacing entries in a list print(first_names) del first_names [0] #deletng entries in a list print(first_names) first_names.append("Anya") print(first_names) print (len(first_names)) #prints number of entries print (first_names[len(first_names) -1 ] ) #prints last entry
# random password generator import random def get_char(list, num): character=[] for i in range(num): character.append(random.choice(list)) return character while True: num_char= int(input("Total number of int in password : ")) num_Upper=int(input("number of uppercharacter in password : ")) num_lower=int(input("number of lower character in password : ")) num_digits=int(input("number of digits in password : ")) num_symbol=int(input("number of symbols in password : ")) if num_char < num_digits + num_lower + num_symbol + num_Upper: print (" Character number does not match ") else : break upper_list=[chr(i) for i in range(65 , 91)] upper_char=get_char(upper_list,num_Upper) lower_list=[chr(i) for i in range(97, 97+26)] lower_char=get_char(lower_list,num_lower) digits_list=[str(i) for i in range(0,10)] digits_char=get_char(digits_list,num_digits) symbol_list=[chr(i) for i in range(32,48)] symbol_list=[chr(i) for i in range(58,65)] symbol_list=[chr(i) for i in range(91,97)] symbol_list=[chr(i) for i in range(123,127)] symbol_char=get_char(symbol_list,num_symbol) whole_list= upper_list+lower_list+digits_list+symbol_list miss_num = num_char-(num_digits+num_lower+num_symbol+num_Upper) miss_char = get_char(whole_list, miss_num) password= upper_char + lower_char + digits_char + symbol_char + miss_char random.shuffle(password) password = ''.join(password) print(password)
#charity money class charity: def __init__(self,balance=100000): self.balance= balance def save_fund(self,amount): self.balance+= amount def spend_funds(self,amount): self.balance-=amount def investment(self, investment_return): self.balance*=1+investment_return def get_balance(self): if self.balance< 0 : print("ypu got a deficit balance"+str(self.balance)) return self.balance def is_danger(self): if self.balance< 50000 and self.balance>=1: print("you are in danger "+str(self.balance)+" balance left") return self.balance<50000 money= charity() money.spend_funds(20000) print(money.get_balance()) money.save_fund(10000) print(money.get_balance()) money.investment(0.10) print(money.get_balance()) money.investment(-0.10) print(money.get_balance()) money.spend_funds(60000.10) print(money.get_balance()) print(money.is_danger())
# PRODUCT PRICE DISCOUNT def get_price(product, quantity): subtotal = price_diction[product] * quantity return subtotal buying_diction={"biscuits":2 , "chicken":3, "fruits":5} price_diction={"biscuits":3 , "chicken":15.5, "fruits":10} bill_price=0 membership = 'golden' for key ,value in buying_diction.items(): bill_price+=get_price(key,value) print("Actual price is " +str(bill_price)) for key , value in buying_diction.items(): print("product " +key+ " and quantity " +str(value)+ " , price is " + str(price_diction[key]*value)) print("But you get dicount") if bill_price>50: if membership =='golden': bill_price=bill_price*0.75 discount = 25 elif membership =='silver': bill_price=bill_price*0.85 discount = 15 print('your member ships is '+membership+" and you got discount of " +str(discount)+ " % and your actual bill is " +str(bill_price))
def validate_puzzle(arr): if len(arr) != 9: return False for i in range(9): if len(arr[i]) != 9: return False return True def print_sudoku(arr): for i in range(9): for j in range(9): print(arr[i][j], end=" ") print('\n') def find_next_void(arr, loc): for i in range(9): for j in range(9): if arr[i][j] == 0: loc[0] = i loc[1] = j return True return False def element_exists_in_row(arr, row, elem): for i in range(9): if arr[row][i] == elem: return True return False def element_exists_in_col(arr, col, elem): for i in range(9): if arr[i][col] == elem: return True return False def element_exists_in_box(arr, row, col, elem): r = row - row % 3 c = col - col % 3 for i in range(3): for j in range(3): if arr[r + i][c + j] == elem: return True return False def is_safe(arr, row, col, elem): return (not element_exists_in_row(arr, row, elem)) and \ (not element_exists_in_col(arr, col, elem)) and \ (not element_exists_in_box(arr, row, col, elem)) def solve_sudoku(arr): loc = [0, 0] if not find_next_void(arr, loc): return True row = loc[0] col = loc[1] for num in range(1, 10): if is_safe(arr, row, col, num): arr[row][col] = num if solve_sudoku(arr): return True arr[row][col] = 0 return False
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ couleurs = ['bleu', 'vert', 'rose', 'orange'] print (couleurs) couleurs[1]=15 print (couleurs) x = 10 print("avant if") if x>0: print("dans if") print("après if") #exercices 6.3 def F_to_C(Tf): """convertit une temperature de Fahrenheit en Celsius""" Tc = (Tf-32)*5/9 return Tc #Tf = float(input('entrez la température en Fahrenheit: ')) #while Tf<-459.67: #print("attention votre temperature est en dessous de zéro !!") #Tf = float(input('entrez la température en Fahrenheit: ')) #print('la temperature en Celsius est ', F_to_C(Tf) ) def F_to_C_new(Tf): """ convertit une temperature de Fahrenheit en Celsius""" while Tf<-459.67: print("attention votre temperature est en dessous de zéro !!") Tf = float(input('entrez la température en Fahrenheit: ')) print('la temperature en Celsius est ') return F_to_C(Tf)
# 로또 생성 프로그램 import random cnt = int(input("로또를 몇 세트 자동생성 할까요? ")) for i in range(1, cnt+1) : numbers = [] while len(numbers) < 6 : rotto = random.randint(1, 45) if rotto not in numbers : numbers.append(rotto) numbers.sort() print(f"{i}번째 세트", end=" ") for z in numbers : print(f"%2d" % z, end=" ") print()
import pandas as pd import csv import statistics df= pd.read_csv("data.csv") heightList= df["Height(Inches)"].to_list() weightList= df["Weight(Pounds)"].to_list() heightMean= statistics.mean(heightList) weightMean= statistics.mean(weightList) heightMedian= statistics.median(heightList) weightMedian= statistics.median(weightList) heightMode= statistics.mode(heightList) weightMode= statistics.mode(weightList) print("Mean, Median and Mode of students height is {},{} and{} rescpectively".format(heightMean,heightMedian,heightMode)) print("Mean, Median and Mode of students weight is {},{} and{} rescpectively".format(weightMean,weightMedian,weightMode)) heightstdDeviation=statistics.stdev(heightList) weightstdDeviation=statistics.stdev(weightList) height1ststdDeviationstart,height1ststdDeviationend=heightMean-heightstdDeviation,heightMean+heightstdDeviation height2ndstdDeviationstart,height2ndstdDeviationend=heightMean-(2*heightstdDeviation),heightMean+(2*heightstdDeviation) height3rdstdDeviationstart,height3rdstdDeviationend=heightMean-(3*heightstdDeviation),heightMean+(3*heightstdDeviation) weight1ststdDeviationstart,weight1ststdDeviationend=weightMean-weightstdDeviation,weightMean+weightstdDeviation weight2ndstdDeviationstart,weight2ndstdDeviationend=weightMean-(2*weightstdDeviation),weightMean+(2*weightstdDeviation) weight3rdstdDeviationstart,weight3rdstdDeviationend=weightMean-(3*weightstdDeviation),weightMean+(3*weightstdDeviation) height_list_of_data_within_1_std_deviation=[result for result in heightList if result>height1ststdDeviationstart and result<height1ststdDeviationend] height_list_of_data_within_2_std_deviation=[result for result in heightList if result>height2ndstdDeviationstart and result<height2ndstdDeviationend] height_list_of_data_within_3_std_deviation=[result for result in heightList if result>height3rdstdDeviationstart and result<height3rdstdDeviationend] weight_list_of_data_within_1_std_deviation=[result for result in weightList if result>weight1ststdDeviationstart and result<weight1ststdDeviationend] weight_list_of_data_within_2_std_deviation=[result for result in weightList if result>weight2ndstdDeviationstart and result<weight2ndstdDeviationend] weight_list_of_data_within_3_std_deviation=[result for result in weightList if result>weight3rdstdDeviationstart and result<weight3rdstdDeviationend] print("{}% of data for height lies within 1 standard deviation".format(len(height_list_of_data_within_1_std_deviation)*100.0/len(heightList))) print("{}% of data for height lies within 2 standard deviation".format(len(height_list_of_data_within_2_std_deviation)*100.0/len(heightList))) print("{}% of data for height lies within 3 standard deviation".format(len(height_list_of_data_within_3_std_deviation)*100.0/len(heightList))) print("{}% of data for weight lies within 1 standard deviation".format(len(weight_list_of_data_within_1_std_deviation)*100.0/len(weightList))) print("{}% of data for weight lies within 2 standard deviation".format(len(weight_list_of_data_within_2_std_deviation)*100.0/len(weightList))) print("{}% of data for weight lies within 3 standard deviation".format(len(weight_list_of_data_within_3_std_deviation)*100.0/len(weightList)))
# socket_echo_server.py import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listaDeEsperaPassageiro = [] listaDeEsperaCarga = [] def decisao(message): message = message.split(',') print(message) if(message[0].upper()=='1'.upper()): # Passageiro listaDeEsperaPassageiro.append((message[0], message[1])) if(listaDeEsperaPassageiro.count((message[0], message[1]))==1): print("Requisição do passageiro registrada com Sucesso!") return 'Requisição do passageiro registrada com Sucesso!'.encode('utf-8') elif(message[0].upper()=='2'.upper()): # Carga listaDeEsperaCarga.append((message[0], message[1])) if(listaDeEsperaCarga.count((message[0], message[1]))==1): print("Requisição do passageiro registrada com Sucesso!") return 'Requisição do passageiro registrada com Sucesso!'.encode('utf-8') # elif(message[0].upper()=='motorista'.upper()) # funcao para definicao do motorista # Bind the socket to the port server_address = ('localhost', 10001) print('starting up on {} port {}'.format(*server_address)) sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print('waiting for a connection') connection, client_address = sock.accept() try: print('connection from', client_address) # Receive the data in small chunks and retransmit it while True: data = connection.recv(512) print('received {!r}'.format(data)) data = decisao(data.decode()) if data: print('sending data back to the client') connection.sendall(data) else: print('no data from', client_address) break finally: # Clean up the connection connection.close()
name = input('What is your name? ') print(name + ' SUCKS!!!!') color = input('what is your favorite? ') print(color + ' SUCKS!!!!') subject = input('What is your favorite subject? ') print(subject + ' SUCKS!!!!!!') animal = input('What is your favorite animal? ') print(animal + ' SUCK!!!!')
#A comment #anything after the pound sign is ignored by python. print "I could have code like this" #and here's a comment #comments can be used to disable a piece of code: #print "This won't run." print "This will run."
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] """ print "The animal at 1: " + animals[1] print "The third animal: " + animals[2] print "The first animal: " + animals[0] print "The animal at 3: " + animals[3] print "The fifth animal: " + animals[4] print "The animal at 2: " + animals[2] print "The sixth animal: " + animals[5] print "The animal at 4: " + animals[4] """ number = 1 print "\n\nHere are the wonderful animals in our zoo:" for x in animals: print number, "\b. %s" % x number +=1 employees = ['Jim', 'Joe', 'Marcus', 'Mark', 'Oliver', 'Oscar', 'Stan', 'Steve'] print "\nHere are the employees at the company," print "listed in order of when they were hired:\n" """ for i in employees: print number, "\b. %s" % i number += 1 print "\n\nThe previous list was incorrectly ordered (alphabetically)." print "Here is the revised list:\n" """ print "1. " + employees[3] print "2. " + employees[5] print "3. " + employees[7] print "4. " + employees[0] print "5. " + employees[1] print "6. " + employees[6] print "7. " + employees[2] print "8. " + employees[4] jobs = ['zoo keeper', 'janitor', 'veterinarian', 'mechanic'] e = len(employees) j = len(jobs) a = len(animals) print "\nThere are %d animals at our zoo!" % a print "Currently, %d employees fill the %d jobs, where" % (e, j) print "they care for the animals and maintain the park!\n\n" print employees[1], "is the head", jobs[0], "\b." print "He primarily looks after the", animals[0], "\b,", animals[3], "\b, and the", animals[5], "\b.\n" print employees[6], "helps", employees[1], "with the", animals[3], "as an assistant", jobs[0], "\b.\n" print employees[7], "is also an assistant", jobs[0], "\b. He works in the reptile house with the", animals[1], "\b.\n" print "Every good park needs a", jobs[3], "to keep the operation running smoothly." print "We can always count on", employees[2], "to keep the zoo in top shape!\n" print "Don't get", employees[2], "confused with", employees[3], "\b!" print employees[3], "is our head", jobs[2], "\b." print "He works primarily with the", animals[0], "\b,", animals[2], "\b,", animals[3], "\b, and", animals[5], "\b.\n" print employees[0], "is the special", jobs[2], "\b. He works with the", animals[1], "and", animals[4], "\b.\n" print "To keep the park clean, we have", employees[5], "as our", jobs[1], "\b.\n" print "And our newest hire is", employees[4], "\b, who is also an assistant", jobs[0], "\b." print "He works with our newest animal: the", animals[4], "\b.\n"
from bs4 import BeautifulSoup import requests import pandas as pd def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {"executable_path": ""} return Browser("chrome", **executable_path, headless=False) def mars_scraper: url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest" response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') results = soup.find_all('div', class_="slide") #print(results) for result in results: # Error handling try: title = result.find_all('img', class_="img-lazy") paragraph = result.find_all('div', class_="rollover_description_inner") # Print results only if title, price, and link are available if (title and paragraph): print(title) print(paragraph) except AttributeError as e: print(e) def image_scraper: featured_image_url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" response2 = requests.get(featured_image_url) soup2 = BeautifulSoup(response2.text, 'lxml') #print(soup2.prettify()) results2 = soup2.find_all('div', class_="img") #print(results2) def weather_scraper: mars_weather_url = "https://twitter.com/marswxreport?lang=en" tables = pd.read_html(mars_weather_url) tables #not 100%% sure what to do here, not sure if this is right or not def mars_hemisphere_scraper: mars_hemispheres = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" response3 = requests.get(mars_hemispheres) soup3 = BeautifulSoup(response3.text, 'lxml') #print(soup3.prettify()) #image scraper results3 = soup3.find_all('img', class_="thumb") #print(results2) #title scraper results4 = soup3.find_all('div', class_ = "description").find_all('h3') #print(results4) #getting an error
num = int(input()) hrs = int(input()) val = float(input()) salary = val * hrs print("NUMBER = %d\nSALARY = U$ %.2f" %(num,salary))
import MapReduce import sys """ Relational Join Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: document identifier # value: document contents key = record[1] rectag= record[0] value = [rectag,record] mr.emit_intermediate(key,value) #words = value.split() #for w in record: # mr.emit_intermediate(key, 1) # #mr.emit_intermediate(w, key) def reducer(key, list_of_values): # key: word # value: list of occurrence counts total = [] count = 0 orderline = [] for v in list_of_values: if count == 0: count = 1 orderline = v[1] continue listline = v[1] mr.emit(orderline + listline) #total.append(myli) count += 1 # Do not modify below this line # ============================= if __name__ == '__main__': #inputdata = open("data/records.json") inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
# Subsets # Given a set of distinct integers, nums, return all possible subsets (the power set). # Note: The solution set must not contain duplicate subsets. # Example: # Input: nums = [1,2,3] # Output: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # ===================================================================================== # Algorithm: # # def subsets(nums): subset = [] def collect_subsets(index, nums, current_set, subset): subset.append(list(current_set)) for i in range(index, len(nums)): current_set.append(nums[i]) collect_subsets(i+1, nums, current_set, subset) current_set.pop() collect_subsets(0, nums, [], subset) return subset if __name__ == "__main__": input_list = [1, 2, 3] print(subsets(input_list))
# Sort List # Sort a linked list in O(n log n) time using constant space complexity. # Example 1: # Input: 4->2->1->3 # Output: 1->2->3->4 # Example 2: # Input: -1->5->3->4->0 # Output: -1->0->3->4->5 # ====================================================================================== # Algorithm: # Merge sort # TC: O(nlogn) # SC: O(1) # Description: https://www.youtube.com/watch?v=pNTc1bM1z-4 # ======================================================================================== class SllNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) def sort_list(head): # 4->2->1->3-> Null # 1->2->3->4-> Null if not head or not head.next: return head # get the middle of the list mid = temp1 = temp2 = head while temp2 and temp2.next: temp1 = mid mid = mid.next temp2 = temp2.next.next temp1.next = None left = sort_list(head) right = sort_list(mid) def merge_list(l1, l2): new_list = SllNode() curr = new_list if not l1: return l2 if not l2: return l1 # Traverse two lists, compare, and merge them while l1 and l2: if l1.val <= l2.val: curr.next = l1 curr = l1 l1 = curr.next else: curr.next = l2 curr = l2 l2 = curr.next curr.next = l1 or l2 return new_list.next return merge_list(left, right) def print_list(llist): curr = llist while curr: print(curr.val) curr = curr.next if __name__ == "__main__": node1 = SllNode(4) node1.next = SllNode(2) node1.next.next = SllNode(1) node1.next.next.next = SllNode(3) print(sort_list(node1))
# Pascal's Triangle # Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. # In Pascal's triangle, each number is the sum of the two numbers directly above it. # Example: # Input: 5 # Output: # [ # [1], # [1,1], # [1,2,1], # [1,3,3,1], # [1,4,6,4,1] # ] # ====================================================================================== # Algorithm: # def generate(num_rows): triangle = [] if not num_rows: return triangle first_row = [1] triangle.append(first_row) for i in range(1, num_rows): prev_row = triangle[i-1] curr_row = list() curr_row.append(1) for j in range(1, i): curr_row.append(prev_row[j-1] + prev_row[j]) curr_row.append(1) triangle.append(curr_row) return triangle if __name__ == "__main__": rows_num = 7 print(generate(rows_num)) # [1], # [1, 1], # [1, 2, 1], # [1, 3, 3, 1], # [1, 4, 6, 4, 1], # [1, 5, 10, 10, 5, 1]
# Delete Linked List # Example: # Input: 1->2->3->4->5->NULL # Output: None # ====================================================================================== # Algorithm: # TC: # SC: # Description: # ======================================================================================== class SllNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) def delete_list(head): """Delete a linked list.""" # 1 -> 2 -> 3 -> 4 -> 5 -> Null if not head: return head curr = head while curr: temp = curr.next del curr.val curr = temp if __name__ == "__main__": node1 = SllNode(1) node1.next = SllNode(2) node1.next.next = SllNode(3) node1.next.next.next = SllNode(4) node1.next.next.next.next = SllNode(5) delete_list(node1)
# Palindromic Substrings # Given a string, your task is to count how many palindromic substrings in this string. # The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. # Example 1: # Input: "abc" # Output: 3 # Explanation: Three palindromic strings: "a", "b", "c". # Example 2: # Input: "aaa" # Output: 6 # Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". # Note: # The input string length won't exceed 1000. # ======================================================================================== # Algorithm: # Use a dynamic programming table. Have three loops, the last loop is nested. # The first loop will look at single characters, the second will look at double characters, # and the third nested loop will look at characters length 3 to n. Keep true/false in a boolean table. # Update count for each non-zero elements of dp and return the count <-- result # TC: O(n^2). Two nested traversals are needed. # SC: O(n^2). Matrix of size n*n is needed to store the dp array. # ======================================================================================== def count_substrings(s): n = len(s) # dp[i][j] is 1 if substring s[i..j] is palindrome, # else 0 dp = [[0 for j in range(n)] for i in range(n)] count = 0 # All substrings of length 1 are palindromes i = 0 while i < n: dp[i][i] = 1 i += 1 count += 1 # Find palindromic substring of length 2 i = 0 while i < n - 1: if s[i] == s[i+1]: dp[i][i+1] = 1 count += 1 i += 1 # Find palindromic substring of length >= 3 # l is length of substring substr_len = 3 while substr_len <= n: # Starting index i i = 0 while i < n - substr_len + 1: # calculate the ending index of substring j = i + substr_len - 1 # Check if substring, from ith index # to jth index, a palindrome or not if s[i] == s[j] and dp[i+1][j-1] == 1: dp[i][j] = 1 count += 1 i += 1 substr_len += 1 return count if __name__ == "__main__": # input_str = "abc" # output: 3 input_str = "aaa" # output: 6 print(count_substrings(input_str))
# Best Time to Buy and Sell Stock III # Say you have an array for which the ith element is the price of a given stock on day i. # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # Note: You may not engage in multiple transactions at the same time # (i.e., you must sell the stock before you buy again). # Example 1: # Input: [3,3,5,0,0,3,1,4] # Output: 6 # Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. # Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. # Example 2: # Input: [1,2,3,4,5] # Output: 4 # Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. # Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are # engaging multiple transactions at the same time. You must sell before buying again. # Example 3: # Input: [7,6,4,3,1] # Output: 0 # Explanation: In this case, no transaction is done, i.e. max profit = 0. # ======================================================================== # Algorithm: # TC: O(n) # SC: O(n) def max_profit(prices): if not prices: return 0 max_total_profit = 0 min_price_so_far = prices[0] first_transaction_profits = [0] * len(prices) # Forward phase: for each day, record maximum profit if sell on that day for i, price in enumerate(prices): min_price_so_far = min(min_price_so_far, price) max_total_profit = max(max_total_profit, price - min_price_so_far) first_transaction_profits[i] = max_total_profit # Backward phase: for each day, calculate maximum profit # if make second transaction on that day max_price_so_far = prices[-1] for i, price in reversed(list(enumerate(prices[1:], 1))): max_price_so_far = max(max_price_so_far, price) max_total_profit = max(max_total_profit, max_price_so_far - price + first_transaction_profits[i-1]) first_transaction_profits[i] = max_total_profit return max_total_profit if __name__ == "__main__": # nums = [3, 3, 5, 0, 0, 3, 1, 4] # output: 6 # nums = [1, 2, 3, 4, 5] # output: 4 nums = [7, 6, 4, 3, 1] # output: 0 print(max_profit(nums))
# Remove duplicates from sorted array II # Given a sorted array nums, remove the duplicates in-place such that duplicates appeared # at most twice and return the new length. # Do not allocate extra space for another array, you must do this by modifying the input array # in-place with O(1) extra memory. # Example 1: # Given nums = [1,1,1,2,2,3], # Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. # It doesn't matter what you leave beyond the returned length. # Example 2: # Given nums = [0,0,1,1,1,1,2,3,3], # Your function should return length = 7, with the first seven elements of nums being # modified to 0, 0, 1, 1, 2, 3 and 3 respectively. # It doesn't matter what values are set beyond the returned length. # ================================================================================================================ # method def remove_duplicates_1(nums): if not nums: return 0 j = 2 for i in range(2, len(nums)): if nums[j-2] != nums[i]: nums[j] = nums[i] j += 1 return j # method def remove_duplicates(arr): new_index = 2 for i in range(2, len(arr)): if arr[new_index-2] != arr[i]: arr[new_index] = arr[i] new_index += 1 return new_index if __name__ == "__main__": arr = [1, 1, 1, 2, 2, 3] # print(remove_duplicates_1(arr)) print(remove_duplicates(arr))
# Path Sum # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that # adding up all the values along the path equals the given sum. # Note: A leaf is a node with no children. # Example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ # 11 13 4 # / \ \ # 7 2 1 # return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. # ====================================================================================== # Algorithm: # TC: O(n) # SC: # Description: https://www.youtube.com/watch?v=Jg4E4KZstFE # ======================================================================================== class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # Method-1: def has_path_sum(root, sum): result = [] def helper(root, sum, result): if not root: return False # check if current node is a leaf node or not if not root.left and not root.right: if root.val == sum: result.append(root.val) return True else: return False if helper(root.left, sum - root.val, result): result.append(root.val) return True if helper(root.right, sum - root.val, result): result.append(root.val) return True helper(root, sum, result) return result if __name__ == "__main__": # Tree # root = [5, 4, 8, 11, Null, 13, 4, 7, 2, Null, 1] # 5 # / \ # 4 8 # / / \ # 11 13 4 # / \ \ # 7 2 1 # L-1: root root = TreeNode(5) # L-2 root.left = TreeNode(4) root.right = TreeNode(8) # L-3 root.left.left = TreeNode(11) root.left.right = None root.right.left = TreeNode(13) root.right.right = TreeNode(4) # # L-4 root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left.left = None root.right.left.right = None root.right.right.left = None root.right.right.right = TreeNode(1) # # L-5 # root.left.right.left.left = None # root.left.right.left.right = None # root.right.right.left.left = None # root.right.right.left.right = None # root.right.right.right.left = TreeNode(1) # root.right.right.right.right = TreeNode(3) s = 22 # print(root) print(has_path_sum(root, s))
# Given a string find longest palindromic subsequence in this string. # Example 1: # Input: # S = 'abcdca' # Output: 5 # Explanation: acdca # ======================================================================================== # Algorithm: # Similar to substring except use the table to keep track of longest length instead of boolean flag. # If the characters on the end are the same, add the longest palindrome plus 2. # Or get the max from [i][j-1] or [i+1][j] # TC: O(n^2). Two nested traversals are needed. # SC: O(n^2). Matrix of size n*n is needed to store the dp array. # ======================================================================================== # Method-1: Dynamic programming # This function prints longest palindromic subsequence # and returns length of the longest palindromic subsequence def longest_palindromic_subsequence(s): n = len(s) idx = [] seq = "" dp = [[0 for j in range(n)] for i in range(n)] # All subsequence of length 1 are palindromes i = 0 while i < n: dp[i][i] = 1 i += 1 # Find palindromic subsequence of length 2 start = 0 i = 0 while i < n - 1: if s[i] == s[i+1]: dp[i][i+1] = 2 else: dp[i][i+1] = 1 i += 1 # Find palindromic subsequence of length >= 3 # l is length of substring subseq_len = 3 while subseq_len <= n: # Starting index i i = 0 while i < n - subseq_len + 1: # calculate the ending index of subsequence j = i + subseq_len - 1 # Check for subsequence from ith index # to jth index if s[i] == s[j]: dp[i][j] = 2 + dp[i+1][j-1] else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) i += 1 subseq_len += 1 return dp[0][n-1] # Method-2: Recursive def calculate_recursive(s, start, subseq_len): if subseq_len == 1: return 1 if subseq_len == 0: return 0 if s[start] == s[start+subseq_len-1]: return 2 + calculate_recursive(s, start+1, subseq_len-2) else: return max(calculate_recursive(s, start+1, subseq_len-1), calculate_recursive(s, start, subseq_len-1)) if __name__ == "__main__": input_str = 'abcdca' # output: 5, acdca # print(calculate_recursive(input_str, 0, len(input_str))) print(longest_palindromic_subsequence(input_str))
# Minimum Depth of Binary Tree # Given a binary tree, find its minimum depth. # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # Note: A leaf is a node with no children. # Example: # Given binary tree [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # return its minimum depth = 2. # ====================================================================================== # Algorithm: # TC: # SC: # Description: https://www.youtube.com/watch?v=z2LEbk5l_gg # ======================================================================================== import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # Method-1: recursive # Tc: O(n) # Sc: O(n) def min_depth(root): if not root: return 0 q = collections.deque() q.append(root) depth = 0 while q: size = len(q) while size > 0: curr = q.popleft() if not curr.left and not curr.right: depth += 1 return depth if curr.left: q.append(curr.left) if curr.right: q.append(curr.right) size -= 1 depth += 1 if __name__ == "__main__": # Tree root = [3, 9, 20, None, None, 15, 7] # 3 # / \ # 9 20 # / \ # 15 7 # L-1: root root = TreeNode(3) # # L-2 root.left = TreeNode(9) root.right = TreeNode(20) # # L-3 root.left.left = None root.left.right = None root.right.left = TreeNode(15) root.right.right = TreeNode(7) # print(root) print(min_depth(root))
# Binary Tree Level Order Traversal II # Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its bottom-up level order traversal as: # [ # [15,7], # [9,20], # [3] # ] # ====================================================================================== # Algorithm: # iterative using queue # TC: # SC: # Description: https://www.youtube.com/watch?v=H2K0CGAjQDc # ======================================================================================== import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # breadth-first-traversal # Method-1: iterative using queue # Tc: O(n) # Sc: O(n) def levelorder_bottom_iter(root): if not root: return [] # res = collections.deque() res = [] q = collections.deque() q.append(root) while q: size = len(q) level = [] while size > 0: curr_node = q.popleft() if curr_node.left: q.append(curr_node.left) if curr_node.right: q.append(curr_node.right) level.append(curr_node.val) size -= 1 res.insert(0, level) return res # breadth-first-traversal # Method-1: recursive # Tc: O(n) # Sc: O(n) def levelorder_bottom_recur(root): result = [] def dfs(node, level, result): if node: if level >= len(result): result.insert(0, []) result[-(level+1)].append(node.val) dfs(node.left, level+1, result) dfs(node.right, level+1, result) dfs(root, 0, result) return result if __name__ == "__main__": # Tree root = [3,9,20,None,None,15,7] # 3 # / \ # 9 20 # / \ # 15 7 # L-1: root root = TreeNode(3) # # L-2 root.left = TreeNode(9) root.right = TreeNode(20) # # L-3 root.left.left = None root.left.right = None root.right.left = TreeNode(15) root.right.right = TreeNode(7) # print(root) print(levelorder_bottom_iter(root)) print(levelorder_bottom_recur(root))
# Remove Duplicates from Sorted List II # Given a sorted linked list, delete all nodes that have duplicate numbers, # leaving only distinct numbers from the original list. # Return the linked list sorted as well. # Example 1: # Input: 1->2->3->3->4->4->5 # Output: 1->2->5 # Example 2: # Input: 1->1->1->2->3 # Output: 2->3 # ====================================================================================== # Algorithm: # Hash table, iterative in-place # TC: # SC: # ======================================================================================== class SllNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # Method - 1 : using hash table def delete_duplicates_ht(head): # 1->2->3->3->4->4->5 Null # 1->2->5 if not head: return head duplicates = dict() curr = head while curr: if curr.val not in duplicates: duplicates[curr.val] = [curr.val] else: # If val not present in hash table duplicates[curr.val].append(curr.val) curr = curr.next curr = head prev = None while curr: if len(duplicates[curr.val]) > 1: if curr == head: head = curr.next curr = head else: prev.next = curr.next curr = None curr = prev.next else: prev = curr curr = curr.next # print(duplicates) print_list(head) return head # Method - 2 : Iterative def delete_duplicates(head): # 1->2->3->3->4->4->5 Null # 1->2->5 if not head: return head temp = prev = SllNode(0) temp.next = head curr = head while curr and curr.next: if curr.val != curr.next.val: prev = curr curr = curr.next else: while curr.next and curr.val == curr.next.val: curr = curr.next curr = curr.next prev.next = curr print_list(temp.next) return temp.next def print_list(llist): curr = llist while curr: print(curr.val) curr = curr.next if __name__ == "__main__": node1 = SllNode(1) node1.next = SllNode(2) node1.next.next = SllNode(3) node1.next.next.next = SllNode(3) node1.next.next.next.next = SllNode(4) node1.next.next.next.next.next = SllNode(4) node1.next.next.next.next.next.next = SllNode(5) # print("Input:") # print_list(node1) print("Output:") print(delete_duplicates(node1))
# Delete Node in a Linked List # Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. # Example 1: # Input: head = [4,5,1,9], node = 5 # Output: [4,1,9] # Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. # Example 2: # Input: head = [4,5,1,9], node = 1 # Output: [4,5,9] # Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. # Note: # # The linked list will have at least two elements. # All of the nodes' values will be unique. # The given node will not be the tail and it will always be a valid node of the linked list. # Do not return anything from your function. # ====================================================================================== # Algorithm: # iterative in-place # TC: # SC: # ======================================================================================== class SllNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # Method - 1 : using hash table def delete_node(head, node): # 4->5->1->9-> Null, node = 5 # 4->1->9 if not head: return head # if first node is the target node if head.val == node: head = head.next # If target node is not head node else: curr = head prev = None while curr.next: if curr.val == node: prev.next = curr.next else: prev = curr curr = curr.next # print(duplicates) print_list(head) return head # Leetcode: solution def delete_node_1(self, node): node.val = node.next.val node.next = node.next.next def print_list(llist): curr = llist while curr: print(curr.val) curr = curr.next if __name__ == "__main__": node1 = SllNode(4) node1.next = SllNode(5) node1.next.next = SllNode(1) node1.next.next.next = SllNode(9) n = 5 # print("Input:") # print_list(node1) print("Output:") print(delete_node(node1, n))
# Find All Anagrams in a String # Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. # Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. # The order of output does not matter. # Example 1: # Input: # s: "cbaebabacd" p: "abc" # Output: # [0, 6] # Explanation: # The substring with start index = 0 is "cba", which is an anagram of "abc". # The substring with start index = 6 is "bac", which is an anagram of "abc". # Example 2: # Input: # s: "abab" p: "ab" # Output: # [0, 1, 2] # Explanation: # The substring with start index = 0 is "ab", which is an anagram of "ab". # The substring with start index = 1 is "ba", which is an anagram of "ab". # The substring with start index = 2 is "ab", which is an anagram of "ab". # ====================================================================================== # Algorithm: # Counter, Hash table, sliding window # TC: # SC: # ======================================================================================== from collections import Counter def find_anagrams(s, p): res = [] s_len = len(s) p_len = len(p) if p_len > s_len: return res p_count = Counter(p) s_count = Counter() i = 0 while i < s_len: s_count[s[i]] += 1 if i >= p_len: if s_count[s[i-p_len]] == 1: del s_count[s[i-p_len]] else: s_count[s[i-p_len]] -= 1 if p_count == s_count: res.append(i - p_len + 1) i += 1 return res if __name__ == "__main__": # s = "cbaebabacd" # p = "abc" # output: [0, 6] # s = "abab" # p = "ab" # [0, 1, 2] s = "ababababab" p = "aab" # [0, 2, 4, 6] print(find_anagrams(s, p))
# Reverse Linked List # Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could you implement both? # ====================================================================================== # Algorithm: # TC: # SC: # ======================================================================================== class SllNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): """Returns a printable representation of object we call it on.""" return "{}".format(self.val) # method-1: recursive def reverse_list_recursive(head): """Reverse a linked list using recursion.""" def helper(curr, prev): if not curr: return prev nxt = curr.next curr.next = prev prev = curr curr = nxt return helper(curr, prev) head = helper(head, None) return head # method-2: iterative def reverse_list_iterative(head): """Reverse a linked list iteratively.""" # 1 -> 2 -> 3 -> 4 -> 5 -> Null curr = head prev = None while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt head = prev def print_list(llist): curr = llist while curr: print(curr.val) curr = curr.next # print([new_list, new_list.next, new_list.next.next, new_list.next.next.next]) print_list(head) return head if __name__ == "__main__": node1 = SllNode(1) node1.next = SllNode(2) node1.next.next = SllNode(3) node1.next.next.next = SllNode(4) node1.next.next.next.next = SllNode(5) # print("Input Lists:") # print([node1, node1.next, node1.next.next]) # print("\n") print("Output:") print(reverse_list_recursive(node1)) # print(reverse_list_iterative(node1))
# Combination Sun II # Given a collection of candidate numbers (candidates) and a target number (target), # find all unique combinations in candidates where the candidate numbers sums to target. # Each number in candidates may only be used once in the combination. # Note: # All numbers (including target) will be positive integers. # The solution set must not contain duplicate combinations. # Example 1: # Input: candidates = [10,1,2,7,6,1,5], target = 8, # A solution set is: # [ # [1, 7], # [1, 2, 5], # [2, 6], # [1, 1, 6] # ] # Example 2: # Input: candidates = [2,5,2,1,2], target = 5, # A solution set is: # [ # [1,2,2], # [5] # ] # ========================================================================== # method-1 def combination_sum2(candidates, target): combinations = [] candidates.sort() def find_combinations(target, idx, curr_list): if target <= 0: if target == 0 and not sorted(curr_list) in combinations: combinations.append(sorted(curr_list)) return if idx < len(candidates): e = candidates[idx] if e > target: return find_combinations(target-e, idx+1, curr_list+[e]) find_combinations(target, idx+1, curr_list) find_combinations(target, 0, []) return combinations if __name__ == "__main__": arr = [10, 1, 2, 7, 6, 1, 5] target = 8 # arr = [2, 5, 2, 1, 2] # target = 5 print(combination_sum2(arr, target))
# ============================================ # ; Title: Exercise 8.3–Python in Action # ; Author: Peter Itskovich # ; Date: 25 Aug 2020 # ; Modified By: Becca Buechle # ; Description: Calc with Python # ;=========================================== add(a,b): return a + b def subtract(a,b): return a - b def divide(a,b): return a / b print(add(5,10)) print(subtract(1,2)) print(divide(4,2))
# -*- coding: utf-8 -*- """ Created on Thu Sep 15 19:45:30 2016 @author: Jian Gao Group c """ ##Prof G - This does not work. Part of the reason is that the reason is that the ##Prof G - "is_palindrome" function calls a function called "reverse", which is ##Prof G - undefined. # Question 1 def palindrome(string): """" This function reverses a string, e.g. "abcd" to "dcba" Parameter: A string Returns: The reverse of x """ # get the length of the string and subtract 1 end_of_str=len(string)-1 revStr='' for Char in string: # start at the end of the string and work back to # beginning to build the reversed string revStr += string[end_of_str] end_of_str=end_of_str - 1 return revStr def is_palindrome(input_word): """ This function, is_palindromo(), recognizes palindromes (i.e. words that look the same written backwards). For instance, is_palindrome("radar") should return True. Parameters: input_word: any word with alphabetic characters Returns: True is the word is a palindrome, false otherwise """ palindrome = False # Initialize our return variable to False input_word=input_word.upper() # Take care of mixed by case by upper # casing the word input_word=input_word.replace(" ","") # Take care of spaces if not input_word.isalpha(): return palindrome if reverse(input_word) == input_word: palindrome = True return palindrome def palindrome_file(file): file1=open(file) # open a file for line in file1.read().split('\n'): # read file by lines seperated if is_palindrome(line): print(line) # print the line if it is palindrome return None palindrome_file('C:/GJ/110.txt') # Question 2 ##Prof G - This does not work. there is no checking that the word pairs are ##Prof G - actually semordnilap def semordnilap(file): ''' This function works that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. Parameter: file Returns: A list of paired words ''' list1=list(open(file).read().split()) # open a text file and convert into list1 list2=[] # create an empty list for i in list1: list2.append(i+' '+i[::-1]) # word + space + backward word return list2 semordnilap('C:/GJ/110.txt') # Question 3 ##Prof G - Nice, handles mixed case but should not count blanks and CR's def char_freq_table(file): ''' This function accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen. Parameter: A file Returns: A table showing frequency of characters ''' string=open(file).read()#open a file and read each line d={} # define a dictiontionary d to save characters and it's frequency print(string) for i in range(len(string)): # manipulate every characters in inputstring string if string[i] in d: # case1: let string[1] denotes the character if the character is in the dictionary d[string[i]]= int(d.get(string[i]))+1 else: d[string[i]]= 1 # case 2: if the character is not in the dictionary # assign value 1 to the character's frequency return d print(char_freq_table('C:/GJ/110.txt')) # local file # Question 4 d={'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot', 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima', 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo', 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 'x':'x-ray', 'y':'yankee', 'z':'zulu'} #define dictionary d import os import time ##Prof G - Does not work on my machine def speak_out(string,ICAO_pause,word_pause_time): ''' This function translate string into ICAO words and speak the out. Parameter: A string Returns: Speak ICAO words ''' for k in string.split():#split a string into words for i in k:#i represents each character if i not in "`~!@#$%^&*()_-=+[]{}\|;:,<.>/?": #not punctuation os.system('say'+d[i.lower()])#speak # speak out time.sleep(ICAO_pause) # pause between ICAO words time.sleep(word_pause_time)# pause between words. ##Prof G - Inappropriate test phrase speak_out('Fuck you Python',0.5,3) # Question 5 ##Prof G - Works well. def hapax(file): ''' Define a function that gives the file of text words only appear once Ignore the capitalization and punctions Parameter: A file Return: A list containing all hapaxes ''' string=open(file).read() # open a file and read each line string=string.lower() # ignore the capitalization puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/?" # ignore punctions for i in string: if i in puncspace: string=string.replace(i,'') # ignore all punctuations in string hapax1=[] # create an empty list for hapax for k in string.split(): if string.count(k)==1: # if the word only appears once hapax1.append(k) # put that word into list hapax1 return hapax1 print(hapax('C:/GJ/110.txt')) # Question 6 ##Prof G - This will not work properly if file contains the full path name. May ##Prof G - consider accepting both the input and output file or finding a more ##Prof G - robust method of creating an output file name (using regex) def numberfile(file): ''' This function gives a text file will create a new text file in which all the lines from the original file are numbered from 1 to n. Parameter: A file Returns: A new file with numbered lines ''' file1=open(file).readlines() # file1 is a list file2=open('new'+file,'w') # new empty file for i in range(len(file1)): file2.write('line'+str(i+1)+': '+file1[i]) # add 'line#: ' to the begining of each line, put them together into line2 file2.close() # save and close numberfile('C:/GJ/110.txt') # Question 7 def average(file): ##Prof G - Nice, works well. ''' Define a function average to calculate the average word length of a text in a file. Parameter: A file Return: A number ''' x=open(file).read() # open a file and read it x=x.lower() puncspace="`~!@#$%^&*()_-=+[]{}\|;:,<.>/? " x=x.replace('\n',' ') # no space in string x number1=len(x.split()) # calculate the number of total files define as number1 for i in x: if i in puncspace: x=x.replace(i,'') # no spaces and punctuations in string x number2=len(x) # calculate the number of characters return number2/number1 print(average('C:/GJ/110.txt')) # Question 8 ##Prof G - Should make this a function. Otherwise, it works well. ''' This program is able to play the 'Guess the number' game. Parameter: A number x Return: You guess is correct or wrong. ''' Attempt=1 Answer=18 # given Name=input("What is your name?") # input your name while True: x=int(input('{} I am thinking of a number between 1 and 20. Take a guess.'.format(Name))) # input a number x if x==Answer: print('Congradulation, {}! You guessed the number in the {} attempt!'.format(Name,Attempt)) break # stop this game elif x<Answer: print('Your guess number is too low. Try again!') Attempt+=1 # Attempt plus 1 else: print('Your guess number is too high. Try again!') Attempt+=1 # Attempt plus 1 # Question 10 ''' This game is to find the correct word by gussing, and in return receive two kinds of clues: 1) the characters that are correct with correct order, mark that character with[] 2) the characters that are correct with wrong order, mark that character with() Parameter: a list of characters with the same range as the answer Return: list of characters ''' answer='lingo' # input correct answer while True: guess=input('Enter your guess word:') new='' for i in range(len(guess)): if guess[i] in answer[i]: new+='['+guess[i]+']' # add [] to the correct character with correct order ##Prof G - This is meant to mean, in the word but in the wrong position. ##Prof G - If I guess lllll the output should be [l]llll (there are no ##Prof G - more l's after the first position) elif guess[i] in answer: new+='('+guess[i]+')' # add () to the correct character but with incorrect order else: new+=guess[i] # if nothing is correct just add those characters if guess==answer: print('Clue:' +new) break else: print('Clue:' +new) # Question 11 import re def splitter(file_name): ##Prof G - Did not work on my test file. ''' This function opens a txt file and works as a sentence splitter to write its sentences with each sentences on a separate line. Sentence boundaries occur at one of "." (periods), "?" or "!", except that a. Periods followed by whitespace followed by a lower case letter are not sentence boundaries. b. Periods followed by a digit with no intervening whitespace are not sentence boundaries. c. Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on. d. Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g). e. Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries. Parameter: A file Returns: The modified file ''' file=open(file_name, 'r') text=file.read() S=re.sub(r'\n', '', text) # remove the newline we already have there # substitute \n with empty string S=re.sub(r'(?<!Mr)(?<!Mrs)(?<!Dr)\.\s([A-Z])', r'.\n\1', S) # preceded by 'Mr', 'Mrs' or 'Dr' and is followed by a space and an uppercase letter S=re.sub(r'!\s', '!\n', S) # substitute after every '!' S=re.sub(r'\?\s', '?\n', S) # substitute after every '?' print(S) print(splitter('C:/GJ/Q11.txt'))
def missing_char(str, n): if n == str[-1]: return str.split(0, n - 1) return print(missing_char("kitten", 4)) print()
# O(n) time & space, n is # of items in merged list (Interview Cake) def merge_lists(my_list, alices_list): merged_length = len(my_list) + len(alices_list) #merged_list = [None] * merged_length merged_list = [] idx = 0 my_p = 0 a_p = 0 while idx < merged_length: if my_p >= len(my_list): #merged_list[idx] = alices_list[a_p] merged_list.append(alices_list[a_p]) a_p += 1 elif a_p >= len(alices_list): #merged_list[idx] = my_list[my_p] merged_list.append(my_list[my_p]) my_p += 1 elif my_list[my_p] < alices_list[a_p]: #merged_list[idx] = my_list[my_p] merged_list.append(my_list[my_p]) my_p += 1 else: #merged_list[idx] = alices_list[a_p] merged_list.append(alices_list[a_p]) a_p += 1 idx += 1 return merged_list # Testing my_list = [3, 4, 6, 10, 11, 15] alices_list = [1, 5, 8, 12, 14, 19] print(merge_lists(my_list, alices_list)) # >>> # Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
""" Input: array of three or more ints Output: sorted array of three largest nums, ascending Consideration: cannot use the native sort method Consideration: should return duplicates if there are any Example: Input: [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7] Output: [18, 141, 541] """ # O(n) time | O(1) space def largest_nums(array): largest = [float('-inf'), float('-inf'), float('-inf')] for num in array: if num > largest[2]: largest[0] = largest[1] largest[1] = largest[2] largest[2] = num elif num > largest[1]: largest[0] = largest[1] largest[1] = num elif num > largest[0]: largest[0] = num return largest #Testing ex_arr = [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7] print(largest_nums(ex_arr))
''' Input: list of strings (3 nums) Input: len(list) = # of scenarios Input: [budget, cost of containers, trade-in price] PRINT RESULTS ON EACH LINE; NO RETURN VALUE ''' def max_containers(scenarios): for scenario in scenarios: scenario_list = scenario.split(' ') budget = int(scenario_list[0]) cost = int(scenario_list[1]) containers = budget // cost total_containers = containers trade_in = int(scenario_list[2]) while containers >= trade_in: additional_containers = containers // trade_in total_containers += additional_containers containers = containers % trade_in + additional_containers #print(f'{total_containers}\n') print(total_containers) # Testing scenarios = ['10 2 5', '12 4 4', '6 2 2'] #scenarios = ['10 2 5'] max_containers(scenarios) # >>> # 6 # 3 # 5
input_file = open("day3", "r") content = input_file.read() content_list = content.split("\n") def count_trees(): counter = 0 for i, line in enumerate(content_list): string = line.strip() * ((len(content_list)//len(line)+1)*3) if string[3*i] == '#': counter += 1 print(counter) count_trees()
a=input("masukkan Nilai a : ") b=input("masukkan Nilai b : ") print("variable a = ", a) print("variable b = ", b) print("Hasil penggabungan {1}&{0}=%d".format(a,b) %(a+b)) # Konversi nilai Variable a=int(255) b=int(255) print("Hasil penjumlahan {1}+{0}=%d".format(a,b) %(a+b)) print("Hasil pembagian {1}/{0}=%d".format(a,b) %(a/b))
import numpy as np def parse_to_matrix(filepath, separator = " ", dtype = np.int32): """ By: Jan Reads a textfile to a matrix. Assumptions:Every line corresponds to one line of the matrix Every line has the same number of items A space character ends every line separator is the sign with which weights are separated dtype names the datatype of the returned matrix. Note that computations with int32 might be way faster! """ file = open(filepath, "r") array = [] for line in file.readlines(): weight_list = line.split(separator)[:-1] # To account for the space after each line of weights array.append(weight_list) return np.asarray(array, dtype = dtype)
import time import pandas as pd import numpy as np # dictionary for acessing file name CITY_DATA = {'chicago': 'chicago.csv', 'new york city' : 'new_york_city.csv', 'washington': 'washington.csv'} # month and week dictionaries hold month and week keys for accesing dictionary values month_index = {'january':1, 'february':2, 'march':3, 'april':4, 'may': 5, 'june':6, 'None':None, 'all':'all'} week_index = {'monday':0, 'tuesday':1, 'wednesday':2, 'thursday':3, 'friday':4, 'saturday':5, 'sunday':6, 'None':None, 'all':'all'} list_city = ['chicago', 'washington', 'new york city'] def get_filters(): """Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) both - name of the day of week and month to filter by, (str) none - no filters applied Returns: city as city as str month and day as ints corresponding to keys in month_index and week_index dictionaries""" city="" month ="" day ="" print("Hello Let\'s explore some US bikeshare data!\n\n") months = ['all', 'january', 'february', 'march', 'april', 'may', 'june', 'all'] days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all'] explore_by = ['month', 'day', 'both', 'none'] try: while city not in list_city: city = input('Enter city you wish to explore (chicago, new york city, washington)\n\n >').lower() print('\n Welcome to the {} bikeshare database.\n'.format(city)) select_by = input('Would you like to explore the data by month, both(month and day), or none\n >').lower() while select_by not in explore_by: select_by = input("Enter 'month', both(month and day), 'none'").lower() if select_by == 'month': month = input('Enter a month name from january,february, march,... june or all\n' + '>').lower() while month not in months: month = input('Enter a valid month name january,...,june or all\n ' + '>').loer() day = 'None' elif select_by == 'day': day = input('Enter a weekday name like monday,...,sunday, or all\n' +'>').lower() while day not in days: day = input('Enter a valid weekday\n' + '>').lower() city = 'None' elif select_by == 'both': while month not in months: month = input('Enter a month name from january,february, march,... june\n' + '>').lower() while day not in days: day = input('Enter a weekday name like monday,...,sunday\n' + '>').lower() elif select_by == 'none': month = 'None' day = 'None' except KeyboardInterrupt: print('You stopped the code execution') except EOFError: print('The program was stopped and an unexpexted EOFError was generated') print('-'*40) return city, month_index.get(month), week_index[day] def get_ValueKey(months, days): """ Takes as args month and days integers creates four temporal list from month_index and week_index dictionaries gets values and keys from week_index and month_index dictionaries Returns: str keys corresponding to dictionaries values """ month_keys = list(month_index.keys()) month_values = list(month_index.values()) week_keys = list(week_index.keys()) week_values = list(week_index.values()) postion_month = month_values.index(months) position_week = week_values.index(days) return month_keys[postion_month], week_keys[position_week] def load_data(city, month, day): """ Loads dataframe base on city, month and day filters loads filename base on the corresponding city key value in CITY_DATA dictionary Returns: df - Pandas DataFrame containing city data filtered by month and day """ filename = CITY_DATA[city] df = pd.read_csv(filename) df['Start Time'] = pd.to_datetime(df['Start Time']) df['DayOfWeek'] = df['Start Time'].dt.dayofweek df['Month'] = df['Start Time'].dt.month if month == None and day == None: df2 = df elif day == 'all': df2 = df elif day != None and day != 'all': df2 = df[df['DayOfWeek'] == day] elif month == 'all': df2 = df elif month != None and month != 'all': df2 = df[df['Month'] == month] elif month != None and day != None: df1 = df[df['Month'] == month] df2 = df1[df1['DayOfWeek'] == day] return df2 def time_stats(df, month_value, day_value): """Displays statistics on the most frequent times of travel. filters dataframe base on month and date displays most common month, day and hour """ print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() month, day = get_ValueKey(month_value, day_value) if month_value == None and day_value == None: print('Sorted by None') print('The following information is base on (Start Time) column') print('Most common Start Time for unsorted data: ', df['Start Time'].mode()[0]) print('Most common hour: ', df['Start Time'].dt.hour.mode()[0]) elif month_value != None and day_value == None: print('Most common month: ', df['Month'].mode()[0]) print('Most common hour: ', df['Start Time'].dt.hour.mode()[0]) elif month_value == None and day_value != None: print('Most common day: ', df[DayOfWeek].mode()[0]) print('Most common hour: ', df['Start Time'].dt.hour.mode()[0]) else: print('Most common month: ', df['Month'].mode()[0]) print('Most common day: ', df['DayOfWeek'].mode()[0]) print('Most common hour: ', df['Start Time'].dt.hour.mode()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df, month_value, day_value): """Displays statistics on the most popular stations and trip. filters dataframe base on month and date display most start station for particular month and day or are None displays the most end station for a particular month and day or are None displays most used start station and end station """ print('\nCalculating The Most Popular Stations and Trip...\n') # display most commonly used start station # display most commonly used end station # display most frequent combination of start station and end station trip Start_time = time.time() month, day = get_ValueKey(month_value, day_value) if ((month_value == 'all' and day_value == None) or (month_value == None and day_value == 'all') or (month_value == None and day_value == None)): print('Sorted by all or None') print('Most used start station: ', df['Start Station'].mode()[0]) print('Most used end station: ', df['End Station'].mode()[0]) print('Most used start and end station: \n', df.groupby(['Start Station', 'End Station']).size().sort_values(ascending=False).head(1)) elif month_value in range(1, len(month_index)-1) and day_value not in range(0, len(day)-2): df1 = df[df['Month']==month_value] print('Sorting by month only\n') print('Most used stations for month number {}'.format(month)) print('Most used start station : ', df1['Start Station'].mode()[0]) print('Most used end station : ', df1['Start Station'].mode()[0]) #print('Most used start and end station: \n', # df1.groupby(df1['Start Station','End Station']).size().sort_values(ascending=False).head(1)) elif month_value not in range(1, len(month_index)-1) and day_value in range(0, len(week_index)-2): df1 = df[df['DayOfWeek'] == day_value] print('Sorting by day only\n') print('Most used stations {}'.format(day)) print('Most used start station: ', df1['Start Station'].mode()[0]) print('Most used end station: ', df1['End Station'].mode()[0]) print('Most used start and end station: \n', df1.groupby(['Start Station', 'End Station']).size().sort_values(ascending=False).head(1)) elif month_value in range(1, len(month_index)-1) and day_value in range(0, len(week_index)-2): df1 = df[df['Month'] == month_value] df2 = df1[df1['DayOfWeek'] == day_value] print('Most used stations for all {} in {} '.format(day, month)) print('Most used start station: ', df2['Start Station'].mode()[0]) print('Most used end station: ', df2['End Station'].mode()[0]) print('Most used start and end station: \n', df2.groupby(['Start Station', 'End Station']).size().sort_values(ascending=False).head(1)) print("\nThis took %s seconds." % (time.time() - Start_time)) print('-'*40) def trip_duration_stats(df, month, day): """Displays statistics on the total and average trip duration. """ print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time if ((month == 'all' and day == None) or (month == None and day == 'all') or (month == None and day == None)): travel_time = df['Trip Duration'].sum() mean_time = df['Trip Duration'].mean() str_mean = str(mean_time)+'S' str_time = str(travel_time) + 'S' print('Sorted by all or None') print('Total travel time indays hrs mins and seconds: ', pd.to_timedelta(str_time)) print('Average travel time: ', pd.to_timedelta(str_mean)) elif month in range(1, len(month_index)-1) and day not in range(0, len(week_index)-2): df1 = df[df['Month'] == month] t_time = df1['Trip Duration'].sum() mean_time = df1['Trip Duration'].mean() str_mean = str(mean_time)+'S' str_time = str(t_time)+'S' print('Sorted by month') print('Total travel time indays hrs mins and seconds:', pd.to_timedelta(str_time)) print('Average travel time: ',pd.to_timedelta(mean_time) ) elif month not in range(1, len(month_index)-1) and day in range(0, len(week_index)-2): df1 = df[df['DayOfWeek'] == month] t_time = df1['Trip Duration'].sum() mean_time = df1['Trip Duration'].mean() str_time = str(t_time)+'S' str_mean = str(mean_time)+'S' print('Sorted by day of a week') print('Total travel time: ',pd.to_timedelta(str_time) ) print('Average traveling time: ', pd.to_timedelta(str_mean)) elif month in range(1, len(month_index)-1) and day in range(0, len(week_index)-2): df1 = df[df['Month'] == month] df2 = df1[df1['DayOfWeek']==day] t_time = df2['Trip Duration'].sum() mean_time = df2['Trip Duration'].mean() str_time = str(t_time)+'S' str_mean = str(mean_time)+'S' print('Sorted by month and day') print('Total travel time: ',pd.to_timedelta(str_time) ) print('Average traveling time: ', pd.to_timedelta(str_mean)) # display mean travel time print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df, city, month, day): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() if ((month == 'all' and day == None) or (month == None and day == 'all') or (month == None and day == None)): if city == 'washington': print('For unsorted data') print('Birth year and Gender columns are absent for this database') print('User Type counts: ', df['User Type'].value_counts()) else: print('For unsorted data') print('User Type counts: ', df['User Type'].value_counts()) print('Gender counts: ', df['Gender'].value_counts()) print('Earliest year of birth: ', df['Birth Year'].min()) print('Most recent year of birth: ', df['Birth Year'].max()) print('Most common birth Year: ',df['Birth Year'].mode()) elif month in range(1, len(month_index)-1) and day not in range(0, len(week_index)-2): df1 = df[df['Month']==month] if city == 'washington': print('For unsorted data') print('Birth year and Gender columns are absent for this database') print('User Type counts: ', df1['User Type'].value_counts()) else: print('For unsorted data') print('User Type counts: ', df1['User Type'].value_counts()) print('Gender counts: ', df1['Gender'].value_counts()) print('Earliest year of birth: ', df1['Birth Year'].min()) print('Most recent year of birth: ', df1['Birth Year'].max()) print('Most common birth Year: ',df1['Birth Year'].mode()) elif month not in range(1, len(month_index)-1) and day in range(0, len(week_index)-2): df1 = df1[df1['DayOfWeek']== day] if city == 'washington': print('For unsorted data') print('Birth year and Gender columns are absent for this database') print('User Type counts: ', df1['User Type'].value_counts()) else: print('For unsorted data') print('User Type counts: ', df1['User Type'].value_counts()) print('Gender counts: ', df1['Gender'].value_counts()) print('Earliest year of birth: ', df1['Birth Year'].min()) print('Most recent year of birth: ', df1['Birth Year'].max()) print('Most common birth Year: ',df1['Birth Year'].mode()) elif month in range(1, len(month_index)-1) and day in range(0, len(week_index)-2): df1 = df[df['Month']==month] df2 = df1[df1['DayOfWeek']==day] if city == 'washington': print('For unsorted data') print('Birth year and Gender columns are absent for this database') print('User Type counts: ', df2['User Type'].value_counts()) else: print('For unsorted data') print('User Type counts: ', df2['User Type'].value_counts()) print('Gender counts: ', df2['Gender'].value_counts()) print('Earliest year of birth: ', df2['Birth Year'].min()) print('Most recent year of birth: ', df2['Birth Year'].max()) print('Most common birth Year: ',df2['Birth Year'].mode()) # Display counts of user types # Display counts of gender # Display earliest, most recent, and most common year of birth print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def view_rawData(city_name): """ Ask user to enter yes to no view raw data if user enters yes 5 lines of the .csv file is dipslayed user types yes to display the next 5 lines of the .csv file user types no or and enters an invalid option to abort the program """ rows = [] global counts counts = 5 dataRaw = ['yes', 'no'] verify = True while verify == True: input_verify = input('Would like to view the raw data ? Enter yes or no\n>').lower() while input_verify not in dataRaw: input_verify = input('Re-enter a value, please enter yes or no\n>') if input_verify == 'yes': while input_verify == 'yes': with open(CITY_DATA[city_name], 'r') as file: filereader = file.readlines() temp = filereader[0:counts] rows.append(temp) count = counts + 5 print(rows) input_verify = input('Type yes to continue and no to stop\n>').lower() if input_verify == 'yes': print('') elif input_verify == 'no': print('Aborting.......') break else: print('invalid option aborting....') break elif input_verify == 'no': verify = False print('Quiting...') break def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df, month, day) station_stats(df, month, day) trip_duration_stats(df, month, day) user_stats(df, city, month, day) view_rawData(city) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
import sys def showSum(number): sum = 0 for i in range(1, number + 1): sum += i print(f'{int(sum)}') number = int(sys.stdin.readline()) showSum(number)
import sys def printUntilNumber(count): for i in range(1, count + 1): print(f'{i}') count = int(sys.stdin.readline()) printUntilNumber(count)
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/30 16:10 # @Author : dxc # @File : change_money.py """ 面额问题 有 100 50 20 10 5 2 1 372 找最少张 贪心算法 """ class ChangeMoney: """ 面额问题 """ def __init__(self): self.amount = [100, 50, 20, 10, 5, 2, 1] def cal_num(self, money): """ 计算面额 :param money: :return: """ m = [0 for _ in range(len(self.amount))] for i, amount in enumerate(self.amount): m[i] = money // amount money = money % amount return m, money if __name__ == '__main__': change = ChangeMoney() print(change.cal_num(372))
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/30 17:49 # @Author : dxc # @File : activity_select.py # 活动时间 activities = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11), (8, 12), (2, 14), (12, 16)] # 保证活动按结束时间排序 activities.sort(key=lambda x: x[1]) def activities_select(a): """ 获取最合适的时间 :param a: :return: """ res = [a[0]] for i in range(1, len(a)): if a[i][0] >= res[-1][1]: res.append(a[i]) return res print(activities_select(activities))
print("<--------------------------->") print("<---------CONTACTOS--------->") print("<--------------------------->") #BUCLE_WHILE-PARA_EL_MENU_DE_CONTACTOS opcion = 0 while opcion != 5: """OPCIONES A ELEGIR""" print("1.Crear contacto en la agenda") print("2.Listado de contactos") print("3.Buscar ingresando el nombre de la persona") print("4.Modificacionde su telefono, mail o direccion") print("5.Finalizar programa!") """SELECCION DE OPCION""" opcion = int(input("¿Que desea?\n")) if opcion == 1: print("Escriba sus datos a continuacion") a = int(input(""))
import random #随机数 date = int(random.randint(0, 10)) #初始金币 money = 2000 #一局游戏玩的次数 i = 0 count = 1 while True: if i <= 10: i = i + 1 count = 10 - i num = input("输入数字:\n") if num.isdigit(): num = int(num) if num < date: money = money - 200 print("小了", "还剩", count, "次机会") elif num > date: money = money - 200 print("大了", "还剩", count, "次机会") else: money = money + 5000 print("可以啊!") haha = int(input("是否继续?1继续 2退出 \n")) if haha == 2: print("走你!") break elif haha == 1: print("来吧!小宝贝") i = 0 date = int(random.randint(0, 10)) else: print("你在干嘛?!") i = 0 date = int(random.randint(0, 10)) else: print("请充钱")
from algorithms import selection_sort import random l = list(map(lambda x: random.randint(10,99), range(12))) print(l) selection_sort(l) print(l) words = ['y', 'n', 'hello', 'goodbye', 'please', 'thanks'] selection_sort(words) print(words)
directions = input().split(",") def sign(a): if a > 0: return 1 if a < 0: return -1 return 0 x = 0 y = 0 for direction in directions: if direction == "n": y += 1 if direction == "ne": x += 1 y += 0.5 if direction == "se": x += 1 y -= 0.5 if direction == "s": y -= 1 if direction == "sw": x -= 1 y -= 0.5 if direction == "nw": x -= 1 y += 0.5 distance = 0 while abs(x) > 0: if (abs(x) >= 2) or (y % 1 == 0.5): y -= 0.5 * sign(y) x -= sign(x) distance += 1 distance += abs(y) print(distance)
stream = input() score = 0 ignore = False garbage = False opened = 0 for c in stream: if not ignore: if not garbage: if c == '{': opened += 1 elif c == '}': score += opened opened -= 1 elif c == '<': garbage = True if c == '>': garbage = False elif c == '!': ignore = True else: ignore = False print(score)
import numpy as np # initial weight and hyper parameters w = 0.0 learning_rate = 0.01 num_epoch = 100 # Training Data & Test data x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] x_test = [4.0] y_test = [8.0] # Initialize the weight, w def init_weight(val = 1.0): global w w = val # Our model for the forward pass def forward(x): return x * w # Loss function def MSE_loss(y_pred, y): return (y_pred - y) ** 2 ''' ### Compute the MSE loss for w for w in np.arange(0.0, 4.1, 0.1): print("w=", w) l_sum = 0 for x_val, y_val in zip(x_data, y_data): y_pred_val = forward(x_val) l = MSE_loss(x_val, y_val) l_sum += 1 print("\t", x_val, y_val, y_pred_val, l) print("MSE=", l_sum / 3) ''' # Gradient descent def gradient(x, y): return 2 * x * (x * w - y) # Train the model to find w for epoch in range(num_epoch): for x_val, y_val in zip(x_data, y_data): grad = gradient(x_val, y_val) y_pred = forward(x_val) w = w - learning_rate * grad print("\tgrad: ", x_val, y_val, grad) l = MSE_loss(y_pred, y_val) print("Progress: ", epoch, "w: ", w, "loss: ", l) # Test the model and print accuracy total_loss = 0 for x_val, y_val in zip(x_data, y_data): y_pred = forward(x_val) l = MSE_loss(y_pred, y_val) total_loss += l print('Loss after training: ', total_loss / len(x_data))
""" A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. Write a function: def solution(A) that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. For example, given array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7, as explained in the example above. Write an efficient algorithm for the following assumptions: N is an odd integer within the range [1..1,000,000]; each element of array A is an integer within the range [1..1,000,000,000]; all but one of the values in A occur an even number of times. """ import unittest from collections import defaultdict def solution(A): seen = defaultdict(int) for value in A: seen[value] += 1 return next((key for key, value in seen.items() if value % 2), None) class SolutionTests(unittest.TestCase): def test_case_0(self): A = [1] self.assertEqual(solution(A), 1) def test_case_1(self): A = [9, 3, 9, 3, 9, 7, 9] self.assertEqual(solution(A), 7) def test_case_2(self): A = [9, 3, 9, 3, 9, 9, 9] self.assertEqual(solution(A), 9) def test_case_3(self): A = [9, 3, 9, 4, 3, 4, 2] self.assertEqual(solution(A), 2) if __name__ == "__main__": unittest.main()
""" An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. For example, consider array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8. Write a function def solution(A) that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator. For example, given array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 the function may return 0, 2, 4, 6 or 7, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. """ import unittest from collections import defaultdict def solution(A: list) -> list: if not A: return -1 occurrencies = defaultdict(lambda: {'count': 0, 'index': -1}) for index, elem in enumerate(A): if not occurrencies[elem]['count']: occurrencies[elem]['index'] = index occurrencies[elem]['count'] += 1 dominator_candidate = sorted(occurrencies.keys(), key=lambda key: occurrencies[key]['count'], reverse=True)[0] occurrence = occurrencies[dominator_candidate] if occurrence['count'] > len(A) / 2: return occurrence['index'] else: return -1 class SolutionTests(unittest.TestCase): def test_case_1(self): A = [3, 4, 3, 2, 3, -1, 3, 3] result = solution(A) self.assertIn(result, [0, 2, 4, 6, 7]) def test_case_2(self): A = [5, 4, 3, 2, 3, -1, 3, 3] result = solution(A) self.assertIn(result, [-1]) def test_case_3(self): A = [] result = solution(A) self.assertIn(result, [-1]) if __name__ == "__main__": unittest.main()
class Solution1: def lengthOfLastWord(self, s: str) -> int: string = s.split() return len(string[-1]) if string else 0 class Solution2: def lengthOfLastWord(self, s: str) -> int: if not s and len(s) == 0: return 0 count = 0 for i in s[::-1]: if i == " ": if count == 0: continue else: break else: count += 1 return count