text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Sat Aug 8 17:32:05 2020 @author: Ana """ #Napišite program koji će N puta ispisati poruku „ #Pozdrav!” i vrijednost kontrolne varijable. Korisnik unosi N. N = int(input("Unesite broj: ")) for i in range(0 , N): print(i,"Pozdrav")
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 16:50:14 2020 @author: Ana """ #Učitati niz X od n članova ispisati one članove niza X koj #i su veći od prvog (zadnjeg) člana niZA. lista = [] n = int(input("Unesite niz")) for j in range(0,n): broj = int(input("Unesite niz")) lista.append(broj) pocetni_niz = lista[0] for j in range(0, n): if(pocetni_niz < niz[j]): print(niz[j])
# -*- coding: utf-8 -*- """ Created on Sun Aug 16 13:42:14 2020 @author: Ana """ #Napišite program u kojem se učitava # prirodan broj, koji se zatim ispisuje u inverznom # (obrnutom) poretku znamenaka. Ne pretvarati početni broj u string. #Koristite funkciju „Obrni” koja prima jedan broj i v #raća broj u inverznom poretku. #54321 #12345 #5 ??? => 10000 def brojZn(broj): return len(str(broj)) def obrni(broj): reverse = 0 while broj > 0: znamenka = broj % 10 reverse = reverse * 10 + znamenka broj = broj //10 print(reverse) broj = int(input("Unesite broj:")) obrni(broj) obrni2(broj)
import random import sys def script(): registry = random.randint(100, 2000)*99 print("Welcome to the Intergalactic Banking Clan Account Directory.") print() print("Now searching Registry #", registry) print() print("Standard systems have Accounts labled: 0-100") print() runtime = 50 the_list = [] chance = random.randint(0,1) while runtime > 0: if chance == 0: the_list.append(random.randint(0,50)*2) else: the_list.append(random.randint(0,50)*2-1) runtime -= 1 while True: try: print("What Account number are you looking for?") search = input("Please input Account number (cap is 100): ") if int(search) in the_list: print() print("Account located.") print("Location of the Account within the Registry: ", "Vault", the_list.index(int(search))) else: print() print("Account not found, we cannot locate the Account you looking for in our system.") except ValueError: print("Invalid Input.") print() continue while True: print() answer = input("Would you like to look for another Account in THIS system? (y/n): ") answer = answer.lower() print() if answer == "y" or answer == "yes": break elif answer == "n" or answer == "no": print("Logging out of system...") print() break else: print("Invalid Input.") if answer == "n" or answer == "no": break while True: restart = input("Would you like to find another Account in a DIFFERENT system? (y/n): ") restart = restart.lower() print() if restart == "yes" or restart == "y": script() elif restart == "n" or restart == "no": print("Script terminating. Goodbye.") sys.exit() else: print("Invalid Input.") continue script()
def input_tuple(a, b, c): try: user_input = str(input(a)).split(c) tuple_result = list() for x in range(0, len(b)): tuple_result.append(b[x](user_input[x])) return tuple(tuple_result) except: return () def input_tuple_lc(a, b, c): try: user_input = str(input(a)).split(c) return tuple([b[x](user_input[x]) for x in range(0, len(b))]) except: return () def read_tuple(file_obj, types, sep): line = file_obj.readline().split(sep) return [types[x](line[x]) for x in range(0, len(types))] def testif(b, testname, msgOK="", msgFailed=""): """Function used for testing. param b: boolean, normally a tested condition: true if test passed, false otherwise param testname: the test name param msgOK: string to be printed if param b==True ( test condition true) param msgFailed: string to be printed if param b==False returns b """ if b: print("Success: " + testname + "; " + msgOK) else: print("Failed: " + testname + "; " + msgFailed) return b try: print("Result: ", input_tuple("Enter first name, last name, age(float), ID(int), fulltime(bool): ", (str, str, float, int, bool), ",")) print("Result: ", input_tuple("Enter first name, last name, age(float), ID(int), fulltime(bool): ", (str, str, float, int, bool), ",")) f = open("cars.csv", "r") mycar = (make, model, mpg_float, modelYr_int, newcar_bool) = read_tuple(f, (str, str, float, int, bool), ",") print(mycar) f.close() except: print("Error")
def compute_Pythagoreans(n): try: n = int(n) pythagoreans = [(a, b, c) for a in range(1, n + 1) for b in range(1, n + 1) for c in range(1, n + 1) if (a * a + b * b == c * c)] return pythagoreans except: return [] print(compute_Pythagoreans(input("Enter n: ")))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 10 17:04:41 2018 @author: csolje """ FirstName = "Chris" # input("Enter your name: ") def printName(name): print("Hello", name, "how are you") printName(FirstName) printName("Henrik")
# open text file containg the words and add them to an array hangman_words = [] hangman_text = open("hangmanwordlist.txt") for word in hangman_text: hangman_words.append(word.strip().lower()) hangman_text.close() # make a function to return a string containing secret and guessed letters def update_word(secret, show, guess): new = "" for i in range(len(secret)): if show[i] == "-": if guess == secret[i]: new = new + secret[i] else: new = new + "-" else: new = new + show[i] return new # chose a random secret word from array import random secret_word = random.choice(hangman_words) updated = "" count = 0 # display secret word as string of "-"s for i in range(len(secret_word)): updated = updated + "-" print(updated) # initialise array containing wrong guesses wrong_list = [] # main program while True: guess_letter = input("Guess a letter: ") guess_letter = guess_letter.lower() # catch cases of multiple letters or non letters if len(guess_letter) > 1 or guess_letter.isalpha() == False: print("Not a valid guess") continue # player guessed a wrong letter again if not guess_letter in secret_word: if guess_letter in wrong_list: print("You have already guessed this letter") else: wrong_list.append(guess_letter) count = count + 1 updated = update_word(secret_word, updated, guess_letter) print(wrong_list) print(updated) if updated == secret_word: print("You won!") break elif count >= 10: print("you lost!") # player exceeded 10 wrong guesses print("The secret word is " + secret_word) break
from succ import Succ Root = {'value': 1, 'depth':1} def BFS_Tree(node): nodes = [node] visited_nodes = [] while len(nodes) > 0: current_node = nodes.pop(0) visited_nodes.append(current_node) nodes.extend(Succ(current_node)) return visited_nodes print(BFS_Tree(Root))
import sys # Takes in an array of arguments, and return a dictionary of key-value pairs. # For example ["--input=a","--output=b"] will result in # {"input":"a", "output":"b"} def parse_flag(arg_list): result = {} for arg in arg_list: if arg[0:2] != "--" : continue equal_position = arg.find("=") if (equal_position==-1): continue key = arg[2 : equal_position] value = arg[equal_position+1 : ] result[key]=value return result # Main function is test purpose only if __name__ == "__main__": print(parse_flag(sys.argv))
# receive input as integer z = int(input('Enter integers : ')) print(z+1) # casting practice a=1 print(type(a)) x='1' y='2' print(x+y) # lab 2-3-1 i=1234 s='1234' print(i==s) s=int(s) print(i==s) # lab 2-3-2 print('What is your name?') x = input() print('Hi! '+x) print('The length of your name is:') print(len(x)) y = int(input('What is your age? ')) print('You will be', y+1 ,'years old in the next year.') print('Bye~~~!') # print function practice print() print(end='\n') print(print()==print(end='\n')) print('python', 5, 'a', 15) # python 5 a 15 print('python', 5, 'a', 15, sep='+') #python+5+a+15 print('1', '2', '3', sep=' @ ', end=' end', file=open('num.txt', 'w')) # print function - revisited name = '홍길동' print('Hi!', name) # Hi! 홍길동 print('Hi! ' + name) # Hi! 홍길동 # the results are the same # , you can use several data types # + you can use only one data type # print(3, 'a') : success # print(3 + 'a') : fail, you should use only one data type print('a', 3, 'b') # a 3 b print('a ' + str(3) + ' b') # a 3 b # print function and merging string age = input() print('your age is', age) print('당신의 나이는', age, '살 입니다.') print('당신의 나이는', age + '살 입니다.') print('당신의 나이는 {}살 입니다.'. format(age))
# Merge sort def mergeSort(array): if len(array) == 1: return array middleIdx = len(array) // 2 leftHalf = array[:middleIdx] rightHalf = array[middleIdx:] return mergeSortedArrays(mergeSort(leftHalf), mergeSort(rightHalf)) def mergeSortedArrays(leftHalf, rightHalf): sortedArray = [None] * (len(leftHalf) + len(rightHalf)) k = i = j = 0 while i < len(leftHalf) and j < len(rightHalf): if leftHalf[i] <= rightHalf[j]: sortedArray[k] = leftHalf[i] i += 1 else: sortedArray[k] = rightHalf[j] j += 1 k += 1 while i < len(leftHalf): sortedArray[k] = leftHalf[i] i += 1 k += 1 while j < len(rightHalf): sortedArray[k] = rightHalf[j] j += 1 k += 1 return sortedArray # https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays/0 T=int(input()) for i in range(T): n=list(map(int,input().split())) x=n[0] y=n[1] arr1= list(map(int,input().strip().split()))[:x] arr2= list(map(int,input().strip().split()))[:y] arr1.extend(arr2) print(*sorted(arr1)) # https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 t = int(input()) for i in range (t): n = int(input()) a = list(map(int, input().split())) c0=c1=c2 = 0 for i in range(len(a)): if a[i]==0: c0 += 1 elif a[i]==1: c1 += 1 else : c2 +=1 i = 0 while c0 != 0: a[i] = 0 c0 -= 1 i += 1 while c1 != 0: a[i]= 1 c1 -= 1 i += 1 while c2 != 0: a[i]= 2 c2 -= 1 i += 1 print(*a)
class Node: def __init__(self, val): self.val = val self.next = None class Queue: def __init__(self): self.head = None self.tail = None def isEmpty(self): if self.head == None: return True else: return False def enqueue(self, val): cur = Node(val) if self.tail == None: self.tail=self.head=cur print(self.tail.val) return self.tail.next = cur self.tail = cur print(self.tail.val) return def dequeue(self): if self.isEmpty(): print('stack is empty!') return else: cur = self.head self.head = cur.next print(cur.val) if self.head == None: self.tail = None return # q = Queue() # q.enqueue(10) # q.dequeue() # q.enqueue(12) # q.enqueue(14) # q.dequeue() # q.dequeue() # q.dequeue() # q.dequeue() # q.dequeue()
from tkinter import * from PIL import ImageTk, Image root = Tk() root.title("welcome") def open(): global my_image top = Toplevel() top.title("New window") my_image = ImageTk.PhotoImage(Image.open("koro.png")) my_label = Label(top, image=my_image) my_label.pack() btn = Button(top, text='Open new', command=open).pack() def open1(): global image1 top = Toplevel() top.title("hello") image1 = ImageTk.PhotoImage(Image.open("nezuko.png")) label = Label(top, image=my_image).pack() button1 = Button(top, text='Exit', command=top.destroy).pack() button = Button(root, text='Click here', command=open).pack() root.mainloop()
from tkinter import* root=Tk() root.title("hello") def show(): mylabel=Label(root,text=var.get()).pack() var=StringVar() checkbtn=Checkbutton(root, text="check this box", variable=var, onvalue="On", offvalue="Off") checkbtn.deselect() checkbtn.pack() myButton=Button(root, text="Show selection", command=show).pack() mainloop()
#!/usr/bin/python3 n = int(input()) count = 0 while n // 100 != 0: if n % 100 == 0: count = n // 100 n = 0 else: count += n // 100 n %= 100 if n // 20 != 0: count += n // 20 n %= 20 if n // 10 != 0: count += n // 10 n %= 10 if n // 5 != 0: count += n // 5 n %= 5 while n != 0: count += 1 n -= 1 print(count)
""" Core class. Node provides graphviz node creation and edge establishment interface. A node can only have one parent, zero or more children. """ class Node: def __init__(self, id, label="", parent=None, eLabel=""): self.id = id self.label = label self.parent = parent self.children = [] # keep a list of children for easy tracking self.eLabel = eLabel # add self to parent's children list if parent: self.parent.addChild(self) """ Build an edge between self and parent, with an optional label """ def connect(self, parent, eLabel=None): self.parent = parent self.eLabel = eLabel self.parent.addChild(self) def addChild(self, child): self.children.append(child) if __name__ == '__main__': root = Node('one',1) two = Node('two', 2, root) three = Node('three', 3, root) four = Node('four', 4, two) five = Node('five', 5, two) six = Node('six', 6, three) seven = Node('seven', 7, three) from Tree import Tree tree = Tree(root) tree.render() from Graph import Graph graph = Graph(root) graph.render()
*** Executed in leetccode: Yes Challenges: Initially array was going out of bounds. Resolved it. Time complexity: O(N) Space complexity: O(N) with left and right array and O(1) using right variable Comments: Given below. *** class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: length = len(nums) # Left and right arrays to store left and right product (excludes the number at that point) ''' L, R = [0]*length, [0]*length L[0] = 1 R[length - 1] = 1 ''' # To store result result = [0]*length ''' # Product at position i includes products of previous elements for i in range(1, length): # At L(0) it is set as 1 L[i] = L[i - 1] * nums[i - 1] # Product at position i includes products of suceeding elements for i in reversed(range(length - 1)): R[i] = R[i + 1] * nums[i + 1] # Find result - product of left and right arrays for i in range(length): result[i] = L[i] * R[i] ''' # For saving space, instead of calculating left and right array, can do it on the fly # Same logic result[0] = 1 for i in range(1, length): result[i] = result[i-1] * nums[i-1] right = 1 for i in reversed(range(length)): result[i] = result[i] * right right *= nums[i] # After multiplying with result, update right to right * number at that point return result
import pandas as pd # We are working with dataframes and csv files from fbprophet import Prophet import matplotlib.pyplot as plt #Read in NYT dataset df = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv") #What will be the number of cases in the future? df_deaths = df.groupby("date").sum()['deaths'].reset_index() #print(df_cases.head()) #Renaming column names so Prophet can take the dataframe as input. df_deaths.columns = ["ds", "y"] #print(df_deaths.head()) #Instantiate a new Prophet object. m = Prophet() m.fit(df_deaths) #Create a space to store future dataframe (creating future dates) future = m.make_future_dataframe(periods=365) #periods parameter is # of days #print(future.tail()) # Forecasting label values (yhat) forecast = m.predict(future) (forecast[['ds','yhat', 'yhat_lower', 'yhat_upper']].tail()) fig1 = m.plot(forecast) plt.show()
# The purpose of this script is to map the global positivity rates from February 2020 to the present. There is an animated feature so that users can view the dates across different periods in time. It reads in the data from owid covid data and isolates the columns "positive_rate", "location", and "date" and filters out unwanted data. Then, we use the .choropleth() function from plotly express to display the data with animation. import pandas as pd import plotly.express as px import numpy as np def datafilter(): df = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv") df["positive_rate"] = df["positive_rate"]*100 newdf = df.loc[:, ["positive_rate", "location", "date"]].copy() newdf["positive_rate"][0] = 0 for n , i in enumerate(newdf["positive_rate"]): if n == 0: continue if newdf["location"][n-1] != newdf["location"][n] and np.isnan(i): newdf["positive_rate"][n] = 0 newdf["positive_rate"].fillna(method = "ffill") return newdf def animatedChoroplethmap(): our_df = datafilter() print("NOTE: Recent data may not be available") colors = px.colors.sequential.Jet fig = px.choropleth(our_df, locationmode= "country names", locations = our_df["location"], color = "positive_rate", # sets the color values based on the date color_continuous_scale = colors, # sets the colorscale based on array of HEX values hover_name = our_df["location"], animation_frame = our_df["date"], title = "Global Covid-19 Positivity Rates (millions)" ) fig.update_layout( geo = dict( showcoastlines = True, coastlinecolor = "blue", )) fig.write_html("positivityrate.html", auto_open = True)
import time problem_number = 30 test_input = 4 test_solution = 19316 problem_input = 5 def is_sum(power, number): result = 0 for char in str(number): result += power[int(char)] return result == number #Solution def solution(limit): result = 0 power = [i**limit for i in range(10)] exp_limit = 2 while exp_limit*power[9] - 10**exp_limit > 0: exp_limit += 1 for i in range(2, 10**exp_limit): if is_sum(power, i): result += i return result #Test & Result fichier = open("Solution "+str(problem_number)+".txt", "w") string = "" begin_test = time.time() test_value = solution(test_input) end_test = time.time() test_time = end_test - begin_test string += "TEST #1\n\n" string += "Input: "+str(test_input)+"\n" string += "Output: "+str(test_value)+"\n" string += "Answer: "+str(test_solution)+"\n" string += "Computation time: "+str(test_time)+" sec\n" string += "Verification: " if(test_value == test_solution): string += "TRUE" else: string += "FALSE" begin_problem = time.time() problem_value = solution(problem_input) end_problem = time.time() problem_time = end_problem - begin_problem string += "\n\n\nRESULT PROBLEM #"+str(problem_number)+"\n\n" string += "Input: "+str(problem_input)+"\n" string += "Output: "+str(problem_value)+"\n" string += "Computation time: "+str(problem_time)+" sec\n" string += "\n\n\nCurrent date & time: " + time.strftime("%c") fichier.write(string) fichier.close()
import math, random def generate_class_code(total_digits,existing_codes) : digits = ''.join([str(i) for i in range(0,10)]) code = "" while True: for i in range(total_digits) : code += digits[math.floor(random.random() * 10)] if code not in existing_codes: print('Code not in existing codes') break return code
# # 1. 通过用户输入数字,计算阶乘。(30分) # a=int(input("请输入数字:")) # jie=1 # sum=0 # i=1 # # 3=1*1+1*2+2*3=9 # # 3*2*1 # while i<=a: # jie=jie*i # i+=1 # print(jie) # # 将一个列表的数据复制到另一个列表中,并反向排序输出。 # list=[] # list1=[] # import random # for i in range(5): # list.append(random.randrange(10)) # print(list) # list1=list # print(list1) # list1.reverse() # print(list1) # list1=sorted(list1,reverse=True) # print(list1) # list=[] # for i in range(101,201): # bool=True # for j in range(2,i-1): # if(i%j==0): # bool=False # if(bool==True): # print(bool) # list.append(i) # else: # continue # print(list) # for i in range(101,201): # bool=True # for j in range(2,i-1): # if(i%j==0): # bool=False # if(bool==True): # list.append(i) # else: # continue # print(list)
"""Write a program that will add 5 and loop until it reaches a number GREATER than 100. It should then spit out the result AND tell the user how many times it had to add 5 (if any)""" def add5(io): oi = 0 while io < 100: io = io + 5 oi = oi + 1 print(io) print(oi) add5(5) """Write a program that will prompt the user for an input value (n) and double it IF is an ODD number, triple it if is an EVEN number and do nothing if it is anything else (like a decimal or a string)""" def oddEven(n): if n % 2 == 0: n = n * 3 if n % 2 == 1: n = n * 2 return n print(oddEven(1)) print(oddEven(2)) print(oddEven(3.1))
#!/usr/bin/python3 def matrix_divided(matrix, div): """ matrix_divided() - divides all elements of a matrix. matrix: matrix list div: number to divide each element in the matrix Return: a new list matrix """ if type(matrix) != list: raise TypeError(type_err) for lis in matrix: if type(lis) != list: raise TypeError("matrix must be a matrix (list of lists) of \ integers/floats") for num in lis: if num * 0 != 0: raise TypeError("matrix must be a matrix (list of lists) of \ integers/floats") sum_l = sum(len(row) for row in matrix) num_div = sum_l / len(matrix[0]) if num_div.is_integer() is False: raise TypeError("Each row of the matrix must have the same size") if div * 0 != 0: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") new_matrix = [row[:] for row in matrix] for a in new_matrix: for b in range(len(a)): a[b] = round(a[b] / div, 2) return new_matrix
#!/usr/bin/python3 def uniq_add(my_list=[]): sum = 0 uniq = set(my_list) uniq = list(uniq) for i in range(len(uniq)): sum += uniq[i] return sum
#!/usr/bin/python3 def complex_delete(a_dictionary, value): keys_to_be_del = [] if value not in a_dictionary.values(): return a_dictionary for k, v in a_dictionary.items(): if v == value: keys_to_be_del.append(k) for key in keys_to_be_del: if key in keys_to_be_del: a_dictionary.pop(key) return a_dictionary
#!/usr/bin/python3 """Function number_of_lines""" def number_of_lines(filename=""): """return the number of lines in a text file """ with open(filename, encoding="utf-8") as file: text = file.readlines() return len(text)
#string quotes #A string as a sequence of characters not intended to have numeric value. In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably. However, if either single or double quote is a part of the string itself, then the string must be placed in double or single quotes respectively. #For example a text Hello “Python” is to be stored as a string, then one should use str1='Hello "Python"' #On the other hand, if string should resemble Hello ‘Python’ then it should be declared as follows: Str2="Hello 'Python'" print(str1) print(Str2) #case sensitive myname="Darren" print(myname.lower()) print(myname.upper()) #newline print("names:\n 1.DARREN\n 2.LANDRA\n")
#Listas-- conjunto de datos almancenados en una variable. #para crear una lista el nombre=[ele1,ele2...eleN] #las listas son MUTABLES--PUEDE CAMBIAR Estudiantes=['Yessica','Ariel','Gisela','Jesus'] notas=['Jesus',4.7,True] #insertar elemento en una lista APPEND,LO HACE AL FINAL DE LA LISTA Estudiantes.append('profe') print('Nuevo elemento de la lista'.center(50,'*')) print(Estudiantes) print(f'Elemento de la posicion 2 {Estudiantes[2]}') Estudiantes[0]='Chica Gonzalez' print(Estudiantes) print('\n\LISTA ORDENADA ASCENDENTE...') #comando sort-- para ordenar la lista Estudiantes.sort() print (Estudiantes) print('\n\LISTA ORDENADA DESCENDIENTE...') Estudiantes.reverse() print(Estudiantes) #Eliminar elemento en una lista REMOVE print('Eliminar elemento de la lista'.center(50,'*')) Estudiantes.remove ('profe') print('Eliminado el elemento profe') print (Estudiantes)
if 5 > 2: print('5 é de fato maior que 2') else: print('5 não é maior que 2')
from tkinter import * ##creando la raiz: root = Tk() # con grid se imagina como cuadricula label = Label(root, text="Nombre muy largo") label.grid(row=0, column=0, sticky="e", padx=5, pady=5) #sticky es para que se justifique el texto al este, north, suth.. entry = Entry(root) entry.grid(row=0, column=1, padx=5, pady=5) entry.config(justify="right", state="disabled") #con state queda deshabilitado o habilitado(normal) el campo label2 = Label(root, text="Contraseña") label2.grid(row=1, column=0, sticky="w", padx=5, pady=5) #sticky entry2 = Entry(root) entry2.grid(row=1, column=1, padx=5, pady=5) entry2.config(justify="center", show="*") #muestre * en lugar del texto #esta es la interfaz, por eso debe ir de último root.mainloop()
import sqlite3 conexion = sqlite3.connect("ejemplo.db") # para ejecutar coigo sql cursor = conexion.cursor() #1. crear tabla #cursor.execute("CREATE TABLE usuarios (nombre VARCHAR(100), edad INTEGER, email VARCHAR(100))") # 2. insertar un registro a la tabla #cursor.execute("INSERT INTO usuarios values ('Walter',29,'walteralonso@ejemplo.com')") # 3. select de tabla usuarios #cursor.execute("SELECT * FROM usuarios") # 4. obtenga el primer registro (lo devuelve como tupla) #usuario = cursor.fetchone() #print(usuario) # 5. insercion de varios registros """ usuarios = [ ('Pepito', 51, 'pepito@eje.com'), ('Maria', 38, 'maria@eje.com'), ('Juan', 47, 'juan@eje.com') ] cursor.executemany("INSERT INTO usuarios VALUES (?,?,?)", usuarios) """ # 6. obetener todos los registros cursor.execute("SELECT * FROM usuarios") usuarios = cursor.fetchall() print(usuarios) for usuario in usuarios: print(usuario) print("Nombre:"+usuario[0]) conexion.commit() conexion.close()
# -*- coding: utf-8 -*- """ Created on Mon Aug 10 12:34:46 2020 @author: DiSoJi """ import numpy as np import perceptron_model as perceptron import activation_functions as act_funcs """ print("Start") #This area is in case you want to test something before starting everything #Just erase the semicolons input("End") """ sigmoid_func = act_funcs.Sigmoid_Func() #Define activation function as sigmoid relu_func = act_funcs.ReLu_Func() #Define activation function as ReLu #Define the perceptron with the act.func and the number of inputs neural_network = perceptron.Perceptron(relu_func, bias=0, input_size=3, learning_rate=1) #Some training inputs, for a problem where the first value of each input is the one that dictates the output, #so should be weighted the most (and in such a way that overshadows the others) #This can be considered a logistic regretion model #Or even a binary classification problem training_inputs = np.array([[0,0,1], [1,1,1], [1,0,1], [0,1,1]]) #Their respective output training_outputs = np.array([[0,1,1,0]]).T #Transposed to have it as a single coulum matriz with 4 rows #Begin training with the data batch and define number of epochs epochs = 10000 for epoch in range(epochs): #Training loop removed from the neuron's model. This makes training an network possible neural_network.train(training_inputs, training_outputs) #Let's see the final weights! Yay! print("Final Weights") print(neural_network.weights) while(True): #ctrl+C if you want to exit #Let's input a new input to test the Neuron #Did them separated because i couldn't be bothered apparently i1 = str(input("Input 1: ")) i2 = str(input("Input 2: ")) i3 = str(input("Input 3: ")) #In case you make some mistake with the inputs I added a try. Thank me later (probably at 3:00 am or something like that) try: result = neural_network.predict(np.array([i1, i2, i3])) print("Exact Output: ") print(result) #If using sigmoid you can compare with 0.5, where above it is 1 and bellow is 0 except: print("Stop fooling around and input valid numbers")
""" Defines how the style of the input text is to be parsed into a complete book. This depends upon the formatting of the input, and needs to be customized based on the style that it was originally written. """ class StyleSheet(object): def __init__(self): object.__init__(self) def update_section(self, section): """Updates the style and text in the section pulled from the book. Returns it as a complete section, or """ raise NotImplementedError() def start_parser(self): """Signal to start the section parsing.""" raise NotImplementedError() def end_parser(self): """End parsing, and return the final elements (list of them).""" raise NotImplementedError()
import numpy as np from scipy.integrate import solve_ivp def orbit_from_equations(a,e,i,O,w,t0,tf,ts): ''' Propagates orbit using direct equations. Returns position and velocity vectors of a satellite. Parameters: a (float): Semi-major axis Largest radius measured from centre of ellipse e (float): Eccentricity Indicates elliptical shape of orbit i (float): Inclination Angle between elliptical plane and reference plane O (float): Right Ascension of the Ascending Node (RAAN) / Longitude of Ascending Node Angle between reference direction and ascending node in travelling direction of satellite from ascending node Generally represented by Omega w (float): Argument of periapsis / Argument of perigee Angle between ascending node and semi-major axis t0 (int): Time of periapsis passage tf (int): Length of orbit path ts (float): Desired time step between points Returns: position (array): Satellite position vectors in the form [[x0, x1...], [y0, y1...], [z0, z1...]] velocity (array): Satellite velocity vectors in the form [[u0, u0...], [v0, v0...], [w0, w0...]] t_list (array): Time vector associated with position and velocity vectors y0 (array): Initial condition vector in the form [x0, y0, z0, u0, v0, w0] ''' # Define Constants G = 6.67430e-20 # Gravitational Constant (km) ME = 5.9725e24 # Mass of Earth (kg) mu = G*ME # Gravitational Parameter for Earth (km*kg) # Define Rotation Matrices C1_i = np.array([[1,0,0],[0, np.cos(i), np.sin(i)], [0,-np.sin(i), np.cos(i)]]) C3_w = np.array([[np.cos(w),np.sin(w),0],[-np.sin(w), np.cos(w), 0], [0,0, 1]]) C3_O = np.array([[np.cos(O),np.sin(O),0],[-np.sin(O), np.cos(O), 0], [0,0, 1]]) # Move from perifocal to ECI frame C_gp = np.linalg.inv(np.matmul(np.matmul(C3_w, C1_i), C3_O)) # Initializa position and velocity vectors r = [] v = [] t_list = np.arange(t0,tf,ts) for t in t_list: M = np.sqrt(mu/a**3)*(t-t0) # Mean Anomaly E = M # First guess for Newton's method n = 0 # Number of iterations n_max = 20 # Max number of iterations (arbitrary) err = 1 # Initial error value # Find Eccentric Anomaly (E) using Newton's method while(err>=1e-6 and n<=n_max): f = E - e*np.sin(E) - M ff = 1 - e*np.cos(E) E_new = E - f/ff err = abs(E-E_new) E = E_new n = n+1 # Calculate True Anomaly (theta) and Radial Distance (R) theta = 2*np.arctan(np.sqrt((1+e)/(1-e))*np.tan(E/2)) l = a*(1-e**2) R = l/(1+e*np.cos(theta)) # Find r0 and v0 r.append(np.matmul(C_gp, [[R*np.cos(theta)],[R*np.sin(theta)], [0]])) v.append(np.matmul(C_gp, [[-np.sin(theta)],[np.cos(theta) + e], [0]]) * np.sqrt(mu/l)) # Initial position and velocity vector y0 = np.concatenate((r[0], v[0]), axis=None) position = [[], [], []] velocity = [[], [], []] for i in r: position[0].append(float(i[0])) position[1].append(float(i[1])) position[2].append(float(i[2])) for j in v: velocity[0].append(float(j[0])) velocity[1].append(float(j[1])) velocity[2].append(float(j[2])) position = np.array(position) velocity = np.array(velocity) return position, velocity, t_list, y0 ''' References: [1] Spacecraft Dynamics and Control (AER506) Course Notes '''
#!/bin/python3 denominations = [ 200, 100, 50, 20, 10, 5, 2, 1, ] def numdenoms_(index, n): if len(denominations) <= index or n < 0: return 0 if n == 0: return 1 return sum([ numdenoms_(dex, n - val) for [dex, val] in enumerate(denominations) if index <= dex ]) def numdenoms(n): return numdenoms_(0, n) def main(): print(numdenoms(200)) main()
#!/bin/python3 from itertools import permutations as perms from functools import reduce as reduce def maybePan(candidate): try: digits = {*list(range(10))} # Make a set containing every digit for digit in candidate: # Ensure that each digit only occurs 1 time at maximum digits.remove(int(digit)) # return True # If no digit occurred more than once, this *could* possibly form a pandigital number except: return False # If any digit occurred more than once, this can't possibly form a pandigital number def initCandidates(): return map( lambda t: ''.join(map( str, t )), perms( range(10), 3 ) ) def filterPan(candidates): for candidate in candidates: if maybePan(candidate): yield candidate def filterPrime(candidates, prime): for candidate in candidates: if int(candidate[:3]) % prime == 0: yield candidate def addRound(candidates): for candidate in candidates: for i in range(10): yield str(i) + candidate def doRound(candidates, prime): return filterPan( addRound( filterPrime( candidates, prime ) ) ) def main(): return sum(map( int, reduce( lambda candidates, p: doRound(candidates, p), [ 17, 13, 11, 7, 5, 3, 2, ], initCandidates() ) )) print(main())
# -*- coding:utf-8 -*- import datetime import calendar def MonthRange(year=None, month=None): """ :param year: 年份,默认是本年,可传int或str类型 :param month: 月份,默认是本月,可传int或str类型 :return: firstDay: 当月的第一天,datetime.date类型 lastDay: 当月的最后一天,datetime.date类型 """ if year: year = int(year) else: year = datetime.date.today().year if month: month = int(month) else: month = datetime.date.today().month # 获取当月第一天的星期和当月的总天数 firstDayWeekDay, monthRange = calendar.monthrange(year, month) # 获取当月的第一天 firstDay = datetime.date(year=year, month=month, day=1) lastDay = datetime.date(year=year, month=month, day=monthRange) return firstDay, lastDay def dateRange(beginDate, endDate): dates = [] dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d") date = beginDate[:] while date <= endDate: dates.append(date) dt = dt + datetime.timedelta(1) date = dt.strftime("%Y-%m-%d") return dates
"""An API, or application programming interface, is an interface which, to put it generally, allows a user to send data to an application from another, or receive data in an application from another. The Blue Alliance has an API called TBA API that can be used to request data about FRC. The data is returned in a format called JSON (JavaScript Object Notation), which is converted to a native Python object with nested data (lists, dictionaries, etc.), making the data easy to process and use. To get the data, this program uses the requests module. The requests module is not a default module and has to be installed using pip, but the module makes API requests easier to make and is an easy, one-time install.""" import requests, json, sys # imports requests module to make requests to TBA API, json module to process requested data, and sys to access headers argument """API authentication key is stored as a program argument that is included in sys.argv at the program's start. Storing the key in the program would make the key accessible to others if pushed to a git repository, so the better way to access the key is to store it as a program argument. The program arguments are stored as a list, the first item of which is always the file path for the program since the only additional argument is the API key, the index of the key will be 1 as it is the second item.""" key = sys.argv[1] # when making an API request, a "headers" dictionary is needed. For TBA API, the dictionary only requires the string "X-TBA-Auth-Key" set to the value of the auth key. headers = {"X-TBA-Auth-Key":key} # taking the input team number as a string team = input("What team would you like to pick? ") # this dictionary will hold the info for the events of a team eventdict = {} """request the 2017 event data for the given team, using the headers argument (the auth key) as needed for requests.get() because the requested item includes not just the data but also other info like the request status code, appending .text returns just the requested data then json.loads() converts the data from a JSON object to a Python object. The data in this case becomes nested lists and dictionaries""" rawevents = json.loads(requests.get("https://www.thebluealliance.com/api/v3/team/frc" + team + "/events/2017/simple", headers=headers).text) # for each event in the data, create a value/key pair in eventdict in this format: {"2017code":{"name":name,"awards":[]}} for event in rawevents: eventdict["2017" + event["event_code"]] = {"name":event["name"],"awards":[]} # for each event, get the awards earned by the inputted team and append each award's name to the "awards" list in the key-dictionary for that event for event in eventdict: awards = json.loads(requests.get("https://www.thebluealliance.com/api/v3/team/frc" + team + "/event/" + event + "/awards", headers=headers).text) for award in awards: eventdict[event]["awards"].append(award["name"]) # this processes the printed output for each event for event in eventdict: # if no awards were won, a message is printed saying that the inputted team did not win an award at that event if len(eventdict[event]["awards"]) == 0: print("Team " + team + " did not win an award at " + eventdict[event]["name"] + ".") # if 1 award was won, a message is printed saying that the inputted team won that award at that event elif len(eventdict[event]["awards"]) == 1: print("Team " + team + " won the " + eventdict[event]["awards"][0] + " at " + eventdict[event]["name"] + ".") # if 2 awards were won, a message is printed saying that the inputted team won the first award and the second award at that event elif len(eventdict[event]["awards"]) == 2: print("Team " + team + " won the " + eventdict[event]["awards"][0] + " and the " + eventdict[event]["awards"][1] + " at " + eventdict[event]["name"] + ".") # in any other scenario (>2 awards won), the printed message is constructed in two steps else: # an output string is created output = "" # for every award *except the last one*, "the [award]," is added to the output string for award in eventdict[event]["awards"]: if award != eventdict[event]["awards"][-1]: output += "the " + award + ", " # " and the [award]" is added to the output string output += "and" + " the " + eventdict[event]["awards"][-1] # the final output string is in this form: "the [award1], the [award2], the [award3],... and the [lastaward]" # a message is printed saying that the team won [output] at that event print("Team " + team + " won " + output + " at " + eventdict[event]["name"] + ".")
# LECAVELIER Maeva - POUEYTO Clement G2 #Projet Version ++++ 1.6 import random from turtle import * from IA import * nbAllum=0 ordiRetire=0 endgame=0 n=random.randint(1,2) ########################################################################### #TIRE LES REGLES ALEATOIRES ############################################################################ def regleAleatoire(mdj): #hasard pour les règles il peut y avoir 3 4 5 6 7 ou 8 if mdj==2: #si le mode de jeu est 2 = "aléatoire" regle1=[1,2] autreValeur=1 #pour dire qu'on rajoute une valeur dans la liste while autreValeur==1: R1=random.randint(3,8) # valeur de la liste allant de 3 à 8 i=0 while i<len(regle1): #filtre si la valeur est deja dans la liste if R1==regle1[i]: regle1.remove(R1) i=i+1 k=0 while k<len(regle1) and R1>regle1[k]: #esthetique: place dans l'ordre croissant k=k+1 regle1.insert(k,R1) autreValeur=random.randint(0,1) # 1 chance sur 2 de rajouter une valeur dans la liste i=i+1 else: #si le mode de jeu est 1 = "classique" regle1=[1,2,3] return regle1 ############################################################################# #fonction : le joueur retire des allumettes ############################################################################# def retireAllum(nbAllum,regle,mdj): choix=0 condition=False if mdj==2: #pour le mode de jeu aléatoire while condition==False: #tant que la condition n'est pas remplie : c'est-à-dire que le joueur n'a pas donné une valeur valable c=0 choix=int(numinput("A votre tour !","Combien d'allumette(s) à retirer ? ",1,1,8)) while c<len(regle): if choix==regle[c] and nbAllum>=choix: # on vérifie les conditions de validité condition=True c=c+1 else: #pour le mode de jeu classique while choix<1 or choix>3: #assure de prendre le bon nombre d'allumettes choix=100 # pour être sur qu'on rentre dans la boucle la première fois while choix>nbAllum: #assure de ne pas retirer plus d'allumettes que ce qu'il y en a. choix=int(numinput("A votre tour !","Combien d'allumette(s) à retirer ? (1, 2 ou 3) : ",1,1,3)) condition=True nbAllum=nbAllum-choix return nbAllum ############################################################################# #fonction : le jeu peut continuer ? ############################################################################ def jeuValide(nbAllum): if nbAllum > 0: #tant qu'il reste des allumettes endgame=0 #le jeu continue else: #sinon la partie est finie nbAllum=0 endgame=1 return endgame #vérifie que la partie peut continuer et qu'elle n'est pas terminée ############################################################################# #fonction: l'ordinateur retire X allumettes ############################################################################ def playOrdinateur(nbAllum, ordiRetire): nbAllum=nbAllum-ordiRetire return nbAllum #renvoie le nombre d'allumettes apres le tour de l'ordinateur ############################################################################### # IA EN MODE FACILE ## ############################################################################ def ordinateurFacile(regleOrdi,nbAllum,mdj): ordiRetire=1000 #on veut juste un nombre au dessus de 40 : pour rentrer dans la boucle if mdj==2: # mdj 2 difficulte facile while ordiRetire>nbAllum: #ne pas retirer plus que ce qu'il y a d'allumettes. ordiRetire=0 limite=len(regleOrdi)-1 r=random.randint(0,limite)#indice de la liste "regle" ordiRetire=regleOrdi[r] #prend un chiffre dans "regle" else: # mdj 1 difficulte facile while ordiRetire>nbAllum: ordiRetire=random.randint(1,3) return ordiRetire ############################################################################# # TIRE ALEATOIREMENT LE NOMBRE D'ALLUMETTES # ############################################################################ def modeDeJeu(mdj,nbAllum): if mdj==2: nbAllum=random.randint(15,40) # entre 15 et 40 allumettes pour le mode de jeu aléatoire else: nbAllum=random.randint(15,20) #entre 15 et 20 allumettes pour le mode de jeu classique return nbAllum ###########################################################################
from random import random, choice from math import sqrt # This generator simulates a "chaos game" def chaos_game(n, shape_points): # Initialize the starting point point = [random(), random()] for _ in range(n): # Update the point position and yield the result point = [(p + s) / 2 for p, s in zip(point, choice(shape_points))] yield point # This will generate a Sierpinski triangle with a chaos game of n points for an # initial triangle with three points on the vertices of an equilateral triangle: # A = (0.0, 0.0) # B = (0.5, sqrt(0.75)) # C = (1.0, 0.0) # It will output the file sierpinski.dat, which can be plotted after shape_points = [[0.0, 0.0], [0.5, sqrt(0.75)], [1.0, 0.0]] with open("sierpinski.dat", "w") as f: for point in chaos_game(10000, shape_points): f.write("{0}\t{1}\n".format(*point))
from math import atan2 def counter_clockwise(p1, p2, p3): """Is the turn counter-clockwise?""" return (p3[1] - p1[1]) * (p2[0] - p1[0]) >= (p2[1] - p1[1]) * (p3[0] - p1[0]) def polar_angle(ref, point): """Find the polar angle of a point relative to a reference point""" return atan2(point[1] - ref[1], point[0] - ref[0]) def graham_scan(gift): gift = list(set(gift)) # Remove duplicate points start = min(gift, key=lambda p: (p[1], p[0])) # Must be in hull gift.remove(start) s = sorted(gift, key=lambda point: polar_angle(start, point)) hull = [start, s[0], s[1]] # Remove points from hull that make the hull concave for pt in s[2:]: while not counter_clockwise(hull[-2], hull[-1], pt): del hull[-1] hull.append(pt) return hull def main(): test_gift = [ (-5, 2), (5, 7), (-6, -12), (-14, -14), (9, 9), (-1, -1), (-10, 11), (-6, 15), (-6, -8), (15, -9), (7, -7), (-2, -9), (6, -5), (0, 14), (2, 8), ] hull = graham_scan(test_gift) print("The points in the hull are:") for point in hull: print(point) main()
class Node: def __init__(self): self.data = None self.children = [] def create_tree(node, num_row, num_child): node.data = num_row if num_row > 0: for i in range(num_child): child = create_tree(Node(), num_row-1, num_child) node.children.append(child) return node def dfs_recursive(node): if node.data != None: print(node.data, end=' ') for child in node.children: dfs_recursive(child) def dfs_recursive_postorder(node): for child in node.children: dfs_recursive_postorder(child) if node.data != None: print(node.data, end=' ') # This assumes only 2 children, but accounts for other possibilities def dfs_recursive_inorder_btree(node): if len(node.children) == 2: dfs_recursive_inorder_btree(node.children[0]) print(node.data, end=' ') dfs_recursive_inorder_btree(node.children[1]) elif len(node.children) == 1: dfs_recursive_inorder_btree(node.children[0]) print(node.data, end=' ') elif len(node.children) == 0: print(node.data, end=' ') else: print("Not a binary tree!") def dfs_stack(node): stack = [node] while stack: node = stack.pop() stack.extend(node.children) print(node.data, end=' ') def bfs_queue(node): queue = [node] while queue: node = queue.pop(0) queue.extend(node.children) print(node.data) def main(): tree = create_tree(Node(), 2, 3) print("[#]\nRecursive DFS:") dfs_recursive(tree) print() print("[#]\nRecursive Postorder DFS:") dfs_recursive_postorder(tree) print() print("[#]\nStack-based DFS:") dfs_stack(tree) print() print("[#]\nQueue-based BFS:") bfs_queue(tree) print() binary_tree = create_tree(Node(), 3, 2) print("[#]\nRecursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() if __name__ == '__main__': main()
def verlet(pos, acc, dt): prev_pos = pos time = 0 while pos > 0: time += dt next_pos = pos * 2 - prev_pos + acc * dt * dt prev_pos, pos = pos, next_pos return time def stormer_verlet(pos, acc, dt): prev_pos = pos time = 0 vel = 0 while pos > 0: time += dt next_pos = pos * 2 - prev_pos + acc * dt * dt prev_pos, pos = pos, next_pos vel += acc * dt return time, vel def velocity_verlet(pos, acc, dt): time = 0 vel = 0 while pos > 0: time += dt pos += vel * dt + 0.5 * acc * dt * dt vel += acc * dt return time, vel def main(): time = verlet(5, -10, 0.01) print("[#]\nTime for Verlet integration is:") print("{:.10f}".format(time)) time, vel = stormer_verlet(5, -10, 0.01) print("[#]\nTime for Stormer Verlet integration is:") print("{:.10f}".format(time)) print("[#]\nVelocity for Stormer Verlet integration is:") print("{:.10f}".format(vel)) time, vel = velocity_verlet(5, -10, 0.01) print("[#]\nTime for velocity Verlet integration is:") print("{:.10f}".format(time)) print("[#]\nVelocity for velocity Verlet integration is:") print("{:.10f}".format(vel)) if __name__ == '__main__': main()
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] a = [root] b = [] r = [] while a: v = [] for n in a: v.append(n.val) if n.left: b.append(n.left) if n.right: b.append(n.right) a = b b = [] if v: r.append(v) return r[::-1] def test_level_order_bottom(): a = TreeNode(3) b = TreeNode(9) c = TreeNode(20) d = TreeNode(15) e = TreeNode(7) a.left = b a.right = c c.left = d c.right = e assert [ [15, 7], [9, 20], [3] ] == Solution().levelOrderBottom(a)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxLevelSum(self, root): """ :type root: TreeNode :rtype: int """ a = [root] level = 0 maxl, maxv = 1, root.val while a: level += 1 s = 0 b = [] for n in a: if n.left: b.append(n.left) if n.right: b.append(n.right) s += n.val a = b if s > maxv: maxl = level maxv = s return maxl def test_max_level_sum(): a = TreeNode(1) b = TreeNode(7) c = TreeNode(0) d = TreeNode(7) e = TreeNode(-8) a.left = b a.right = c b.left = d b.right = e assert 2 == Solution().maxLevelSum(a)
class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ stack = [] for ch in s: if ch != ']': stack.append(ch) continue sss = [] while stack: v = stack.pop() if v == '[': times, n = 0, 0 while stack and stack[-1].isdigit(): times += int(stack.pop()) * pow(10, n) n += 1 vvv = ''.join(sss[::-1]) * times stack.append(vvv) break sss.append(v) return ''.join(stack) def test_decode_string(): s = Solution() assert "aaabcbc" == s.decodeString("3[a]2[bc]") assert "accaccacc" == s.decodeString("3[a2[c]]") assert "abcabccdcdcdef" == s.decodeString("2[abc]3[cd]ef") assert "lclclclclclclclclclclc" == s.decodeString("11[lc]") assert "zzzyypqefefefefyypqefefefefef" == s.decodeString( "3[z]2[2[y]pq4[e1[f]]]ef")
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def searchBST(self, root: TreeNode, val: int) -> TreeNode: """ :type root: TreeNode :type val: int :rtype: TreeNode """ if root is None or root.val == val: return root if root.val > val: return self.searchBST(root.left, val) if root.val < val: return self.searchBST(root.right, val) def test_search_bst(): a = TreeNode(4) b = TreeNode(2) c = TreeNode(7) d = TreeNode(1) e = TreeNode(3) a.left = b a.right = c b.left = d b.right = e root = Solution().searchBST(a, 2) assert 2 == root.val assert 1 == root.left.val assert 3 == root.right.val assert root.left.left is None assert root.left.right is None assert root.right.left is None assert root.right.right is None
# Definition for a Node. class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ dic = dict() m = n = head while m: dic[m] = Node(m.val, None, None) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = n.next return dic.get(head) def test_copy_random_list(): s = Solution() a = Node(1, None, None) b = Node(2, None, None) b.random = b a.random = b a.next = b aa = s.copyRandomList(a) assert 1 == aa.val assert 2 == aa.next.val assert 2 == aa.random.val assert 2 == aa.next.random.val
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ m = {0: 0, 1: 0, 2: 0} for n in nums: m[n] = m.get(n) + 1 for i in range(m[0]): nums[i] = 0 for i in range(m[0], m[0] + m[1]): nums[i] = 1 for i in range(m[0] + m[1], len(nums)): nums[i] = 2 return nums def test_sort_colors(): r = [2, 0, 2, 1, 1, 0] Solution().sortColors(r) assert [0, 0, 1, 1, 2, 2] == r
class Solution(object): def scoreOfParentheses(self, S): """ :type S: str :rtype: int """ stack = [] for s in S: if s == '(': stack.append(s) else: v = 0 while stack: last = stack.pop() if last == '(': if v > 0: stack.append(v * 2) else: stack.append(1) break else: v += last return sum(stack) def test_score_of_parentheses(): s = Solution() assert 1 == s.scoreOfParentheses("()") assert 2 == s.scoreOfParentheses("(())") assert 2 == s.scoreOfParentheses("()()") assert 6 == s.scoreOfParentheses("(()(()))")
class Solution(object): def canMakeArithmeticProgression(self, arr): """ :type arr: List[int] :rtype: bool """ sa = sorted(arr) diff = sa[1] - sa[0] for i in range(2, len(sa)): if sa[i] - sa[i - 1] != diff: return False return True def test_can_make_arithmetic_progression(): s = Solution() assert s.canMakeArithmeticProgression([3, 5, 1]) assert s.canMakeArithmeticProgression([1, 2, 4]) is False
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ sn = sorted(nums) res = sn[0] + sn[1] + sn[2] min_distance = abs(res - target) for i in range(len(sn) - 2): left, right = i + 1, len(sn) - 1 while left < right: three_sum = sn[i] + sn[left] + sn[right] distance = abs(three_sum - target) if distance == 0: return three_sum if distance < min_distance: min_distance = distance res = three_sum if three_sum < target: left += 1 else: right -= 1 return res def test_three_sum_closest(): s = Solution() assert 2 == s.threeSumClosest([-1, 2, 1, -4], 1) assert 0 == s.threeSumClosest([0, 0, 0], 1) assert 2 == s.threeSumClosest([1, 1, 1, 0], -100) assert 0 == s.threeSumClosest([0, 2, 1, -3], 1)
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head n = head.next head.next = self.swapPairs(n.next) n.next = head return n def test_swap_pairs(): s = Solution() a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(4) a.next = b b.next = c c.next = d head = s.swapPairs(a) assert 2 == head.val assert 1 == head.next.val assert 4 == head.next.next.val assert 3 == head.next.next.next.val
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ if root is None: return [] a = [root] b = [] r = [] while a: s, c = 0, 0 for n in a: s += n.val c += 1 if n.left: b.append(n.left) if n.right: b.append(n.right) r.append(float(s) / c) a = b b = [] return r def test_average_of_levels(): s = Solution() a = TreeNode(3) b = TreeNode(9) c = TreeNode(20) d = TreeNode(15) e = TreeNode(7) a.left = b a.right = c c.left = d c.right = e assert [3, 14.5, 11] == s.averageOfLevels(a)
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ return matrix and \ [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1]) def test_spiral_order(): s = Solution() assert [1, 2, 3, 6, 9, 8, 7, 4, 5] == s.spiralOrder([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) assert [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] == s.spiralOrder([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ])
class Solution(object): def findAndReplacePattern(self, words, pattern): """ :type words: List[str] :type pattern: str :rtype: List[str] """ res = [] for word in words: if len(word) == len(pattern): d1, d2 = {}, {} match = True for i in range(len(word)): if word[i] in d1: if d1[word[i]] != pattern[i]: match = False break else: d1[word[i]] = pattern[i] if pattern[i] in d2: if d2[pattern[i]] != word[i]: match = False break else: d2[pattern[i]] = word[i] if match: res.append(word) return res def test_find_and_replace_pattern(): s = Solution() assert ["mee", "aqq"] == s.findAndReplacePattern( ["abc", "deq", "mee", "aqq", "dkd", "ccc"], "abb")
from functools import cmp_to_key class Solution(object): def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ if sum(nums) == 0: return "0" def compare(x, y): return int(y + x) - int(x + y) sns = sorted([str(s) for s in nums], key=cmp_to_key(compare)) return ''.join(sns) def test_largest_number(): s = Solution() assert s.largestNumber([10, 2]) == "210" assert s.largestNumber([3, 30, 34, 5, 9]) == "9534330" assert s.largestNumber([121, 12]) == "12121" assert s.largestNumber([0, 0]) == "0" assert s.largestNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) == "9876543210"
class Solution(object): def getRow(self, rowIndex): """ :type numRows: int :rtype: List[List[int]] """ if rowIndex == 0: return [1] if rowIndex == 1: return [1, 1] r = [1, 1] for n in range(2, rowIndex + 1): row = [] for k in range(0, n + 1): if k == 0 or k == n: row.append(1) continue row.append(r[k - 1] + r[k]) r = row return r def test_get_row(): s = Solution() assert [1] == s.getRow(0) assert [1, 1] == s.getRow(1) assert [1, 2, 1] == s.getRow(2) assert [1, 3, 3, 1] == s.getRow(3) assert [1, 4, 6, 4, 1] == s.getRow(4)
class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ sws = set(words) ws = sorted(words, key=lambda x: len(x), reverse=True) find = "" length = 0 for word in ws: if find and len(word) < length: break wanted = True for i in range(len(word) - 1, 0, -1): if not word[0:i] in sws: wanted = False break if wanted: if not find or word < find: find = word length = len(find) return find def test_longest_word(): assert "world" == Solution().longestWord( ["w", "wo", "wor", "worl", "world"]) assert "apple" == Solution().longestWord( ["a", "banana", "app", "appl", "ap", "apply", "apple"]) assert "breakfast" == Solution().longestWord( ["b", "br", "bre", "brea", "break", "breakf", "breakfa", "breakfas", "breakfast", "l", "lu", "lun", "lunc", "lunch", "d", "di", "din", "dinn", "dinne", "dinner"]) assert "english" == Solution().longestWord( ["t", "ti", "tig", "tige", "tiger", "e", "en", "eng", "engl", "engli", "englis", "english", "h", "hi", "his", "hist", "histo", "histor", "history"])
class Solution(object): def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ if len(nums) * len(nums[0]) != r * c: return nums res = [] for i in range(len(nums)): ii = i * len(nums[i]) for j in range(len(nums[i])): nth = ii + j if nth % c == 0: res.append([nums[i][j]]) else: res[-1].append(nums[i][j]) return res def test_matrix_reshape(): s = Solution() assert [[1, 2, 3, 4]] == s.matrixReshape([[1, 2], [3, 4]], 1, 4) assert [[1, 2], [3, 4]] == s.matrixReshape([[1, 2], [3, 4]], 2, 4)
class Solution(object): def subtractProductAndSum(self, n): """ :type n: int :rtype: int """ p, s = 1, 0 while n: a = n % 10 p *= a s += a n = n // 10 return p - s def test_subtract_product_and_sum(): s = Solution() assert 15 == s.subtractProductAndSum(234) assert 21 == s.subtractProductAndSum(4421)
class Solution(object): def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ d = {} for i in range(len(nums)): a, b, c = d.get(nums[i], (0, 0, 0)) a = a + 1 if a == 1: b = i else: c = i d[nums[i]] = (a, b, c,) m = 0 r = len(nums) for _, (a, b, c) in sorted(d.items(), key=lambda kv: kv[1], reverse=True): m = max(m, a) if m > a: break if m == 1: r = 1 break r = min(r, c - b + 1) return r def test_find_shortest_subarray(): assert 2 == Solution().findShortestSubArray([1, 2, 2, 3, 1]) assert 6 == Solution().findShortestSubArray([1, 2, 2, 3, 1, 4, 2]) assert 1 == Solution().findShortestSubArray([2, 1])
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num == 0: return False num = self.division(num, 2) num = self.division(num, 3) num = self.division(num, 5) return num == 0 or num == 1 def division(self, num, factor): while num and num % factor == 0: num = num // factor return num def test_is_ugly(): assert Solution().isUgly(0) is False assert Solution().isUgly(1) assert Solution().isUgly(6) assert Solution().isUgly(8) assert Solution().isUgly(14) is False
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True def test_is_palindrome(): s = Solution() assert s.isPalindrome("A man, a plan, a canal: Panama") is True assert s.isPalindrome("race a car") is False assert s.isPalindrome("") is True assert s.isPalindrome(" ") is True
class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ for i in range(0, len(s)): if s[i] == s[len(s) - 1 - i]: continue if self.is_palindrome(s[i + 1:len(s) - i]): return True if self.is_palindrome(s[i:len(s) - 1 - i]): return True return False return True def is_palindrome(self, s): print(s) for i in range(0, len(s) // 2 + 1): if s[i] != s[len(s) - 1 - i]: return False return True def test_valid_palindrome(): assert Solution().validPalindrome("aba") assert Solution().validPalindrome("abc") is False assert Solution().validPalindrome("abca") assert Solution().validPalindrome("deeee")
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.whole_tilt = 0 self.traverse(root) return self.whole_tilt def traverse(self, node): if node: tilt = abs(self.sum_tree(node.left) - self.sum_tree(node.right)) self.whole_tilt += tilt self.traverse(node.left) self.traverse(node.right) def sum_tree(self, node): if not node: return 0 return node.val + self.sum_tree(node.left) + self.sum_tree(node.right) def test_find_tilt(): a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) a.left = b a.right = c s = Solution() assert 1 == s.findTilt(a)
class Solution: def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) for i in range(0, length - 1): if nums[i] != 0: continue k = i while nums[k] == 0 and k < length - 1: k += 1 if nums[k] != 0: nums[i], nums[k] = nums[k], 0 break def test_move_zeroes(): s = Solution() a = [0, 1, 0, 3, 12] s.moveZeroes(a) assert a == [1, 3, 12, 0, 0] a = [0, 1] s.moveZeroes(a) assert a == [1, 0] a = [0] s.moveZeroes(a) assert a == [0] a = [1] s.moveZeroes(a) assert a == [1]
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True stack = [] pre = None while root is not None or len(stack) > 0: while root is not None: stack.append(root) root = root.left root = stack.pop() if pre is not None and root.val <= pre.val: return False pre = root root = root.right return True def test_is_valid_bst_1(): assert Solution().isValidBST(None) is True def test_is_valid_bst_2(): a = TreeNode(3) assert Solution().isValidBST(a) is True def test_is_valid_bst_3(): a = TreeNode(1) b = TreeNode(1) a.left = b assert Solution().isValidBST(a) is False def test_is_valid_bst_4(): a = TreeNode(2) b = TreeNode(1) c = TreeNode(3) a.left = b a.right = c assert Solution().isValidBST(a) is True def test_is_valid_bst_5(): a = TreeNode(5) b = TreeNode(1) c = TreeNode(7) a.left = b a.right = c d = TreeNode(3) e = TreeNode(8) c.left = d c.right = e assert Solution().isValidBST(a) is False def test_is_valid_bst_6(): a = TreeNode(5) b = TreeNode(3) c = TreeNode(9) a.left = b a.right = c d = TreeNode(1) e = TreeNode(4) b.left = d b.right = e f = TreeNode(6) g = TreeNode(10) c.left = f c.right = g assert Solution().isValidBST(a) is True
class Solution(object): def sortString(self, s): """ :type s: str :rtype: str """ ss = sorted(s) res = [] while ss: ss, taken = self.walk(ss) res.extend(taken) if ss: ss, taken = self.walk(ss[::-1]) res.extend(taken) ss = ss[::-1] return ''.join(res) def walk(self, source): remained = [] taken = [] if source: taken.append(source[0]) for v in source[1:]: if v == taken[-1]: remained.append(v) else: taken.append(v) return remained, taken def test_sort_string(): s = Solution() assert "abccbaabccba" == s.sortString("aaaabbbbcccc") assert "art" == s.sortString("rat") assert "cdelotee" == s.sortString("leetcode") assert "ggggggg" == s.sortString("ggggggg") assert "ops" == s.sortString("spo")
class Solution(object): def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ xx = self.sqrt(x, bound) yy = self.sqrt(y, bound) res = set() for i in range(0, xx): a = pow(x, i) for j in range(0, yy): b = pow(y, j) s = a + b if s > bound: break res.add(s) return list(res) def sqrt(self, x, bound): if x == 1: return 1 v = 0 while bound > 0: bound = bound // x v += 1 return v def test_powerful_integers(): r = Solution().powerfulIntegers(2, 3, 10) assert 7 == len(r) assert 2 in r assert 3 in r assert 4 in r assert 5 in r assert 7 in r assert 9 in r assert 10 in r assert [2] == Solution().powerfulIntegers(2, 3, 2) r = Solution().powerfulIntegers(3, 5, 15) assert 6 == len(r) assert 2 in r assert 4 in r assert 6 in r assert 8 in r assert 10 in r assert 14 in r
# Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ res = [] if root is None: return res stack = [root] while stack: curr = stack.pop() res.append(curr.val) stack.extend(curr.children) return res[::-1] def test_post_order(): s = Solution() a = Node(1, []) b = Node(3, []) c = Node(2, []) d = Node(4, []) e = Node(5, []) f = Node(6, []) a.children.append(b) a.children.append(c) a.children.append(d) b.children.append(e) b.children.append(f) assert [5, 6, 3, 2, 4, 1] == s.postorder(a)
class MyHashSet(object): def __init__(self): """ Initialize your data structure here. """ self.factor = 1000000 self.buckets = [False] * self.factor def add(self, key): """ :type key: int :rtype: None """ self.buckets[key % self.factor] = True def remove(self, key): """ :type key: int :rtype: None """ self.buckets[key % self.factor] = False def contains(self, key): """ Returns true if this set contains the specified element :type key: int :rtype: bool """ return self.buckets[key % self.factor] def test_hash_set(): hs = MyHashSet() hs.add(1) hs.add(2) assert hs.contains(1) assert hs.contains(3) is False hs.add(2) assert hs.contains(2) is True hs.remove(2) assert hs.contains(2) is False
class Solution(object): def largestPerimeter(self, A): """ :type A: List[int] :rtype: int """ a = sorted(A)[::-1] first = 0 second = a[0] third = a[1] for i in range(2, len(a)): first = second second = third third = a[i] if second + third > first: return first + second + third return 0 def test_largest_perimeter(): s = Solution() assert 5 == s.largestPerimeter([2, 1, 2]) assert 0 == s.largestPerimeter([1, 2, 1]) assert 10 == s.largestPerimeter([3, 2, 3, 4]) assert 8 == s.largestPerimeter([3, 6, 2, 3])
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True a = [root] b = [] while True: for n in a: if n is None: continue b.append(n.left) b.append(n.right) if not b: break else: a = b if not self.isSymmetricArray(a): return False b = [] return True def isSymmetricArray(self, arr): length = len(arr) for i in range(0, length // 2): if arr[i] is None and arr[length - i - 1] is None: continue if arr[i] is None: return False if arr[length - i - 1] is None: return False if arr[i].val != arr[length - i - 1].val: return False return True def test_is_symmetric_1(): a = TreeNode(1) assert Solution().isSymmetric(a) is True def test_is_symmetric_2(): a = TreeNode(1) b = TreeNode(2) c = TreeNode(2) a.left = b a.right = c assert Solution().isSymmetric(a) is True def test_is_symmetric_3(): a = TreeNode(1) b = TreeNode(2) c = TreeNode(2) d = TreeNode(3) e = TreeNode(4) f = TreeNode(4) g = TreeNode(3) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g assert Solution().isSymmetric(a) is True def test_is_symmetric_4(): a = TreeNode(1) b = TreeNode(2) c = TreeNode(2) d = TreeNode(3) e = TreeNode(3) a.left = b a.right = c b.right = d c.right = e assert Solution().isSymmetric(a) is False def test_is_symmetric_5(): a = TreeNode(1) b = TreeNode(2) c = TreeNode(2) d = TreeNode(3) e = TreeNode(3) a.left = b a.right = c b.right = d c.left = e assert Solution().isSymmetric(a) is True def test_is_symmetric_6(): a = TreeNode(2) b = TreeNode(3) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) f = TreeNode(5) g = TreeNode(4) h = TreeNode(8) i = TreeNode(9) j = TreeNode(9) k = TreeNode(8) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g e.left = h e.right = i g.left = j g.right = k assert Solution().isSymmetric(a) is False
class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} z = 0 for i in range(0, len(s) - 1): if roman[s[i]] < roman[s[i + 1]]: z -= roman[s[i]] else: z += roman[s[i]] return z + roman[s[-1]] def test_roman_to_int(): s = Solution() assert 3 == s.romanToInt("III") assert 4 == s.romanToInt("IV") assert 9 == s.romanToInt("IX") assert 58 == s.romanToInt("LVIII") assert 1994 == s.romanToInt("MCMXCIV")
class Solution(object): # 要注意是最长前缀!!! def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" i = 0 done = False while i < len(strs[0]): v = strs[0][i] for j in range(0, len(strs)): s = strs[j] if i >= len(s): done = True break if v != s[i]: done = True break if done: break i += 1 return strs[0][:i] def test_longest_common_prefix(): s = Solution() assert "fl" == s.longestCommonPrefix(["flower", "flow", "flight"]) assert "" == s.longestCommonPrefix(["dog", "racecar", "car"])
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s res = [[] for _ in range(numRows)] row, down = 0, True for i in range(len(s)): res[row].append(s[i]) if down: row += 1 if row == numRows - 1: down = False else: row -= 1 if row == 0: down = True return ''.join([''.join(a) for a in res]) def test_convert(): s = Solution() assert "PAHNAPLSIIGYIR" == s.convert("PAYPALISHIRING", 3) assert "PINALSIGYAHRPI" == s.convert("PAYPALISHIRING", 4) assert "AB" == s.convert("AB", 1)
class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype: bool """ start, end = 0, 0 for i in range(1, len(s)): if s[i] != s[0]: end += 1 else: if self.repeated(s, end - start + 1): return True else: end += 1 return False def repeated(self, s, k): if len(s) % k != 0: return False for i in range(k, len(s), k): if s[i:i + k] != s[i - k:i]: return False return True def test_repeated_substring_pattern(): s = Solution() assert s.repeatedSubstringPattern("abab") assert s.repeatedSubstringPattern("aba") is False assert s.repeatedSubstringPattern("abcabcabcabc")
class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ d = {} for move in moves: d[move] = d.get(move, 0) + 1 return d.get('U', 0) == d.get('D', 0) and \ d.get('L', 0) == d.get('R', 0) def test_judge_circle(): assert Solution().judgeCircle("UD") assert Solution().judgeCircle("LL") is False assert Solution().judgeCircle("RLUURDDDLU")
class Solution(object): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ r = [] for i in range(left, right + 1): if self.is_self_dividing(i): r.append(i) return r def is_self_dividing(self, n): v = n while v > 0: mod = v % 10 if mod == 0: return False if n % mod != 0: return False v = v // 10 return True def test_self_dividing_numbers(): s = Solution() assert [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] == s.selfDividingNumbers(1, 22)
import heapq class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class CmpNode: def __init__(self, node): self.node = node self.val = node.val def __gt__(self, another): return self.val > another.val class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ h = [] for node in lists: if node: heapq.heappush(h, CmpNode(node)) if not h: return None head, prev = None, None while h: cmpn = heapq.heappop(h) if not head: head = cmpn.node prev = head else: prev.next = cmpn.node prev = cmpn.node if cmpn.node.next: heapq.heappush(h, CmpNode(cmpn.node.next)) return head def test_merge_k_lists_1(): s = Solution() a = ListNode(1, ListNode(4, ListNode(5))) b = ListNode(1, ListNode(3, ListNode(4))) c = ListNode(2, ListNode(6)) r = s.mergeKLists([a, b, c]) assert 1 == r.val assert 1 == r.next.val assert 2 == r.next.next.val assert 3 == r.next.next.next.val assert 4 == r.next.next.next.next.val assert 4 == r.next.next.next.next.next.val assert 5 == r.next.next.next.next.next.next.val assert 6 == r.next.next.next.next.next.next.next.val assert r.next.next.next.next.next.next.next.next is None
class Auto: tuneado = False def __init__(self, puertas=None, color=None): self.pertas = puertas self.color = color if puertas is not None and color is not None: print(f'Se ha creado un auto con {puertas} puertas y color {color}.') else: print('Se ha creado un auto.') def tunear(self): self.tuneado = True def confirmar(self): if self.tuneado == True: print('Se ha tuneado el auto.') else: print('No se ha tuneado el auto.') def __del__(self): print('Se eliminó el auto', self.color) a = Auto(5,'negro') a.confirmar() a.tunear() a.confirmar() b = Auto(3,'amarillo')
#v = quantidade de numeros no vetor #ai elevado a 2 #formula: 2^v - 1 = x #soma dos numeros elevados ao que tem no vetor def calculateFormula(sommatory): return pow(2,sommatory) - 1 n = int(input()) numbers = list(dict.fromkeys(list(map(int,input().split()))).keys()) ##v = len(numbers) ##for i in numbers: ## sommatory += i ## powedNumbers += pow(2,i) ##res = calculateFormula(sommatory) maximum = max(numbers) count = len(numbers) print(maximum - count + 1) ##print(powedNumbers) ##print(res) ##if powedNumbers == res: ## print(0) ##else: ## i = 0 ## sumOfMissing = 0 ## nums = 0 ## while i < sommatory: ## if i not in numbers: ## nums += 1 ## sumOfMissing += pow(2,i) ## if sumOfMissing+powedNumbers >= res: ## if sumOfMissing == res: ## print(nums) ## i += 1
import sqlite3 from sqlite3 import Error import MySQLdb class database: def execute_sql(self, sql): self.conn = self.create_connection() self.cur = self.conn.cursor() self.cur.execute(sql) self.conn.commit() def create_sqlite_connection(self, db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return None def create_connection(self): try: conn = MySQLdb.connect(host="111.185.227.34", # your host, usually localhost user="web104", # your username passwd="cnap*74182", # your password db="cstock", port=3307, use_unicode=True, charset="utf8") # name of the data base return conn except Error as e: print(e) return None
# -*- coding: utf-8 -*- """ Created on Sun May 27 16:47:28 2018 @author: Administrator """ def list2string(spam): s = spam[0] for i in range(len(spam)-2): i += 1 s += ', '+spam[i] s += ' and '+spam[len(spam)-1] print(s) spam = ['apples','bananas'] list2string(spam)
#!/usr/bin/python # This program is to convert the band gap to the wavelength corresponding light. import math gap=float(input('Please input the gap(in ev) ')) ee=1.60217662 *10**-19 # elementary charge cc=299792458.0 # speed of light hh=6.62607004*10**-34 #Planck's constant wl=hh*cc/gap/ee *10**9 # in nano meters print 'the wavelength (in nm) of the corresponding light is ', wl
''' http://developer.51cto.com/art/201403/430986.htm 常见的排序算法 2017-10-12 ''' class QuickSort: def quickSort(self, nums): ''' 快速排序 ''' self.quickSortDetail(nums, 0, len(nums) - 1) return nums def quickSortDetail(self, nums, left, right): if left > right: return None # 基准数 stdMark = nums[left] i, j = left, right # 右边[小于]基准的数据与左边[大于]基准的数据进行交换,递增 # 反之,递减 while i != j: while nums[j] >= stdMark and j > i: j -= 1 while nums[i] <= stdMark and j > i: i += 1 nums[i], nums[j] = nums[j], nums[i] # 基准归位 nums[left], nums[i] = nums[i], nums[left] # 基准左边进行排序 self.quickSortDetail(nums, left, j - 1) # 基准右边进行排序 self.quickSortDetail(nums, i + 1, right) class HeapSort: def heapSort(self, nums): ''' 堆排序 ''' n = len(nums) # 创最大堆 self.heapCreate(nums, n) while n > 0: # 将最大值放到最后一片叶子 nums[0], nums[n - 1] = nums[n - 1], nums[0] # 除去最大点 n -= 1 # 保持堆特性 self.heapCreate(nums, n) return nums def heapCreate(self, nums, n): ''' 将nums改变成一个最大堆 最大堆比最小堆效率更高,不需要额外的空间来存临时输值 ''' # 叶子节点忽略,因为他们没有儿子 # 从最后一片叶子向根节点保持最大堆特性 i = n // 2 while i >= 0: self.heapShift(nums, i, n) i -= 1 def heapShift(self, nums, i, n): ''' 交换父子节点 ''' t = 0 if i * 2 < n: # 左边儿子>父节点 if nums[i * 2] > nums[i]: t = i * 2 else: t = i # 右边儿子>父节点 if i * 2 + 1 < n and nums[i * 2 + 1] > nums[t]: t = i * 2 + 1 if t != i: # 交换父节点与儿子 nums[t], nums[i] = nums[i], nums[t] if __name__ == "__main__": quickSort = QuickSort() heapSort = HeapSort() nums = [45, 9, 2, 19, 2, 4, 0, 2, 6, 8, 33] quickSortNumsStr = ",".join([str(i) for i in quickSort.quickSort(nums[:])]) print("quickSort: "+quickSortNumsStr) heapStortStr = ",".join([str(i) for i in heapSort.heapSort(nums[:])]) print("heapSort: "+heapStortStr)
import shlex, re from typing import List def split(s): if '"' not in s: return s.split(' ') try: return list(shlex.split(s)) except ValueError: pass def check_message(message: str, banned_words: List[str]): for bw in banned_words: if bw.startswith('re:'): if re.search(bw[3:], message, flags=re.IGNORECASE): return True continue s = split(bw) if all([re.search(rf'\b{a}\b', message, flags=re.IGNORECASE) for a in s]): return True return False
def findDelimitor(inputString): for c in inputString: if not( c.isdigit() or c.isalpha()): return c return "" def findThingy(time, arrayDate, arrayFormat): for i in range(0, 3): if time == arrayFormat[i]: return arrayDate[i] return "" def convert(inputString): L = inputString.split() delimitorOrg = findDelimitor(L[0]) delimitorDes = findDelimitor(L[2]) # year goes first, then month, then day arrayActual = L[1].split(delimitorOrg) #Actual format arrayDesired = L[2].split(delimitorDes) # Desired format actualDate = L[0].split(delimitorOrg) final = ["", "", ""] output = "" for i in arrayDesired: output += findThingy(i, actualDate, arrayActual) output += delimitorDes l = output.__len__() return output[0:l-1] if __name__ == "__main__": f = open("output.txt", "w") with open("Calendar-confusion_InputForSubmission_2.txt") as f: for line in f: print((convert(line)))
""" This program will open the quiz in an interactive window and have the user complete the quiz through the web application.""" from flask import Flask, redirect, url_for, render_template, request app = Flask(__name__) # Create instance of web application questions = {"What is the fifth month of the year?":"May", "How many days in a leap year?":"366", "What is 2 + 5?":"7", "True/False - Eleven is a prime number.": "True", "True/False - 5449 is a prime number.": "True", "What is 1230 * 3084?": "3793320", "What is the 17th letter of the alphabet?": "Q", "True/False - The 29th letter of the Greek alphabet is Tau.": "False", "How many legs does a butterfly have?": "6", "What is 8 * 120?": "960", "True/False - The hashtag symbol is technically called an octothorpe.": "True", "True/False - Some cats are allergic to people.": "True", "What is 6869055 - 75594?": "679346", "True/False - Scotland's national symbol is the unicorn.": "True", "True/False - M&M stands for Mars & Milkyway.": "False", "True/False - The odds of getting a royal flush are exactly 1 in 649740.": "True", "What is (500 * (15 / (5 + 10)) - 3520) ** 2?": "9120400", "True/False - There are 15820024210 possible ten-card hands in gin rummy.": "False", "What is a baby puffin is called?": "Puffling", "What is 6 * 6549?": "39294", "True/False - The reason a bug is called a bug in CS is due to a bug being found in a computer.": "True", "What is 6869055 % 75594?": "65595" } @app.route("/", methods=["POST", "GET"]) # Path will take user to the default home page of the game. def login(): return render_template("submitted.html", contents=questions) #if request.method == "POST": # user = request.form["nm"] # return redirect(url_for("user", usr=user)) #else: # return render_template("submitted.html") # Combines template with given dictionary and # will return an HttpResponse object with that rendered text @app.route("/submit") # Will load answers when user presses 'Submit Query' button. def submit(): return render_template("index.html", contents=questions) if __name__ == "__main__": app.run(debug=True)
''' By Jason Krone for Khan Academy Implementation of subset sum Utils ''' BASE_TUPLE = (True, 0, 0) def subset_sum_within_range(nums, n, delta): ''' returns a subset of the given numbers that sum within the given range (n - delta, n + delta) if such a subset exists. Otherwise, returns None ''' assert nums subset = None subset_sum_arr = positive_subset_sum_table(nums, n + delta) # loop through values in range n - k to n + k for i in range(n - delta, n + delta + 1): # check if there is a sum set sum to i if type(subset_sum_arr[i]) is tuple and subset_sum_arr[i] != BASE_TUPLE: # get the subset that sums to i subset = get_subset_with_sum(subset_sum_arr, i) break return subset def get_subset_with_sum(table, n): ''' returns the subset of numbers listed in the table that sum to n ''' assert table subset = [] i = n while i > 0: subset.append(table[i][1]) i = table[i][2] return subset def positive_subset_sum_table(A, x): ''' attribution: this code was modified from http://www.geekviewpoint.com/python/dynamic_programming/positive_subset_sum ''' assert A # algorithm sub_sum = [None] * ( x + 1 ) sub_sum[0] = BASE_TUPLE p = 0 while not sub_sum[x] and p < len( A ): a = A[p] q = x while not sub_sum[x] and q >= a: if not sub_sum[q] and sub_sum[q - a]: sub_sum[q] = (True , a, q - a) q -= 1 p += 1 return sub_sum
from Components.Component import Component import sqlite3 class Database(Component): """ A database class that implements database creation and methods to read and write from the database. """ def __init__(self): """ Initializes a Database object, calls the parent constructor, and connects to a sqlite3 database. """ super().__init__("Database", 1) self.connection = sqlite3.connect('db.sqlite3') def update(self, context): """ Concrete implementation of Component.update(). Takes a dictionary (context) as a parameter, and writes it to a new row in the database. """ print(context) cursor = self.connection.cursor() # TODO: write context to database self.connection.commit() def initdb(self): """ Creates database tables if they don't exist. 1. A firstBoot table that stores only the first boot time 2. A picture table that stores the filepaths of various photos taken 3. A data table that stores datapoints taken by the sensors """ cursor = self.connection.cursor() try: cursor.execute(''' CREATE TABLE firstBoot (time timestamp PRIMARY KEY) [without rowid]''') except: pass try: cursor.execute(''' CREATE TABLE picture (time timestamp PRIMARY KEY, Packet_Type Int, Mission_Mode Int, Reboot_Count Int, Payload_Size Int, Payload_Count Int, filepath text) [without rowid]''') except: pass try: cursor.execute(''' CREATE TABLE attitudeDetermination (time timestamp PRIMARY KEY, Packet_Type Int, Mission_Mode Int, Reboot_Count Int, Payload_Size Int, Payload_Count Int, SS_1 Float, SS_2 Float, SS_3 Float, SS_4 Float, SS_5 Float, MF_X Float, MF_Y Float, MF_Z Float, LA_X Float, LA_Y Float, LA_Z Float, powermode int) [without rowid]''') except: pass try: cursor.execute(''' CREATE TABLE data (time timestamp PRIMARY KEY, uvintensity float, boomdeployed bool, magx float, magy float, magz float, magxr float, magyr float, magzr float, battvoltage float, therm0 float, therm1 float, therm2 float, therm3 float, therm4 float, therm5 float, therm6 float, powermode int) [without rowid] ''') except: pass try: cursor.execute(''' CREATE TABLE housekeeping (time timestamp PRIMARY KEY, Packet_Type Int, Mission_Mode Int, Reboot_Count Int, Payload_Size Int, Payload_Count Int, Boombox_UV Float, SPX+_Temp1 Float SPZ+_Temp2 Float, RaspberyyPi_Temp Float, EPS_MCU_Temp Float, Cell_1_Battery_Temp Float, Cell_2_Battery_Temp Float, Cell_3_Battery_Temp Float, Cell_4_Battery_Temp Float, Battery_Voltage Float, Battery_Current Float, BCR_Voltage Float, BCR_Current Float, EPS_3V3_Current Float, EPS5V_Current Float, SPX_Voltage Float, SPX+_Current Float, SPX-_Current Float, SPY_Voltage Float, SPY+_Current Float, SPY-_Current Float, SPZ_Voltage Float, SPZ+_Voltage Float, powermode int) [without rowid] ''') except: pass self.connection.commit()
# coding: utf-8 # In[1]: import matplotlib.pyplot as plt # In[2]: get_ipython().magic(u'matplotlib inline') # In[3]: import numpy as np # In[4]: graph = [] min_val = 100 for i in range(1,10000000): x = np.random.rand() y = np.random.rand() val1 = (x+y)/(x*1.0) val2 = x/(y*1.0) diff = abs(val1 - val2) if(diff<min_val): min_val = diff graph.append(val2) gr = val2 # In[5]: print(gr) # In[6]: plt.plot(graph) plt.show() # In[7]: plt.plot(graph) plt.savefig("gr_converence.png") # In[14]: plt.plot(graph[16:]) plt.savefig("gr_converence_smaller.png") # For more info visit: # https://www.mathsisfun.com/numbers/golden-ratio.html # In[ ]:
import random #imports random nuber import os playercount=0 compcount=0 while True: print("\n\t\t\t\t!!!ROCK PAPER SCISSOR GAME!!!") #displaying score print("\nSCORE:") print(f"computer:{compcount} player: {playercount} ") #game algorithm def game(comp,player): if comp==player: return None elif comp == 'r': if player=='p': return True elif player == 's': return False elif comp == 'p': if player=='r': return False elif player == 's': return True elif comp == 's': if player=='r': return True elif player == 'p': return False # assigning computer'r variable print("\n\nComputer turn: Rock(r)/Paper(p)/Scissors(s)") radNum= random.randint(1,3) #chooses random number from range 1-3 i.e. 1,2and3 if radNum == 1: comp='r' elif radNum == 2: comp='p' elif radNum == 3: comp='s' # taking input from user player=input("Your turn: Rock(r)/Paper(p)/Scissors(s): ") a=game(comp,player) print(f"\nComputer chose {comp}") print(f"You chose {player}\n") # printing result if a==None: print("Tie Round!") elif a: print("You get 1 point") playercount=playercount+1 else: print("Computer gets 1 point") compcount=compcount+1 #final win, counts who has scored 5 frist if(playercount==5 and compcount<playercount): os.system('cls') print("\n\n\n\n\n\t\t\t\t!!!YOU WIN!!!") playercount=0 compcount=0 b=input("\n\n\tDo you want to play again?(Y/N): ") os.system('cls') if b=='n'or b=='N': break elif(compcount==5 and compcount>playercount): os.system('cls') print("\n\n\n\n\n\t\t\t\t!!!YOU LOSE!!!") playercount=0 compcount=0 b=input("\n\n\tDo you want to play again?(Y/N): ") os.system('cls') if b=='n'or b=='N': break input() os.system('cls')
#You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, except the number 0 itself. # # Example: # # #Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) #Output: 7 -> 0 -> 8 #Explanation: 342 + 465 = 807. # # Related Topics Linked List Math #leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ dummy = ListNode(0) curNode = dummy carry = 0 n1 = l1 n2 = l2 while n1 is not None or n2 is not None or carry is not 0: curSum = 0 if n1 is not None: curSum += n1.val n1 = n1.next if n2 is not None: curSum += n2.val n2 = n2.next curSum += carry carry = curSum / 10 curNode.next = ListNode(curSum % 10) curNode = curNode.next return dummy.next #leetcode submit region end(Prohibit modification and deletion)
#Write a function to find the longest common prefix string amongst an array of strings. # # If there is no common prefix, return an empty string "". # # Example 1: # # #Input: ["flower","flow","flight"] #Output: "fl" # # # Example 2: # # #Input: ["dog","racecar","car"] #Output: "" #Explanation: There is no common prefix among the input strings. # # # Note: # # All given inputs are in lowercase letters a-z. # Related Topics String #leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ lcp = "" if len(strs) == 0: return lcp minLen = len(strs[0]) for i in range(len(strs)): minLen = min(minLen, len(strs[i])) isCp = True for i in range(minLen): if not isCp: break for j in range(len(strs)): if strs[j][i] == strs[0][i]: continue else: isCp = False break if isCp: lcp = lcp + strs[0][i] return lcp #leetcode submit region end(Prohibit modification and deletion)
import tkinter as tk # for the UI import requests # I was having problems with the PIP on on my desktop It worked on my laptop But I test it on the replit IDE. def getWeather(canvas): # zip = textField.get() api = "https://api.openweathermap.org/data/2.5/weather?zip=90210,us&appid=09d000cd760c041414c09bede4f3eb27" json_data = requests.get(api).json() condition = json_data['weather'][0]['main'] # The Json file provides the temp in kelvin, so to use in US Fahrenheit I use the formula to convert it . f+ K * 1.8 - 459.67 temp = int(json_data['main']['temp'] * 1.8 - 459.67 ) min_temp = int(json_data['main']['temp_min'] * 1.8 - 459.67) max_temp = int(json_data['main']['temp_max'] * 1.8 - 459.67) final_info = condition + "\n" + str(temp) + "°F" final_data = "\n" + "Min Temp: " + str(min_temp) + "°F" + "\n" + "Max Temp: " + str(max_temp) + "°F" + "\n\n\n" + " by Mario Montenegro" label1.config(text=final_info) label2.config(text=final_data) canvas = tk.Tk() canvas.geometry("700x500") canvas.title("Leidos Weather App By Zip code") f = ("Times", 20, "bold") t = ("poppins", 35, "bold") textField = tk.Entry(canvas, justify='center', width=20, font=t) textField.pack(pady=20) textField.focus() textField.bind('<Return>', getWeather) label1 = tk.Label(canvas, font=t) label1.pack() label2 = tk.Label(canvas, font=f) label2.pack() canvas.mainloop()
class Matrix: def __init__(self, data): self.data = data def __str__(self): return '\n'.join('\t'.join([f'{itm:04}' for itm in line]) for line in self.data) def __add__(self, another): try: m = [[int(self.data[line][itm]) + int(another.data[line][itm]) for itm in range(len(self.data[line]))] for line in range(len(self.data))] return Matrix(m) except IndexError: return f'Error. Matrices have different size. You can not sum them without modification.' m_1 = [[3, 5, 7], [12, 8, -5], [7, 9, 12]] m_2 = [[7, 5, -2], [4, -2, -12], [7, 5, 74]] mtr_1 = Matrix(m_1) mtr_2 = Matrix(m_2) sum_mtr = mtr_1 + mtr_2 print('Result summation of Matrix(m_1) and Matrix(m_2) is\n') print(sum_mtr)