text
stringlengths
37
1.41M
#Lecture 3 notes #Gives perfect square without check # x = 16 # ans = 0 # while ans*ans < x: # ans = ans + 1 # print ans #gives square root but checks if it is a perfect square and checks for negativity and prints each step # x = 16 # ans = 0 # if x >= 0: # while ans*ans < x: # ans = ans + 1 # if ans*ans != x: # print x,'is not a perfect square' # else: print ans # else: print x, 'is a negative number' #Finds all the divisors of a number # x = 10 # i = 1 # while i<x: # if x%i == 0: # print 'divisor', i # i= i+1 #Finds all the divisors of a number using range # x = 10 # for i in range(1,x): # if x%i == 0: # print 'divisor ',i #Finds all the divisors of a number and puts them in a tuple x = 100 divisors = () for i in range (1,x): if x%i == 0: divisors = divisors + (i,) print divisors [0:]
matriz1 = [[1,2,3],[4,5,6],[7,8,9]] matriz2 = [[10,11,12],[13,14,15],[16,17,18]] matriz3 = [[1,2,3],[4,5,6],[7,8,9]] print(matriz1) print(matriz2) for posF,value1 in enumerate(matriz1): for posC, value2 in enumerate(value1): matriz3[posF][posC] = value2 + matriz2[posF][posC] print(matriz3)
#questionsNC.py q1 = bool(False) score = int(0) # the score q1ans = int(0) # the answer to user inputs q1ask = str("""1. What is the most well-known coding language?\n 1. Elixir 2. Python 3. JavaScript 4. Swift\n""") print("") print("please only type the number of the answer choice you have chosen.") print("") while q1 == False: #while the question hasn't been answered try: q1ans = int(input(q1ask)) #ask the question print("") if q1ans == int(3): #if the user gets the right answer q1 = True #change the state of the question. make it true score += 1 #add to the score print("Correct.") print("Move on to the next question!") elif 0 < q1ans < 5: #if the answer is one of the choices but wrong print("Sorry your answer is not correct. The answer was 3.\n") print("Please move on to the next question.") break #break the loop. except ValueError: #if they inputted anything else print("") print("Please put the number of the answer choice\n") #tell directions
''' Disciplina: GCC218 - Algoritmo em Grafos Integrantes: Igor Antônio dos Santos Alves Mendes Isaías Gonçalves Ribeiro Pedro Antônio de Souza Problema: 1454 - O País das Bicicletas Estratégia Adotada: Para cada instância, modelamos um grafo onde as interseções entre ruas são os vértices. As arestas representam as ruas e o peso associado a cada aresta representa a altura entre as interseções de ruas. Modificamos o Algortimo de Floyd-Warshall para a resolução das instâncias. No algoritmo original, o objetivo é calcular distâncias entre vértices, sendo a distância definida como a soma do peso das arestas que pertencem ao caminho. Porém, nesse problema o objetivo é encontrar o caminho entre dois vértices que utilizem arestas com os menores pesos possíveis. Assim, o cálculo de novas distâncias (nesse caso, as distâncias são as alturas) foi modificado da seguinte maneira: calcula-se o menor valor entre a altura já definida na matriz de distâncias (alturas) e o maior valor encontrado entre vértice de origem até um vértice intermediário e entre o vértice intermediário e o vértice de destino. Portanto, o algoritmo sempre buscará o menor entre os maiores valores já encontrados. ''' ''' Classe implementada para resolução do problema. Instancia um grafo não direcionado. ''' class GrafoMrLee(): """Construtor da classe. :param n: quantidade de vértices do grafo (interseções entre ruas) """ def __init__(self, n:int): self.__n = n # Matriz de adjacência do grafo self.__matriz_adjacencia = list() # Inicializa a matriz de adjacencia self.__inicializa_matriz_adjacencia() """Adiciona arestas no grafo. :param v1: primeiro vértice da aresta :type v1: int :param v2: segundo vértice da aresta :type v2: int :param altura: peso da aresta :type altura: int """ def add_aresta(self, v1:int, v2:int, altura:int): self.__matriz_adjacencia[v1][v2] = altura self.__matriz_adjacencia[v2][v1] = altura """Inicializa matriz de altura. Para posições da matriz com índice de linha e coluna iguais, define valor como zero. Para as demais, define o valor como infinito.""" def __inicializa_matriz_adjacencia(self): for i in range(self.__n): self.__matriz_adjacencia.append([0 if j == i else float('inf') for j in range(self.__n)]) """Calcula a menor altura máxima entre cada par de vértices do grafo, atualizando a matriz de alturas. :returns: matriz com alturas máximas entre vértices. :rtype: list """ def floyd_warshall_modificado(self) -> list: matriz = self.__matriz_adjacencia.copy() for k in range(self.__n): for i in range(self.__n): for j in range(self.__n): if i != j: matriz[i][j] = min(matriz[i][j], max(matriz[i][k], matriz[k][j])) return matriz; # Inicia a variável instancia com 1. Ela será utilizada na impressão das # soluções. instancia = 1 # Lê as entradas de quantidade de interseções (n) e quantidade de ruas (m). n, m = map(int, input().split()) while not (n == 0 and m == 0): G = GrafoMrLee(n) # Instancia um novo grafo # Adiciona arestas. for _ in range(m): v1, v2, altura = map(int, input().split()) # No problema, o índice dos vértices se iniciam em 1. No código, eles # são decrementados para facilitar a implementação e utilização de listas. G.add_aresta(v1-1, v2-1, altura) # Recebe a quantidade de rotas a serem caluladas. qtd_rotas = int(input()) rotas = list() # Adiciona as rotas (recebidas como entrada) em forma de tupla na lista de rotas for _ in range(qtd_rotas): rotas.append(tuple(map(int, input().split()))) print('Instancia', instancia) # Aplica o algoritmo implementado para solução do problema atualizando, # assim, a matriz de altura. alturas = G.floyd_warshall_modificado() for rota in rotas: v1, v2 = rota[0], rota[1] # Aqui, os índices dos vetores também são decrementados para fazer a # "conversão" de índices. print(alturas[v1-1][v2-1]) print() # Incrementa a variável instancia e recebe novos paramêtros da próxima # instância. instancia = instancia + 1 n, m = map(int, input().split())
def is_polindrom(s): forward = s backward = s[::-1] if forward == backward: return True else: return False def only_alpha(s): new_s = [] for ch in s: if ch.isalpha(): new_s.append(ch) new_s = ''.join(new_s).lower() new_s = new_s.replace('ё', 'е') return ''.join(new_s).lower() def main(): with open('input.txt') as f: data = f.readlines() for s in data[1:]: s = only_alpha(s) if is_polindrom(s): print('yes') else: print('no') if __name__ == "__main__": main()
# the question is how many different groups of 3 can you take # from this list that are equal to 10 my_list = [1,2,3,4,5,6] combinations = itertools.combinations(my_list, 3) permutations = itertools.permutations(my_list, 3) print([result for result in combinations if sum(result) == 10]) # the output is # [(1,3,6), (1,4,5), (2,3,5)] # if we place permuatitons instead of combinations print([result for result in permutations if sum(result) == 10]) # the output is # [(1,3,6),(1,4,5),(1,5,4),(1,6,3),(2,3,5),(2,5,3),(3,1,6),(3,2,5),(3,5,2), # (3,6,1),(4,1,5),(4,5,1),(5,1,4),(5,2,3),(5,3,2),(5,4,1),(6,1,3),(6,3,1)] # you can see that we get a lot more values and order matters # this is the example where the order would matter -> # a word matching game word = 'sample' my_letters = 'plmeas' combinations = itertools.combinations(my_letters, 6) permutations = itertools.permutations(my_letters, 6) for p in permutations: # print p if ''.join(p) == word: print("Match!") break else: print("No match!") # can't find a match with combinations # permutations should be used in this example
# the speciality of a set is that the elements inside a set are unique that is they do not show repeated elements my_set={1,2,4,5,6,3,5} print(my_set) my_set.add(100) my_set.add(3) print(my_set) print(1 in my_set) # removing repeated elements from a list my_list=[1,2,3,4,5,6,5,4,3,2,1,] print(my_list) print(set(my_list)) new_set={4,5,7,8,9,43,3} print(new_set) print(my_set.difference(new_set)) print(my_set.discard(5)) print(my_set) # print(my_set.difference_update(new_set)) print(my_set) print(my_set.intersection(new_set)) print(my_set.isdisjoint(new_set)) print(my_set.union(new_set)) print(my_set.issubset(new_set)) print(new_set.issuperset(my_set))
basket=[1,2,3,4,5] print(len(basket)) # adding basket.append(6) print(basket) # insert basket.insert(2,'insert') print(basket) # extend basket.extend([100,1001]) print(basket) # poping - removing basket.pop() print(basket) basket.remove('insert') print(basket) # reverse basket.reverse() print(basket) basket.sort() print(basket) # returns indec of the element print(basket.index(2)) # to check if 'd' is in the list print(basket.index('d',0,4)) # to check if variable is in the list print('x' in basket) print(2 in basket) # count print(basket.count(4)) # sorteed built in function that doesnt modify the list print(sorted(basket))
from graphics import * from graphicsCG import * import math def matMult(M, N): # print(M) # print(N) R=[] for i in range(len(M)): R.append([]) for j in range(len(N[0])): R[i].append(0) for i in range(len(M)): for j in range(len(N[0])): for k in range(len(N)): R[i][j] += M[i][k] * N[k][j] for i in range(len(M)): for j in range(len(N)): M[i][j]=R[i][j] # print(M) return M[0] def copyMetrics(M): a=[] for i in range(len(M)): a.append([]) for j in M[i]: a[i].append(j) a[i].append(1) return a def choices(): print("select choice for transformation->") print("1. Translation") print("2. Scaling") print("3. Rotation") print("4. Shearing") print("5. Reflection") print("6. Quit") pass if __name__=="__main__": print("enter xmin, ymin, xmax, ymax for window: ", end="") xmin , xmax , ymin , ymax = map(int, input().split()) window = size(xmin , xmax , ymin , ymax) print("enter xmin, ymin, xmax, ymax for viewPort: ", end="") xvmin , xvmax , yvmin , yvmax = map(int, input().split()) viewPort = size(0 , xvmax - xvmin, 0 , yvmax - yvmin) win = GraphWin(' Line ' , xvmax - xvmin , yvmax - yvmin, autoflush = False) drawLine(win, 0 , window.ymax, 0, window.ymin, 'blue', window,viewPort ) drawLine(win, window.xmin , 0 , window.xmax, 0, 'red', window,viewPort ) print("Enter number of edges of polygon: ", end="") n=int(input()) print("Enter vertices of the edges as (x, y) one by one") vertices=[] for i in range(n): vertices.append(list(map(int, input().split()))) print("Enter color of the Edges:- ", end="") color = input() drawPolygon(win, n, vertices, color, window, viewPort) choices() while(1): choice=int(input()) if(choice==1): #translation print("enter Tx: ", end="") Tx=float(input()) print("enter Ty: ", end="") Ty=float(input()) T=[[1, 0, 0], [0, 1, 0], [Tx, Ty, 1]] k=copyMetrics(vertices) print(k) for i in k: i=matMult([i], T)[:2] i[0]=math.ceil(i[0]) i[1]=math.ceil(i[1]) print(k) print(vertices) drawPolygon(win, n, k, 'red', window, viewPort) elif(choice==2): #Scaling print("enter Sx: ", end="") Sx=float(input()) print("enter Sy: ", end="") Sy=float(input()) S=[[Sx, 0, 0], [0, Sy, 0], [0, 0, 1]] print("Reference point for rotation (x, y): ", end=" ") x, y = map(int, input().split()) k=copyMetrics(vertices) print(k) for i in k: l=[i[0]-x, i[1]-y, i[2]] l=matMult([l], S)[:2] print(l) i[0]=x+l[0] i[1]=y+l[1] i=i[:2] i[0]=math.ceil(i[0]) i[1]=math.ceil(i[1]) print(k) print(vertices) drawPolygon(win, n, k, 'red', window, viewPort) elif(choice==3): print("enter t such that angle of rotation is pi/t: ", end="") angle=math.pi/float(input()) print("enter directon of rotation->") print("1. Anti Clockwise") print("2. Clockwise") k=int(input()) if(k==2): angle=-angle R=[[math.cos(angle), math.sin(angle), 0], [-math.sin(angle), math.cos(angle), 0], [0, 0, 1]] print(R) print("Reference point for rotation (x, y): ", end=" ") x, y = map(int, input().split()) k=copyMetrics(vertices) print(k) for i in k: l=[i[0]-x, i[1]-y, 1] l = matMult([l], R) print(l) i[0]=x+l[0] i[1]=y+l[1] i=i[:2] i[0]=math.ceil(i[0]) i[1]=math.ceil(i[1]) print(k) print(vertices) drawPolygon(win, n, k, 'red', window, viewPort) elif(choice==4): print("enter shx: ", end="") shx=float(input()) print("enter shy: ", end="") shy=float(input()) Sh=[[1, shy, 0], [shx, 1, 0], [0, 0, 1]] print("Reference point for rotation (x, y): ", end=" ") x, y = map(int, input().split()) k=copyMetrics(vertices) print(k) for i in k: l=[i[0]-x, i[1]-y, i[2]] l=matMult([l], Sh)[:2] print(l) i[0]=x+l[0] i[1]=y+l[1] i=i[:2] i[0]=math.ceil(i[0]) i[1]=math.ceil(i[1]) print(k) print(vertices) drawPolygon(win, n, k, 'red', window, viewPort) elif(choice==5): print("enter a, b, c where ax+by+c=0 is reference line: ", end="") a, b, c = map(float, input().split()) k=copyMetrics(vertices) Ref = [[(b*b-a*a)/(a*a+b*b), -2*a*b/(a*a+b*b), 0], [-2*a*b/(a*a+b*b), (a*a-b*b)/(a*a+b*b), 0], [-2*a*c/(a*a+b*b), -2*b*c, 1]] for i in k: x=i[0] y=i[1] l=[x, y, 1] # i[0]=((b*b-a*a)*x-2*a*b*y-2*a*c)/(a*a+b*b) # i[1]=((a*a-b*b)*y-2*a*b*x-2*b*c)/(a*a+b*b) l=matMult([l], Ref)[:2] print(l) i[0]=math.ceil(l[0]) i[1]=math.ceil(l[1]) i=i[:2] print(k) print(vertices) drawPolygon(win, n, k, 'red', window, viewPort) elif(choice==6): break else: pass print("please enter valid choice.") choices() print("Click on window to exit") win.getMouse() win.close
import sys word_List = ["access", "hactivist" , "framework", "hacker", "cryptography", "farmer", "fundamental", "government", "helicopter", "identification", "intellectual", "journalist", "legislation", "management", "network", "parking", "radio", "scenario", "telescope", "universal" , "vehicle", "warning", "youth", "zone"] STAGES = [ ''' x----x | O | /|\\ | / \\ === ''',''' x----x | O | /|\\ | / === ''',''' x----x | O | /|\\ | === ''',''' x----x | O | /| | === ''', ''' x----x | O | | | === ''', ''' x----x | O | | === ''', ''' x----x | | | === '''] field_array = []#Here the array to print the word's spaces word_playing = []#Here we take the word chose and add in this array word_wrong = []#here we take the wronged letters guessed Game_Over = False#Variable to stop or continue the game loop errors = 6 #Function to check for winner variable and stop the game if change in true def Winner_check(): global Game_Over splitted = [] for x, y in enumerate (word_playing): for q, w in enumerate (y): splitted.append (w + " ") if field_array == splitted: Game_Over = True elif errors == 0: Game_Over = True else: Game_Over = False #Function to print the word if not guessed at the end def Secret_word (): for x, y in enumerate (word_playing): print (y) def draw_Field (array): for x, y in enumerate (array): for q, w in enumerate (y): print (w, end= "") #Here we modify the field based on guessing enters def add_field (field): for x, elem in enumerate (word_playing): for y, char in enumerate (elem): if char in letters: for q, w in enumerate (field): if "_ " in field [q]: field[y] = w.replace ("_ ", char + " ") def word_chosen (start): for num, word in enumerate (word_List): if num == start: word_playing.append (word) #Check to see if the character is in the word or not and if it's not we add in wrong array and decrease errors number by 1 def checkGuess (letters): global errors for x, y in enumerate (word_playing): for z, c in enumerate (y): if letters == c: print ("Good guess!!") break else: if letters not in word_wrong: errors -= 1 word_wrong.append (letters) print ("Sorry,", letters, " not in the word.") def words_playedShow (letters): if len(word_wrong) != 0: print ("That's characters had been chosen:") print (word_wrong) print ("Let's play to Hangman!") print ("To exit the game digit 'ctrl+c' command.") #We show a list of word and corrisponding numbers to choosing for num, word in enumerate (word_List): print (num, word) while (True): try: start = int(input ("\nPlayer 1 \nplease insert the number corrisponding the word you want: ")) if start < 0 or start >= len(word_List): print ("Please only number thrue 0 and ", len(word_List) - 1) continue else: break except KeyboardInterrupt:#To not disclusure some information about errors and code we want to manage interrupt error as well. print ("Program interrupted") sys.exit(0) except: print ("Sorry, choose only with numbers printed in screen.") word_chosen(start) for x, y in enumerate (word_playing): for q, w in enumerate (y): field_array.append ("_ ") print(chr(27) + "[2J") print ("Player 2 it's your turn!", "\n") while (Game_Over == False): try: if len (word_wrong) != 0:#We want to print characters wrong only we have. print ("\n", "The wrong characters until now are:\n", word_wrong) print (STAGES[errors])#Here we show the hangman based on number in errors variable draw_Field (field_array) print ("\n") letters = input ("Please insert your guessing letter: ") if len(letters) > 1:#We want to limit the number of digits only to one character per time. print ("Sorry only one digit a time. Try again.") continue else: if letters.isalpha() == True:#We don't trust on user input. We want to handle if the user use int, float, symbols or space. checkGuess (letters) #but we leave the choice to interrupt the program with ctrl + c. add_field (field_array) Winner_check () else: print ("Sorry, only alphabetic characters. Try again.") except EOFError:#Want to exit only with ctrl+c command! print ("Sorry, 'ctrl+d' command not accepted. To exit the game digit 'ctrl+c' command.") except KeyboardInterrupt: print ("Program interrupted") sys.exit(0) #Result of end of game. If player win or lose if errors == 0: print ("\n", STAGES[errors]) print ("\n", "GAME OVER \n Sorry you lose.", "\n") print ("The secret word was: ", end="") Secret_word () else: print ("Congratulation you win!!!!")
# coding: utf-8 # In[1]: from urllib import request from bs4 import BeautifulSoup # In[2]: # BeautifulSoup lib note url = 'https://movie.douban.com/' html_page = request.urlopen(url) # In[3]: # can try out some other parser such as html.parser, lxml for normal html doc. lxml-xml for parsing html to xml soup = BeautifulSoup(html_page, 'lxml') soup # In[4]: # four kinds of object in bs: tag, navigablestring, BeautifulSoup and Comment tag = soup.a tag # In[5]: # each attribute has a name which could also be modified print(tag.name) tag.name = "p" print(tag) # In[6]: # accessing the attributes tag['class'] # In[7]: # get the attributes as a dictionary which also means you can modify the attributes the way you modify a dictionary tag.attrs # In[8]: del tag['rel'] tag.attrs # In[9]: # NavigableString: basically, it is the content inside the tag print(tag.string) type(tag.string) # In[10]: # modification tag.string.replace_with("Log in") tag # In[11]: # BeautifulSoup soup.name # In[12]: # navigating a tree: note that these operation could be done in the types described above soup.head # In[13]: soup.title # In[14]: # get the first <a> tag print(soup.a) # get all the <a> tag print(soup.find_all('a')) # In[15]: # .contents to get the list of sub node soup.body.contents # In[16]: # .children to get the list generator of the sub node for child in soup.body.children: print(child) # In[17]: # use descendants to get all the nested nodes print(len(list(soup.children))) # get the direct children print(len(list(soup.descendants))) # In[18]: # .strings or stripped_strings to view things inside tags for string in soup.stripped_strings: print(string) # In[19]: # going up from the current node by using .parent title_tag = soup.title print(title_tag) print(title_tag.parent) # In[20]: # .parents to get all the parents for parent in soup.a.parents: if parent is None: print(parent) else: print(parent.name) # In[21]: # get the next tag which has the same parent of the current node soup.div.next_sibling # In[22]: soup.div.next_sibling.next_sibling # In[23]: # to get the right next to the current element soup.div.next_element # In[24]: # same goes to previous_siblings for e in soup.div.next_siblings: print(e) # In[26]: # Searching a tree # string filter soup.find_all('a') # In[29]: # regex filter import re for tag in soup.find_all(re.compile('^b')): print(tag.name) # In[31]: # list filter # match every element in the list soup.find_all(['a','div']) # In[41]: # define customized function with True filter def has_id_but_no_class(tag): return tag.has_attr('id') and not tag.has_attr('class') soup.div.find_all(has_id_but_no_class) # In[43]: # argument of find_all method soup.find_all(id='top-nav-appintro') # In[44]: soup.find_all(id=True) # In[47]: soup.find_all(href=re.compile('douban'), id=True) # In[50]: soup.find_all(href=re.compile('douban'), attrs={'data-moreurl-dict':'{"from":"top-nav-click-market","uid":"0"}'}) # In[ ]: # css selector # urlparse: parse a url into a formated url from urllib.parse import urlparse parsed_url = urlparse(url) # returns ParseResult(scheme='https', netloc='movie.douban.com', path='', params='', query='', fragment='') # lambda expression soup.find_all(lambda tag: len(tag.attrs) == 2)
mat= [[0,1,2,0],[1,0,3,1],[2,3,0,2],[0,1,2,0]] INFI = 100000 def Dijkstra(matr, source): Q = [] dist = [] pred = [] c=0 dist=[INFI for _ in range(0,len(matr))] pred= ["non c'è" for i in range(0,len(matr))] #non esistono Q= [i for i in range(0,len(matr))] dist[source] = 0 scelto= source while len(Q)>0: print(f"\nPasso: {c}") print(f"Successori: {Q}") print(f"Distanze: {dist}") minn = INFI for i in Q: if(dist[i]<minn): minn = dist[i] scelto=i Q.remove(scelto) for v,w in enumerate(matr[Q]): if (dist[scelto]+w<dist[v]) and (w>0): dist[v] = dist[scelto] + w pred[i]=Q[i] c=c+1 return dist, pred def neighbor(mat, indice): matNeigh = [] for i,c in mat: if (mat[i][c] == indice): matNeigh.append(mat[i][c]) return matNeigh def main(): Dijkstra(mat, 0) if __name__ =="__main__": main()
class Parser(object): """ An abstract class tha contains a dictionary and has a get method to return it and has a parse method that parses a text given. """ def __init__(self): """ The constructor, initializes the dictionary. """ self._ip_dictionary = {} def parse(self, raw_ip_info): """ A method that parses a text given as an input and then saves is inside the dictionary. :param raw_ip_info: the input that needs to be parsed. :return: the method returns nothing. """ pass def get_ip_dictionary(self): """ Getter :return: The method returns the dictionary. """ return self._ip_dictionary
class Node: def __init__(self, ID, Fx=0, Fz=0, Ty=0, ux=0, uz=0, phi_y=0, point=None): """ :param ID: ID of the node, integer :param Fx: Value of Fx :param Fz: Value of Fz :param Ty: Value of Ty :param ux: Value of ux :param uz: Value of uz :param phi_y: Value of phi :param point: Point object """ self.ID = ID # forces self.Fx = Fx self.Fz = Fz self.Ty = Ty # displacements self.ux = ux self.uz = uz self.phi_y = phi_y self.point = point def show_result(self): print("\nID = %s\n" "Fx = %s\n" "Fz = %s\n" "Ty = %s\n" "ux = %s\n" "uz = %s\n" "phi_y = %s" % (self.ID, self.Fx, self.Fz, self.Ty, self.ux, self.uz, self.phi_y)) def __add__(self, other): assert(self.ID == other.ID), "Cannot add nodes as the ID's don't match. The nodes positions don't match." Fx = self.Fx + other.Fx Fz = self.Fz + other.Fz Ty = self.Ty + other.Ty ux = self.ux + other.ux uz = self.uz + other.uz phi_y = self.phi_y + other.phi_y return Node(self.ID, Fx, Fz, Ty, ux, uz, phi_y, self.point) def __sub__(self, other): assert (self.ID == other.ID), "Cannot subtract nodes as the ID's don't match. The nodes positions don't match." Fx = self.Fx - other.Fx Fz = self.Fz - other.Fz Ty = self.Ty - other.Ty ux = self.ux - other.ux uz = self.uz - other.uz phi_y = self.phi_y - other.phi_y return Node(self.ID, Fx, Fz, Ty, ux, uz, phi_y, self.point)
import random print("H A N G M A N") def menu(): global hangman, repeat, word_list, word word_list = ['python', 'java', 'kotlin', 'javascript'] word = random.choice(word_list) hangman = ['-' for _ in range(0, len(word))] repeat = [] choice = input('''Type "play" to play the game, "exit" to quit: ''').lower().strip() print() if choice == 'play': return guessword(0) elif choice == 'exit': return exit() else: return menu() def exit(): pass def guessword(count= 0): while count <= 7: print(''.join(hangman)) guess = input("Input a letter:") if len(guess) > 1 or guess == '': print("You should input a single letter\n") return guessword(count=count) if not guess.isascii() or not guess.islower(): print("It is not an ASCII lowercase letter\n") return guessword(count=count) if guess not in hangman: if guess in word: for i in range(0, len(word)): if guess == word[i]: hangman.pop(i) hangman.insert(i, guess) if ''.join(hangman) == word: print('''You guessed the word {}!\nYou survived!\n'''.format(''.join(hangman))) break print() else: if guess in repeat: print("You already typed this letter\n") else: count += 1 repeat.append(guess) if count == 8: print("No such letter in the word") print("You are hanged!\n") break else: print("No such letter in the word\n") else: print("You already typed this letter\n") menu()
import random import os, sys from random import shuffle # The Rules # 1) N stones forming a sequence labeled 1 to N. -> input N stones # 2) Alice and Bob take 2 cosecutive stones until there no consectutive stones left. # the number of the stone left determines the winner # 3) Alice plays first def clear_and_greet(): os.system('cls' if os.name == 'nt' else 'clear') print(''' ********************************************* **************** Alice N Bob **************** ************* A Game of Stones ************** ********************************************* ''') def start_game(): ''' For now, the game only creates a list that contains the number of stones inputted by the user. And then it checks if the last 'stone' in the list is odd. If odd Alice wins the game. It doesn't let Alice play first and let each player remove two stones each turn until there is no two stones to taken left. ''' clear_and_greet() # clears screen and shows game "logo" print('Enter number of stones:\n') # ask user for the sequence of stones n = int(input('> ')) clear_and_greet() # clears screen and shows game "logo" stones = list(range(1, n+1)) # create (list) sequence of stones shuffle(stones) # shuffle the sequence of stones to have them in a random order print('The stones are: {}\n'.format(stones)) if stones[-1] % 2 == 1: # Checks if the last stone in sequence is odd. If odd Alice wins. print('Last stone is {}. Alice wins!!!'.format(stones[-1])) else: print('The last stone is ({}). Bob wins!!!'.format(stones[-1])) while True: start_game() play_again = input('\nWould you like to play again? (Y/n): ') # ask if player wants to play again if play_again.lower() != 'n': continue else: sys.exit()
# -*- coding: utf-8 -*- """ Created on Sun Oct 14 10:20:57 2018 @author: clyman Given a 32-bit signed int, reverse digits of int Assume dealing with environment that can only store ints within 32-bit signed int range [-2^31, 2^31 - 1] Return 0 when reversed int overflows """ ''' NOTE: In Python 3, int is unbounded. Python will automatically switch to long when limit of int reached. Can still check with sys.maxsize and -sys.maxsize-1 ''' import sys def reverse(num): flip = 0 maxsize = sys.maxsize minsize = -sys.maxsize-1 while num != 0: end = num % 10 num = num//10 if flip > maxsize/10 or (flip==maxsize/10 and end>7): return 0 if flip < minsize/10 or (flip==minsize/10 and end<-8): return 0 flip = flip*10 + end return flip num = int(input("Give a number: ")) print(reverse(num))
import os os.system('cls') #Technique for different cases : branching #In CS, branches can rejoin later #chocolate sales BAR_COST = 2 #cost of a bar of chocolate def is_yes(word): return word[0] == "Y" or word[0] == "y" ##ask user for number of bars bars = int(input("Enter number of bars : ")) ##compute the cost of chocolate cost = bars * BAR_COST ##ask user if donation is desired donate = input("Donate $10 ? ") if is_yes(donate): cost = cost + 10 print("$" + str(cost)) #odd-length string def is_odd_string(word): if len(word) % 2 == 1: return True else: return False print(is_odd_string("a")) print(is_odd_string("ab")) #simplified Pig Latin ##word nonempty, consists of letters only def is_vowel(word): return word[0] == "a" or word[0] == "A" or word[0] == "e" or word[0] == "E" or word[0] == "i" or word[0] == "I" or word[0] == "o" or word[0] == "O" or word[0] == "u" or word[0] == "U" def easy_pig(word): if is_vowel(word): part = word + "w" else: part = word[1:] + word[0] return part + "ay" #Shorter code can be def shorter_pig(word): if is_vowel(word): return word + "w" + "ay" return word[1:] + word[0] + "ay" print(easy_pig("hello")) print(shorter_pig("ello")) def offpeak(hour): if hour < 9 or hour > 17: return("Off peak") else: return("Peak") print(offpeak(7)) print(offpeak(9)) print(offpeak(20)) #More than two sets of instructions def size(mass): if mass >= 70: return("Jumbo") elif mass >= 63: return("Extra Large") elif mass >= 56: return("Large") elif mass >= 49: return("Medium") elif mass >= 42: return("Small") else: return("Peewee") print(size(45)) print(size(90)) #Three questions with nested branching def guess(digit): if digit < 5: if digit < 3: if digit < 2: return 1 else: return 2 else: if digit < 4: return 4 else: return 3 else: if digit < 7: if digit < 6: return 5 else: return 6 else: if digit < 8: return 7 else: return 8 print(guess(6)) x = 3 y = 10 if x > 0: y = 12 y = y + 5 print(y) x = -3 y = 10 if x > 0: y = 12 y = y + 5 print(y) x = -3 y = 10 if x > 0: y = 12 y = y + 5 print(y) def choose(x): if not x < 5: return "Yes" else: return "No" print(choose(y)) def choose1(x): if x < 5 or x > 90: return "Yes" else: return "No" print(choose(y)) def bigger(x, y): if x > y: return x else: return y #Write a function total_bill that consumes the cost of merchandise, age in years, and tax rate and produces the total bill, where there is a discount of 10% for ages of at least 65. The discount is applied before the tax is computed. The tax is given as a number between 0 and 1. def total_bill(cost, age, tax): if age >= 65: return (1 + tax) * (0.9 * cost) else: return (1 + tax) * cost #Write a function greeting that consumes a string of length at least three and produces "Hello" if the first three characters are "Hi!" and produces "Bye" otherwise. def greeting(string): if len(string) >= 3: three = string[:3] if three == "Hi!": return "Hello" return "Bye" return "Bye" #Write a function is_time that consumes two integers, one representing hours in 24-hour time and the other minutes in 24-hour time. #The function should produce "Passes" if the values are legal values for a time (that is, from 0 to 23 for hours and from 0 to 59 for minutes), and "Fails" otherwise. def is_time(hour, minute): if 0 <= hour <= 23 \ and 0 <= minute <= 59: return "Passes" return "Fails" x = 8 if x < 6: if x > 3: x = x + 1 else: x = x - 1 else: if x > 9: x = x + 2 else: x = x - 2 print(x) x = 120 if x > 0: print("pos") elif x < 0: print("neg") else: print("zero") #Write a function max_of_three that consumes three numbers and produces the maximum of the three numbers. The numbers do not need to be distinct. def max_of_three(x, y, z): if x >= y >= z or x >= z >= y: return x elif y >= x >= z or y >= z >= x: return y elif z >= x >= y or z >= y: return z #Write a function total_bill that consumes the cost of merchandise, age in years, and tax rate and produces the total bill, such that: ## there is a discount of 10% for ages of at least 65, applied before the tax is computed or the shipping charge added ## there is a shipping charge of $5 for all purchases of less than $100 (where the value is the purchase is considered before the discount is applied, if any, and does not include tax) #The percentage tax rate is given as a number between 0 and 1. def total_bill1(cost, age, tax): if age >= 65: before65 = (1 + tax) * (0.9 * cost) if before65 <= 100: return before65 + 5 return before65 else: before = (1 + tax) * cost if before <= 100: return before + 5 return before #Write a function integer_type that consumes a value of any type and produces "Even integer" if it is an even integer, "Odd integer" if it is an odd integer, and "Not an integer" otherwise. def integer_type(anything): if type(anything) == type(1) and anything % 2 == 0: return "Even integer" elif type(anything) == type(1) and anything % 2 == 1: return "Odd integer" else: return "Not an integer" #Write a function off_peak that consumes any type of data and determines if the time is eligible for off peak rates. Your function should produce one of the following outputs: "Off peak", "Peak", and "Not a time". Off-peak rates are based on 24-hour time, for values less than 9 or greater than 17. def off_peak(time): if type(time) == type(1) and \ (0 <= time < 9 or 17 < time <= 23): return "Off peak" elif type(time) == type(1) and \ 9 <= time <= 17: return "Peak" else: return "Not a time" #Write a function leap_year that consumes a positive integer and produces "Leap year" if it is a leap year and "Common year" otherwise. A year is a leap year if it is a multiple of 4, 100, and 400, or if it is multiple of 4 but not a multiple of 100. def is_multiple(number, factor): return number % factor == 0 def leap_year(year): of_4 = is_multiple(year, 4) of_100 = is_multiple(year, 100) of_400 = is_multiple(year, 400) if type(year) == type(1) and of_400: return "Leap year" elif type(year) == type(1) and of_4 and not of_100: return "Leap year" else: return "Common year" print(leap_year(4)) print(leap_year(100)) print(leap_year(400)) def romanize(digit): tipe = type(digit) == type(1) if tipe and digit <= 3: if digit == 3: return "III" elif digit == 2: return "II" else: return "I" elif tipe and digit <= 6: if digit == 6: return "VI" elif digit == 5: return "V" else: return "IV" elif tipe and digit <= 10: if digit == 10: return "X" elif digit == 9: return "IX" elif digit == 8: return "VIII" else: return "VII"
""" The ColorWheel allows us to work with colors using Hue/Saturation/Value (HSV) and then convert it to Red/Green/Blue (RGB) for rendering HSV: 0 ≤ H < 2PI, 0 ≤ S ≤ 1 and 0 ≤ V ≤ 1: RGB: 0 ≤ R, G, B ≤ 255 """ import math class ColorWheel: def __init__(self, hue, sat, val): self.hue = hue self.sat = sat self.val = val def rotate(self, angle): """Rotate hue in radians""" self.hue = (2 * math.pi + self.hue + angle) % (2 * math.pi) def as_rgb(self): """Converts HSV to RGB""" # 1 - calculate inscrutable intermediate values h = self.hue / (math.pi / 3) c = self.val * self.sat x = c * (1 - math.fabs(h % 2 - 1)) o = self.val - c # 2 - smash them together idx = math.floor(h) vals = get_hue_prime(x, c, idx) vals = [color + o for color in vals] return tuple([round(255 * color) for color in vals]) def get_hue_prime(x, c, idx): """No idea what this does, and I don't care""" lookup = [ [c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x], [0, 0, 0], ] return lookup[idx]
#coding:utf-8 def needpassword(user_id): import sqlite3 import json conn=sqlite3.connect("srtp.db") c=conn.cursor() #判断输入的用户名是否已经在数据库中 flag=0 cursor=c.execute("select id,password from user")# for row in cursor: id_sql=json.dumps(row[0], ensure_ascii=False)#row[0]为id列 if user_id==json.loads(id_sql): flag=1 break if flag==1:#查询用户名所对应的密码 cursor=c.execute("select password from user where id='%s'"%user_id) for row in cursor: str1 = json.dumps(row, ensure_ascii=False) elif flag==0: str1="wrong id" return str1 #password=needpassword("2018112285") #print(password)
#!/usr/bin/env python3 # importing ipaddress inorder to properly validiate the ip address import ipaddress ipchk = input("Apply an IP address: ") # this line now prompts the user for input try: if ipaddress.ip_address(ipchk): print("This is a real IP address") except: print("Not a valid IP address") # if user set IP of gateway if ipchk == "192.168.70.1": print("Looks like the IP address of the Gateway was set: " + ipchk + " This is not recommended.") elif ipchk: # if any data is provided, this will test true print("Looks like the IP address was set: " + ipchk) # indented under if else: # if data is NOT provided print("You did not provide input.") # indented under else
#!/usr/bin/env python3 # create a list called list1 list1 = ["cisco_nxos", "arista_eos", "cisco_ios"] # display list1 print(list1) # display list[1] which should only display arista_eos print(list1[1]) # create a new list containing a single item list2 = ["juniper"] # extend list1 by list2 (combine both lists together into a single list) list1.extend(list2) # display list1, which now contains juniper print(list1) # create list3 list3 = ["10.1.0.1", "10.2.0.1", "10.30.0.1"] # use the append operation to append list1 by list3 list1.append(list3) # display the new complex list1 print(list1) # display the list of IP addresses print(list1[4]) # display the first item in the list (0th item) - first IP address print(list1[4][0])
#!/usr/bin/env python3 challenge= ["science", "turbo", ["goggles", "eyes"], "nothing"] trial= ["science", "turbo", {"eyes": "goggles", "goggles": "eyes"}, "nothing"] nightmare= [{"slappy": "a", "text": "b", "kumquat": "goggles", "user":{"awesome": "c", "name": {"first": "eyes", "last": "toes"}},"banana": 15, "d": "nothing"}] # challenge attempt _, _, [goggles, eyes], nothing = challenge print(f"My {eyes}! The {goggles} do {nothing}!") # trial attempt _, _, face, nothing = trial print(f"My {face['goggles']}! The {face['eyes']} do {nothing}!") # nightmare attempt goggles = nightmare[0]["kumquat"] eyes = nightmare[0]["user"]["name"]["first"] nothing = nightmare[0]["d"] print(f"My {eyes}! The {goggles} do {nothing}!")
class Parent(): def __init__(self,last_name,eye_colour): print("Parent Constructor Called") self.last_name=last_name self.eye_colour=eye_colour def show_info(self): print(self.last_name) print(self.eye_colour) class Child(Parent): def __init__(self,last_name,eye_colour,number_of_toys): print("Child Constructor Called") Parent.__init__(self, last_name, eye_colour) self.number_of_toys=number_of_toys def show_info(self): print(self.last_name) print(self.eye_colour) print(self.number_of_toys) #billy_cyrus=Parent("Cyrus","green") #print(billy_cyrus.last_name) miley_cyrus=Child("Cyrus","Blue",5) #print(miley_cyrus.last_name) #print(miley_cyrus.number_of_toys) miley_cyrus.show_info()
#Find Square triangular numbers #Square Triangular Number by Euler Formula def SquareTriangularNumber(k,res="N",roundi=True): if(res=="N"): r=((((3 + 2 * (2)**(1/2))**(k))-((3 - 2 * (2)**(1/2))**(k)))/(4 * (2)**(1/2)))**2 elif(res=="t"): r=(((3 + 2 * (2)**(1/2))**(k))-((3 - 2 * (2)**(1/2))**(k)) - 2)/(4) elif(res=="s"): r=(((3 + 2 * (2)**(1/2))**(k))-((3 - 2 * (2)**(1/2))**(k)))/(4 * (2)**(1/2)) if(roundi): return round(r) else: return r def doTest(toPrint=False,toProgress=False,start=0,toEnd=1000,algo="euler"): s=set() KK=10000 from IPython.display import clear_output for i in range(start,toEnd+1): if(toProgress and (i<KK or (i>=KK and i%(KK/100)==0))): clear_output(wait=True) print(i,end="\t") if(algo=="euler"): sqrnn=SquareTriangularNumber(i) if(algo=="t"): sqrnn=SquareTriangularNumber(i,"t") if(algo=="s"): sqrnn=SquareTriangularNumber(i,"s") if(sqrnn): s.add(sqrnn) if(toPrint and not toProgress): print(sqrnn,end=", ") if(toProgress and (i<KK or (i>=KK and i%(KK/100)==0))): print(s) if(not toPrint): return s #SquareTriangularNumber(2) #doTest(True,True,0,100) #SquareTriangularNumber(3,"s") #sorted(doTest(False,False,0,100,"t")) #sorted(doTest(False,False,0,100,"s"))
from math import sqrt as mmmsqrt def PythagoreanTriplet(n,toInv=False): s=set() fr=0 if(toInv): fr=-n for b in range(fr,n): for a in range(fr+1, b): c=mmmsqrt( a * a + b * b) if c%1==0: s.add((a, b, int(c))) return s def PythagoreanTriplet2(limits): c,m=0,2 s=set() while c<limits: for n in range(1, m): a=m*m-n*n b=2*m*n c=m*m+n*n if c>limits: break s.add((a,b,c)) m = m + 1 return s #PythagoreanTriplet(5000) #3.46 s #PythagoreanTriplet2(27000) #19 ms
# Find Prime Numbers #One def isPrime(n): if n % 2 == 0: return n == 2 d = 3 while d * d <= n and n % d != 0: d += 2 return d * d > n def StudentMethod(n): lst=[] k=0 for i in range(2,n+1): for j in range(2,i): if i%j==0: k=k+1 if k==0: lst.append(i) else: k=0 return lst def _bf1(n): lst=[] for i in range(2,n+1): for j in range(2,i): if i%j==0: break else: lst.append(i) return lst def _bf2(n): lst=[] for i in range(2,n+1): for j in lst: if i%j==0: break else: lst.append(i) return lst def _bf3(n): from math import sqrt lst=[] for i in range(2,n+1): for j in lst: if j>int((sqrt(i))+1): lst.append(i) break if (i%j==0): break else: lst.append(i) return lst def _bf4(n): from math import sqrt lst=[] for i in range(2,n+1): if (i>10): if (i%2==0) or (i%10==5): continue for j in lst: if j>int((sqrt(i))+1): lst.append(i) break if (i%j==0): break else: lst.append(i) return lst def _bf5(n): from math import sqrt lst=[2] for i in range(3,n+1,2): if (i>10) and (i%10==5): continue for j in lst: if j>int((sqrt(i))+1): lst.append(i) break if (i%j==0): break else: lst.append(i) return lst def _bf6(n): lst=[2] for i in range(3,n+1,2): if (i>10) and (i%10==5): continue for j in lst: if j*j-1>i: lst.append(i) break if (i%j==0): break else: lst.append(i) return lst #Get Sieve of Eratosthenes sequence def SieveofEratosthenes(n=5): a = list(range(n+1)) a[1]=0 lst = [] i=2 while i<=n: if a[i]!=0: lst.append(a[i]) for j in range(i,n+1,i): a[j]=0 i+=1 return (lst) def to_matrix(l, n): return [l[i:i+n] for i in range(0, len(l), n)] #SieveofEratosthenes(1000)
import pygame from pygame.sprite import Sprite # When we use sprite we can group related elements in our game and act on all the group elements at once such as the tridents class Trident(Sprite):#Trident class inherits from Sprite which we have imported from pygame.sprite module # A class to manage the tridents being shot by the pewds model def __init__(self,cNM_S,screen,pewdsModel): #create a trident object at the pewds model's position super(Trident,self).__init__()#To inherit from Sprite self.screen=screen self.image=pygame.image.load('C:\\Users\\Rahul Pillai\\Desktop\\_\\College\\SkillShare\\PythonGameDevelopment\\Codes\\CreeperNahMan\\CreeperNahMan\\CreeperNahMan\\ImageAssets\\Trident.png') self.rect=self.image.get_rect() #self.rect=pygame.Rect(0,0,cNM_S.tridentWidth, cNM_S.tridentHeight) #not using this #Set the correct position of the trident rectangle as the same position as that of pewds model self.rect.centerx = pewdsModel.rect.centerx #self.rect.top = pewdsModel.rect.top#If we want the trident to shoot from inside the pewds model self.rect.bottom = pewdsModel.rect.centery#If we want the trident to shoot from middle part of the pewds model # Store the trident's position as a decimal value self.y = float(self.rect.y) #self.color = cNM_S.tridentColor self.speed = cNM_S.tridentSpeed def update(self): #Move the trident up the screen #Update the decimal position of the trident self.y-=self.speed # as trident moves up the screen we need to decrease its y coordinate value depending on the speed #update the rect position self.rect.y = self.y def drawTrident(self): # Draw the trident to the screen self.screen.blit(self.image,self.rect)#inside the bracket the arguments go as (source(pygame surface which in this case is the image),destination)
# STRING MANIPULATION name = "Maayan Politzer is in the h'ouse" name2 = 'Maayan has\\\' left the "WOW" building!' # print(name2) x = 'Maayan\'s home' x2 = "Maayan\"s home!" multi_line_text = """First line. Second line. Third line.""" # print(multi_line_text) #print(len(name)) # list index 0 1 2 3 4 5 d = "Maayan" # ["M", "a", "a", "y", "a", "n"] #print(d[3]) # i = 0 # while i < len(d): # x = d[i] # print(x) # i += 1 # for x in d: # print(x) # def is_text_in_str(text, str): # for x in str: # if text == x: # return True # return False my_text = "Los Angeles lakers" # print(is_text_in_str("L", my_text)) #print("s le" in my_text) list = [3, 6, 0, -40] list2 = [] list.append(2546) # method: my_new_string = my_text.capitalize() print("k".isdecimal()) print(my_new_string)
import json class CustomersFile: def __init__(self): self.__file_name = "customers.txt" self.__customers = [] def __write_file(self): my_data = customer.get_dictionary() # convert dictionary to json: j = json.dumps(my_data) # insert this json object into the file: open(self.__file_name, "a").truncate() def __read_file(self): pass def add_customer(self, customer): self.__customers.append(customer) open("customer.log").write(customer.get_log_data()) def search(self, search_value, key="name"): pass ''' 1. כשנפעיל את התוכנה, נשלוף את הנתונים מהקובץ לקוחות. 2. כשנסגור את התוכנה, נכתוב את רשימת הלקוחות לקובץ. 3. במהלך הפעילות של התוכנה, ננהל את הלקוחות בעזרת רשימה. 4. במקרה של הפסקת חשמל/קריסה של התוכנה, נשמור את הלקוחות כגיבוי על קובץ נוסף. 5. להוסיף כפתור ״export״ בשביל לאפשר החלפת מחשב. '''
def first(text, n): x = 0 result = "" while x < n: result += text x += 1 return result # print(first("Hello", 5)) # "HelloHelloHelloHelloHello" # print(first("o", 3)) # "ooo" # a1 = 4-2 # a2 = first("Yes", a1) # print(a2) # print(first("Yes", (4-2))) def second(first, second): return first > second #print(second(45, 23)) #print(second(50, 7)) # False def third(x,y,z): # result = 0 # if x % 2 == 0: # result += x # if y % 2 == 0: # result += y # if z % 2 == 0: # result += z return helperToThird(x) + helperToThird(y) + helperToThird(z) def helperToThird(number): if number % 2 == 0: return number return 0 # what is the sum of the even numbers. #print(third(1,2,3)) # 2 #print(third(2,6,1)) # 8 #print(third(8,8,8)) # 24 def average(x,y): return (x + y) / 2 #print(average(90,70)) # 80 # return the sum of the arguments but don't add the number 7 and one param to the right print(notSevenOrAfterSeven(5,8,12)) # 25 print(notSevenOrAfterSeven(5,7,12)) # 5 print(notSevenOrAfterSeven(7,8,2)) # 2 print(notSevenOrAfterSeven(1,8,7)) # 9
## #Zodiac Capatibility # # @Author Saillesh # @date 10/22/2019 # @course ICs 3UC #Subprogram fro Get Birthday def getBirthday(): day = 1 month=1 #Ask user for Day and Month valid = False while(not valid): try: day = int(input("What is your Birth Day?: ")) if(day <32): valid = True else: print("Plese enter the day in number form (range from 1-31) ") except: print("Enter something valid") #Ask user for thier brith month valid = False while(not valid): try: month = int(input("What is your Birth Month?: ")) if(month<13): valid = True else: print("Plese enter the month in number formd. Ex:(jan=1, Feb=2)") except: print("Enter something valid") return month,day #Subprogram for Get Zodiac def getZodiac(month,day): result = "result" if (month == 1): if(day < 20): result = "Sagittarius" else: result = "Capricorn" elif(month == 2): if (day < 16): result = "Capricorn" else: result = "Aquarius" elif(month == 3): if (day < 11): result = "Aquarius" else: result = "Pisces" elif(month == 4): if (day < 18): result = "Pisces" else: result = "Aries" elif(month == 5): if (day < 13): result = "Aries" else: result = "Taurus" elif(month == 6): if (day < 21): result = "Taurus" else: result = "Gemini" elif(month == 7): if (day < 20): result = "Gemini" else: result = "Cancer" elif(month == 8): if (day < 20): result = "Cancer" else: result = "Leo" elif(month == 9): if (day < 16): result = "Leo" else: result = "Virgo" elif(month == 10): if (day < 30): result = "Virgo" else: result = "Libra" elif(month == 11): if (day < 23): result = "Libra" elif(day < 29): result = "Scorpio" else: result = "Ophiuchus" elif(month == 12): if (day < 17): result = "Ophiuchus" elif(day < 31): result = "Sagittarius" return result #Subprogram for Compatibility def getCompatability(sign): fire = ["Aries" , "Leo", "Sagittarius"] water = ["Pisces", "Cancer", "Scorpio", "Ophiuchus"] air = ["Gemini", "Aquarius", "Libra"] earth = ["Capricorn" , "Taurus" , "Virgo"] if (sign1==sign2): element = "Compatibe" elif(sign1 in fire and sign2 in fire): element = "Compatible" elif (sign1 in water and sign2 in water): element = "Compatible" elif (sign1 in earth and earth in fire): element = "Compatible" elif (sign1 in air and earth in air): element = "Compatible" else: element = "Not Comaptible" return element #main if __name__=="__main__": #get Birthday From Person 1 month1,day1 = getBirthday() #get Birthday From Person 1 month2,day2 = getBirthday() #Get Zodiac Sign sign1 = getZodiac(month1,day1) sign2 = getZodiac(month2,month2) #Determind Capatibility element = getCompatability(sign1) print(sign1 + " and " + sign2 + " are: " + element)
# Write a function that takes in a non-empty array of integers # and returns the maximum sum that can be obtained by summing up # all of the integers in a non-empty subarray of the input array. # A subarray must only contain adjacent numbers # O(n) time | O(1) space - where n is the length of the input array def kadanesAlgorithm(array): maxEndingHere = array[0] maxSoFar = array[0] for i in range(1, len(array)): num = array[i] maxEndingHere = max(num, maxEndingHere + num) maxSoFar = max(maxSoFar, maxEndingHere) return maxSoFar
# You are given a non-empty array of arrays where each subarray holds three # integers and represents a disk. These integers denote each disk's width, depth # and height, respectively. Your goal is to stack up the disks and to maximize the total # height of the stack. A disk must have a strictly smaller width, depth, and height than and other disk below it. # Write a function that returns an array of the disks in the final stack, starting with the top disk # and ending with the bottom disk. Note that you can't rotate disks; in other words, the integers in each subarray # must represent [width, depth, height] at all times. # You can assume that there will only be one stack with the greatest total height. # O(n^2) time | O(n) space def diskStacking(disks): disks.sort(key=lambda disk:disk[2]) heights = [disk[2] for disk in disks] sequences = [None for disk in disks] maxHeightIdx = 0 for i in range(1, len(disks)): currentDisk = disks[i] for j in range(0, i): otherDisk = disks[j] if areValidDimensions(otherDisk, currentDisk): if heights[i] <= currentDisk[2] + heights[j]: heights[i] = currentDisk[2] + heights[j] sequences[i] = j if heights[i] >= heights[maxHeightIdx]: maxHeightIdx = i return buildSequence(disks, sequences, maxHeightIdx) def areValidDimensions(o, c): return o[0] < c[0] and o[1] < c[1] and o[2] < c[2] def buildSequence(array, sequences, currentIdx): sequence = [] while currentIdx is not None: sequence.append(array[currentIdx]) currentIdx = sequences[currentIdx] return list(reversed(sequence))
# Given a list of strings, write a function that returns the longest string chain that # can be buit from those strings # O(n * m^2 + nlog(n)) time, O(nm) space, n = number of string, m = length of the longest string def longestStringChain(strings): # For every string, imagine the longest string chain that starts with it. # Set up every string to point to the next string in its respective longest # string chain. Also keep track of the lengths of these longest string chains. stringChains = {} for string in strings: stringChains[string] = {"nextString": "", "maxChainLength": 1} # Sort the strings based on their length so that whenever we visit a # string (as we iterate through them from left to right), we can # already have computed the longest string chains of any smaller strings. sortedStrings = sorted(strings, key = len) for string in sortedStrings: findLongestStringChain(string, stringChains) return buildLongestStringChain(strings, stringChains) def findLongestStringChain(string, stringChains): # Try removing every letter of the current string to see if the # remaining strings form a string chain for i in range(len(string)): smallerString = getSmallerString(string, i) if smallerString not in stringChains: continue tryUpdateLongestStringChain(string, smallerString, stringChains) def getSmallerString(string, index): return string[0:index] + string[index + 1 : ] def tryUpdateLongestStringChain(currentString, smallerString, stringChains): smallerStringChainLength = stringChains[smallerString]["maxChainLength"] currentStringChainLength = stringChains[currentString]["maxChainLength"] # Update the string chain of the current string only if the smaller string leads # to a longer string chain if smallerStringChainLength + 1 > currentStringChainLength: stringChains[currentString]["maxChainLength"] = smallerStringChainLength + 1 stringChains[currentString]["nextString"] = smallerString def buildLongestStringChain(strings, stringChains): # Find the string that starts the longest string chain maxChainLength = 0 chainStartingString = "" for string in strings: if stringChains[string]["maxChainLength"] > maxChainLength: maxChainLength = stringChains[string]["maxChainLength"] chainStartingString = string # Starting at the string found above, build the longest string chain. ourLongestStringChain = [] currentString = chainStartingString while currentString != "": ourLongestStringChain.append(currentString) currentString = stringChains[currentString]["nextString"] return [] if len(ourLongestStringChain) == 1 else ourLongestStringChain
# Given a non-empty array of integers, write a function that returns the longest strictly # increasing subsequence in the array. # O(n^2) time, O(n) space def longestIncreasingSubsequence(array): seq = [None for x in array] lengths = [1 for x in array] maxLengthIdx = 0 for i in range(len(array)): currentNum = array[i] for j in range(0, i): otherNum = array[j] if otherNum < currentNum and lengths[j] + 1 >= lengths[i]: lengths[i] = lengths[j] + 1 seq[i] = j if lengths[i] >= lengths[maxLengthIdx]: maxLengthIdx = i return buildSeq(array, seq, maxLengthIdx) def buildSeq(array, seqs, currentIdx): seq = [] while currentIdx is not None: seq.append(array[currentIdx]) currentIdx = seqs[currentIdx] return list(reversed(seq))
# Write a function that takes in a Binary Tree (where nodes have an additional pointer # to their parent node) and traverses it iteratively using the in-order tree-traversal technique; # the traversal should specifically not use recursion. As the tree is being traversed, # a callback function passed in as an argument to the main function should be called on each node def iterativeInOrderTraversal(tree, callback): previousNode = None currentNode = tree while currentNode is not None: if previousNode is None or previousNode == currentNode.parent: if currentNode.left is not None: nextNode = currentNode.left else: callback(currentNode) nextNode = currentNode.right if currentNode.right is not None else currentNode.parent elif previousNode == currentNode.left: callback(currentNode) nextNode = currentNode.right if currentNode.right is not None else currentNode.parent else: nextNode = currentNode.parent previousNode = currentNode currentNode = nextNode
# Write a function that takes in three strings and returns a boolean representing whether the third # string can be formed by interweaving the first two strings # O(2^(n + m)) time, O(n+m) space, where n is the length of the first stirng, # m is the length of the second string def interweavingStrings(one, two, three): if len(three) != len(one) + len(two): return False return areInterwoven(one, two, three, 0, 0) def areInterwoven(one, two, three, i, j): k = i + j if k == len(three): return True if i < len(one) and one[i] == three[k]: if areInterwoven(one, two, three, i + 1, j): return True if j < len(two) and two[j] == three[k]: return areInterwoven(one, two, three, i, j + 1) return False
# You are given three inputs, all of which are instances of an AncestralTree class # that have an ancestor property pointing to their younger ancestor. The first input is the top ancestor # in an ancestral tree, and the othe two inputs are decendants in the ancestral tree. # Write a function that returns the youngest common ancestor to the two descendants # This is an input class. Do not edit. class AncestralTree: def __init__(self, name): self.name = name self.ancestor = None def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): depthOne = getDescendantDepth(descendantOne, topAncestor) depthTwo = getDescendantDepth(descendantTwo, topAncestor) if depthOne > depthTwo: return backtrackAncestralTree(descendantOne, descendantTwo, depthOne - depthTwo) else: return backtrackAncestralTree(descendantTwo, descendantOne, depthTwo - depthOne) def getDescendantDepth(descendant, topAncestor): depth = 0 while descendant != topAncestor: depth += 1 descendant = descendant.ancestor return depth def backtrackAncestralTree(lowerDescendant, higherDescendant, diff): while diff > 0: lowerDescendant = lowerDescendant.ancestor diff -= 1 while lowerDescendant != higherDescendant: lowerDescendant = lowerDescendant.ancestor higherDescendant = higherDescendant.ancestor return lowerDescendant
# Write a function that takes a list of Cartesian coordinates and returns the number of rectangles formed by these coordinates # O(n^2) time, O(n) space where n is the number of coordinates def rectangleMania(coords): coordsTable = getCoordTable(coords) return getRectangleCount(coords, coordsTable) def getCoordTable(coords): coordsTable = {} for coord in coords: coordString = coordToString(coord) coordsTable[coordString] = True return coordsTable def getRectangleCount(coords, coordsTable): rectangleCount = 0 for x1, y1 in coords: for x2, y2 in coords: if not isInUpperRight([x1, y1], [x2, y2]): continue upperCoordString = coordToString([x1, y2]) rightCoordString = coordToString([x2, y1]) if upperCoordString in coordsTable and rightCoordString in coordsTable: rectangleCount += 1 return rectangleCount def isInUpperRight(coord1, coord2): x1, y1 = coord1 x2, y2 = coord2 return x2 > x1 and y2 > y1 def coordToString(coord): x, y = coord return str(x) + "-" + str(y)
from linkedList import LinkedList from linkedList import Node from linkedList import list_to_linkedList def delete_middle(chain: LinkedList, size=[0], curr=0): # This is just to get the middle node : the helper function isnt needed if chain: size[0] += 1 delete_middle(chain.next, size, curr+1) if curr == int(size[0]/2): delete_middle_given_middle(chain) # chain.next = chain.next.next def delete_middle_given_middle(chain: LinkedList): if chain.next == None or not chain: return chain.val = chain.next.val chain.next = chain.next.next if __name__ == "__main__": s = list_to_linkedList([1,2,3,4,5]).head delete_middle(s) s.print()
def tripleStep(steps: int) -> int: if steps < 0: return 0 if steps == 0: return 1 else: return tripleStep(steps-1) + tripleStep(steps-2) + tripleStep(steps-3) if __name__ == "__main__": print(tripleStep(2))
def magicIndex(array: list) -> int: return magicIndex(array, 0 , len(array)-1) def magicIndex(array:list, int start, int end) -> int: if end > middle: return -1 middle = (array[start] + array[end])/2 if array[middle] == middle: return middle elif array[middle] < middle: return magicIndex(array, middle, end) elif array[middle] > middle: return magicIndex(array, start, middle)
class queue: def __init__(self): self.values = [] def isEmpty(self): return self.values.length == 0 def push(self, val): self.values.append(val) def remove(self): if not self.isEmpty(): return self.values.pop(0) def peek(self): if not self.isEmpty(): return self.values[0]
from linkedList import LinkedList from linkedList import Node from linkedList import list_to_linkedList def partition(chain: Node, target: int) -> LinkedList: beforeStart = Node() beforeEnd = Node() afterStart = Node() afterEnd = Node() while(chain): nex = chain.next chain.next = None # Used so that we dont accidently create a circular linked list if chain.val < target: if beforeStart.val == None: # Kind of like a bool beforeStart = chain beforeEnd = beforeStart else: beforeEnd.next = chain beforeEnd = chain else: if afterStart.val == None: afterStart = chain afterEnd = afterStart else: afterEnd.next = chain afterEnd = chain chain = nex if not beforeStart: return afterStart beforeEnd.next = afterStart return beforeStart if __name__ == "__main__": chain = list_to_linkedList([3,5,8,5,10,2,1]) partition(chain.head, 5).print()
import math def isPrime(N): sq = int(math.sqrt(N)) + 1 if N < 2: return False elif N == 2: return True else: for i in range(3, sq, 2): if N%i == 0: return False return True isPrime(15) def x(): if 2 in {3, 4, 2}: return True else: return False # def solution(A, B): # m = 100001 # available = set() # for i in range(len(A)): # if A[i] == B[i]: # available.add(A[i]) # else: # if A[i] > B[i]: # available.add(A[i]) # if (int(min(B[i], m)) in available): # continue # else: # m = min # else: # available.add(B[i]) # if (int(min(A[i], m)) in available): # continue # else: # m = min # # return m # # # def solution(A, B): # m = 100001 # available = set() # for i in range(len(A)): # if A[i] == B[i]: # available.add(A[i]) # else: # if A[i] > B[i]: # available.add(A[i]) # x = min(B[i], m) # if (x in available): # continue # else: # m = min # else: # available.add(B[i]) # x = min(A[i], m) # if (x in available): # continue # else: # m = min # # return m # [1, 2], [1, 2] -> 3 # [1,3,6,4], [1,2,3,4] def solution(A, B): m = 100001 available = set() for i in range(len(A)): if A[i] == B[i]: available.add(A[i]) else: if A[i] > B[i]: available.add(A[i]) x = min(B[i], m) if (x in available): continue else: m = x else: available.add(B[i]) x = min(A[i], m) if (x in available): continue else: m = x if m == 100001: return max(A) + 1 else: return m # solution([1,3,6,4], [1,2,3,4]) # 2 # solution([1, 2], [1, 2]) # 3 solution([4,5,7,9,0,3,6,2,7], [7,3,6,45,32,45,8,12,4]) # 3 solution([4,5,7,9,1,3,6,2,7], [7,3,6,45,32,45,8,12,4])
import unittest class Vector: def __init__(self, data): self.data = data def __add__(self, other): self.__check_len(other) return Vector(map(lambda x, y: x+y, self, other)) def __check_len(self, other): if (len(self) != len(other)): raise Exception('vectors must have same length') def __getitem__(self, index): return self.data[index] def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def __eq__(self, other): return self.data == other.data class Matrix(Vector): def __init__(self, data): self.data = map(Vector, data) class LinAlgTests(unittest.TestCase): def setUp(self): pass def testVectorAdd(self): v1 = Vector([1,2,3]) v2 = Vector([3,4,5]) v3 = Vector([4,6,8]) self.assertEqual(v1 + v2, v3) def testMatrixAdd(self): M1 = Matrix([[1,2],[3,4]]) M2 = Matrix([[5,6],[7,8]]) M3 = Matrix([[6,8],[10,12]]) self.assertEqual(M1 + M2, M3) def main(): unittest.main() if __name__ == '__main__': main()
def MergeIncomingAndOutgoing(incoming, outgoing): # Set up variables merged_list = [ ] incoming_index = 0 outgoing_index = 0 incoming_length = len(incoming) outgoing_length = len(outgoing) # Go through each list while len(merged_list) < incoming_length + outgoing_length: if incoming_index == incoming_length: while outgoing_index != len(outgoing): merged_list.append((outgoing[outgoing_index], "outgoing")) outgoing_index += 1 break elif outgoing_index == outgoing_length: while incoming_index != len(incoming): merged_list.append((incoming[incoming_index], "incoming")) incoming_index += 1 break # Compare transaction heights if incoming[incoming_index].transaction.height > outgoing[outgoing_index].transaction.height: merged_list.append((incoming[incoming_index], "incoming")) incoming_index += 1 else: merged_list.append((outgoing[outgoing_index], "outgoing")) outgoing_index += 1 # It is a list of tuples to keep track of whether it is in incoming or ougoing transaction. # Transaction data is [0] and incoming/outgoing status is [1] return merged_list
num = int(input(" Enter a non-negative number: ")) for x in range (1,num+1): if x%3==0 and x%5==0: print("fizz buzz") elif x%3==0: print('fizz') elif x%5==0: print('buzz') else: print(x)
import random from typing import List class Drawer: def __init__(self, lower: int, upper: int, num_of_ticket: int): """ :param lower: the lower bound of drawer :param upper: the upper bound of drawer :param num_of_ticket: number of selected ticket, lower <= num_of_ticket < upper """ self.lower = lower self.upper = upper self.num_of_ticket = num_of_ticket self.max = self.get_max() @property def num_of_ticket(self): return self._num_of_ticket @num_of_ticket.setter def num_of_ticket(self, value): if self.lower <= value < self.upper: self._num_of_ticket = value else: raise ValueError("should be lower <= num_of_ticket < upper") def get_max(self) -> int: """ :return: the total length of permutation """ res = 1 for i in range(self.upper - self.num_of_ticket, self.upper): res *= i return res def draw(self) -> List[int]: """ :return: permutation result """ return random.sample(range(self.lower, self.upper), self.num_of_ticket)
#welcome to Manual Dual Player Tic Tac Toe Game Clone import pygame , sys import numpy as np pygame.init() WIDTH = 600 HEIGHT = 600 RED = (255,0,0) LINE_COLOR =(23,145,135) BG_COLOR =(28,170,156) CIRCLE_COLOR = (239,231,200) CROSS_COLOR=(66,66,66 ) BOARD_ROWS =3 BOARD_COLS =3 CIRCLE_RADIUS =60 CIRCLE_WIDTH = 15 CROSS_WIDTH = 25 LINE_WIDTH = 15 SPACE = 55 screen = pygame.display.set_mode((WIDTH,HEIGHT)) pygame.display.set_caption("TIC-TAC-TO") screen.fill(BG_COLOR) board = np.zeros((BOARD_ROWS,BOARD_COLS)) player =1 game_over = False def draw_lines(): pygame.draw.line(screen,LINE_COLOR,(0,200),(600,200),5) pygame.draw.line(screen,LINE_COLOR,(0,400),(600,400),5) pygame.draw.line(screen,LINE_COLOR,(200,0),(200,600),5) pygame.draw.line(screen,LINE_COLOR,(400,0),(400,600),5) draw_lines() def mark_square(row ,coloum,player): board[row][coloum] =player #mark_square(0,0,1) def available_square(row,coloum): return board[row][coloum] == 0 def is_board_full(): for row in range(BOARD_ROWS): for cols in range(BOARD_COLS): if(board[row][cols]==0): return False return True def draw_figures(): for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if board[row][col] == 1: pygame.draw.circle(screen,CIRCLE_COLOR,(int(col*200 +100),int(row*200+100)),CIRCLE_RADIUS,CIRCLE_WIDTH) elif board[row][col] == 2: pygame.draw.line(screen,CROSS_COLOR,(col*200+SPACE,row*200+200-SPACE),(col *200+200-SPACE,row*200+SPACE) ,CROSS_WIDTH) pygame.draw.line(screen,CROSS_COLOR,(col*200+SPACE,row*200+SPACE),(col *200+200-SPACE,row*200+200-SPACE) ,CROSS_WIDTH) #print(board) def cheack_win(player): #vertical cheack for col in range(BOARD_COLS): if board[0][col]==player and board[1][col]==player and board[2][col]== player: draw_vertical_winning_line(col,player) return True # horizontal cheack for row in range(BOARD_ROWS): if board[row][0] == player and board[row][1]==player and board[row][2]==player: draw_horizontal_winning_line(row,player) return True # original daigonal check if board[0][0] == player and board[1][1] == player and board[2][2] ==player: draw_dec_daigonal(player) return True #backword daigonal check if board[2][0] ==player and board[1][1]==player and board[0][2]==player: draw_asc_daigonal(player) return True return False def draw_vertical_winning_line(col,player): posx = col *200 +100 if player ==1: color=CIRCLE_COLOR elif player == 2: color= CROSS_COLOR pygame.draw.line(screen,color,(posx,15),(posx,HEIGHT-15),15) def draw_horizontal_winning_line(row,player): posy = row * 200 +100 if player ==1: color=CIRCLE_COLOR elif player == 2: color= CROSS_COLOR pygame.draw.line(screen,color,(15,posy),(WIDTH-15,posy),15) def draw_asc_daigonal(player): if player ==1: color=CIRCLE_COLOR elif player == 2: color= CROSS_COLOR pygame.draw.line(screen,color,(15,HEIGHT-15),(WIDTH-15,15),15) def draw_dec_daigonal(player): if player ==1: color=CIRCLE_COLOR elif player == 2: color= CROSS_COLOR pygame.draw.line(screen,color,(15,15),(WIDTH-15,HEIGHT -15),15) def restart(): screen.fill(BG_COLOR) draw_lines() player = 1 for row in range(BOARD_ROWS): for col in range(BOARD_COLS): board[row][col] =0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and not game_over: mousex = event.pos[0] # x-axis position mousey =event.pos[1] #y-axis position clicked_row = int( mousey//200) clicked_col = int( mousex//200) if available_square(clicked_row,clicked_col) : if player ==1: mark_square(clicked_row,clicked_col,player) if cheack_win(player): game_over=True player =2 elif player==2: mark_square(clicked_row,clicked_col,player) if cheack_win(player): game_over=True player =1 draw_figures() if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: restart() pygame.display.update()
import turtle turtle.shape('turtle') k=10 for i in range (0,40,2): turtle.left(90) turtle.forward(k+i*2) turtle.left(90) turtle.forward(k+i*2) turtle.left(90) turtle.forward(k+i*2) turtle.left(90) turtle.forward(k+i*2) turtle.penup() turtle.goto(i+2,-i-2) turtle.pendown()
max1=0 max2=0 a = -1 while a!=0: a = int(input()) if a>max1: max2=max1 max1=a elif a>max2: max2=a print(max2)
import random class consumer: effort = 4 #amount they could work daily_effort = effort wealth = 0 q_table = [ [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] #holds the benefit of any given decision epsilon = 1 #rate at which it randomly explores learning_rate = .8 #rate at which it values new data discount_rate = .2 #rate at which it values future benefit priceg1 = 1 priceg2 = 1 priceg3 = 1 curve1 = [] curve2 = [] curve3 = [] def __init__(self): print(self.q_table) def consume(self, price1, price2, price3, ben1, ben2, ben3, step): range1 = range(0, price1, step) #range of the demand range2 = range(0, price2, step) range3 = range(0, price3, step) for i in range1: for j in range2: for k in range3: self.priceg1 = i self.priceg2 = j self.priceg2 = k for i in range(500): #number of iterations at each price set if(self.epsilon > random.random()): #should we explore or not if i % 2 == 0: self.sell(random.randint(0,len(self.q_table[0])-1)) else: self.buy_rand(ben1, ben2, ben3) else: if i % 2 == 0: self.sell(self.max_col(self.q_table[0])) else: self.buy(ben1, ben2, ben3) self.curve1.append((i, max_col(q_table[1]))) self.curve2.append((j, max_col(q_table[2]))) self.curve3.append((k, max_col(q_table[3]))) self.epsilon -= .001 self.learning_rate -= .002 self.discount_rate -= .002 print(self.q_table) print() def sell(self, col): self.daily_effort -= col self.wealth += col self.q_table[0][col] = self.q_table[0][col] + self.learning_rate * (self.daily_effort*(1 - self.discount_rate) + self.discount_rate * self.q_table[1][self.max_col(self.q_table[1][:(self.wealth + 1)])] - self.q_table[0][col]) #mightbe broke return 0 def buy_rand(self, b1, b2, b3): if self.wealth == 0: self.q_table[1][0] = self.q_table[1][0] + self.learning_rate*(-1000 + \ self.discount_rate*(self.q_table[2][self.max_col(self.q_table[2][:(self.wealth + 1)])] - self.q_table[1][0])) else: x = random.randint(0, self.wealth) if x > 4: x = 4 self.wealth -= x*self.priceg1 print("line 57", x, self.wealth) self.q_table[1][x] = self.q_table[1][x] + self.learning_rate*(x * b1 + \ self.discount_rate*(self.q_table[2][self.max_col(self.q_table[2][:(self.wealth + 1)])] - self.q_table[1][x])) if x == 0: return x = random.randint(0, self.wealth) if x > 4: x = 4 self.wealth -= x*self.priceg2 self.q_table[2][x] = self.q_table[2][x] + self.learning_rate*(x * b2 + \ self.discount_rate*(self.q_table[3][self.max_col(self.q_table[3][:(self.wealth + 1)])] - self.q_table[2][x])) if x == 0: return x = random.randint(0, self.wealth) if x > 4: x = 4 self.wealth -= x*self.priceg3 print("wealth",self.wealth) self.q_table[3][x] = self.q_table[3][x] + self.learning_rate*(x * b3 + \ self.discount_rate*(self.q_table[1][self.max_col(self.q_table[1][:\ self.max_col(self.q_table[0]) + self.wealth + 1])]) - self.q_table[1][x]) def buy(self, b1, b2, b3): if self.wealth == 0: self.q_table[1][0] = self.q_table[1][0] + self.learning_rate*(-100 + \ self.discount_rate*(self.q_table[2][self.max_col(self.q_table[2][:(self.wealth + 1)])] - self.q_table[1][0])) print(self.wealth) x = self.max_col(self.q_table[1][:self.wealth + 1]) self.wealth -= x*self.priceg1 self.q_table[1][x] = self.q_table[1][x] + self.learning_rate*(x * b1 + \ self.discount_rate*(self.q_table[2][self.max_col(self.q_table[2][:(self.wealth + 1)])] - self.q_table[1][x])) if self.wealth >= 0: x = self.max_col(self.q_table[2][:self.wealth + 1]) self.wealth -= x*self.priceg2 self.q_table[2][x] = self.q_table[2][x] + self.learning_rate*(x * b2 + \ self.discount_rate*(self.q_table[3][self.max_col(self.q_table[3][:(self.wealth + 1)])] - self.q_table[2][x])) if self.wealth >= 0: x = self.max_col(self.q_table[3][:self.wealth + 1]) self.wealth -= x*self.priceg3 print("line 101: ", x,self.wealth) self.q_table[3][x] = self.q_table[3][x] + self.learning_rate*(x * b3 + \ self.discount_rate*(self.q_table[1][self.max_col(self.q_table[1][:\ self.max_col(self.q_table[0]) + self.wealth + 1])]) - self.q_table[1][x]) def max_col(self, stuff): max = stuff[0] max_col_index = 0 for i in range(1, len(stuff)): if stuff[i] > max: max = stuff[i] max_col_index = i return max_col_index def get_curve1(self): pass
from operator import add, sub, mul, truediv #Converting from infix notation to postfix notation def infix_to_post(s): try: stack, b = [], [] a = s.split() for i in a: if i not in '/*-+': b.append(i) else: if not stack: stack.append(i) else: if stack[-1] in '+-' and i in '*/': stack.append(i) else: while stack: b.append(stack.pop()) stack.append(i) while stack: b.append(stack.pop()) return ' '.join(b) except: return 0 #Solving postfix notation def postfix_solve(s): try: op = {'+': add, '-': sub, '*': mul, '/': truediv} stack = [] c = s.split() for i in c: if i in op: a, b = stack.pop(), stack.pop() stack.append(op[i](float(b), float(a))) elif i: stack.append(i) return stack.pop() except: return 'No'
""" Example class for downloading and storing text files. Uses a local file cache to avoid repeatedly downloading >>> moby = Text("http://www.gutenberg.org/files/2701/2701-0.txt") # doctest: +ELLIPSIS INFO: 'http://www.gutenberg.org/files/2701/2701-0.txt' found in ... >>> print(moby.text[28622:28638]) Call me Ishmael. """ # In your code you can try using a database or pickle instead of saving files. # This example does not do any processing or cleaning on the text data # (but you should) import os import requests import sys import time def strip_scheme(url): """ Return 'url' without scheme part (e.g. "http://") >>> strip_scheme("https://www.example.com") 'www.example.com' >>> strip_scheme("http://www.gutenberg.org/files/2701/2701-0.txt") 'www.gutenberg.org/files/2701/2701-0.txt' """ # TODO: This ad-hoc implementation is fairly fragile # and doesn't support e.g. URL parameters (e.g. ?sort=reverse&lang=fr) # For a more robust implementation, consider using # https://docs.python.org/3/library/urllib.parse.html scheme, remainder = url.split("://") return remainder class Text: """ Text class holds text-based information downloaded from the web It uses local file caching to avoid downloading a given file multiple times, even across multiple runs of the program. """ def __init__(self, url, file_cache=os.path.join(sys.path[0], "cache")): """ Given 'url' of a text file, create a new instance with the text attribute set by either downloading the URL or retrieving it from local text cache. Optional 'file_cache' argument specifies where text cache should be stored (default: same directory as the script in a "cache" folder) """ self.url = url self.local_fn = os.path.join(file_cache, strip_scheme(url)) # First see if file is already in local file cache if self.is_cached(): print("INFO: {url!r} found in local file cache, reading".format(url=self.url)) self.read_cache() # If not found, download (and write to local file cache) else: print("INFO: {url!r} not found in local file cache, downloading".format(url=self.url)) self.download() self.write_cache() def __repr__(self): return "Text({url!r})".format(url=self.url) def is_cached(self): """Return True if file is already in local file cache""" return os.path.exists(self.local_fn) def download(self): """Download URL and save to .text attribute""" self.text = requests.get(self.url).text # TODO: Exception handling # Wait 2 seconds to avoid stressing data source and rate-limiting # You don't need to do this here (only has to happen between requests), # but you should have it somewhere in your code time.sleep(2) def write_cache(self): """Save current .text attribute to text cache""" # Create directory if it doesn't exist directory = os.path.dirname(self.local_fn) if not os.path.exists(directory): os.makedirs(directory) # Write text to local file cache with open(self.local_fn, 'w') as fp: fp.write(self.text) def read_cache(self): """Read from text cache (file must exist) and save to .text attribute""" with open(self.local_fn, 'r') as fp: self.text = fp.read() def get_example(): """ Return a dictionary with key: book title, value: Text objects for books. """ urls = { "Pride and Prejudice": "http://www.gutenberg.org/files/1342/1342-0.txt", "Moby Dick": "http://www.gutenberg.org/files/2701/2701-0.txt", "Iliad": "http://www.gutenberg.org/ebooks/6130.txt.utf-8" } books = {} for title, url in urls.items(): t = Text(url) books[title] = t return books if __name__ == '__main__': #import doctest #doctest.testmod() from pprint import pprint # "Pretty-print" dictionary books = get_example() pprint(books) ## Example: using text contents of Text instances for title, book in books.items(): print("Excerpt from {title}: {txt!r}".format(title=title, txt=book.text[2000:2010])) # In the above example we access the .text attribute of the class directly. # Exercise: Try adding a "lines" method to the class that returns a list # of all the individual lines in the text file (after cleaning # the text), so that you can use it to write code like: # # example = Text(my_url) # for line in example.lines(): # do_something(line)
# 1. program to find out maximum of two numbers a=34 b=56 if a>b: print(a) else: print(b) # 2. Write a program to find the maximum of three numbers stored in variables. a=2 b=3 c=4 big=a if b>=big: big=b if c>=big: big=c print(big) # 3. Write a program to check whether a number is negative, positive or zero. Print out “negative”, “positive”, or “zero”. a= 34 if a>0: print("positive") elif a<0: print("negative") else: print("zero") # 4. Write a program that prints “YES” if a number is divisible by both 5 and 11, and prints “NO” otherwise. a=55 if ((a%5==0) and (a%11==0)): print("YES") else: print("NO") # 5.Write a program to check whether a year is leap year or not. a=2100 if a%100==0: if a%400==0: print("Leap year") else: print("Not a leap year") else: if(a%4==0): print("Leap year") else: print("Not a leap year") # 6.Write a program to check whether a character is uppercase or lowercase alphabet. Print “U” for uppercase and “L” for lowercase. a = 'z' print(ord(a)) if ord(a)>=65 and ord(a)<=90: print("U") if ord(a)>=97 and ord(a)<=122: print("L") # 7. Write a program which takes month number and print number of days in that month. For example: # For month=1 print “31 days” # For month=2 print “28 days” month=8 if month<=7: if month==2: print("28 days") elif month%2==0: print("30 days") else: print("31 days") else: if month%2==0: print("31 days") else: print("30 days") # 8. Write a program to print the minimum number of Rupee notes needed to match a given amount. Available denominations of notes are 2000, 500, 100, 50. # For example, if the amount is 28,550, then you need 14 notes of 2000, 1 note of 500, and 1 note of 50. So total number of notes is 14+1+1 = 16. a=2350 count2000=a//2000 remaining=a%2000 count500=remaining//500 remaining=remaining%500 count100=remaining//100 remaining=remaining%100 count50=remaining//50 print(count2000,count500,count100,count50) # 9. Write a program to print the profit or loss, given cost price and selling price. costprice=2000 sellingprice=2500 if costprice>sellingprice: print("Loss") elif sellingprice>costprice: print ("profit") else: print("No profit or loss") # 10. Write a program to check if a triangle can be formed using the given lengths of 3 sides side1=3 side2=4 side3=6 if (side1+side2)>side3 and (side2+side3)>side1 and (side1+side3)>side2: print("valid triangle") else: print("Not a a valid triangle") #11. Write a program to check whether the triangle is equilateral, isosceles or scalene triangle. (Equilateral triangle has all 3 sides equal. Isosceles triangle has 2 sides equal. Scalene triangle has no side equal). side1=3 side2=4 side3=6 if (side1==side2) and (side2==side3): print("Equilateral triangle") elif (side1==side2) or (side2==side3) or (side3==side1): print("Isoceles triangle") else: print("scalene triangle")
# tup=1,2,3 # print(tup) # arr=list(tup) # # # elem=tup[0]*2 # tup1=(elem,) # print(tup1+tup[1:]) # oops # class Student: # counter=1 # def __init__(self,name): # self.name=name # self.rollnum=Student.counter # Student.counter+=1 # def __str__(self): # return "Roll: {} Name: {}".format(self.rollnum,self.name) # s1=Student("Deepak") # print(s1) # # s2=Student("Manish") # print(s2) # # s1.counter=30 # print(Student.counter) # print(s1.counter) # print(s2.counter) # length=5 # breadth=3 # print("The length of rect id "+str(length)+" and breadth is "+str(breadth)) # print("The length of rect is {0} and breadth is {1}. Length is {0}".format(length,breadth)) # class Account: # counter=1 # def __init__(self,openingbalance=0): # self.__bankbalance= openingbalance # self.id=Account.counter # Account.counter+=1 # self.trans=0 # self.maxtrans=3 # def deposite(self,amount): # if self.__bankbalance+amount>=0 and self.trans<self.maxtrans: # self.__bankbalance+=amount # self.trans+=1 # def withdraw(self,amount): # if amount<=self.__bankbalance and amount>=0 and self.trans<self.maxtrans: # self.__bankbalance-=amount # self.trans+=1 # def __str__(self): # return "bankbalance is {} and id is {}".format(self.__bankbalance,self.id) # def getbalance(self): # return self.__bankbalance # class SavingAccounts(Account): # def getinterest(self): # return self.getbalance()*0.05 # class CurrenAccount(Account): # def __init__(self): # super().__init__() # self.maxtrans=5 # # # sa1=SavingAccounts() # sa1.deposite(100) # sa1.withdraw(10) # sa1.withdraw(10) # sa1.withdraw(10) # print(sa1) # # ca1=CurrenAccount() # ca1.deposite(100) # ca1.withdraw(10) # ca1.withdraw(10) # ca1.withdraw(10) # ca1.withdraw(10) # ca1.withdraw(10) # print(ca1) # a1=Account() # a1.deposite(1000) # a1.withdraw(100) # a1.__bankbalance=9999999 # print(a1) # a2=Account(100) # a2.deposite(20) # a2.withdraw(1) # print(a2)
# spiral printing # mat= [ # [1,2,3], # [4,5,6], # [7,8,9], # [10,11,12] # ] # # def spiralprint(mat): # numrows=len(mat) # numcols=len(mat[0]) # top=0 # bottom=numrows-1 # left=0 # right=numcols-1 # while left<=right and top<=bottom: # for r in range(top,bottom+1): # print(mat[r][left]) # left+=1 # if not(left<=right and top<=right): # break # # for c in range(left,right+1): # print(mat[bottom][c]) # bottom-=1 # if not (left <= right and top <= right): # break # # for r in range(bottom,top-1,-1): # print(mat[r][right]) # right-=1 # if not (left <= right and top <= right): # break # # for c in range(right,left-1,-1): # print(mat[top][c]) # top+=1 # # spiralprint(mat) ## recursion # def factorial(num): # if num==1: # return 1 # return num*factorial(num-1) # print(factorial(5)) # def fabonacci(num): # if num==1 or num==0: # return num # return fabonacci(num-1)+fabonacci(num-2) # print(fabonacci(7)) # def pow(a,b): # if b==0: # return 1 # return a*pow(a,b-1) # print(pow(2,3)) # def reverseprint(num): # if num==0: # return # print(num) # reverseprint(num-1) # reverseprint(6) # def straightprint(num): # if num==0: # return # straightprint(num-1) # print(num) # straightprint(6) # memory=[-1]*1000 # def fib(i): # if memory[i]!=-1: # return memory[i] # if i==0 or i==1: # return i # result=fib(i-1)+fib(i-2) # memory[i]=result # return result # print(fib(990)) # def powerpositive(a,b): # if b==0: # return 1 # p=b if b>=0 else -b # partial=pow(a,b//2) # result=partial*partial # if p%2!=0: # result*=a # return result if b>0 else 1/result # # print(power(-2,-3)) # def pow(a,b): # if b<0: # return 1/powerpositive(a,-b) # else: # return powerpositive(a,b) # def hcf(a,b): # if a==0 or b==0: # return max(a,b) # if a>b: # return hcf(a%b,b) # else: # return hcf(a,b%a) # print(hcf(12,60))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #迭代器 #我们已经知道,可以直接作用于for循环的数据类型有以下几种: #一类是集合数据类型,如list、tuple、dict、set、str等; #一类是generator,包括生成器和带yield的generator function。 #这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。 #可以使用isinstance()判断一个对象是否是Iterable对象: from collections import Iterable print(isinstance([],Iterable)) print(isinstance({},Iterable)) print(isinstance('abc',Iterable)) print(isinstance((x for x in range(0,100)),Iterable)) print(isinstance(100,Iterable)) print('##############################') #而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。 #可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 #可以使用isinstance()判断一个对象是否是Iterator对象 from collections import Iterator print(isinstance([],Iterator)) print(isinstance({},Iterator)) print(isinstance('abc',Iterator)) print(isinstance((x for x in range(0,100)),Iterator)) #生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 #把list、dict、str等Iterable变成Iterator可以使用iter()函数 print(isinstance(iter([]),Iterator)) #你可能会问,为什么list、dict、str等数据类型不是Iterator? #这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。 #Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
patternFirstStar = [1, 9, 25, 49] patternSecondStarIndexOf = [0, 9, 25, 36, 49, ] ## first star input = 265149 base = 1 while 1: base += 2 squared = base ** 2 if squared > input: print 'squared: ' + str(squared) print 'base: ' + str(base) difference = squared - input print 'difference: ' + str(difference) print 'offset: ' + str(base - difference) stepsLeft = (base/2) - difference print 'steps to the left: ' + str(stepsLeft) stepsUp = base/2 print 'steps up: ' + str(stepsUp) print 'total steps: ' + str(stepsLeft + stepsUp) break ## second star print '====second star==============================\n\n' def spiral(n): vectorDict = {'0|0': 1} x = 0 y = 0 count = 1 sign = 1 step = 1 for i in xrange(0, n): for j in xrange(0, count): total = 0 x += step # check all adjacent numbers for adjacentX in range(-1,2): for adjacentY in range(-1,2): if adjacentX == 0 and adjacentY == 0: continue adjacentKey = str(x + adjacentX) + '|' + str(y + adjacentY) if adjacentKey in vectorDict: total += vectorDict[adjacentKey] # print 'adjacent1 x: ' + str(x) + str(y) if total > 265149: print total break vectorDict[str(x) + '|' + str(y)] = total for k in xrange(0, count): total = 0 y += step # check all adjacent numbers for adjacentX in range(-1,2): for adjacentY in range(-1,2): if adjacentX == 0 and adjacentY == 0: continue adjacentKey = str(x + adjacentX) + '|' + str(y + adjacentY) if adjacentKey in vectorDict: total += vectorDict[adjacentKey] # print 'adjacent1 x: ' + str(x) + str(y) if total > 265149: print total break vectorDict[str(x) + '|' + str(y)] = total count += 1 step *= -1 return vectorDict spiral = spiral(40) print spiral print '----test------' print '0,0: ' + str(spiral['0|0']) print '1,0: ' + str(spiral['1|0']) print '1,1: ' + str(spiral['1|1']) print '0,1: ' + str(spiral['0|1']) print '-1,1: ' + str(spiral['-1|1']) # print '-2,-2: ' + str(spiral['-2|-2']) # print '-4,-4: ' + str(spiral['-4|-4']) try: print 'number: ' + str(spiral['1|122']) except: print 'key does not exist'
#!/usr/bin/python3 """ Make Change """ def makeChange(coins, total): """ determine the fewest number of coins needed to meet a given amount total. Args: coins: (list) the values of the coins in your possession. total: (int) amount to be calculated. Returns: (int) fewest number of coins needed to meet total or -1. """ if total <= 0: return 0 coins = sorted(coins) change = [total + 1] * (total + 1) change[0] = 0 for i in range(total + 1): for coin in coins: if coin <= i: change[i] = min(change[i], 1 + change[i - coin]) return change[total] if change[total] < total else -1
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @author : shengxd @Contact : shengxd@huahuan.com @File : merge_list.py @Time : 2019/11/11 18:06 @Desc : """ """ Definition of ListNode """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param l1: ListNode l1 is the head of the linked list @param l2: ListNode l2 is the head of the linked list @return: ListNode head of linked list """ def mergeTwoLists(self, l1, l2): # write your code herel merge_list = [] if l1 == None and l2 == None: return elif l1 == None and l2 != None: return l2 elif l1 != None and l2 == None: return l1 elif l1 != None and l2 != None: while l1: merge_list.append(l1.val) l1 = l1.next while l2: merge_list.append(l2.val) l2 = l2.next merge_list.sort() head_node = ListNode(merge_list[0]) p = head_node for i in range(1, len(merge_list)): node = ListNode(merge_list[i]) p.next = node p = p.next return head_node
size = int(input()) # 회의 정보 meeting = [[] for _ in range(size)] for i in range(size): start, end = map(int, input().split(" ")) meeting[i].append(start) meeting[i].append(end) # print(meeting) ## 내가 틀린 이유: 회의 종료시간과 회의 시작시간에 따른 오름차순 정렬을 해야한다!!!! & 시간초과 ## 우선 회의 종료시간에 대해 오름차순으로 정렬 후 그 후 시작시간에 대해 오름차순 정렬을 해야한다. meeting.sort(key=lambda x:(x[1],x[0])) # 종료시간이 빠른 애들부터 가장 빨리 시작하는 애들을 더해준다. m_cnt = 0 start = 0 for m in meeting: if m[0] >= start: m_cnt += 1 start = m[1] print(m_cnt) """ 시간초과 코드 # 확정된 회의 배열 mt = [] mt_cnt = 0 # 일단 가장 종료시간이 빠른 회의 삽입 mt.append(meeting[0]) mt_cnt += 1 # 실수로 for문 중첩의 순서?를 바꿨다. # 바깥에 있는 for문에서는 선택된 회의가 for문으로 돌고, 안의 for문에서 회의정보 배열이 돌아야 하는데 이 반대로 했다. for v in mt: v_start = v[0] v_end = v[1] for m in meeting: start = m[0] end = m[1] if start >= v_end: # print("기존 회의 시간 ({0}, {1})".format(v_start, v_end)) # print("새로운 회의 시간 ({0}, {1})".format(start, end)) if v_start == v_end: # 회의 시작과 종료가 같은 특수한 경우가 존재함. (3, 3)에 (3, 7)이 들어갈 수는 없다. if start > v_start: mt.append(m) mt_cnt += 1 break mt.append(m) mt_cnt += 1 break # print(mt) print(mt_cnt) """
# We start by importing the neccesary libraries # and by creating the GUI window import tkinter as tk window = tk.Tk() window.geometry("620x780") window.title(" Age Calculator App ") # Now the labels and positions # into de Window name = tk.Label(text = "Name") name.grid(column = 0, row = 1) year = tk.Label(text = "Year") year.grid(column = 0, row = 2) month = tk.Label(text = "Month") month.grid(column = 0, row = 3) day = tk.Label(text = "Day") day.grid(column = 0, row = 4)
import numpy as np from sklearn.linear_model import LinearRegression np.random.seed(111) ''' The data is generated adding noise to the values from y = 0.8x + 2 equation Therefore the expectation of the auto encoder is to get the values w and b closer to 0.8 and 2 respectively ''' # generate random x values X_train = np.random.random((1, 50))[0] # get the reference y value y_reference = 0.8 * X_train + 2 # add noise to the reference y value y_train = y_reference + np.sqrt(0.01) * np.random.random((1, 50))[0] # reshape (model expect a 2D array and X_train is a 1D. So reshape (50,) in to (50, 1)) X_train = X_train.reshape(-1, 1) # build model model = LinearRegression() # train model model.fit(X_train, y_train) # get weights and bias of the learned model w = model.coef_[0] b = model.intercept_ print('\nSklearn Linear Regression completed') print('w Expected : 0.8' + ' Learned : ' + str(w)) print('b Expected : 2.0' + ' Learned : ' + str(b))
import re with open('02-input.txt') as f: lines = f.read() rows = re.findall('(\d+)\-(\d+)\s+(\S):\s(\S+)', lines) def part_1_predicate(row): min_count, max_count, letter, password = row return int(min_count) <= password.count(letter) <= int(max_count) def part_2_predicate(row): lower_index, higher_index, letter, password = row return (password[int(lower_index)-1] == letter) ^ (password[int(higher_index)-1] == letter) print(sum([part_1_predicate(row) for row in rows])) print(sum([part_2_predicate(row) for row in rows]))
import sys def quicksort(target): left = [] right = [] if(len(target)<=1): return target pivot = int(len(target)/2) pivotVal = target[pivot] target.pop(pivot) for x in range(0, len(target)): if(target[x][2]<pivotVal[2]): left.append(target[x]) elif(target[x][2]==pivotVal[2]): if(target[x][3]<pivotVal[3]): right.append(target[x]) else: left.append(target[x]) else: right.append(target[x]) return quicksort(left)+[pivotVal]+quicksort(right) inBuffer = [] n, m = [int(x) for x in sys.stdin.readline().split()] for counter in range(0, n): newLine = sys.stdin.readline().split() freq = long(newLine[0]) name = newLine[1] q = float(freq*float((1+counter))) inBuffer.append([freq, name, q, counter]) inBuffer = quicksort(inBuffer) for x in range(0, m): print(inBuffer[len(inBuffer)-x-1][1])
#!/usr/bin/env python3 """keras module""" import tensorflow.keras as K def one_hot(labels, classes=None): """ function that converts a label vector into a one-hot matrix: The last dimension of the one-hot matrix must be the number of classes Returns: the one-hot matrix """ one_hot = K.utils.to_categorical(labels, classes) return one_hot
#!/usr/bin/env python3 """ Module of create RMSprop in tensorflow """ import tensorflow as tf def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ function that creates the training operation for a neural network in tensorflow using the RMSProp optimization algorithm: loss is the loss of the network alpha is the learning rate beta2 is the RMSProp weight epsilon is a small number to avoid division by zero Returns: the RMSProp optimization operation """ decay_optimizer = tf.train.inverse_time_decay(alpha, global_step, decay_step, decay_rate, staircase=True) return decay_optimizer
#!/usr/bin/env python3 """ Module to create a confusion matrix""" import numpy as np def create_confusion_matrix(labels, logits): """ function that creates a confusion matrix: labels is a one-hot numpy.ndarray of shape (m, classes) containing the correct labels for each data point m is the number of data points classes is the number of classes logits is a one-hot numpy.ndarray of shape (m, classes) containing the predicted labels Returns: a confusion numpy.ndarray of shape (classes, classes) with row indices representing the correct labels and column indices representing the predicted labels """ confusion_matrix = np.zeros((labels.shape[1], labels.shape[1])) for data_point_iterator in range(labels.shape[0]): correct_index = labels[data_point_iterator].argmax() predicted_index = logits[data_point_iterator].argmax() confusion_matrix[correct_index][predicted_index] += 1 return confusion_matrix
#!/usr/bin/env python3 """keras module""" import tensorflow.keras as K def train_model(network, data, labels, batch_size, epochs, validation_data=None, verbose=True, shuffle=False): """ function that trains a model using mini-batch gradient descent: - network is the model to train - data is a numpy.ndarray of shape (m, nx) containing the input data - labels is a one-hot numpy.ndarray of shape (m, classes) containing the labels of data - batch_size is the size of the batch used for mini-batch gradient descent - epochs is the number of passes through data for mini-batch gradient descent - validation_data is the data to validate the model with, if not None - verbose is a boolean that determines if output should be printed during training - shuffle is a boolean that determines whether to shuffle the batches every epoch. Returns: the History object generated after training the model """ history = network.fit(data, labels, batch_size, epochs, verbose, validation_data=validation_data, shuffle=shuffle) return history
#!/usr/bin/env python3 """ Process a matrix multiplication """ def mat_mul(mat1, mat2): """ With 3 for realize a matrix multiplication """ multMatrix = [] shapem1 = matrix_shape(mat1) shapem2 = matrix_shape(mat2) if shapem1[1] != shapem2[0]: return None multIndex = shapem1[1] for mat1Index in range(shapem1[0]): row = [] for mat2Index in range(shapem2[1]): add = 0 for comIndex in range(multIndex): add += mat1[mat1Index][comIndex] * mat2[comIndex][mat2Index] row.append(add) multMatrix.append(row) return multMatrix def matrix_shape(mat1): """Return the shape of the matrix in all of his dimensions""" shape = [] while(1): if isinstance(mat1, list): shape.append(len(mat1)) else: return shape mat1 = mat1[0]
import re text= "Agent Alice gave the secret documents to Agent bob." agentRegex = re.compile("Agent [A-Z][a-z]*") mo=agentRegex.search(text) print(mo,mo.group()) for match in agentRegex.findall(text): print(match) newText=agentRegex.sub('BLACK_HIGHLIGHTER',text) print(newText) #replace whatever in regex with black highliter ###test question #import re text=open("ssn.txt",'r') output=open("ssnRemoved.txt",'w') ssnRegex=re.compile(r"\d\d\d-\d\d-\d\d\d\d") #how to create a regex for line in text: newline= ssnRegex.sub("REDACTED",line) output.write(newline) output.close()
"LA unit test utility functions." import numpy as np from numpy.testing import assert_equal, assert_almost_equal from la import larry def assert_larry_equal(actual, desired, msg='', dtype=True, original=None, iscopy=True): """ Assert equality of two larries or two scalars. If either `actual` or `desired` has a dtype that is inexact, such as float, then almost-equal is asserted; otherwise, equal is asserted. However, if both `actual` and `desired` are scalars then almost-equal is asserted. Parameters ---------- actual : {larry, scalar} If you are testing a larry method, for example, then this is the larry (or scalar) returned by the method. desired : {larry, scalar} This larry represents the expected result. If `actual` is not equal to `desired`, then an AssertionError will be raised. msg : str If `actual` is not equal to `desired`, then the string `msg` will be added to the top of the AssertionError message. dtype : {True, False}, optional The default (True) is to assert that the dtype of `actual` is the same as `desired`. If set to False, the dtype check is skipped. original : {None, larry}, optional If no `reference` or `nocopy` are True, then `original` must be a larry. Continuing the example discussed in `actual`, `original` would be the larry that was passed to the method. iscopy : {True, False}, optional Note: `iscopy` is ignored if `original` is None. If True (default) and if `original` is not None, then check that `actual` and `desired` share no references (i.e., are copies). If False and if `original` is not None, then check that `actual` and `desired` are views of each other (not copies). Returns ------- None Raises ------ AssertionError If the two larrys are not equal. Notes ----- If either `actual` or `desired` has a dtype that is inexact, such as float, then almost-equal is asserted; otherwise, equal is asserted. Examples -------- >>> from la.util.testing import assert_larry_equal >>> x = larry([1]) >>> y = larry([1.1], [['a']]) >>> assert_larry_equal(x, y, msg='x, y test') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "la/util/testing.py", line 189, in assert_larry_equal raise AssertionError, err_msg AssertionError: --------------- TEST: x, y test --------------- ----- LABEL ----- Items are not equal: item=0 item=0 ACTUAL: 0 DESIRED: 'a' ------------ X DATA ARRAY ------------ Arrays are not almost equal (mismatch 100.0%) x: array([1]) y: array([ 1.1]) ----- DTYPE ----- Items are not equal: ACTUAL: dtype('int64') DESIRED: dtype('float64') """ # Initialize fail = [] # Check input if dtype not in (True, False): raise TypeError('dtype must be True or False.') if iscopy not in (True, False): raise TypeError('iscopy must be True or False.') if type(msg) is not str: raise TypeError('msg must be a string.') # Function to make section headings def heading(text): line = '-' * len(text) return '\n\n' + line + '\n' + text + '\n' + line + '\n' # The assert depends on the type of actual and desired if np.isscalar(actual) and np.isscalar(desired): # Both actual and desired are scalars try: try: assert_equal(actual, desired) except: # The following line gives a warning in py3/nose # when the inputs are np.bool_. That's why we try # assert_equal first (above) assert_almost_equal(actual, desired) except AssertionError as err: fail.append(heading('SCALARS') + str(err)) if dtype: try: assert_equal(type(actual), type(desired)) except AssertionError as err: fail.append(heading('TYPE') + str(err)) elif (type(actual) == larry) + (type(desired) == larry) == 1: # Only one of actual and desired are larrys; test failed try: assert_equal(type(actual), type(desired)) except AssertionError as err: fail.append(heading('TYPE') + str(err)) else: # Both actual and desired are larrys # label try: assert_equal(actual.label, desired.label) except AssertionError as err: fail.append(heading('LABEL') + str(err)) # Data array, x try: # Does one larrys have inexact dtype? if (issubclass(actual.x.dtype.type, np.inexact) or issubclass(desired.x.dtype.type, np.inexact)): # Yes, so check for almost equal try: assert_almost_equal(actual.x, desired.x, decimal=13) except TypeError: # One of the larrys probably has a weird type like str assert_equal(actual.x, desired.x) else: # No, so check for exactly equal assert_equal(actual.x, desired.x) except AssertionError as err: fail.append(heading('X DATA ARRAY') + str(err)) # dtype if dtype: try: assert_equal(actual.dtype, desired.dtype) except AssertionError as err: fail.append(heading('DTYPE') + str(err)) # If original is not None, assert copies or views if not original is None: if iscopy: # Check that the larrys are copies try: assert_iscopy(actual, original) except AssertionError as err: fail.append(heading('NOT A COPY') + str(err)) else: # Check that the larrys are views try: assert_isview(actual, original) except AssertionError as err: text = heading('IS A COPY') + str(err) fail.append(text) # Did the test pass? if len(fail) > 0: # No err_msg = ''.join(fail) err_msg = err_msg.replace('\n', '\n\t') if len(msg): err_msg = heading("TEST: " + msg) + err_msg raise AssertionError(err_msg) def assert_iscopy(larry1, larry2): "Return True if there are no shared references" if not isinstance(larry1, larry): raise TypeError('Input must be a larry') if not isinstance(larry2, larry): raise TypeError('Input must be a larry') msg = [] if np.may_share_memory(larry1.x, larry2.x): msg.append('The data arrays share a reference.') for i in range(min(larry1.ndim, larry2.ndim)): if larry1.label[i] is larry2.label[i]: msg.append('The labels along axis %d share a reference.' % i) if len(msg) > 0: msg.insert(0, '\n') msg = '\n'.join(msg) raise AssertionError(msg) def assert_isview(larry1, larry2): "Return True if there are only references" if not isinstance(larry1, larry): raise TypeError('Input must be a larry') if not isinstance(larry2, larry): raise TypeError('Input must be a larry') msg = [] if not np.may_share_memory(larry1.x, larry2.x): msg.append('The data arrays do not share a reference.') for i in range(min(larry1.ndim, larry2.ndim)): if larry1.label[i] is not larry2.label[i]: text = 'The labels along axis %d does not share a reference.' msg.append(text % i) if len(msg) > 0: msg.insert(0, '\n') msg = '\n'.join(msg) raise AssertionError(msg) # Old-style testing functions ----------------------------------------------- def printfail(theory, practice, header=None): x = [] if header is not None: x.append('\n\n%s\n' % header) x.append('\ntheory\n') x.append(str(theory)) x.append('\n') x.append('practice\n') x.append(str(practice)) x.append('\n') return ''.join(x) def noreference(larry1, larry2): "Return True if there are no shared references" if not isinstance(larry1, larry): raise TypeError('Input must be a larry') if not isinstance(larry2, larry): raise TypeError('Input must be a larry') if larry1.ndim != larry2.ndim: raise ValueError('larrys must have the same dimensions') out = True out = out & (larry1.x is not larry2.x) for i in range(larry1.ndim): out = out & (larry1.label[i] is not larry2.label[i]) return out def nocopy(larry1, larry2): "Return True if there are only references" if not isinstance(larry1, larry): raise TypeError('Input must be a larry') if not isinstance(larry2, larry): raise TypeError('Input must be a larry') if larry1.ndim != larry2.ndim: raise ValueError('larrys must have the same dimensions') out = True out = out & (larry1.x is larry2.x) for i in range(larry1.ndim): out = out & (larry1.label[i] is larry2.label[i]) return out
base = int(input("Введіть основу трикутника:\t")) height = int(input("Введіть висоту трикутника:\t")) sq_triangle = 1/2 * base * height print('Площа трикутника = ', sq_triangle, "см2")
import math add_1 = input('Enter number 1\t') add_2 = input('Enter number 2\t') num1 = int(add_1) num2 = int(add_2) print('+ = ', num1 + num2) print('- = ', num1 - num2) print('/ = ', num1 / num2) print('// = ', num1 // num2) print('% = ', num1 % num2) print('ABS = ', abs(num1)) print('sqrt (num1) ', math.sqrt(num1)) print('sqrt (num2) ', math.sqrt(num2))
answer = '' while(answer != "yes"): answer = input ("Are we in Canada?\t") print("We are there. At last ;-)")
import random choice_taken= ["rock", "paper", "scissor"] # your name playerchoice=input("your name") # no. of rounds n=int(input("No of rounds you want to play")) #game playing loop while True: print("THE GAME BEGINS") playerscore = 0 computerscore = 0 for i in range (1,n+1): print("The round", i, "begins") print("choose") print("1.rock","2.paper","3.scissor") player_choice = int(input("playerchoice in integer choice:")) if player_choice == 1: print("rock") player_choice = "rock" elif player_choice == 2: print("paper") player_choice = "paper" elif player_choice == 3: print("scissor") player_choice = "scissor" else: print("none of the choice chosen") break #computer random choice computer_choice = random.choice(choice_taken) print("computer taken :", computer_choice) #tie condition if player_choice == computer_choice: print("its a tie", "both go home and do practice") #winning condition elif (player_choice == "paper" and computer_choice == "rock" ) or (player_choice == "rock" and computer_choice == "scissor" ) or (player_choice == "scissor" and computer_choice == "paper" ): print(playerchoice,"won the round") playerscore = playerscore + 1 else: print("computer won the round") computerscore = computerscore + 1 if playerscore > computerscore: print(playerchoice, "won the game", "playerscore" ,playerscore , "computerscore", computerscore ) elif computerscore > playerscore: print("computer won the whole game", "playerscore",playerscore, "computerscore", computerscore) #restarting or ending the game player = input("want to play again for the revenge?") if player == "yes": continue else: print("THE GAME ENDS HERE") break
#Answer to String Validators if __name__ == '__main__': s = input() a = b = c = d = e = False for i in s: if(i.isalnum()): a=True if(i.isalpha()): b=True if(i.isdigit()): c=True if(i.islower()): d=True if(i.isupper()): e=True print(a,b,c,d,e,sep="\n") """ str.isalnum() This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). >>> print 'ab123'.isalnum() True >>> print 'ab123#'.isalnum() False str.isalpha() This method checks if all the characters of a string are alphabetical (a-z and A-Z). >>> print 'abcD'.isalpha() True >>> print 'abcd1'.isalpha() False str.isdigit() This method checks if all the characters of a string are digits (0-9). >>> print '1234'.isdigit() True >>> print '123edsd'.isdigit() False str.islower() This method checks if all the characters of a string are lowercase characters (a-z). >>> print 'abcd123#'.islower() True >>> print 'Abcd123#'.islower() False str.isupper() This method checks if all the characters of a string are uppercase characters (A-Z). >>> print 'ABCD123#'.isupper() True >>> print 'Abcd123#'.isupper() False """
#Answer to String Split and Join def split_and_join(line): line=line.split(" ") line="-".join(line) return line """ >>> a = "this is a string" >>> a = a.split(" ") # a is converted to a list of strings. >>> print a ['this', 'is', 'a', 'string'] Joining a string is simple: >>> a = "-".join(a) >>> print a this-is-a-string """
#Answer to Alphabet Rangoli def print_rangoli(size): alpha=['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'] i=size k=0 while i>0: print("-"*((2*size)-2-(k*2)),end="") j=size-1 while j>=i: print(alpha[j],end="-") j-=1 while j<size: print(alpha[j],end="") j+=1 if(j!=size): print("-",end="") print("-"*((2*size)-2-(k*2)),end="\n") i-=1 k+=1 k-=1 i=size-1 p=1 while i>0: print("-"*((2*size)-(k*2)),end="") j=size-1 while j>=p: print(alpha[j],end="-") j-=1 j+=2 while j<=size-1: print(alpha[j],end="-") j+=1 print("-"*((2*size)-1-(k*2)),end="\n") i-=1 k-=1 p+=1
#Answer to Find a string def count_substring(string, sub_string): l=0 i=0 while i < len(string): if(string[i]==sub_string[0]): k=0 for j in range(0,len(sub_string)): if(i+j<len(string) and string[i+j]!=sub_string[j]): k=1 elif(i+j>=len(string)): k=1 if(k==0 and j==len(sub_string)-1): l+=1 i+=1 return l
#Answer to Compress the String! from itertools import groupby for k,g in groupby(input()): print((len(list(g)),int(k)),end=" ")
#Answer to Day 18: Queues and Stacks from collections import deque class Solution: def __init__(self): self.stack = deque() self.queue = deque() def pushCharacter(self,val): self.stack.append(val) def enqueueCharacter(self,val): self.queue.append(val) def popCharacter(self): return self.stack.pop() def dequeueCharacter(self): return self.queue.popleft()
#Answer to Day 13: Abstract Classes class MyBook(Book): def __init__(self,title, author, price): Book.__init__(self,title,author) self.price=price def display(self): print("Title: "+self.title+"\nAuthor: "+self.author+"\nPrice: "+str(self.price))
#Answer to Exceptions for i in range(int(input())): try: a,b=map(int,input().split()) print(a//b) except ZeroDivisionError: print("Error Code: integer division or modulo by zero") except ValueError as e: print("Error Code:",e) """ ZeroDivisionError This error is raised when the second argument of a division or modulo operation is zero. >>> a = '1' >>> b = '0' >>> print int(a) / int(b) >>> ZeroDivisionError: integer division or modulo by zero ValueError This error is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value. >>> a = '1' >>> b = '#' >>> print int(a) / int(b) >>> ValueError: invalid literal for int() with base 10: '#' #Code try: print 1/0 except ZeroDivisionError as e: print "Error Code:",e """
#Answer to Dot and Cross import numpy n=int(input()) a,b=[],[] for i in range(n): a.append(list(map(int,input().split()))) for i in range(n): b.append(list(map(int,input().split()))) print(numpy.dot(numpy.array(a),numpy.array(b))) """ dot The dot tool returns the dot product of two arrays. import numpy A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) print numpy.dot(A, B) #Output : 11 cross The cross tool returns the cross product of two arrays. import numpy A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) print numpy.cross(A, B) #Output : -2 """
def collinear(x1, y1, x2, y2, x3, y3): a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2) if (a == 0): print("yes") else: print("no") x1,y1=[int (x) for x in input().split()] x2,y2=[int (x) for x in input().split()] x3,y3=[int (x) for x in input().split()] collinear(x1, y1, x2, y2, x3, y3)
import random account_number=random.randint(1000,2000) l=[] print("WELCOME TO OUR BANK") select=input("Create New Account(CA)/Login Account(LA)/Customer service(CS) :") if(select=="CA"): a=account_number print("Your Account number is :",a) name=input("Enter Your Name :") password=input("Enter Password :") address=input("Enter Address :") l.append(a) l.append(name) l.append(password) l.append(address) elif(select=="LA"): b=input("enter account number :") print("Welcome",name) user_name=input("enter user name :") password=input("enter password :") balance=5000 choice=int(input("1.Deposit/2.Withdraw/3.Balance/4.profile/5.Log Out")) if(choice=="1"): l=int(input("enter the amount to debit :")) balance=balance+l print(l+"is debited and the available balance is",balance) elif(choice=="2"): m=int(input("enter the amount to Withdraw :")) balance=balance-m print(l+"is debited and the available balance is",balance) elif(choice=="3"): balance=balance print("available balance is :",balance) elif(choice=="4"): print("user profile") print(name,address) else: exit()
# Removes misc characters from string def replace(string): string = string.replace("&", "") string = string.replace("-", " ") string = string.replace("(", "") string = string.replace(")", "") string = string.replace("/", " ") string = string.replace(",", "") string = string.replace(".", "") string = string.replace(" ", "_") string = string.replace("'", "") return string
# https://www.acmicpc.net/problem/2751 # 분할 정복법 : divide + conquer, combine # top-down sol과 동일 def combine(num_list, start_idx, mid_idx, end_idx): l_idx = start_idx # start_idx ... mid_idx (포함) r_idx = mid_idx+1 # mid_idx+1 ... end_idx sorted_list = [] while l_idx <= mid_idx and r_idx <= end_idx: if num_list[l_idx] < num_list[r_idx]: min_val = num_list[l_idx] l_idx += 1 else: min_val = num_list[r_idx] r_idx += 1 sorted_list.append(min_val) if l_idx <= mid_idx: # start_idx ... mide_idx 부분에 정렬된 원소들이 남아 있음 sorted_list += num_list[l_idx:mid_idx+1] else: sorted_list += num_list[r_idx:end_idx+1] num_list[start_idx:end_idx+1] = sorted_list def merge_sort(num_list, start_idx, end_idx): if start_idx < end_idx: mid_idx = (start_idx + end_idx) // 2 merge_sort(num_list, start_idx, mid_idx) merge_sort(num_list, mid_idx+1, end_idx) combine(num_list, start_idx, mid_idx, end_idx) # return None이 생략 된 것 n = int(input()) num_list = [] for _ in range(n): num_list.append(int(input())) merge_sort(num_list, 0, len(num_list)-1) print(num_list)
from collections import deque def logn_calc(n): max_pow = 1 while max_pow < n: max_pow *= 2 return n * 2 - max_pow # 2*(n-max_power) def deque_calc(n): d_list = deque([i for i in range(1, n+1)]) # for _ in range(n-1): while len(d_list) > 1: # O(N) d_list.popleft() d_list.rotate(-1) return d_list.popleft() n = int(input()) print(logn_calc(n)) # print(deque_calc(n))
# https://www.acmicpc.net/problem/1920 # pass # 슬라이싱으로 접근하면 O(N)이 돼서 linear search와 같아짐 # → 배열을 그대로 두고 인덱스로 보는 위치만 변경하기 def search_idx(target_num, num_list, start_idx, end_idx): mid_idx = int((end_idx + start_idx)/2) # --(start_idx + end_idx) // 2와 동일 if start_idx > end_idx: return -1 if num_list[mid_idx] == target_num: return mid_idx elif num_list[mid_idx] < target_num: return search_idx(target_num, num_list, mid_idx+1, end_idx) elif num_list[mid_idx] > target_num: return search_idx(target_num, num_list, start_idx, mid_idx-1) n = int(input()) fixed_list = list(map(int, input().split())) fixed_list.sort() m = int(input()) compare_list = list(map(int, input().split())) for num in compare_list: if search_idx(num, fixed_list, 0, len(fixed_list)-1) >= 0: print("1") else: print("0")
from abc import ABCMeta, abstractmethod class Sensor: __metaclass__ = ABCMeta def __init__(self,name=None,normalize=None): self.name = name self.normalize = 1 if not normalize == None: self.normalize = normalize @abstractmethod def getState(self,entity): pass def normalization(self,value): return value / self.normalize class Basic(Sensor): def getState(self,entity): return min(self.normalization(float(entity.state)),1) class Binary(Sensor): def __init__(self, name=None,nullValue=None, *args, **kwargs): self.nullValue = 'off' if not self.nullValue == None: self.nullValue = nullValue super(Binary, self).__init__(*args, **kwargs) def getState(self,entity): if entity.state == self.nullValue : return 0 return 1 class Sun(Sensor): def getState(self,entity): return (float(entity.attributes['elevation']) + 90) / 180
#Fibonacci Heap implementation #Author: Kevin Holligan #Based on the pseudocode from the CLRS text, ch 20. class FibHeap: # internal node class class node: def __init__(self, key): self.key = key self.parent = None self.child = None self.left = None self.right = None self.degree = 0 self.mark = False # Global access point to start of list and mininum node rootList, minNode = None, None totalNodes = 0 def returnMin(self): return self.min_node def insert(self, key): node = self.node(key) node.left = node node.right = node #If rootList is empty, set it to the node if self.rootList is None: self.rootList = node #Otherwise, insert the node on to left of the root of rootList else: #Node points to root list and rootList's left node.left = self.rootList.left node.right = self.rootList #Old left node points to new node on its right self.rootList.left.right = node #RootList left points to node self.rootList.left = node #Update minNode pointer if necessary if self.minNode is None or node.key < self.minNode.key: self.minNode = node self.totalNodes += 1 def merge(self, H2): H = FibHeap() H.minNode = self.minNode H.rootList = self.rootList #rootList points to tail of H2. tail of rootList points to head of H2 h2tail = H2.rootList.right h1tail = self.rootList.right self.rootList.right = h2tail h2tail.left = self.rootList h1tail.left = H2.rootList H2.rootList.right = h1Tail #update minNode if necessary if H.minNode is None or (H2.minNode is not None and H2.minNode.key < H.minNode.key): H.minNode = H2.minNode H.totalNodes = self.totalNodes + H2.totalNodes del self del H2 return H def deleteMin(self): z = self.minNode if z is not None: if z.child is not None: childNodes = [x for x in self.iterate(z.child)] for i in range(len(childNodes)): #If rootList is empty, set it to the node if self.rootList is None: self.rootList = childNodes[i] #Otherwise, insert the node on to left of the root of rootList else: #Node points to root list and rootList's left childNodes[i].left = self.rootList.left childNodes[i].right = self.rootList #Old left node points to new node on its right self.rootList.left.right = childNodes[i] #RootList left points to node self.rootList.left = childNodes[i] childNodes[i].parent = None #Remove z from the root list of the heap #If z is first item in rootList, update rootList to next item if z is self.rootList: self.rootList = z.right #Update z's neighbors to point to each other z.left.right = z.right z.right.left = z.left #Set new min node in heap if z is z.right: self.minNode = self.rootList = None else: self.minNode = z.right self.consolidate() self.totalNodes -= 1 return z def consolidate(self): #Create empty array based on number of nodes A = [None] * self.totalNodes #For each node w in the root list of H nodes = [w for w in self.iterate(self.rootList)] for w in range(len(nodes)): x = nodes[w] d = x.degree while A[d] is not None: y = A[d] #Swap which node is going to be the new parent when linking if x.key > y.key: temp = x x = y y = temp #Link the nodes together self.heapLink(y, x) #Set array element to none and increase degree A[d] = None d += 1 A[d] = x #Update the minNode if there is a lower key in A for i in range(len(A)): if A[i] is not None: if A[i].key < self.minNode.key: self.minNode = A[i] def heapLink(self, y, x): #Remove y from the root list of the heap #If y is first item in rootList, update rootList to next item if y is self.rootList: self.rootList = y.right #Update y's neighbors to point to each other y.left.right = y.right y.right.left = y.left #Point y to itself (reset it in a sense) y.left = y y.right = y #Because y is new child of x, when need it include it on child linked list #If root has no children if x.child is None: x.child = y #Insert the node between two nodes and update pointers else: y.left = x.child.left y.right = x.child x.child.left.right = y x.child.left = y #Update node properties x.degree += 1 y.parent = x y.mark = False def decreaseKey(self, x, k): if k > x.key: return None x.key = k y = x.parent if y is not None and x.key < y.key: self.cut(x, y) self.recursiveCut(y) #update the new minimum if x.key < self.minNode.key: self.minNode = x #Remove a child node and put it on root list def cut(self, x, y): # self.remove_from_child_list(y, x) #Remove x from child list of y if y.child is y.child.left: y.child = None #Make new entry into child list elif y.child is x: y.child = x.right x.right.y = y #Update child list pointers x.left.right = x.right x.right.left = x.left y.degree -= 1 #Put node x in the rootList if self.rootList is None: self.rootList = x #Insert the node on the left of the root of rootList else: #Node points to root list and rootList's left x.left = self.rootList.left x.right = self.rootList #Old left node points to new node on its right self.rootList.left.right = x #RootList left points to node self.rootList.left = x #Update properties x.parent = None x.mark = False #Cut parents if two child nodes have been cut def recursiveCut(self, y): z = y.parent if z is not None: if y.mark is False: y.mark = True else: self.cut(y, z) self.recursiveCut(z) #Helper function to iterate over list def iterate(self, head): node = end = head while True: #only child if node.right is None and node.left is None: yield node break #If we've looped back to the beginning elif node.right is end: yield node break else: node = node.right
#!/usr/bin/env python3 # coding: utf-8 # 斐波拉契数列 def fib(max): n, a, b = 0, 0, 1 while n < max: # print(a, b) print(b) a, b = b, a + b n = n+1 return 'done' # TEST fib(5)
class Queue(object): def __init__(self): self.q = [] def isEmpty(self): return len(self.q)==0 def size(self): return len(self.q) def front(self): return self.q[0] def pop(self): if len(self.q)==0: raise Exception("The Queue is empty!") return None else: del self.q[0] def push(self,elem): self.q.insert(0,elem) if __name__ == '__main__': q = Queue() for i in range(5): q.push(i) while not q.isEmpty(): q.pop() print('Dequing... Current Size: ',q.size())
from tkinter import * mainWindow = Tk() #function to print with an event argument def printName(event): print("Hello Roger!") # create the button button_1 = Button(mainWindow, text="Print my name") # binding left button to printName function button_1.bind("<Button-1>", printName) # display the button button_1.pack() mainWindow.mainloop()
from tkinter import * import tkinter.messagebox mainWindow=Tk() tkinter.messagebox.showinfo("Window Title", "Monkeys can live up to 150years") answer = tkinter.messagebox.askquestion("Question 1", "Do you like to eat?") if answer== "yes": print("hotdogs it is then!") mainWindow.mainloop()