text
stringlengths
37
1.41M
#!/usr/bin/python3 """Lists all cities from a database""" if __name__ == "__main__": from sys import argv import MySQLdb if len(argv) == 4: db = MySQLdb.connect(user=argv[1], passwd=argv[2], db=argv[3], host="localhost", port=3306) c = db.cursor() select = ("""SELECT cities.id, cities.name, states.name FROM cities LEFT JOIN states ON states.id=cities.state_id ORDER BY cities.id""") c.execute(select) for row in c: print("{}".format(row)) c.close() db.close()
#!/usr/bin/python3 def remove_char_at(str, n): newstr = str[:n] + str[n + 1:] for i in str: j = j + 1 if j != n: return i
#!/usr/bin/python3 from sys import argv if __name__ == "__main__": num = 0 if len(argv) > 1: for i in argv[1:]: num = num + int(i) print("{:d}".format(num))
""" pymysql库使用代码示例 """ import pymysql # 连接数据库 def db_connect(): conn = pymysql.connect(host='localhost', user='root', password='Zpj12345', port=3306, db='test') return conn # 创建一个数据库表 def create_table(c): c.execute( "CREATE TABLE IF Not Exists person(id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(30) NOT NULL DEFAULT '',age INT,sex CHAR(2))") # 插入数据 def insert_data(c, table, data_dict): try: keys = ', '.join(data_dict.keys()) values = ', '.join(['%s'] * len(data_dict)) sql = 'INSERT INTO {table} ({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values) print(sql) c.execute(sql, tuple(data_dict.values())) db.commit() except Exception as e: print(e) db.rollback() # 删除数据 def delete_data(c, table, condition): try: sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table, condition=condition) c.execute(sql) db.commit() except Exception as e: print(e) db.rollback() # 修改数据 def update_data(c, table, old, new): try: sql = 'UPDATE {table} SET {old} WHERE {new}'.format(table=table, old=old, new=new) c.execute(sql) db.commit() except Exception as e: print(e) db.rollback() # 查看数据 def inquire_data(c, table, condition): try: sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table, condition=condition) c.execute(sql) print('共有 %d 行数据' % c.rowcount) row = c.fetchone() while row: print(row) row = c.fetchone() except Exception as e: print(e) if __name__ == '__main__': db = db_connect() cursor = db.cursor() create_table(cursor) # data = { # 'name': '大黄', # 'age': '17', # 'sex': '男', # } # insert_data(cursor, 'person', data) # delete_data(cursor, 'person', 'age < 10') # update_data(cursor, 'person', 'age = 10', "name = '小红'") inquire_data(cursor, 'person', 'age > 15') db.close()
"""Input gathering functions""" import readline from typing import List, Union import completions def get_project() -> str: """Take user input and return project""" readline.set_completer(completions.project_complete) project = input("project: ") if project == "": project = None return project def get_due() -> Union[None, str]: """Take user input and return date""" readline.set_completer(completions.date_complete) due = input("due: ") if due == "": return None return due def get_labels() -> Union[None, List[str]]: """Take user input and return list of labels""" readline.set_completer(completions.label_complete) labels = input("labels: ") if labels == "": return None return labels.split(",") def get_priority() -> Union[None, int]: """Take user input and return priority""" while True: priority = input("priority: ") if priority == "": return None try: if int(priority) not in [1, 2, 3, 4, 5]: print("Priority must be between 1 and 5!") continue return int(priority) except ValueError: print("Priority must be between 1 and 5!") continue def get_task() -> int: """Take user input and return task""" readline.set_completer(completions.task_complete) return int(input("task: "), 16)
import sys; def convert(c): return { 'A' : "100000", 'B' : "110000", 'C' : "100100", 'D' : "100110", 'E' : "100010", 'F' : "110100", 'G' : "110110", 'H' : "110010", 'I' : "010100", 'J' : "010110", 'K' : "101000", 'L' : "111000", 'M' : "101100", 'N' : "101110", 'O' : "101010", 'P' : "111100", 'Q' : "111110", 'R' : "111010", 'S' : "011100", 'T' : "011110", 'U' : "101001", 'V' : "111001", 'W' : "010111", 'X' : "101101", 'Y' : "101111", 'Z' : "101011", ' ' : "000000" }[c] def answer(plaintext): str = ""; ci = 0; for i in plaintext: ci+=1; if ci > 49: return ""; tmps = ""; try: tmps = convert(i.upper()); except KeyError: print("Non-alphabetic character encountered (character {})".format(ci)); pass; if i.isupper(): str += "000001"; str += tmps; if str == "": return ""; return str; def main(argc, argv): if argc != 2: print("Failed"); return; ans = answer(argv[1]); if ans == "": print("Failed"); else: print(ans); return; if __name__== "__main__": main(len(sys.argv), sys.argv)
class Solution: def threeSum(self,nums): ''' :type nums:List[int] :rtype:List[List[int]] ''' result = [] nums.sort() for i in range(len(nums)-2): if i>0 and nums[i] == nums[i-1]: continue l,r = i+1,len(nums)-1 while l<r: temp = nums[l]+nums[r]+nums[i] if temp == 0: result.append([nums[l],nums[r],nums[i]]) while l<r and nums[l] == nums[l+1]: l += 1 while l<r and nums[r] == nums[r-1]: r -= 1 l += 1 r -= 1 elif temp > 0: r -= 1 else: l += 1 return result ''' 普通算法时间复杂度为n^3, n^2算法为排序后固定一个数,然后让另两个数分别从首尾开始,往中间循环。 注意:三元组不能重复,即[1,0,-1]和[-1,1,0]视为同一三元组, 出现重复三元组有两种情况,一是同一个三元组在不同的循环中重复出现, 解决:l初始化为i+1 二是数组中有相同的数, 解决:判断相邻的数是否相同,同则忽略 '''
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self,root): if not root: return [] stack,out = [],[] while True: while root: stack.append(root) root = root.left if not stack: return out root = stack.pop() out.append(root.val) root = root.right return out
# day 23 # This solution is super ugly cup_labels = [3, 6, 4, 2, 9, 7, 5, 8, 1] print(f"original cup labels {cup_labels}") current_cup = cup_labels[0] picked_up_cup_indices = [] picked_up_cups = [] destination_cup = "" move = 0 while move < 101: #designate current cup print(f"cup labels {cup_labels}") print(f"current cup value {current_cup}") #debug print(f"current cup index {cup_labels.index(current_cup)}") #debug current_cup_index = cup_labels.index(current_cup) print(f"min label {min(cup_labels)}") print(f"max label {max(cup_labels)}") #remove three numbers to the right of current cup and store picked_up_cups_indices = [(current_cup_index + 1) % len(cup_labels), (current_cup_index + 2) % len(cup_labels), (current_cup_index + 3) % len(cup_labels)] #debug print(f"picked up cups indices {picked_up_cups_indices}") #debug picked_up_cups = [cup_labels[(current_cup_index + 1) % len(cup_labels)], cup_labels[(current_cup_index + 2) % len(cup_labels)], cup_labels[(current_cup_index + 3) % len(cup_labels)]] for i in picked_up_cups: cup_labels.remove(i) print(f"picked up cups {picked_up_cups}") print(f"cup labels {cup_labels}") #find destination cup destination_cup = current_cup - 1 if destination_cup < min(cup_labels): destination_cup = max(cup_labels) while destination_cup in picked_up_cups: if destination_cup >= min(cup_labels): destination_cup = destination_cup - 1 #print(f"destination cup {destination_cup}") else: destination_cup = max(cup_labels) print(f"destination cup {destination_cup}") #insert picked up cups for label in cup_labels: if label == destination_cup: index = cup_labels.index(label) cup_labels.insert(index + 1, picked_up_cups[0]) cup_labels.insert(index + 2, picked_up_cups[1]) cup_labels.insert(index + 3, picked_up_cups[2]) #set new current cup value current_cup = cup_labels[((cup_labels.index(current_cup)) + 1) % len(cup_labels)] print(f"new current cup index {cup_labels.index(current_cup) + 1}") print(f" new current_cup {current_cup}") move += 1 print(f"move {move}") print("-----------------")
import csv class Bike: def __init__(self,name,color,status): self.name = name self.color = color self.status = status def readBikes(): bikes=[] print("Opna bikes.txt") with open('bikes.txt', 'r', newline='', encoding='utf-8')as file: reader = csv.reader(file, delimiter=';') for row in reader: bike = Bike(row[0],row[1],row[2]) bikes.append(bike) print("Finished") return bikes def writeBikes(bikes): print("Skrifa í bikes.txt") file = None try: file = open("bikes.txt", "w", newline='', encoding="utf-8") for bike in bikes: line = "" line = bike.name + ";" + bike.color + ";" + bike.status + "\r\n" file.write(line) except IOError: print("An error occured trying to read this file") finally: print("Finished") if (file != None): file.close() print() def __str__(self): return f'Name: {self.name}\nColor: {self.color}\nStatus: {self.status}\n'
import functools import math import operator __author__ = 'Skurmedel' import problem as pm import itertools def sieve(n): candidates = list(range(2, n)) c = 2 end = False while not end: for i in range(2, n): m = c * i if m >= n: break candidates[m - 2] = -1 f = False for next in candidates[c - 1:]: if next == -1: continue f = True c = next break end = not f return filter(lambda x: x != -1, candidates) @pm.problem(1, "Multiples of 3 and 5") def problem1(): multiples = [] for i in range(1, 1000): mod1, mod2 = i % 3, i % 5 if mod1 == 0 or mod2 == 0: multiples.append(i) return sum(multiples) @pm.problem(2, "Even Fibonacci numbers") def problem2(): fibs = [1, 2] p, c = fibs while c <= 4e6: p, c = c, p + c fibs.append(c) def even(x): return x % 2 == 0 return sum(filter(even, fibs)) @pm.problem(3, "Largest prime factor") def problem3(): n = 600851475143 upper = int(math.sqrt(n)) factors = list(filter(lambda x: n % x == 0, sieve(upper))) return factors[-1] if __name__ == "__main__": pm.run_problems()
#Exercise 5.1.1 print("\n Exercise 5.1.1*** \n") import time def t(): epoch=time.time() print(epoch,"epoch \n ") return epoch t() def t1(): e_date = t() #e_date=epoch total_days = e_date // 3600 // 24 print(total_days,"days since epoch") c_date = total_days * 24 * 3600 seconds = e_date - c_date c_hours = seconds // 3600 c_minutes = (seconds - (c_hours*3600))//60 c_seconds = seconds - (c_hours*3600 + c_minutes*60) c_time = "%s:%s:%s" % (c_hours,c_minutes,c_seconds) print(c_time,"ON",total_days,"Days Since Epoch") t1() #Exercise 5.2.1 print("\n ***Exercise 5.2.1*** \n") import math def check_fermat(a, b, c, n): if n > 2 and (a**n + b**n == c**n): print("Holy smokes, Fermat was wrong!") else: print("No, that doesn’t work.") check_fermat(3,5,6,3) #Exercise 5.2.2 print("\n ***Exercise 5.2.2*** \n") def check_numbers(): a = int(input("Enter the Value for a: ")) b = int(input("Enter the Value for b: ")) c = int(input("Enter the Value for c: ")) n = int(input("Enter the Value for n: ")) return check_fermat(a, b, c, n) check_numbers() #Exercise 5.3.1 print("\n ***Exercise 5.3.1*** \n") def is_triangle(x, y, z): if (x + y == z): print("Yes!") else: print("No!") is_triangle(2,4,6) #Exercise 5.3.2 print("\n ***Exercise 5.3.2*** \n") def is_triangle_v(): x = int(input("Enter the value for x: ")) y = int(input("Enter the value for y: ")) z = int(input("Enter the value for z: ")) return is_triangle(x, y, z) is_triangle_v() #Exercise 5.4.1 print("\n ***Exercise 5.4.1*** \n") def recurse(n, s): if n == 0: print(s) else: recurse(n-1, n+s) recurse(3, 0) #Exercise 5.4.2 print("\n ***Exercise 5.4.2*** \n") print("\n if i called this function like this: recurse(-1, 0),then it will give a Recursion Error(Maximum Recursion depth exceeded in comparison) \n") print("\n This is recursion function: \n first of all it will go to function recurse(), then for if conditon and go for else condition because if condition is false because n=3 \n now n=2,s=3 \n ") print("\n Then again it will go to if condition then again it is false because this time n=2 again it will go for else condition and now n=1 , s=5 \n again it will go for if condition then again it is false and go for else condition \n now n=0, s=6 \n") print("\n Again it come to if condition this time if condition is true and will print S that is 6.")
import pandas as pd #merging two df by key/keys.(may be used in database) #simple example left=pd.DataFrame({'key':['K0','K1','K2','K3'],'A':['A0','A1','A2','A3'],'B':['B0','B1','B2','B3']}) right=pd.DataFrame({'key':['K0','K1','K2','K3'],'C':['C0','C1','C2','C3'],'D':['D0','D1','D2','D3']}) print(left) print(right) res=pd.merge(left,right,on='key') #res=pd.merge(left,right,on=['key1','key2'],how='inner') #default is how ='inner'. it can be how='outer',how='right',how='left' print(res) df1=pd.DataFrame({'col1':[0,1],'col_left':['a','b']}) df2=pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]}) out=pd.merge(df1,df2,on='col1',how='outer',indicator='indicator_column') # the default ignore index, if you wanna use index ,you can declear it as .merge(left,right,left_index=True) print(df1) print(df2) print(out) #differentiate data from different belongings boys=pd.DataFrame({'k':['K0','K1','K2'],'age':[1,2,3]}) girls=pd.DataFrame({'k':['K0','K0','K3'],'age':[4,5,6]}) dif=pd.merge(boys,girls,on='k',suffixes=['_boy','_girl'],how='outer') print(dif)
""" Recursive sorting module """ def merge(arr_a, arr_b): """ Merge Sort helper function """ merged_arr = [] while len(arr_a) > 0 and len(arr_b) > 0: if arr_a[0] > arr_b[0]: merged_arr.append(arr_b[0]) arr_b.pop(0) else: merged_arr.append(arr_a[0]) arr_a.pop(0) while len(arr_a) > 0: merged_arr.append(arr_a[0]) arr_a.pop(0) while len(arr_b) > 0: merged_arr.append(arr_b[0]) arr_b.pop(0) # TO-DO return merged_arr # print(merge([2, 3, 6], [1, 2])) # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort(arr): """ Merge sort implementation """ if len(arr) <= 1: return arr half = len(arr)//2 # Python slice api is bae split_a = arr[half:] split_b = arr[:half] # Recursively split split_a = merge_sort(split_a) split_b = merge_sort(split_b) return merge(split_a, split_b) # print(merge_sort([8, 9, 1, 4, 12, 6, 133])) # STRETCH: implement an in-place merge sort algorithm # def merge_in_place(arr, start, mid, end): # """ # In-Place Merge sort with O(1) space complexity # """ # TO-DO # def merge_sort_in_place(arr, l, r): # TO-DO # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt # def timsort(arr): # return arr
""" This simple animation example shows how to move an item with the keyboard. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.move_keyboard """ import arcade #making the arcade library accessable for this code SCREEN_WIDTH = 640 #setting the width of the display screen SCREEN_HEIGHT = 480 #setting the height of the display screen SCREEN_TITLE = "Move Keyboard Example" #setting the title of the display screen MOVEMENT_SPEED = 3 #determining how fast the ball will move on screen class Ball: #establishing the object that will be on the display screen def __init__(self, position_x, position_y, change_x, change_y, radius, color): #establishing what variables of this object will be defined # Take the parameters of the init function above, and create instance variables out of them. self.position_x = position_x #variable for the x coordinate self.position_y = position_y #variable for the y coordinate self.change_x = change_x #sets how much change there is in the x coordinate after an event self.change_y = change_y #sets how much change there is in the y coordinate after an event self.radius = radius #determines the size of the ball self.color = color #determines the color of the ball def draw(self): #draws the object with the variables we have outlined """ Draw the balls with the instance variables we have. """ arcade.draw_circle_filled(self.position_x, self.position_y, self.radius, self.color) #lets the computer know the specifc variables and take them into account while creating the ball def update(self): #the computer needs to update the postion of the object # Move the ball self.position_y += self.change_y #how much an event affects the y coordinate self.position_x += self.change_x #how much an event affects the x coordinate # See if the ball hit the edge of the screen. If so, change direction if self.position_x < self.radius: #if the x postion is smaller than the radius self.position_x = self.radius #then the x postion equals the radius if self.position_x > SCREEN_WIDTH - self.radius: #if the x postion is larger than the screen width i.e. on the edge of the screen self.position_x = SCREEN_WIDTH - self.radius #its x postion will stop there on the very edge of the screen if self.position_y < self.radius: #if the y postion is smaller than the radius self.position_y = self.radius #then the y postion equals the radius if self.position_y > SCREEN_HEIGHT - self.radius: #if the y postion is larger than the screen width i.e. on the edge of the screen self.position_y = SCREEN_HEIGHT - self.radius #its y postion will stop there on the very edge of the screen class MyGame(arcade.Window): #establishing a game object in the arcade library def __init__(self, width, height, title): #establishes the variables for this game object # Call the parent class's init function super().__init__(width, height, title) # Make the mouse disappear when it is over the window. # So we just see our object, not the pointer. self.set_mouse_visible(False) arcade.set_background_color(arcade.color.ASH_GREY) #sets the background to a color in the arcade library # Create our ball self.ball = Ball(50, 50, 0, 0, 15, arcade.color.AUBURN) def on_draw(self): #in order to draw the display window """ Called whenever we need to draw the window. """ arcade.start_render() #first step before anything can be rendered on the screen self.ball.draw() #draws the ball with our specific variables def update(self, delta_time): #function to update the postion over time self.ball.update() #establishes that the ball is the object being updated def on_key_press(self, key, modifiers): #function for a key press event """ Called whenever the user presses a key. """ if key == arcade.key.LEFT: #if the left key is pressed self.ball.change_x = -MOVEMENT_SPEED #there is a negative effect on the x coordinate postion elif key == arcade.key.RIGHT: #if the right key is pressed self.ball.change_x = MOVEMENT_SPEED #there is a positve effect on the x coordinate postion elif key == arcade.key.UP: #if the up key is pressed self.ball.change_y = MOVEMENT_SPEED #there is a postive effect on the y coordinate postion elif key == arcade.key.DOWN: #if the down key is pressed self.ball.change_y = -MOVEMENT_SPEED #there is a negative effect on the y coordinate postion def on_key_release(self, key, modifiers): #function for a released key event """ Called whenever a user releases a key. """ if key == arcade.key.LEFT or key == arcade.key.RIGHT: #if the left or right key is released self.ball.change_x = 0 #the postion will not change elif key == arcade.key.UP or key == arcade.key.DOWN: #if the up or down key is released self.ball.change_y = 0 #the postion will not change def main(): #defines the entry point for the program window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) #establishing some variables for the display window arcade.run() #the main game loop in the arcade library if __name__ == "__main__": #action to take if this module is not the main file main() #makes this module the main file to execute
#count the number in a list my_dict={"a":[1,2,3],"b":[3,4,5],"c":[8,3,4]} # count=0 # for x in my_dict: # if isinstance(my_dict[x],list): # # count += len(my_dict[x]) # print(count) ctr=sum(map(len ,my_dict.values())) print(ctr)
from matplotlib import pyplot as plt from matplotlib import style a=[1,2,3] y=[5,6,7] plt.plot(a,y,'g',label='data') plt.legend() plt.xlabel("x axis") plt.ylabel("y axis") plt.show()
#program to reverse a tuple tuple=(1,2,3,4,5) print("original:",tuple) tup=tuple[::-1] #by slicing technique print("reverse:",tup)
#program to count occurance of substring in a string str= input("enter the element in string") print(str) substring=input("enter the substring which u want to count") print(str.count(substring))
from array import * class occurance_specified_element(): def occurance(self): arr=array('i',[]) arr_length = int(input("Enter the Length of the array:")) for x in range(arr_length): element=int(input("Enter the element: ")) arr.append(element) print("Original array : ", arr) print() key_element=int(input("Enter the element u want to remove the first occurance: ")) print() if key_element in arr: ("remove element is: ",arr.remove(key_element)) print("New array: ",arr) else: print() print("OOPS!!it seems to be error" "Try again") specified_element=occurance_specified_element() specified_element.occurance()
import time def sum(a): start_time=time.time() s=0 for i in range(1,a+1): s=s+i end_time=time.time() return s,end_time-start_time print(sum(5))
def clone(): list=[] m=[] length=int(input("enter the length of a list")) for value in range(length): number=int(input("enter the element in the list")) list.append(number) print("old list",list) m=list.copy() print("new list",m) clone()
# Curso Intensivo de Python # 12/06/2021 - UFOP - Eng. da Computação - Victor Ivan Piloto Santos # Apresentação de metodo para tornar as letras em maiusculas e minusculas ex = "victor ivan" # O metodo .title() atua emcima da variavel 'ex', exibindo cada palavra com uma letra maiuscula no inicio. print(ex.title()) ex2 = "chapelzinho foi a casa do chapeleiro magico na fortaleza vermelha." print(ex2.title()) ########################################################################################################## ex = "Victor Ivan Piloto Santos" # .upper() faz com que todas as letras fiquem maiusculas print(ex.upper()) # .lower() faz com que todas as letras fiquem minusculas print(ex.lower()) ########################################################################################################## primeiro_nome = "Victor Ivan" ultimo_nome = "Piloto Santos" # Operador '+' em String, cocatena as Strings e até variaveis que são String nome_completo = primeiro_nome + " " + ultimo_nome mensagem = nome_completo = "Ola, " + nome_completo + "!" print(mensagem) ########################################################################################################## # Tabulação 'tab' um breakspace maior que o normal print("Victor\tIvan") # Quebra de linha 'Enter' em textos print("1 - Computadores\n2 - Mouses\n3 - Teclados\n4 - Mousepads\n") ########################################################################################################## # Retirando espaços vazios em uma string # .rstrip() - Retira espaço vazio a direita da string (temporariamente) ex = "Victor Ivan " print(ex.rstrip()) # .lstrip() - Retira espaço vazio a esquerda da string (temporariamente) ex = " Victor Ivan" print(ex.lstrip()) # .strip() - Retira espaço vazio a esquerda e a direita da string (temporariamente) ex = " Victor Ivan " print(ex.strip()) # Caso seja necessario manter a operação de retirada do espaço vazio, faça com que a variavel receba ela mesma com a operação ex = " Victor Ivan " ex = ex.strip() print(ex)
# Curso Intensivo de Python # 23/06/2021 - UFOP - Eng. da Computação - Victor Ivan Piloto Santos print('1º Parte - Conceitos Iniciais') # Lista é uma coleção de itens em uma ordem em particular. #Ex: [a,b,c,d,e,f] ou [0,1,2,3,4,5,6,7,8,9] # Não precisam estar relacionados de nenhum modo em particular. bicycles = ['trek','cannondale','redline','specialized'] print(bicycles) #Acessando os dados da lista # Ex: 1º Item da lista bicycles print(bicycles[0]) # O [0] representa o indice ou posição do item desejado. # O [0] representa o 1º indice ou posição de uma lista. # Ex: 2º e o 4º Item da lista bicycles print(bicycles[1]) print(bicycles[3]) # Ex: Como acessar o ultimo item de uma lista print(bicycles[-1]) # Retorna o valor 'specialized'. # print(bicycles[-2]) devolve o segundo item a partir do final da lista. print('') print('#########################################') print('2º Parte - Inserção, Alteração e Exclusão') #Alterando, acrescentando e removendo elementos #As Listas são dinamicas, significando que podemos criar uma lista adicionando e removendo elementos dela. motos = ['honda','yamaha','suzuki'] print(motos) #Sobreescrevemos 'ducati' na posição 0 da lista motos, colocando no lugar de honda motos[0] = 'ducati' print(motos) #Acrecentando elementos na lista # Concatenando elementos no final de uma lista # O elemento adicionado vai para o final da lista. motos = ['honda','yamaha','suzuki'] motos.append('ducati') print(motos) #Inserindo elementos em uma lista # Conseguimos adicionar um novo elemento em qualquer posição de sua ista usando o método insert(). # Especifique o indice do elemento e o valor. motos.insert(0,'harley') print(motos) #Removendo elementos de uma lista # Podemos remover um item de acordo com sua posição na lista ou seu valor. # Removemos o 1º item da lista. motos = ['honda','yamaha','suzuki'] print(motos) del motos[0] print(motos) # É possivel remover qualquer item de uma lista usando o metodo del, desde que se saiba o seu índice. #Removendo um item com o método Pop() # Util para usar o valor de um item depois de removê-lo de uma lista. # Permite trabalhar com esse item depois da remoção. # Por padrão remove o ultimo. motos = ['honda','yamaha','suzuki','harley'] print(motos) ex = motos.pop() print(motos) print(ex) # Pop() pode remover um item de qualquer posição de uma lista, se incluir o item que se deseja remover entre parenteses. motos = ['honda','yamaha','suzuki','harley'] print(motos) ex = motos.pop(2) print(motos) print(ex) #Removendo item de acordo com o valor # Não sabendo a posição do item, mas sabendo o seu valor é possivel remove-lo da lista. # Usando o método remove() motos = ['honda','yamaha','suzuki','harley'] print(motos) motos.remove('yamaha') print(motos) print('') print('#########################################') print('3º Parte - Ordenação') #Organizando uma lista # As listas serão criadas em uma ordem imprevisível, pois nem sempre você poderá controlar a ordem em que seus usuários fornecem seus dados. # Mesmos sendo inevitavel, python oferece várias maneiras de organizar suas listas de acordo com a situação. #Ordenando com o Método sort() #Suponhando que temos uma lista de carros e queremos alterar a ordem da lista para armazenar os itens em ordem alfabetica. carros = ['bmw','audi','toyota','subaru'] print(carros) carros.sort() print(carros) # Preservando a ordem original de uma lista, mas apresentando-a de forma ordenada, usamos a função sorted(). carros = ['bmw','audi','toyota','subaru'] print('Lista Original') print(carros) print('Lista Ordenada') print(sorted(carros)) print('Lista') print(carros) # Exibindo a lista em ordem inversa carros = ['bmw','audi','toyota','subaru'] print('Lista Original') print(carros) carros.reverse() print('Lista Invertida') print(carros) # O metodo reverse muda a ordem de uma lista de forma permanente, mas conseguimos retorna-la ao normal usando o reverse novamente. # Descobrindo o tamanho de uma lista #Utilizamos o metodo len(). #É util para descobrir a contagem de dados que existem em uma lista. carros = ['bmw','audi','toyota','subaru'] print('Itens na lista de carros: '+ str(len(carros))) print('') print('#########################################') print('4º Parte - Evitando erros com indices') # Um erro comum quando trabalhamos com lista pela primeira vez. #motos = ['honda','yamaha','suzuki'] #print(motos[3]) # Rodando esse codigo dá erro, já que o indice 3 representa o 4 item da lista, que não existe. # Para acessar o ultimo item da lista use o indice -1 motos = ['honda','yamaha','suzuki'] print(motos[-1]) # Caso a lista seja vazia e não há indices, se tentarmos retornar o ultimo item da lista, existe outro erro de indice.
import turtle vertices = [[-200, -100], [0, 200], [200, -100]] yes = {'yes', 'ye', 'y'} no = {'no', 'n'} # function to have the turtle draw a triangle, the basic unit of our fractal def draw_triangle(vertices, ChaosTriangle): ChaosTriangle.up() ChaosTriangle.goto(vertices[0][0], vertices[0][1]) ChaosTriangle.down() ChaosTriangle.goto(vertices[1][0], vertices[1][1]) ChaosTriangle.goto(vertices[2][0], vertices[2][1]) ChaosTriangle.goto(vertices[0][0], vertices[0][1]) # the same midpoint function we wrote for the chaos game def midpoint(point1, point2): return [(point1[0] + point2[0]) / 2, (point1[1] + point2[1]) / 2] # recursive function that draws the different "levels" of the fractal def draw_fractal(vertices, level, my_turtle): draw_triangle(vertices, my_turtle) # call function recursively to draw all levels of fractal if level > 0: # draw first segment of fractal # the vertices being passed in are the bottom corner of the first # section, the bottom corner of the second section, and the bottom # corner of the third secion. draw_fractal([vertices[0], midpoint(vertices[0], vertices[1]), midpoint(vertices[0], vertices[2])], level - 1, my_turtle) draw_fractal([vertices[1], midpoint(vertices[0], vertices[1]), midpoint(vertices[1], vertices[2])], level - 1, my_turtle) draw_fractal([vertices[2], midpoint(vertices[2], vertices[1]), midpoint(vertices[0], vertices[2])], level - 1, my_turtle) level = int(input("ow many recursions deep do we want to draw the fractal? ")) Chaos_triangle = turtle.Turtle() Chaos_triangle.shape('turtle') screen = turtle.Screen() screen.colormode(255) # to use the RGB codes for the colors vertices = [[-200, -100], [0, 200], [200, -100]] draw_fractal(vertices, level, Chaos_triangle) screen.exitonclick()
#!/usr/bin/python3 def print_last_digit(number): if (number > 0): lastnumber = number % 10 else: tmp = number * -1 lastnumber = tmp % 10 print("{:d}".format(lastnumber), end="") return lastnumber
#!/usr/bin/python3 """Function to print a text. If it finds a specific letter it will print two newlines. This fucntion provides a .txt file to test""" def text_indentation(text): """Text Arguments: text {[str]} -- [text] """ if type(text) != str: raise TypeError("text must be a string") for i in range(len(text)): print(text[i], end="") if (text[i] == "." or text[i] == "?" or text[i] == ":"): print("\n") print()
#!/usr/bin/python3 """Module which creates an inherited class of list""" class MyList(list): """Class to Initialize the class Arguments: list {[list]} -- [list] """ def print_sorted(self): """Prints lists sorted""" lista = self.copy() lista.sort() print(lista)
#!/usr/bin/python3 """Counts the number of lines in a file""" def number_of_lines(filename=""): """function to count number of lines Keyword Arguments: filename {str} -- [Filename] (default: {""}) Returns: [int] -- [number of lines] """ lines = 0 with open(filename) as f: for i in f.readlines(): lines += 1 return lines
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dict = a_dictionary.copy() for i, j in a_dictionary.items(): new_dict[i] = j*2 return (new_dict)
#!/usr/bin/python3 """Module which contain a function to find a Peak in a list""" def find_peak(list_of_integers): """function to find a Peak in a lis Args: list_of_integers ([list]): [List to evaluate] """ lista = sorted(list_of_integers) try: return(lista[-1]) except: return(None)
#!/usr/bin/python3 """Module to create a class for an object and modify private attribute size. There are also two method to get the area fo size and print the square""" class Square: """Class of the object""" def __init__(self, size=0): self.__size = size @property def size(self): """Returns size to then modify it Returns: [int] -- [Returns size] """ return self.__size @size.setter def size(self, value): """Function to assign new value Arguments: value {[int]} -- [Value] Raises: TypeError: [Catchs type errors] ValueError: [Catchs value errors] """ if (type(value) != int): raise TypeError("size must be an integer") elif (value < 0): raise ValueError("size must be >= 0") else: self.__size = value def area(self): """ Finds the current square area Returns: [int] -- [Returns the area] """ return self.__size * self.__size def my_print(self): """Prints the Square """ if (self.__size <= 0): print() else: for i in range(self.__size): for b in range(self.__size): print("#", end="") print()
# Import the matplotlib.pyplot and numpy libraries. import matplotlib.pyplot as plt import numpy as np # Import the confusion_matrix method from scikit-learn. from sklearn.metrics import confusion_matrix """ Visualize a confusion matrix with labels. """ # Tested results from an experiment y_test = ["cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat"] # Predicted values y_pred = ["dog", "cat", "cat", "cat", "cat", "cat", "dog", "dog", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "dog", "dog", "cat", "dog"] labels = ["cat", "dog"] # Create the confusion matrix. cm = confusion_matrix(y_test, y_pred, labels) # Plot. fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(cm) # Label the matrix. for (i, j), z in np.ndenumerate(cm): ax.text(j, i, "{:0.1f}".format(z), ha="center", va="center", fontsize=36, bbox=dict(facecolor="white")) plt.title("Confusion matrix of the classifier") fig.colorbar(cax) ax.set_xticklabels([""] + labels, fontsize="large") ax.set_yticklabels([""] + labels, fontsize="large") plt.xlabel("Predicted", fontsize="large") plt.ylabel("True", fontsize="large") plt.show()
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns raddf = pd.read_csv("data/santacruz/airborne/santa_cruz_rad.csv", index_col="fid", encoding="utf-8") magdf = pd.read_csv("data/santacruz/airborne/santa_cruz_mag.csv", index_col="fid", encoding="utf-8") # K-Nearest neighbors clustering (kNN) with # greater circle distance as a metric to minimize. # Also kd-tree (kd tree kdtree). def valpoint(p): """ Validate a point. """ lat, lon = p assert -90 <= lat <= 90, "bad latitude" assert -180 <= lon <= 180, "bad longitude" def distance_haversine(a): """ Calculate the great circle distance between two lists of latitudes and longitudes of points on the earth (specified in decimal degrees). Haversine formula: a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √(1−a) ) d = R ⋅ c where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km); note that angles need to be in radians to pass to trig functions! """ lat, lon = a for p in zip(lat, lon): valpoint(p) R = 6371 # km - earths's radius # convert decimal degrees to radians lat, lon = map(np.radians, [lat, lon]) # haversine formula dlon, dlat = np.diff(lon), np.diff(lat) print(dlon) np.insert(dlon, 0) np.insert(dlat, 0) f = np.sin(dlat/2)**2 + np.cos(lat) * np.cos(lat) * np.sin(dlon/2)**2 c = 2 * np.asin(np.sqrt(f)) # 2 * np.atan2(np.sqrt(f), np.sqrt(1-f)) d = R * c return d distances = distance_haversine((magdf["latitude"], magdf["longitude"]))
import csv import os import pandas as pd """ Usage: "python dataskills.py" Use a scaffolding on competencies through various domains of data management. This is based on existing research in data management skills. """ # Check which directory we are in. If we're not in the main journalism # directory, then cd to it. while os.getcwd().split("/")[-1] != "journalism": os.chdir("..") # Check if the output file directory exists. If not, make it. if not os.path.isdir("output/skills"): os.mkdir("output/skills") # Input the .csv as a pandas DataFrame. df = pd.read_csv("data/skills/skills.csv")
"""Functions for scraping IMDB""" from bs4 import BeautifulSoup as bs import requests import re ROOT = "http://imdb.com" def get_html(link): return bs(requests.get(link).text) def get_a(html, find=''): """Finds all the 'a' tags with find in their href""" links = [] for a in html.find_all('a'): if a.get('href').find(find) != -1: links.append(a) return links def episode_list(a): """List of all episodes of a season""" html = get_html(ROOT + a.get('href')) div = html.find('div', {'class': "list detail eplist"}) links = [] for tag in div.find_all('a', {'itemprop': "name"}): links.append(tag) return links def get_rating(html): """Rating of an episode Works for any page with a rating Incase no rating found, returns None """ try: div = html.find('div', {'class': "titlePageSprite star-box-giga-star"}) return div.text.strip(' ') except AttributeError: return None def get_name_date(html): head = html.find('h1', {'class': "header"}) spans = head.findChildren() name = spans[0].text if len(spans) == 2: date = spans[1].text[1:-1] else: date = None return name, date def get_season_epi_num(html): head = html.find('h2', {'class': "tv_header"}) spans = head.findChildren() if len(spans) == 2: season, epi = spans[1].text.split(',') season = re.search('\d+', season).group() epi = re.search('\d+', epi).group() return season, epi else: return None, None def parse_episode(a): """Collects data related to an episode""" d = {} html = get_html(ROOT + a.get('href')) d['rating'] = get_rating(html) d['episode-name'], d['date'] = get_name_date(html) season, d['episode-num'] = get_season_epi_num(html) return season, d def parse(link): """Parses a Tv Series returns the dataset as a dictionary """ html = get_html(link) data = {'rating': get_rating(html), 'name': get_name_date(html)[0]} div = html.find(id="title-episode-widget") season_tags = get_a(div, find="season=") episodes = {} for slink in season_tags: for e in episode_list(slink): season, d = parse_episode(e) if season in episodes: episodes[season].append(d) else: episodes[season] = [d] data['episodes'] = episodes return data
import six from tabulate import tabulate __all__ = ["dict_to_string", "merge_as_list", "ask_to_proceed_with_overwrite", "create_table"] def create_table(small_dict): """ Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. Args: small_dict (dict): a result dictionary of only a few items. Returns: str: the table as a string. """ keys, values = tuple(zip(*small_dict.items())) table = tabulate( [values], headers=keys, tablefmt="pipe", floatfmt=".3f", stralign="center", numalign="center", ) return table def dict_to_string(d, fmt="%.4f"): s = "" for k, v in d.items(): fmt_string = "%s: " + fmt + " - " s += fmt_string % (k, v) if d: s = s[:-2] return s def merge_as_list(*args): out = [] for x in args: if x is not None: if isinstance(x, (list, tuple)): out += x else: out += [x] return out def ask_to_proceed_with_overwrite(filepath): """Produces a prompt asking about overwriting a file. Parameters: filepath: the path to the file to be overwritten. Returns: True if we can proceed with overwrite, False otherwise. """ overwrite = six.moves.input('[WARNING] %s already exists - overwrite? ' '[y/n]' % (filepath)).strip().lower() while overwrite not in ('y', 'n'): overwrite = six.moves.input('Enter "y" (overwrite) or "n" ' '(cancel).').strip().lower() if overwrite == 'n': return False print('[TIP] Next time specify overwrite=True!') return True
import pandas as pd import numpy as np import acquire as a import os def clean_sales_data(): ''' Requires no inputs and returns cleaned sales data df ''' df = a.combined_df() # call acquire function to get all data from API df = df.drop(columns=['item', 'store']) # drop redundant columns df.sale_date = pd.to_datetime(df.sale_date.apply(lambda x: x[:-13])) # convert data column into datetime dtype removing unneeded data df = df.set_index('sale_date') # set data column as index df['month'] = df.index.month_name() # add month name column df['day_of_week'] = df.index.day_name() # add day name column df['sales_total'] = df.sale_amount * df.item_price # add total sale amount column return df def get_clean_sales_data(): ''' This function reads data, writes data to a csv file if a local file does not exist, and returns a df. ''' if os.path.isfile('clean_sales_data.csv'): # If csv file exists, read in data from csv file. df = pd.read_csv('clean_sales_data.csv', index_col=0, parse_dates=True) else: # Read fresh data from db into a DataFrame and clean df = clean_sales_data() # Write DataFrame to a csv file. df.to_csv('clean_sales_data.csv') return df def get_clean_power_data(): ''' Gets and cleans power data with imputation ''' df = a.get_power() # call function from acquire to get data from .csv url df.Date = pd.to_datetime(df.Date) # make date column into datetime dtype df = df.set_index('Date') # set date column as index df['month'] = df.index.month_name() # add month name column df['year'] = df.index.year # add year column # Wind imputation df.Wind = np.where(df.year < 2010, 0, df.Wind) # fill missing values with 0s for dates before data was collected df['wind_previous_day'] = df.Wind.shift(1) # add a column for wind values from previous day to use for remaining imputation df.Wind[np.isnan(df.Wind)] = df.wind_previous_day # impute using value for previous day # Solar imputation df.Solar = np.where(df.year < 2012, 0, df.Solar) # fill missing values with 0s for dates before data was collected df['solar_previous_day'] = df.Solar.shift(1) # add a column for solar values from previous day to use for remaining imputation df.Solar[np.isnan(df.Solar)] = df.solar_previous_day # impute using value for previous day df['solar_previous_day'] = df.Solar.shift(1) # run again since missing values were grouped df.Solar[np.isnan(df.Solar)] = df.solar_previous_day # run again since missing values were grouped df['Wind+Solar'] = np.where(df.year < 2012, 0, df['Wind+Solar']) # set values to 0 for time before solar data was collected df['Wind+Solar'][np.isnan(df['Wind+Solar'])] = df.Wind + df.Solar # impute remaining missing values with sum df = df.drop(columns=['wind_previous_day', 'solar_previous_day']) # drop columns used for imputation that are no longer needed return df
###列表(可变) py_type = ["string","number","list","tuple","dictionary"] print(py_type); human = ["body","head"]; human.append("leg"); ##列表末尾增加 human.insert(1,"arm"); ##在第0个后面增加 print(human) del human[0] ##删除第0个元素 print(human) poped_human = human.pop(); ##删除最后一个元素并使用它(括号内可添加元素对应的序号值) print(poped_human) human.remove("arm"); ##根据值直接删除元素 print(human) learn = ['javascript','python','java','php'] print(sorted(learn)) #临时性正排序 print(learn); learn.sort();#永久正排序 print(learn); learn.reverse();#永久倒排序 print(learn) print(len(learn))#列表长度 for x in learn: #for循环 print(x) print("for is end!") for x in range(0,len(learn)):#常用for循环遍历列表 print(learn[x]); nums = list(range(1,6));#创建一个从1开始到小于6的列表 print(nums) nums1 = list(range(0,15,2))#创建一个从0开始到小于15每个相差2的列表 print(nums1); squares = [] #创建列表 for x in list(range(1,11)): squares.append((x**2)) print(squares) print(min(squares)) print(max(squares)) print(sum(squares)) #列表解析 squares = [value**2 for value in range(1,11)] print(squares) ##demo test #1数到20 nums = [value for value in range(1,21)] print(nums) #计算1-1000000的总和 lists = [value for value in range(1,1000001)] print(min(lists)) print(max(lists)) print(sum(lists)) #1-20之内的奇数 lists = list(range(1,20,2)) print(lists) #3-30内3的倍数 newList = [value for value in range(0,31,3)] print(newList) #-------------------------------------------- ###元组(不可修改) dimensions = (200,50) print(dimensions)
def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ count1 = 0 count2 = 0 newString = '' while count1 != len(s1) and count2 != len(s2): newString += s1[count1] count1 += 1 newString += s2 [count2] count2 += 1 if len(s1) != len(s2): newString += s1[count1:] or s2[count2:] return newString
""" Illustration return a without elements present in both a and b """ def array_diff(a, b): for i in b: if i in a: for j in range(a.count(i)): a.remove(i) return a print(array_diff([1,2,2], [1]))
class Node: def __init__(self, key, data=None): self.key = key self.data = data self.children = {} self.word_count = 0 class Trie: def __init__(self): self.head = Node(None) def insert(self, string): node = self.head for char in string: if char not in node.children: node.children[char] = Node(char) node = node.children[char] node.word_count += 1 node.data = string def search(self, string): node = self.head depth = 0 for char in string: if char in node.children: node = node.children[char] depth += 1 if node.word_count == 1: return depth elif node.data == string: return depth else: return False def solution(words): answer = 0 trie = Trie() for word in words: trie.insert(word) for word in words: answer += trie.search(word) return answer
# Lab 4: List, Tuple, Dictionary # Exercise 1: The List Data Type myFruitList = ["apple", "banana", "cherry"] print(myFruitList) print(type(myFruitList)) print(myFruitList[0]) print(myFruitList[1]) print(myFruitList[2]) myFruitList[2] = "orange" print(myFruitList) # Exercise 2: The Tuple Data Type myFinalAnswerTuple = ("apple", "banana", "pineapple") print(myFinalAnswerTuple) print(type(myFinalAnswerTuple)) print(myFinalAnswerTuple[0]) print(myFinalAnswerTuple[1]) print(myFinalAnswerTuple[2]) # Exericise 3: The Dictionary Data Type myFavoriteFruitDictionary = { "Adam" : "apple", "Ben" : "banana", "Penny" : "pineapple" } print(myFavoriteFruitDictionary) print(type(myFavoriteFruitDictionary)) print(myFavoriteFruitDictionary["Adam"]) print(myFavoriteFruitDictionary["Ben"]) print(myFavoriteFruitDictionary["Penny"])
from Tiles import * from random import shuffle ## @file Bag.py # @author The Trifecta # @brief This method implements the back end model of the bag for the Scrabble game. # @date Feb.15,2020 class Bag: ## @brief initializes the bag model by calling the initBag() method, which adds the default 100 tiles to the bag. def __init__(self): self.bag = [] self.initBag() ## @brief Adds a certain quantity of a certain tile to the bag. Takes a tile and an integer quantity as arguments. # @param1 a tile object that represents the letter tile. # @param2 the number of tiles being added to the back. def addToBag(self, tile, numOfTiles): for i in range(numOfTiles): self.bag.append(tile) ## @brief initializes the bag with the 100 letter tiles needed to play the game. def initBag(self): #Added 1 extra A and S tile compared to regular scrabble game to compensate for removal of blank tile. self.addToBag(Tile("A"), 10) self.addToBag(Tile("B"), 2) self.addToBag(Tile("C"), 2) self.addToBag(Tile("D"), 4) self.addToBag(Tile("E"), 12) self.addToBag(Tile("F"), 2) self.addToBag(Tile("G"), 3) self.addToBag(Tile("H"), 2) self.addToBag(Tile("I"), 9) self.addToBag(Tile("J"), 1) self.addToBag(Tile("K"), 1) self.addToBag(Tile("L"), 4) self.addToBag(Tile("M"), 2) self.addToBag(Tile("N"), 6) self.addToBag(Tile("O"), 8) self.addToBag(Tile("P"), 2) self.addToBag(Tile("Q"), 1) self.addToBag(Tile("R"), 6) self.addToBag(Tile("S"), 5) self.addToBag(Tile("T"), 6) self.addToBag(Tile("U"), 4) self.addToBag(Tile("V"), 2) self.addToBag(Tile("W"), 2) self.addToBag(Tile("X"), 1) self.addToBag(Tile("Y"), 2) self.addToBag(Tile("Z"), 1) shuffle(self.bag) ## @brief Removes a tile from the bag. # @return Returns the tile from the end of the bag. def takeFromBag(self): return self.bag.pop() ## @brief Returns the number of tiles left in the bag. # @return Number of tiles left in the bag. def getRemainingTiles(self): return len(self.bag)
## @file Board.py # @author The Trifecta # @brief This method implements the back end model of the board for the Scrabble game. # @date Apr.06,2020 class Board: ## @brief initializes the board object. def __init__(self): self.backBoard = [["0" for col in range(0, 15)] for row in range(0, 15)] ## @brief returns board object. # @return backBoard. def getBoard(self): return self.backBoard ## @brief updates the back end version of the board with the valid word. # @param1 an integer that represents the row of the starting tile. # @param2 an integer that represents the column of starting tile. # @param3 a string that represents the direction of the word placed on the board. # @param4 a string that represents the word being placed on the board. # @exceptions ValueError if word does not meet board constraints. def updateBackBoard(self, word, row, col, dir): dirLower = dir.lower() wordUp = word.upper() row = int(row) col = int(col) if row > 14 or col > 14 or len(word) > 14: raise ValueError("Word is out of bounds") if(dirLower == "right"): countCol = int(col) for char in wordUp: char = char.upper() self.backBoard[int(row)][int(countCol)] = char countCol += 1 elif(dirLower == "down"): countRow = int(row) for char in word: char = char.upper() self.backBoard[int(countRow)][int(col)] = char countRow += 1 else: raise ValueError("Not a valid direction")
import pandas as pd import matplotlib.pyplot as plt import numpy as np #pre_processing dataset=pd.read_csv('Position_Salaries.csv') X=dataset.iloc[:,1:2].values #level itself decides Y=dataset.iloc[:,2].values #no need of splitting as X contain only 1 col '''from sklearn.cross_validation import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0) #feature Scaling from sklearn.preprocessing import StandardScaler #no use on y sc_X=StandardScaler() # making object X_train=sc_X.fit_transform(X_train) X_test=sc_X.transform(X_test) #test is part so only fit ''' #poly linear regression from sklearn.linear_model import LinearRegression linear_reg=LinearRegression() linear_reg.fit(X,Y) #initial regression (learning) #for polyfeatures from sklearn.preprocessing import PolynomialFeatures poly_reg=PolynomialFeatures(4) #add degree here X_poly=poly_reg.fit_transform(X) #X_poly adds ones vector automatically linear_reg_2=LinearRegression() linear_reg_2.fit(X_poly,Y) #learning final poly X_grid=np.arange(min(X),max(X),0.1) X_grid=X_grid.reshape((len(X_grid),1)) #visualising linear regression over the data set plt.scatter(X,Y,color='red') plt.plot(X,linear_reg.predict(X),color='blue') plt.show() #visualising poly_reg data plt.scatter(X,Y,color='red') plt.plot(X,linear_reg_2.predict(poly_reg.fit_transform(X)),color='blue') #more visualisation plt.scatter(X,Y,color='red') plt.plot(X_grid,linear_reg_2.predict(poly_reg.fit_transform(X_grid)),color='blue') #prediction using linear regression linear_reg.predict(6.5) #enter the inpu here #predict using poly linear_reg_2.predict(poly_reg.fit_transform(6.5))
z=int(input("")) sum=0 rem=0 k=z while k>0: rem=k%10 sum=sum*10+rem k=k//10 if(sum==z): print("yes") else: print("no")
""" Face Detection using Face_recognition and HOG FACE DETECTOR """ import cv2 import dlib import face_recognition from matplotlib import pyplot as plt def show_image_with_matplotlib(color_image,title,pos): """Shows an image using matplotlib capabilities""" img_RGB=color_image[:,:,::-1] ax=plt.subplot(1,2,pos) plt.imshow(img_RGB) plt.title(title) plt.axis('off') def detect_face(img,faces): """Draws a rectangle over each detected face""" for top,right,bottom,left in faces: cv2.rectangle(img,(left,top),(right,bottom),(0,255,0),10) return img # Load image: img=cv2.imread("face_detection.jpg") #img_Gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Perform face detection using face_recognition (internally calls dlib HOG face detector): rects_1=face_recognition.face_locations(img,0,"hog") rects_2=face_recognition.face_locations(img,1,"hog") img_1=detect_face(img.copy(), rects_1) img_2=detect_face(img.copy(), rects_2) # Create the dimensions of the figure and set title: fig=plt.figure(figsize=(10,4)) plt.suptitle("Face Detection using Face_recognition and HOG",fontsize=14,fontweight='bold') fig.patch.set_facecolor('silver') # Plot the images: show_image_with_matplotlib(img_1, "Detector(img,0) :"+str(len(rects_1)), 1) show_image_with_matplotlib(img_2, "Detector(img,1):"+str(len(rects_2)), 2) # Show the Figure: plt.show()
# Python naming convention. # 1- Modules (filenames) all-lowercase names, contains underscores "_" # 2- Packages ( directories) all-lowercase without underscore. # More info in: https://stackoverflow.com/questions/48721582/how-to-choose-proper-variable-names-for-long-names-in-python/48721872#48721872 # Python variables. name_one = "Mario" print(name_one) # console.log(javascript) or puts(Ruby on Rails) # Python variables exercises. # Create two variables, var1 and var2, both with the same value. var1 = 5 var2 = 10 #template string ${} in JS or #{name} in RUBY #The Old way of doing it: %s (s is equal to string) format specifier here to tell Python where to substitute the value of name, represented as a string. print("This is var1 value: %s and this is var2 value: %s" % (var1, var2)) # Newer way, works on python 3 and python 2.7 var1 = 20 var2 = 40 print('This is var1 is now: {a} and var2 also changed!: {b}'.format(a=var1, b=var2)) # STANDARD CONVENTION! Usage of F. Strings is commonly use. only works on +3.6 python num1 = 35 num2 = 55 print(f"This is num1 is now: {num1} and num2 also changed!: {num2}.") # Create two variables, num1 and num2, which multiply together to give 16. num1 = 8 num2 = 2 print(num1 * num2)
#!/usr/bin/env python3 import time class Task: """ Class describing a Task for use in the TaskManager Args: run_at: when should the task run, use "now" for a immediate task recurrence_time: after how many seconds should the task re-occur recurrence_count: how often should the task re-occur """ def __init__(self, *args, **kwargs): """ Define the task name, set the run at time and define recurrence if any kwargs: run_at: when should the task run, use "now" for a immediate task recurrence_time: after how many seconds should the task reoccur recurrence_count: how often should the task reoccur """ run_at = kwargs.get('run_at', None) recurrence_time = kwargs.get('recurrence_time', None) recurrence_count = kwargs.get('recurrence_count', None) self.run_on_nodes = kwargs.get('run_on_nodes', []) self.run_on_groups = kwargs.get('run_on_groups', []) if recurrence_count and not recurrence_time: raise ValueError('Can\'t create recurring task without ' 'providing recurrence_count') if not run_at: self.run_at = time.time() else: self.run_at = run_at self.name = self.__class__.__name__ self.recurrence_time = recurrence_time self.recurrence_count = recurrence_count self.task_id = None def db_record(self): """ Should return what we want to write to the database """ return {'type': self.name, 'recurrence_time': self.recurrence_time, 'recurrence_count': self.recurrence_count, 'run_at': self.run_at, 'run_on_nodes': self.run_on_nodes, 'run_on_groups': self.run_on_groups} def reschedule(self): """ Check if the Task has to reoccur again This should be run by the task_manager class each time it has run a Task that has the potential to be run again """ if self.recurrence_time and not self.recurrence_count: # persistent reoccuring task self.run_at += self.recurrence_time return True elif self.recurrence_time and self.recurrence_count > 1: # no persistent reoccuring task self.run_at += self.recurrence_time self.recurrence_count -= 1 return True else: # one off task return False def run(self): """ Runs the specified task each task type has to overload this function """ raise NotImplementedError class RemoteTask(Task): """ Task that need to communicate through the message_handler """ def __init__(self, message_handler, *args, **kwargs): super().__init__(*args, **kwargs) self.message_handler = message_handler class RegisterNode(RemoteTask): """ Registers a node to the message_handler """ def __init__(self, node_details, *args, **kwargs): super().__init__(*args, **kwargs) self.node_details = node_details def run(self): self.message_handler.register(self.node_details) class UnregisterNode(RemoteTask): """ Unregisters a node from the message_handler """ def __init__(self, node_details, *args, **kwargs): super().__init__(*args, **kwargs) self.node_details = node_details def run(self): self.message_handler.unregister(self.node_details)
import div import add import mult import sub def main(): while True: try: var_a = input('Введите первое число: ') if var_a == "exit": print ('Выход') exit() else: var_a = float(var_a) pass var_c = input("Введите знак операции (+,-,*,/): ") if var_c in ('+', '-', '*', '/'): pass else: print("Неправильный знак. Попробуйте еще раз...") continue var_b = float(input('Введите второе число: ')) except(TypeError, ValueError): print ("Неправильный ввод. Попробуйте еще раз...") continue break if var_c == "/": count = div.div(var_a, var_b) elif var_c == "*": count = mult.mult(var_a, var_b) elif var_c == "+": count = add.add(var_a, var_b) elif var_c == '-': count = sub.sub(var_a,var_b) print("Результат равен "+ str(count)) if __name__ == '__main__': main()
def encode_to_morse(text): '''функция для кодировки текста азбукой Морзе''' itog = [] for i in text.lower(): itog.append(MorseCode[i]) return ' '.join(itog) def decode_from_morse(code): '''функция для декодировки текста из азбуки Морзе''' itog = [] tmp = code.replace(' ', '*') for i in tmp.split(): if i[-1] == '*': itog.append(CharCode.get(i[:-1], '(несуществующая комбинация "{}")'.format(i[:-1]))) itog.append('*') else: itog.append(CharCode.get(i, '(несуществующая комбинация "{}")'.format(i))) return ''.join(itog).replace('*', ' ') def reverse_morse(slovar): '''функция для "разворота" словаря. Меняем ключи и их значения местами''' slovartmp = {} for key, val in slovar.items(): slovartmp[val] = key return slovartmp MorseCode = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', 'а': '.-', 'б': '-...', 'в': '.--', 'г': '--.', 'д': '-..', 'е': '.', 'ж': '...-', 'з': '--..', 'и': '..', 'й': '.---', 'к': '-.-', 'л': '.-..', 'м': '--', 'н': '-.', 'о': '----', 'п': '.--.', 'р': '.-.', 'с': '...', 'т': '-', 'у': '..-', 'ф': '..-.', 'х': '....', 'ц': '-.-.', 'ч': '---.', 'ш': '----', 'щ': '--.-', 'ъ': '.--.-.', 'ы': '-.--', 'ь': '-..-', 'э': '...-...', 'ю': '..--', 'я': '.-.-', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ' ': ' ', '*': '*'} # словари для кодирования и декодирования текста CharCode = reverse_morse(MorseCode) # перевернутый словарь text = input('''Здравствуйте!\nДанная программа передназначена для кодирования и декодирования текста из/в азбуки(у) Морзе на английском и русском языках.\n Введите буквы, цифры или символы. Символы разных букв друг от друга отделяйте одним пробелом, а отдельные слова - тройным пробелом. Программа сама поймет, в какую сторону осуществить перевод:\n''') # проверка введенного текста на допустимые символы proverka = not text.isalnum() and (not text.isalpha() or not text.isdigit()) for i in text: if i in '!@#$%^&*()+="№;%:?*': a = False else: a = True if not a: while proverka: text = input('Упс... Кажется, в тексте присутствуют некодируемые символы. Повторите ввод:\n') proverka = not text.isalnum() and (not text.isalpha() or not text.isdigit()) if text[0].isalnum() or text[0].isalpha() or text[0].isdigit(): print(encode_to_morse(text) + '\nКодирование выполнено!') elif text[0] == '.' or '-': print(decode_from_morse(text) + '\nДекодирование выполнено!') print(decode_from_morse(text) + '\nДекодирование выполнено успешно!')
N = int(input()) lista = [6,2,5,5,4,5,6,3,7,6] for i in range(N): soma = 0 V = input() for x in V: soma += lista[int(x)] print("{} ".format(soma))
""" This problem was asked by Twitter. You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. You should be as efficient with time and space as possible. """ class CircularQueue: def __init__(self, size): self.size = size self.data = [None for _ in range(size)] self.front, self.rear = None, None def record(self, order_id): if self.front is None: # if queue is empty self.front, self.rear = 0, -1 elif (self.rear + 1) % self.size == self.front: self.front = (self.front + 1) % self.size self.rear = (self.rear + 1) % self.size self.data[self.rear] = order_id def get_last(self, i): index = (self.front + self.size - i) % self.size return self.data[index] if __name__ == '__main__': queue = CircularQueue(3) queue.record(1) queue.record(2) queue.record(3) queue.record(4) queue.record(5) queue.record(6) print(queue.get_last(2)) print(queue.get_last(1)) print(queue.get_last(3))
""" This problem was asked by Jane Street. cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. """ # cons(3, 4).__closure__[0].cell_contents is 3 # cons(3, 4).__closure__[1].cell_contents is 4 def cons(a, b): def pair(f): return f(a, b) return pair def car(f): def return_first_element(*pargs): return pargs[0] return f(return_first_element) def cdr(f): def return_second_element(*pargs): return pargs[1] return f(return_second_element) if __name__ == '__main__': print(car(cons(3, 4))) # 3 print(cdr(cons(3, 4))) # 4 print(car(cons(13, 14))) # 13 print(cdr(cons(13, 14))) # 14
#Input #Assignment Statement r = input("What is the radius: ") r = int(r) #Casting is the process of changing type #Strings - collections of characters #int - integers #float - numbers with decimals h = input("What is the height: ") h = int(h) #Process sa = (2 * (3.14) * r * h) + (2 * (3.14) * (r * r)) #Output print(sa)
#f = open("data.txt","w") f = open("data.txt","a") #a = appended to file, it gets added along #with the the other/previous results #f.write("Line 1\n") #f.write("Line 2\n") name = input("What is your name: ") age = input("What is your age: ") f.write(name + "\n") f.write(age + "\n") f.close()
#!/usr/bin/env python3 """ This is the db-connect file. This file contains all the functions that the tool need. """ import psycopg2 DBNAME = "news" def execute_query(query): """ execute_query returns the results of an SQL query. execute_query takes an SQL query as a parameter, executes the query and returns the results as a list of tuples. args: query - an SQL query statement to be executed. returns: A list of tuples containing the results of the query. """ try: db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(query) result = c.fetchall() db.close() return result except (Exception, psycopg2.DatabaseError) as error: print(error) def top_three_articles(): """Display TOP 3 articles sorted by number of views.""" result = execute_query(""" SELECT title, hits FROM articles, path_hits WHERE articles.slug = replace(path_hits.path, '/article/', '') LIMIT 3; """) print("Top 3 most viewed articles of all time: \n") for i, (title, views) in enumerate(result, 1): print('{} - Title: {}'.format(i, title)) print('Views: {}'.format(views)) def top_authors(): """Display top authors based on the sum of views in their articles.""" result = execute_query(""" SELECT authors_table.name, sum(path_hits.hits) AS total FROM authors_table, path_hits WHERE authors_table.slug = replace(path_hits.path, '/article/', '') GROUP BY authors_table.name ORDER BY total DESC; """) print("Top authors based on overall views: \n") for i, (name, views) in enumerate(result, 1): print('{} - Name: {}'.format(i, name)) print('Views: {}'.format(views)) def top_failed_requests(): """Display dates where more than 1% of requests failed.""" result = execute_query(""" SELECT * from date_reqs where error_percent > 1; """) print("Dates where more than 1% of requests failed: \n") for i, (date, percent) in enumerate(result, 1): print( "{} - Date: {} - Failed Requests: {}%".format( i, date, ("{0:.2f}".format(percent))) ) def main(): """Generate Report.""" print('NEWS REPORT TOOL') print('\n') top_three_articles() print('\n') top_authors() print('\n') top_failed_requests() print('\n') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- #----------------------------------------------------------------------- # # FRC Game Field Mapper # # This class maps out an FRC game field including all fixed obstacles, # loading stations, and scoring locations. The game field itself is # divided into M x N squares. An extra square is included on each side # of the field to represent the hard edge walls of the field as well as # potential scoring locations. In code, the field is represented as an # (M+2) x (N+2) NUMPY array. The size of the field as well as the # physical size of each square are read in from a text file. In this # class, the size of the game field is referred to as LENGTH (M) and # WIDTH (N). The size of each grid sqaure is referred to as the # SCALEFACTOR, which has units of inches. # # The field obstacles, loading, and scoring locations are read in from # a separate text file so the map can be customized for each game. # # The position of field/game elements are represented by integers # in the array. The standard integers used every year are: # -1 = impassable field element square # 0 = open field square # 1 = 4121 robot position # 2 = Other robots # The meaning of other integers can vary from game to game and is, # therefore, read in from the same text file used to set the size # of the game field. # # The left edge of the map is assumed to be the alliance stations. # A robot heading of 0 degrees points to the right edge of the field. # Angles are measured clockwise which means a heading of +90 degrees # points to the bottom edge of the field. # # This class provides methods for tracking and returning the # position of the robot in real time. Methods are also provided # to return the direction and distance to the closest scoring # square of a specified type. # # @Version: 1.0 # # @Created: 2019-12-28 # # @Author: Team 4121 # #----------------------------------------------------------------------- '''FRC Field Mapper - Provides tracking of robot on game field''' #Imports import numpy as np import math #Define the field mapper class class FrcFieldMapper: #Define class fields fieldDesignFile="" gameElementsFile = "" elementsMapFile = "" fieldValues = {} fieldMap = 0 robotPosition = [0,0,0] #Define class initialization def __init__(self, designFile, elementsFile, mappingFile): #Set game files self.fieldDesignFile = designFile self.gameElementsFile = elementsFile self.elementsMapFile = mappingFile #Initialize game field self.init_game_field() self.init_game_elements() #Initialize overall structure of game field def init_game_field(self): #Read in the field setup file self.read_field_file() #Setup NUMPY array field representation fieldWidth = int(self.fieldValues["WIDTH"]) + 2 fieldLength = int(self.fieldValues["LENGTH"]) + 2 self.fieldMap = np.zeros(((fieldWidth + 2),(fieldLength + 2)), dtype=int) #Initialize game elements def init_game_elements(self): #Initialize edges of field widthEdge = int(FrcFieldMapper.fieldValues["WIDTH"]) + 1 lengthEdge = int(FrcFieldMapper.fieldValues["LENGTH"]) + 1 self.fieldMap[0:widthEdge,0] = -1 self.fieldMap[0:widthEdge,lengthEdge] = -1 self.fieldMap[0,0:lengthEdge] = -1 self.fieldMap[widthEdge,0:lengthEdge] = -1 #Load current game field elements fieldData = np.loadtxt(FrcFieldMapper.gameElementsFile, dtype=int, delimiter=',') #Apply data to game field for x,y,h in fieldData: self.fieldMap[x,y] = h if h == 1: self.robotPosition[0] = x self.robotPosition[1] = y #Read field setup file def read_field_file(self): #Open the file and read contents try: #Open the file for reading in_file = open(self.designFile, 'r') #Read in all lines value_list = in_file.readlines() #Process list of lines for line in value_list: #Remove trailing newlines and whitespace clean_line = line.strip() #Split the line into parts split_line = clean_line.split(',') #Save the value into dictionary self.fieldValues[split_line[0]] = split_line[1] except: self.fieldValues['LENGTH'] = 54 self.fieldValues['WIDTH'] = 27 self.fieldValues['SCALEFACTOR'] = 12.0 #Round a number to specified decimal places def RoundNumber(self, n, decimals=0): multiplier = 10**decimals round_abs = math.floor(abs(n)*multiplier + 0.5) / multiplier return math.copysign(round_abs, n) #Update robot's position on the field def UpdatePosition(self, distance, angle): #Convert distance and angle to X, Y movement dx = distance * math.cos(math.radians(angle)) dy = distance * math.sin(math.radians(angle)) #Round movement to next highest foot scaleFactor = float(self.fieldValues['SCALEFACTOR']) dx_squares = int(self.RoundNumber((dx / scaleFactor), 0)) dy_squares = int(self.RoundNumber((dy / scaleFactor), 0)) #Adjust robot position current_x = self.robotPosition[0] current_y = self.robotPosition[1] new_x = current_x new_y = current_y if angle <= 90.0 and angle >= -90.0: new_x = current_x + dx_squares if angle >= 0: new_y = current_y + dy_squares else: new_y = current_y - dy_squares else: new_x = current_x - dx_squares if angle >= 0: new_y = current_y + dy_squares else: new_y = current_y - dy_squares self.fieldMap[current_x, current_y] = 0 self.fieldMap[new_x, new_y] = 1 self.robotPosition[0] = new_x self.robotPosition[1] = new_y self.robotPosition[2] = angle
print('\nWelcome the Avgerage Test Caculaator') stop = int (1) #Program Loop while stop != 2: zerocheck = int(0) # Zero Check Var #Checking for Zero while zerocheck == 0: total = input('\nHow many tests did you take? : ') total = int(total) zerocheck = total totalcount = total # Counter var grade = 0 # Grade avg var testcount = 1 # Counter var #Test Score Collection while totalcount != 0: gradesum = input(f'Test {testcount} Grade (0.00 - 100.00): ') gradesum = float(gradesum) while gradesum < 0 or gradesum > 100: print("\nYou inputed an Invaid Grade try again!") gradesum = input(f'Test {testcount} Grade (0.00 -100.00): ') gradesum = float(gradesum) grade = grade + gradesum testcount = testcount + 1 totalcount = totalcount - 1 grade = grade / total # Grade avg #Grade Check if grade >= 90 and grade <= 100: message = 'A' elif grade >= 80 and grade <= 89: message = 'B' elif grade >= 70 and grade <= 79: message = 'C' elif grade >= 60 and grade <= 69: message = 'D' else: message = 'F' grade = round(grade, 2) # Rounds to 2 Dec. print(f'\nAfter taking {total} test(s) you have an avg of {grade} Getting you a {message}!') stop = input('\nDo you want to Try it again? 1 For Yes, 2 For No :') stop = int(stop) while ((stop != 1 or stop == 2) and (stop == 1 or stop != 2)): stop = input('\nInvaid input! Do you want to Try it again? 1 For Yes, 2 For No :') stop = int(stop) zerocheck = int(0) # Zero Check Var print('\nThanks For Running This Program!\n\n')
print('\nWelcome the Avgerage Test Calculator') stop = int (1) #1st Start #1 for go, 2 for Stop Program Loop while stop != 2: zerocheck = int(0) # Zero Check Var #Checking for Zero while zerocheck == 0: # Int only while True: try: print('\n\nRemember 0 is not a good number and Only Whole Numbers!') total = int(input('\nHow many tests did you take? : ')) zerocheck = total break except: print("\n\nReminder Whole Numbers are Allowed, Repeat Input! \n\n") totalcount = total # Counter var grade = 0 # Grade avg var testcount = 1 # Counter var #Test Score Collection while totalcount != 0: # Float Only while True: try: gradesum = float(input(f'Test {testcount} Grade (0.00 - 100.00): ')) break except: print("\n\nNumbers Only, Repeat Input! \n\n") while gradesum < 0 or gradesum > 100: print("\n\nOut of Range!! (0.00 - 100.00)\n\n") gradesum = float(input(f'Test {testcount} Grade (0.00 - 100.00): ')) grade = grade + gradesum testcount = testcount + 1 totalcount = totalcount - 1 grade = grade / total # Grade avg #Grade Check if grade >= 90 and grade <= 100: message = 'A' elif grade >= 80 and grade <= 89: message = 'B' elif grade >= 70 and grade <= 79: message = 'C' elif grade >= 60 and grade <= 69: message = 'D' else: message = 'F' grade = round(grade, 2) # Rounds to 2 Dec. print(f'\nAfter taking {total} test(s) you have an avg of {grade} Getting you a {message}!') #Int Only while True: try: stop = int(input('\nDo you want to Try it again? 1 For Yes, 2 For No :')) break except: print("\n\nInvaid input! 1 For Yes, 2 For No, Repeat Input! \n\n") #1 or 2 Only while ((stop != 1 or stop == 2) and (stop == 1 or stop != 2)): #Int Only while True: try: stop = int(input('\n\nInvaid input! To Try it again 1 For Yes, 2 For No :')) break except: print("\n\nInvaid input! 1 For Yes, 2 For No, Repeat Input! \n\n") zerocheck = int(0) # Zero Check Var print('\n\n\nThanks For Running This Program Goodbye!\n\n\n')
from tkinter import * master = Tk() listbox = Listbox(master) scrollbar = Scrollbar(listbox) scrollbar.pack(side=LEFT, fill=Y) listbox.pack() listbox.insert(END, "a list entry") listy = "hello my name is joseph and I really like to type into lists like these because I can type a lot of words" listy = listy.split() for item in listy: listbox.insert(END, item) mainloop()
""" Program: test_assign_average.py Author: Michael Skyberg, [email protected] Last date modified: June 2020 Purpose: test a switch style statement """ import unittest import unittest.mock as mock from more_fun_with_collections import assign_average as aa class MyTestCase(unittest.TestCase): def test_case_A(self): self.assertEqual(aa.get_switch_value('A'), 90) self.assertEqual(aa.get_switch_value('a'), 90) def test_case_B(self): self.assertEqual(aa.get_switch_value('B'), 80) self.assertEqual(aa.get_switch_value('b'), 80) def test_case_C(self): self.assertEqual(aa.get_switch_value('C'), 70) self.assertEqual(aa.get_switch_value('c'), 70) def test_case_D(self): self.assertEqual(aa.get_switch_value('D'), 60) self.assertEqual(aa.get_switch_value('d'), 60) def test_case_F(self): self.assertEqual(aa.get_switch_value('F'), 50) self.assertEqual(aa.get_switch_value('f'), 50) def test_case_not_exists(self): with self.assertRaises(ValueError): aa.get_switch_value('E') def test_average_grade(self): grade_list = ['A', 'b', 'C', 'd'] self.assertEqual(aa.switch_average(grade_list), 75) if __name__ == '__main__': unittest.TestCase()
# a) number_list = [i for i in range(100)] print(number_list) # b) total = 0 for number in number_list: if number % 3 == 0 or number % 10 == 0: total += number print(total) # c) for i in range(0, len(number_list) - 1, 2): number_list[i], number_list[i + 1] = number_list[i + 1], number_list[i] print(number_list) # d) reversed_list = [] for i in range(len(number_list)-1, -1, -1): reversed_list.append(number_list[i]) print(reversed_list)
def c2f(): c = int(input("Temperatur i celsuis: ")) print(c, "grader celsius er", round((c * 9 / 5) + 32, 1), "grader Fahrenheit.") def f2c(): f = int(input("Temperatur i Fahrenheit: ")) print(f, "grader fahrenheit er", round((f - 32) * 5 / 9, 1), "grader celsius") def main(): c2f() f2c() main()
while True: print('Hei, jeg er THE DOORMAN!') navn = input('Hva heter du? ') alder = int(input('Okey ' + navn + ', hvor gammel er du? ')) if alder < 18: print('Du er for ung,', navn) else: print('Du er gammel nok') full = input('Men er du for full? ') if full == 'ja': print('Du slipper ikke inn, for du er for full!') else: print('Velkommen inn', navn) if input('Igjen? ') == 'j': continue else: break
facebook = [["Mark", "Zuckerberg", 32, "Male", "Married"], ["Therese", "Johaug", 28, "Female", "Complicated"], ["Mark", "Wahlberg", 45, "Male", "Married"], ["Siv", "Jensen", 47, "Female", "Single"]] # a) def add_data(user): list = user.split() list[2] = int(list[2]) return list print(add_data('Mark Zuckerberg 32 Male Married')) # b) def get_person(given_name, facebook): people = [] for i in facebook: if given_name == i[0]: people.append(i) return people print(get_person('Mark', facebook)) # c) def main(): print('Her kan du legge til brukere i fjesboka. Avslutt med "done".') while True: print('Legg inn ny bruker på formen ("given_name surname age gender relationship_status")') user = input() if user == 'done': break facebook.append(add_data(user)) while True: print('Ønsker du søke etter en bruker? (avslutt med "done")') user = input() if user == 'done': break print(get_person(user, facebook)) main()
# Deloppgave a) print("Oppgave a)") def is_leap_year(year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True def weekday_newyear(year): weekdays = ['man', 'tir', 'ons', 'tor', 'fre', 'lor', 'son'] day = 0 for i in range(1900, year + 1): #print(i, weekdays[day % 7]) if is_leap_year(i): day += 2 else: day += 1 weekday_newyear(1919) # Deloppgave b) def is_workday(day): if day % 7 == 5 or day % 7 == 6: return False else: return True print("") # Deloppgace c) print("Oppgave c)") def workdays_in_year(year): for i in range(1900, year + 1): work_days = 0 day = weekday_newyear(i) if is_leap_year(i): days_in_year = 366 else: days_in_year = 365 for j in range(day, days_in_year + day + 1): if is_workday(j): work_days += 1 day += 1 print("%s har %s arbeidsdager" % (i, work_days)) workdays_in_year(1919)
from time import sleep def show_display(content): print() if len(content) == 6 and len(content[0]) == 30: print("####################################") print("# #") for row in content: print('# ' + row.upper() + " #") print("# #") print("####################################") else: print("Error: Wrong dimensions") def enter_line(prompt, length): sentence = '' while len(sentence) != length: sentence = input(prompt + ': ') if len(sentence) != length: print('Input must be', length, 'characters long.') return sentence # print(enter_line('Please input string', 6)) def adjust_string(text, length): if len(text) > length: text = text[:length] elif len(text) < length: tall = length//2 - len(text)//2 return ' '*(length-tall-len(text)) + text + ' '*tall return text # print(adjust_string('12345', 6)) def enter_line_smart(prompt, length): sentence = input(prompt + ': ') sentence = adjust_string(sentence, length) return sentence # print(enter_line_smart('Gi meg en linje a', 5)) def enter_show_text(): liste = [] for i in range(6): text = input('Line ' + str(i+1) + ': ') text = adjust_string(text, 30) liste.append(text) show_display(liste) # enter_show_text() def scroll_display(content, line): for i in range(30): show_display(content) content[line - 1] = content[line - 1][1:] + content[line - 1][0] sleep(0.1) show_display(content) content = ['Dette er en linje med tekst so', '='*30, 'Dette er en linje med tekst so', 'Dette er en linje med tekst so', 'Dette er en linje med tekst so', 'Dette er en linje med tekst so'] # scroll_display(content, 3) def display_from_file(filename): f = open(filename) content = f.readlines() f.close() for i in range(len(content)): content[i] = content[i].rstrip() for i in range(len(content)): content[i] = adjust_string(content[i], 30) for i in range(0, len(content), 6): show_display(content[i:i + 6]) sleep(5) display_from_file('message.txt')
def power(a, n, pow): while n > 0: pow *= a n -= 1 while n < 0: pow /= a n += 1 return(pow) a = float(input()) n = int(input()) pow = 1 print(power(a, n, pow))
str = input() str = str.replace("h", "H") pos1 = str.find("H") pos2 = str.rfind("H") str1 = str[0:pos1] + "h" + str[pos1 + 1:pos2] + "h" + str[pos2 + 1:len(str)] print(str1)
from math import sqrt a = float(input()) b = float(input()) c = float(input()) if a == 0: if b == 0: if c == 0: print("3") else: print("0") else: print("1", c*(-1)/b) else: d = b ** 2 - 4 * a * c if d > 0: x1 = (b * (-1) - sqrt(d)) / (2 * a) x2 = (b * (-1) + sqrt(d)) / (2 * a) print("2", min(x1, x2), max(x1, x2)) elif d == 0: print("1", (b * (-1)) / (2 * a))
import math a = int(input()) summ = 0 sqs = 0 n = 0 while a != 0: summ += a sqs += a**2 n += 1 a = int(input()) s = summ / n ans = (sqs - 2*summ*s + n*s*s) / (n-1) print(math.sqrt(ans))
a = int(input()) aprev = a a = int(input()) count = 0 while a != 0: if a > aprev: count += 1 aprev = a a = int(input()) print(count)
maxm = int(input()) maxm2 = int(input()) if maxm2 > maxm: temp = maxm maxm = maxm2 maxm2 = temp a = int(input()) while a != 0: if a > maxm: maxm2 = maxm maxm = a elif a > maxm2: maxm2 = a a = int(input()) print(maxm2)
str = input() pos1 = str.find("h") pos2 = str.rfind("h") str1 = str[0:pos1] + str[pos2 + 1:len(str)] print(str1)
a = int(input()) count = 1 maxcount = 1 sign = 0 numb = 1 while a != 0: if numb == 1: pass elif numb == 2 and a != aprev: count += 1 elif sign == -1 and a < aprev: count += 1 elif sign == 1 and a > aprev: count += 1 elif a == aprev: count = 1 else: count = 2 if numb == 1: pass elif a > aprev: sign = 1 elif a < aprev: sign = -1 else: sign = 0 if count > maxcount: maxcount = count aprev = a a = int(input()) numb += 1 print(maxcount)
a = int(input()) b = int(input()) c = int(input()) if a >= b: if a >= c: print (a) else: print (c) elif b >= c: print (b) else: print (c)
a1 = 1 a0 = 1 a = int(input()) i = 3 if a == 0: print(0) else: while a0 <= a: temp = a0 a0 += a1 a1 = temp i += 1 if a == a1: print(i-2) else: print("-1")
menu = {'burger':3.5 , 'chips':2.5 , 'drink':1.75} # Establishing dictionary salads = ['cucumber' , 'lettuce' , 'tomato'] # Establishing list sauces = ['mustard', 'bbq', 'tomato'] # Establishing list price = 0 # Initialising value of price outside of function total_price = 0 # Initialising value of total_price outside of function print('Welcome!') # Welcome message # Creating a function to call back in loop. def menu(): global total_price # making variable global so that it is preserved outside of function burger = input('Burger (Y/N): ').lower() # Burger Input if burger == 'y': # if burger, run the rest of the options for the burger. total_price = price + 3.5 # adds price of burger input(f'White bread? (Y/N): ').lower() # Bread Choice, normalised input through .lower() string function input(f'Vegetarian Pattie? (Y/N): ').lower() # Pattie Choice for salad in salads: # loops through elements in list to ask for salads salad_choice = input(f'{salad.capitalize()}? (Y/N): ').lower() # input if salad_choice == 'y': total_price = total_price + 0.75 # adds price per salad in the loop for sauce in sauces: # loops through elements in list to ask for salads sauce_choice = input(f'{sauce.capitalize()}? (Y/N): ').lower() # input if sauce_choice == 'y': total_price = total_price + 0.5 # adds price per sauce chips = input('Chips (Y/N): ').lower() # chips input if chips == 'y': if burger == 'y': total_price = total_price + 1.5 # changes price according to if a burger had been ordered else: total_price = total_price + 2.5 drinks = input('Drink? (Y/N): ').lower() # drink input if drinks == 'y': if burger == 'y': total_price = total_price + 1 # changes price according to if a burger had been ordered else: total_price = total_price + 1.75 return total_price # returns total_ price to the loop outside of the function while True: # creates a loop for the menu function total_price += menu() # runs the function ending = input('Would you like anything more with that? (Y/N): ').lower() # reruns the function if user wants anything more if ending == 'n': # if user has finished the order, total price is given print(f'Your total price comes to ${total_price}!') break # breaks the loop if user has finished
#coding:utf-8 x = int(input()) ans = 'Christmas' for i in range(25-x): ans+=' Eve' print (ans)
#coding:utf-8 K = int(input()) odd = int((K+1)/2) even = int(K/2) print (odd*even)
#coding:utf-8 y = int(input()) if ((y%4==0 and y%100!=0) or y%400==0): print ("YES") else: print ("NO")
N = int(input()) N%=10 if N==3: print('bon') elif N in (0,1,6,8): print('pon') else: print('hon')
#coding:utf-8 S = input().split() d = {"Left":"<", "Right":">", "AtCoder":"A"} S = [d[s] for s in S] print (" ".join(S))
import datetime import json_file import sys class database: def __init__(self): self.json = json_file.return_base_json() def appendToDatabase(self, string): with open("database.csv", "a") as myfile: myfile.write(string) def addToDatabase(self, foodNames): now = datetime.datetime.now() hour = now.hour time_of_day = '' if hour<=10: time_of_day = 'Breakfast' elif hour>10 and hour<=18: time_of_day = 'Lunch' else: time_of_day = 'Dinner' day = now.strftime("%A") print("day -> ", day) csv_text = day + "," + time_of_day + "," + foodNames + "\n" self.add_to_json(day, time_of_day, foodNames) self.appendToDatabase(csv_text) def add_to_json(self, day, time_of_day, foodNames): try: foodNames = foodNames.split(';') foodNames = [x.strip() for x in foodNames] foodNames = [x for x in foodNames if x != ''] print("foodName", foodNames) for days in self.json: print(days.keys()) if day.lower() in days.keys() or day.title() in days.keys(): print("current day", days[day.lower()][time_of_day.lower()], day) days[day.lower()][time_of_day.lower()] += foodNames days[day.lower()][time_of_day.lower()] = list(set(days[day.lower()][time_of_day.lower()])) print("current day", days[day.lower()][time_of_day.lower()], day) print(self.json) except: print("Error in function add_to_json", sys.exc_info()) return if __name__ == '__main__': db = database() db.add_to_json('Sunday', 'lunch', 'Rice; And; Beef;')
# Question: Given an unsorted array, find 2 elements that sum to 15. arr1 = [4, 12, 21, 1, 5] arr2 = [12, 7, 2, 1, 10, 3] def two_element_sum(arr): arr.sort() print("Sorted Array: " + str(arr)) for num, next_num in zip(arr[::], arr[1::]): if num + next_num == 15: return num, next_num return "No 2 elements add up to 15 in this array." print("Arr1: " + str(two_element_sum(arr1))) print("Arr2: " + str(two_element_sum(arr2)))
# 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 i = 0 j = 0 k = 0 while i < len(arrA) and j < len(arrB): if arrA[i] < arrB[j]: merged_arr[k] = arrA[i] i += 1 else: merged_arr[k] = arrB[j] j += 1 k += 1 while i < len(arrA): merged_arr[k] = arrA[i] i += 1 k += 1 while j < len(arrB): merged_arr[k] = arrB[j] j += 1 k += 1 return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): if len(arr) > 1: ind = len(arr) // 2 arrA = merge_sort(arr[:ind]) arrB = merge_sort(arr[ind:]) arr = merge(arrA, arrB) return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): arrA = arr[start:mid] arrB = arr[mid:end] i = 0 j = 0 k = start while i < len(arrA) and j < len(arrB): if arrA[i] < arrB[j]: arr[k] = arrA[i] i += 1 else: arr[k] = arrB[j] j += 1 k += 1 while i < len(arrA): arr[k] = arrA[i] i += 1 k += 1 while j < len(arrB): arr[k] = arrB[j] j += 1 k += 1 return arr def merge_sort_in_place(arr, l, r): if 1 + r - l > 1: mid = (1 + r - l) // 2 + l - 1 arr = merge_sort_in_place(arr, l, mid) arr = merge_sort_in_place(arr, mid+1, r) arr = merge_in_place(arr, l, mid+1, r+1) return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
# Python Program for implementing DFS on a Directed Graph using Adjacency List method (Recursive Method # Riddhesh Bonde - 202170002 visitedNodes = set() # Empty Set from storing visited nodes graph = {} # Empty Dictionary for storing the adjacency List nodes = [] temp_list = [] def nodesInput(): try: while True: nodes.append(int(input("Enter Nodes (press s to stop entering nodes) : "))) except: print(nodes) def dictInput(): for i in nodes: n = input("Enter Visited Nodes for " + str(i) + " (use ',' to seperate nodes or Enter 0 if Node hasn't visited) : ") if n == str(0): temp = [] else: temp = n.split(",") graph[str(i)] = temp print(graph) nodesInput() dictInput() # graph = { # '1' : ['2','3'], # '2' : ['4', '5'], # '3' : ['6'], # '4' : [], # '5' : ['6'], # '6' : [] # } def dfs(visitedNodes, graph, node): if node not in visitedNodes: print (str(node) + "\t") visitedNodes.add(node) for neighbour in graph[node]: dfs(visitedNodes, graph, neighbour) firstNode = input("Start Traversing from Which Node: ") print("DFS Traversal Output: \n") dfs(visitedNodes, graph, firstNode)
print("answer these!!") name = input("what is your name? ") quest = input("enter your company:") color = input("what is your favorite sport:") print(name, quest,color) age = input("what is your age:") print(age)
#!/usr/bin/env python import sys count = 0 word = str(sys.argv[1]) with open('DATA/alice.txt') as alice_in: for raw_line in alice_in: if word in raw_line: count += 1 print(f"There are {count} lines with the word '{word}' in them")
#!/usr/bin/env python movie_star = "Tommy Trotter" print(movie_star) print(movie_star.upper()) print(movie_star.count('t')) print(movie_star.count('Tom')) print(len(movie_star)) print(type(movie_star)) print(movie_star.count('T') + movie_star.count('t')) print(movie_star.lower().count('t')) print(movie_star.startswith('Tom')) print(movie_star.startswith('Brad')) print(movie_star.replace('Tom', 'Brad')) print(movie_star.replace('Tom', '')) s = " All my exes live in Texas " print("|" + s.lstrip() + '|') print("|" + s.rstrip() + '|') print("|" + s.strip() + '|') print() s = "xyxxyyxxxyyyxyxyxyxAll my exes live in Texasxyxyxyxyyyyyy" print("|" + s.lstrip('xy') + '|') print("|" + s.rstrip('xy') + '|') print("|" + s.strip('xy') + '|') print() word_string = 'spink warf blom yuvu' words = word_string.split() print(words) word_string = 'spink/warf/blom/yuvu' words = word_string.split('/') print(words) print(words[0], words[0][0])
#!/usr/bin/env python def add(arg1, arg2): val = float(arg1) + float(arg2) return val def subtract(arg1, arg2): val = float(arg1) - float(arg2) return val def divide(arg1, arg2): if float(arg2) == 0: print("Cannot Divide by Zero") return else: val = float(arg1) / float(arg2) return val def multiply(arg1, arg2): val = float(arg1) * float(arg2) return val def exponent(arg1, arg2): val = float(arg1) ** float(arg2) return val while True: user_value = input("Enter a math expression( ex. '9 + 4' make sure you seperate by whitespace)(q for quit):") if user_value == 'q' or user_value == 'Q': break else: values = user_value.split(' ') if values[1] == '+': result = add(values[0],values[2]) elif values[1] == '-': result = subtract(values[0],values[2]) elif values[1] == '*': result = multiply(values[0],values[2]) elif values[1] == '/': result = divide(values[0], values[2]) elif values[1] == '**': result = exponent(values[0], values[2]) else: print("you didnt follow directions so I quit") break print(f"Your answer is {result}")
#!/usr/bin/env python a_list = [] b_list = [] with open('DATA/alt.txt') as alt_in: for raw_line in alt_in: line = raw_line.strip() if line[0] == 'a': a_list.append(raw_line) elif line[0] == 'b': b_list.append(raw_line) else: print(raw_line.rsplit()) # a_list = sorted(a_list,reverse=True) # b_list = sorted(b_list,reverse=True) with open('a_sort.txt','w') as a_out: a_out.writelines(sorted(a_list,reverse=True)) with open('b_sort.txt','w') as b_out: b_out.writelines(sorted(b_list, reverse=True))
import tensorflow as tf ''' tf.get_default_graph() -->是默认计算图。在Tensorflow程序中,系统会自动维护一个默认的计算图。 a.graph -->获取张量的计算图。a为计算图上面的一个节点 因为a、b张量没有特意指定计算图,所以他们都属于默认计算图上面的节点。所以张量计算图等于默认计算图 每一次运行程序默认计算图tf.get_default_graph()的值都会变化。但是不管怎么变张量计算图等于默认计算图 不同python脚本的默认计算图的值是不一样的。但是同一个脚本获取的值都是一样的 ''' def tensor(): a = tf.constant([1.0, 2.0], name="a") b = tf.constant([2.0, 3.0], name="b") sess = tf.Session() print(sess.run(a)) sess.close() result = a + b print(result) print(b.graph) print(a.graph) print(a.name) print(tf.get_default_graph()) pass ''' 除了使用默认计算图。还可以利用tf.Graph()函数来生成新的计算图。不同计算图上的张量和运算都不会共享 张量情况下:1.在两个计算图上定义了相同张量名的张量,在不指定计算图的情况下,获取的是第二个计算图定义的张量 2.如果在两个计算图上定义了相同张量名v的张量,在指定g2计算图的情况下,获取张量v报错,错误信息显示v不在此g2计算图内 3.在一个指定的计算图里面获取其他计算图的张量,如果不用sess可以获取,用sess.run()获取则会报错不在此计算图内 ''' def tensor_graph(): g1 = tf.Graph() with g1.as_default(): v1 = tf.constant([1.0, 2.0 , 3.0], name="v1") print(v1.graph) g2 = tf.Graph() with g2.as_default(): v = tf.constant([2.0, 3.0], name="v") print(v.graph) g3 = tf.Graph() with g3.as_default(): v = tf.constant([2.0, 3.0], name="v") print(v.graph) print(v) print(v.graph) print(v1) print(v1.graph) with tf.Session(graph=g2) as sess: print(v1) print(v1.graph) try: print(sess.run(v)) print(v.graph) except Exception: print('no graph!') pass def variable_graph(): #在g4计算图上面定义v变量,并初始值为0,shape为必填的参数 g4 = tf.Graph() with g4.as_default(): v = tf.get_variable("v", initializer=tf.zeros_initializer(), shape=[1]) # 在g5计算图上面定义v变量,并初始值为0,shape为必填的参数 g5 = tf.Graph() with g5.as_default(): v = tf.get_variable("v", initializer=tf.ones_initializer(), shape=[1]) #获取g4计算图上面的v变量 with tf.Session(graph=g4) as sess: init = tf.global_variables_initializer() sess.run(init) with tf.variable_scope("", reuse=True): print(sess.run(tf.get_variable("v"))) # 获取g4计算图上面的v变量 with tf.Session(graph=g5) as sess: init = tf.global_variables_initializer() sess.run(init) with tf.variable_scope("", reuse=True): print(sess.run(tf.get_variable("v"))) pass ''' 所有数据都是通过张量的形式来表示。从功能的角度来看,张量可以被简单的理解为多维数组。其中零阶张量表示标量(scalar),也就是一个数 第一阶张量为向量(vector),也就是一个一维数组,第n阶的张量可以理解为一个n维数组。但张量在Tensorflow中的实现并不是直接采用数组的形式, 它只是对Tensorflow中运算结果的引用。在张量中并没有真正的保存数字,他保存的是如何得到这些数字的计算过程。 tf.add的输出结果result为Tensor("add:0", shape=(2,), dtype=float32),里面的三种属性分别为名字(name),维度(shape),类型(type).shape=(2,)表示是一个一维数组,长度为2 定义张量如果不指定类型的话会采用默认类型,比如不带小数点的数会被默认为int32,带小数点的会默认为float32,因为使用默认可能会导致潜在的类型不匹配问题,所以一般建议通过指定dtype来给出变量或者常量的类型。 比如下面的a+b因为类型相同所以不会报错。但是a+c因为类型不同,会报错。但是变量d指定了类型在计算时就不会报错了 Tensorflow支持14种类型,主要包括实数(tf.float32、tf.float64)、整数(tf.int8、tf.int16、tf.int32、tf.int64、tf.uint8)、布尔型(tf.bool)和复数(tf.complex64、tf.complex128) Tensorflow张量使用主要总结为两大类:1.对中间计算结果的引用,比如如下a和b是结果result的中间结果。2.当计算图构造完成后,张量可以用来获取计算结果,也就是得到真实的数字,比如如下sess_result ''' def add_tensor(): #tf.constant是一个计算,这个计算结果为一个张量,保存在变量a中 a = tf.constant([1.0, 2.0], name="a") b = tf.constant([[1.0, 2.0], [2.0, 3.0]], name="b") c = tf.constant([5, 6], name="c") d = tf.constant([7, 8], name="d", dtype=tf.float32) result = tf.add(a, b, name="add") try: result_error = tf.add(a, c, name="add_error") print(result_error) except Exception: print("add error") result_type = tf.add(a, d, name="add_type") print(result_type) print(result) with tf.Session() as sess: sess_result = sess.run(result) print(sess_result) if __name__ == "__main__": # tensor() # tensor_graph() # variable_graph() add_tensor()
def play_the_game(players_num, last_marble_score): winning_score = 0 current_marble = 1 game = [0, 1] current_player = 1 current_marble_index = 1 players_score = [] for i in range(0, players_num): players_score.append(0) while current_marble != last_marble_score: current_marble += 1 current_player = (current_player + 1) % players_num if current_marble % 23 == 0: players_score[current_player] += current_marble additional_score_marble_index = current_marble_index - 7 if additional_score_marble_index < 0: additional_score_marble_index = len(game) + additional_score_marble_index players_score[current_player] += game[additional_score_marble_index] game.remove(game[additional_score_marble_index]) current_marble_index = additional_score_marble_index if players_score[current_player] > winning_score: winning_score = players_score[current_player] else: new_marble_position = (current_marble_index + 2) if new_marble_position == 0 % len(game): game.append(current_marble) else: new_marble_position = new_marble_position % len(game) game.insert(new_marble_position, current_marble) current_marble_index = new_marble_position return winning_score file_read = open("input.txt", "r") line = file_read.readline() PLAYERS_NUM = int(line.split(' ')[0]) LAST_MARBLE_SCORE = int(line.split('worth ')[1].split(' ')[0]) assert play_the_game(9, 25) == 32, 'TEST' # TESTS assert play_the_game(10, 1618) == 8317, '1st assertion failed' assert play_the_game(13, 7999) == 146373, '2nd assertion failed' assert play_the_game(17, 1104) == 2764, '3rd assertion failed' assert play_the_game(21, 6111) == 54718, '4th assertion failed' assert play_the_game(30, 5807) == 37305, '5th assertion failed' print(f'Winning elf score is {play_the_game(PLAYERS_NUM, LAST_MARBLE_SCORE)}.') # Takes so much time print(f'New winning elf score would be {play_the_game(PLAYERS_NUM, LAST_MARBLE_SCORE * 100)} if the last marble score ' f'was 100 times larger.')
class Worker: worker_id = 0 working_on = '' time_left = -1 def __init__(self, wid): self.worker_id = wid def can_step_be_performed(reqs, done): for req in reqs: if not done.__contains__(req): return False return True def get_instruction_time(instr): # return ord(instr) - ord('A') + 1 return 61 + ord(instr) - ord('A') file_read = open("input.txt", "r") #file_read = open("test.txt", "r") line = file_read.readline() # Fill steps info steps_info = dict() while line: symbol = line.split('before step ')[1][0] requirement = line.split('Step ')[1][0] if not steps_info.__contains__(symbol): steps_info[symbol] = [] steps_info[symbol].append(requirement) line = file_read.readline() # for key in steps_info: # print(f'{key}: [{steps_info[key]}]') # Find step that doesn't have requirements. That will be first step. steps_order = '' all_requirements = set() all_requiring_steps = set() steps_that_can_be_initially_performed = [] for key in steps_info: all_requiring_steps.add(key) all_requirements = all_requirements | set(steps_info[key]) steps_that_can_be_initially_performed = list(all_requirements.difference(all_requiring_steps)) steps_that_can_be_initially_performed.sort() # print(all_requirements) # print(all_requiring_steps) # print(steps_that_can_be_initially_performed) # Alphabetically add initial steps to order and to performed steps steps_performed = [] for step in steps_that_can_be_initially_performed: steps_order += step steps_performed.append(step) # Find order of the rest was_all_steps_fired = False i = 0 keys = [k for k in steps_info] steps_that_can_be_performed_now = [] while len(keys) > 0: if can_step_be_performed(steps_info[keys[i]], steps_performed): steps_that_can_be_performed_now.append(keys[i]) i += 1 if i >= len(keys): steps_that_can_be_performed_now.sort() steps_performed.append(steps_that_can_be_performed_now[0]) steps_order += steps_that_can_be_performed_now[0] keys.remove(steps_that_can_be_performed_now[0]) steps_that_can_be_performed_now.clear() i = 0 print(f'Steps have to be completed in following order: {steps_order}.') '''===================== Second Puzzle =====================''' # I'm basing on puzzle 1 as it gathers data I'll need. # Initialize workers and reset variables. WORKERS_NUM = 5 total_time = 0 steps_performed.clear() workers = [] for i in range(0, WORKERS_NUM): workers.append(Worker(i)) steps_to_perform = steps_order # Now that I've got workers initialized I'll start the workflow. while len(steps_performed) != len(steps_order): # Check which steps can now be performed viable_steps = [] for i in range(0, len(steps_to_perform)): if not steps_info.__contains__(steps_to_perform[i]) or \ can_step_be_performed(steps_info[steps_to_perform[i]], steps_performed): viable_steps.append(steps_to_perform[i]) # Assign work if possible for worker in workers: if len(viable_steps) == 0: break if not worker.working_on == '': continue worker.working_on = viable_steps[0] worker.time_left = get_instruction_time(viable_steps[0]) steps_to_perform = steps_to_perform.replace(viable_steps[0], '', 1) viable_steps = viable_steps[1:] print(f'Second ', total_time) for worker in workers: print(f'Worker #{worker.worker_id} working on {worker.working_on}. Time left {worker.time_left}.') # Time flow total_time += 1 for worker in workers: worker.time_left -= 1 # Check if some work was finished for worker in workers: if worker.time_left == 0: steps_performed.append(worker.working_on) worker.working_on = '' worker.time_left = -1 print(f'Done: {steps_performed}') print(f'Sleight building took {total_time} seconds.')
def count_number_of_recipes_until_input_occurrence(n): n = [int(i) for i in n] scores = [3, 7] elves_positions = [0, 1] last_scores = scores[:] position = 0 while True: # Check if we got input if last_scores == n: break # Check if we got input if last_scores == n: break # Count new score new_choco_score = 0 for elf_pos in elves_positions: new_choco_score += scores[elf_pos] # Add this score to board new_choco_score = str(new_choco_score) for char in new_choco_score: scores.append(int(char)) last_scores.append(int(char)) # Move elves for j in range(len(elves_positions)): elves_positions[j] = (elves_positions[j] + 1 + scores[elves_positions[j]]) % len(scores) # Trim last_scores while len(last_scores) > len(n): position += 1 last_scores = last_scores[1:] if last_scores[:-1] == n: return position if last_scores == n: return position return position assert count_number_of_recipes_until_input_occurrence('51589') == 9 assert count_number_of_recipes_until_input_occurrence('01245') == 5 assert count_number_of_recipes_until_input_occurrence('92510') == 18 assert count_number_of_recipes_until_input_occurrence('59414') == 2018 print(f'The scores of the ten recipes immediately after the number of recipes in your puzzle input is \ {count_number_of_recipes_until_input_occurrence("793061")}.')
people = ['Nathaniel', 'Ngethe'] print() for name in people: print(name) index = 0 while index < len(people): print(people[index]) index = index + 1 print()
"""That data.strip().split(',') line looks a little weird. Can you explain what’s going on? A: That’s called method chaining. The first method, strip(), is applied to the line in data, which removes any unwanted whitespace from the string. Then, the results of the stripping are processed by the second method, split(','), creating a list. The resulting list is then applied to the target identifier in the previous code. In this way, the methods are chained together to produce the required result. It helps if you read method chains from left to right. """ """By default, both the sort() method and the sorted() BIF order your data in ascending order. To order your data in descending order, pass the reverse=True argument to either sort() or sorted() and Python will take care of things for you.""" """The sort() method changes the ordering of lists in-place. ƒƒ The sorted() BIF sorts most any data structure by providing copied sorting. ƒƒ Pass reverse=True to either sort() or sorted() to arrange your data in descending order. ƒƒ When you have code like this: new_l = [] for t in old_l: new_l. append(len(t)) rewrite it to use a list comprehension, like this: new_l = [len(t) for t in old_l] ƒƒ To access more than one data item from a list, use a slice. For example: my_list[3:6] accesses the items from index location 3 up-to-but-not-including index location 6. ƒƒ Create a set using the set() factory function."""