blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
acb0cc7f05d64d6852a64f839c0c14e198cb2971
Git-Math/linear_regression
/file.py
1,176
3.5
4
import sys def read_theta(): try: with open("data/theta.csv", "r") as theta_file: theta_file.readline() theta_list = theta_file.readline().split(",") theta0 = float(theta_list[0]) theta1 = float(theta_list[1]) theta_file.close() except: theta0 = 0.0 theta1 = 0.0 return theta0, theta1 def write_theta(theta0, theta1): try: with open("data/theta.csv", "w") as theta_file: theta_file.write("theta0,theta1\n") theta_file.write(str(theta0) + "," + str(theta1) + "\n") theta_file.close() except: print("open theta file failed") exit(1) def read_data(): data = [] try: with open("data/data.csv", "r") as data_file: data_file.readline() data_line = data_file.readline() while data_line: data_list = data_line.split(",") data.append((float(data_list[0]), float(data_list[1]))) data_line = data_file.readline() data_file.close() except: print("data.csv invalid") exit(1) return data
a862750fa386a55b2995a86974fbea13283e09c5
AishaGhayas/Artificial-Intelligence
/bookexercises/updatename.py
156
3.53125
4
with open("name.txt", "w") as f: f.write("hello") with open("name.txt", "a") as f: f.write("Aisha") with open("name.txt") as f: print(f.read())
4e1ba46177292b8da6dcd2d5d3b30458fafc2ce4
imyoungmin/cs8-s20
/W3/p4.py
251
3.859375
4
""" Problem 4: Your Initials Here, Please... """ # Reading in first and surename. name = input( "Input name: " ) # Splitting and retrieving initials. splitAt = name.find( " " ) print( "Hello {}!".format( name[0].upper() + name[splitAt+1].upper() ) )
a320b940332a8e47aad2e19e0082ab2705e933ff
imyoungmin/cs8-s20
/W5/p1.py
461
4.09375
4
""" Problem 1: Squares. """ # Reading in a number and making sure it is at least 1. n = max( 1, int( input( "Provide square length: " ) ) ) # Printing the hollow square. for i in range( n ): for j in range( n ): if j == 0 or j == n - 1: # First and last columns are always printed. print( "*", end="" ) elif i == 0 or i == n - 1: # First and last rows are full of *'s. print( "*", end="" ) else: print( " ", end="" ) # Hollow part. print()
59b53e13a6f8bb9d2d606de898fc92738e5bd10b
imyoungmin/cs8-s20
/W3/p6.py
692
4.125
4
''' Write a program which takes 5 strings as inputs and appends them to a list l. Swap each element in l with its mirror - that is, for some element at index i, swap l[i] with l[4-i] if i < 3. For instance, if l = ['Alex', 'Bob', 'Charlie', 'David', 'Ethan'], then after swapping, l should read ['Ethan', 'David', 'Charlie', 'Bob', 'Alex'] Finally, finish the program by creating a dictionary mapping each name to its length. ''' # Solution here l = [] while len(l) < 5: l.append(input("Enter a name: ")) temp = l[0] temp1 = l[1] l[0] = l[4] l[1] = l[3] l[3] = temp1 l[4] = temp print(l) name_to_length = {} for name in l: name_to_length[name] = len(name) print(name_to_length)
98aabd046d1199b77b3ffc9e0bad9cf9a3a6bb27
imyoungmin/cs8-s20
/W3/p1.py
307
3.96875
4
''' Given a string *s* of length 5, write a function to determine if *s* is palindromic. ''' def isPalindromic(s): for i in range (0, 2): if s[i] != s[4-i]: return False return True def main(): s = input() print(isPalindromic(s)) if __name__ == '__main__': main()
952628cbcb0b3bcffc567eebd19a4b4b2477fa1f
Grace-TA/project-euler
/solutions/problem_004.py
611
4.125
4
from utils import is_palindromic def problem_004(n_digits: int = 3): """ In a loop from sqrt(n) to 1 check if i is factor of n and i is a prime number. - O(n^2) time-complexity - O(1) space-complexity """ result = 0 for i in range(10**n_digits - 1, 10**(n_digits - 1) - 1, -1): for j in range(10**n_digits - 1, 10**(n_digits - 1) - 1, -1): n = i * j if n < result: continue if is_palindromic(n): result = n return result if __name__ == '__main__': print(f'Problem 4 solution: {problem_004()}')
b152adfe7e1ff55ac64ebf85d89ca23ffcd501b7
Grace-TA/project-euler
/solutions/problem_009.py
443
3.6875
4
def problem_009(n: int = 1000) -> int: """ Use loop over a with nested loop over b (express c = n - a - b). - O(n^2) time-complexity - O(1) space-complexity """ for a in range(1, n // 2 + 1): for b in range(1, n // 2 + 1): c = n - a - b if a**2 + b**2 == c**2: return a * b * c return 0 if __name__ == '__main__': print(f'Problem 9 solution: {problem_009()}')
8c1e1d27ec113d5b1c0161aaaf6dde6300bf6f44
wuxum/learn-python
/25-time.py
254
3.875
4
#!/usr/bin/python # website: https://pythonbasics.org/time-and-date/ import time timenow = time.localtime(time.time()) year,month,day,hour,minute = timenow[0:5] print(str(day) + "/" + str(month) + "/" + str(year)) print(str(hour) + ":" + str(minute))
9a0267943b24849377b0a9f5b00bec1e8d8a050c
wuxum/learn-python
/29-getter-setter.py
352
3.765625
4
#!/usr/bin/python # website: https://pythonbasics.org/getter-and-setter/ class Friend: def __init__(self): self.job = "None" def getJob(self): return self.job def setJob(self, job): self.job = job Alice = Friend() Bob = Friend() Alice.setJob("Carpenter") Bob.setJob("Builder") print(Bob.job) print(Alice.job)
45e42d4282a7485fb3265c29970a32e4cc41aea8
EduardoMJ99/EstructuraDDatos
/U1_IntroEstructurasDatos/Practica1-U1-NumerosNaturales.py
531
3.671875
4
resultado = 1 #Declaro e inicializo variable. def Operacion(resultado): #Metodo que recibe el valor 'resultado' y primero compara if resultado <= 100: #si el valor es menor a 100, si si, lo imprime, si no, print (resultado) #llama a este metodo con el valor aumentado a uno y asi return (Operacion(resultado+1)) #recursivamente hasta que imprime el numero. Operacion(resultado) #Llamo al metodo y le envio un parametro.
eaee1fc7860608ca24c9d6457516d2710bb7b7f8
EduardoMJ99/EstructuraDDatos
/U2_Recursividad/Practica9-U2-pop()cola.py
5,925
3.671875
4
cola = [] #Declaro mis variables import sys #Importo esta libreria para poder salir del programa. def Crear(): #Metodo que inicializa la cola a ceros. cola = [0,0,0,0,0] #Regreso la cola inicializada. return cola def push(valor,indice): #Metodo que ingresa valores a la cola. cola[indice] = valor #Se ingresa el valor en el indice. return indice+1 #Regreso el indice aumentado en uno. def Menu(): #Metodo que muestra la interfaz del programa al usuario. global cola #LLamo a mi variable global cola. print ("1- Crear la cola.\n" #Interfaz... "2- Insertar valores a la cola.\n" "3- Eliminar valores de cola.\n" "4 - Salir.") eleccion = int(input("Que desea realizar?: ")) print() if eleccion == 1: #Si el usuario elige esta opcion llama al metodo Crear() y regresa la cola cola = Crear() #inicializada en ceros. print("Cola creada...\n") Menu() #LLamo a Menu() para seguir con recursividad. else: if eleccion == 2: #Si el usuario elige esta opcion... if len(cola) > 0: #Averiguo si la cola tiene valores para saber si ha sido creada. lugaresdisponibles = [cont for cont,x in enumerate(cola) if x == 0] #Ingreso a una variable todos los ceros que tenga la cola ya que indicecola = len(lugaresdisponibles) #estos me indican cuantos lugares disponibles hay en la cola. indiceciclo = 0 #Cuento los ceros y asi determinar cuantos valores puedo ingresar. try: #Para saber donde iniciar a ingresar valores a la cola busco el primer cero, dondeiniciar = cola.index(0) #de esta manera me regresa el indice del primer cero y de ahi inicio. except: #Si no hay ningun valor con 0 significa que esta llena, para corregir este error pass #utiliza un catch - except. while (indiceciclo) < len(lugaresdisponibles): #Mientras que el indice sea menor a los lugares disponibles... valor = int(input("Ingrese valores enteros (Espacios disponibles: "+str(indicecola)+") : ")) #Le pido un valor entero y le muestro dondeiniciar = push(valor,dondeiniciar) #cuantos lugares disponibles hay. indicecola = indicecola -1 #Llamo al metodo push() e ingreso el valor que ingreso al usuario indiceciclo = indiceciclo +1 #en la posicion donde se debe iniciar segun los lugares disponibles. #Me regresa el indice aumentado y resto los lugares disponibles. print("La cola esta llena.\n") Menu() #LLamo a Menu() para seguir con recursividad. else: print("La cola no ha sido creada, favor de crearla...\n") #Si la cola no tiene indices es porque no ha sido creada. Menu() #LLamo a Menu() para seguir con recursividad. else: if eleccion == 3: #Si el usuario eligio esta opcion quiere eliminar un valor de la cola... if len(cola) > 0: #Si la cola tiene valores... if cola[0] == 0: print ("La cola esta vacia.\n") #Si la primera posicion tiene 0 es porque la pila esta vacia. else: for indicecola in range(0,4,1): #Cada vez que se quiere eliminar un elemento hay que recorrer los valores de la pila. cola[indicecola] = cola[indicecola+1] cola[4] = 0 #A la ultima posicion de la cola le asigno un 0. print ("Elemento eliminado.\n") Menu() else: print("La cola no ha sido creada, favor de crearla...\n") #Si la cola no tiene indices es porque no ha sido creada. Menu() else: if eleccion == 4: #Si el usuario eligio esta opcion salgo del programa llamando a este metodo reservado. sys.exit() else: print ("Opcion incorrecta...\n") #SI no es ninguna de las opciones le muestro opcion incorrecta. Menu() #LLamo a Menu() para seguir con recursividad. Menu() #LLamo a Menu() para empezar la recursividad.
eb21c95cf20a2f7960bfbe2fdbec14c508b02433
EduardoMJ99/EstructuraDDatos
/U2_Recursividad/Practica10-U2-peek()cola.py
8,729
3.8125
4
cola = [] #Declaro mis variables import sys #Importo esta libreria para poder salir del programa. def Crear(): #Metodo que inicializa la cola a ceros. cola = [0,0,0,0,0] #Regreso la cola inicializada. return cola def push(valor,indice): #Metodo que ingresa valores a la cola. cola[indice] = valor #Se ingresa el valor en el indice. return indice+1 #Regreso el indice aumentado en uno. def pop(): if cola[0] == 0: print ("La cola esta vacia.\n") #Si la primera posicion tiene 0 es porque la cola esta vacia. else: for indicecola in range(0,4,1): #Cada vez que se quiere eliminar un elemento hay que recorrer los valores de la pila. cola[indicecola] = cola[indicecola+1] cola[4] = 0 #A la ultima posicion de la cola le asigno un 0. print ("Elemento eliminado.\n") def peek(eleccion): if eleccion == "T": #Si 'eleccion' es igual a 'T' muestra todos los valores de la cola. print (cola) print ("\n") else: if eleccion == "U": #SI 'eleccion' es igual a 'U' muestro el ultimo valor de la pila. print ("El ultimo valor de la cola es "+str(cola[len(cola)-1])) #Obtengo su longitud e imprimo la ultima posicion. print ("\n") else: #Si no es porque decidio mostrar el indice del valor ingresado. if eleccion == "P": print ("El primer valor de la cola es "+str(cola[0])) print ("\n") else: eleccion = int(eleccion) #Convierto el valor a entero para poder manejarlo. indices = [cont for cont,x in enumerate(cola) if x == eleccion] #Mediante un ciclo ingreso a un arreglo los indices en donde #se encuentra el valor, para eso uso "enumerate" que lo que #hace es evaluar cada posicion de la pila en busca de 'x'. if len(indices) == 0: print ("Valor no encontrado en la pila.\n") #Si el arreglo no aumenta es porque no encontro el valor en la pila. else: indices = str(indices) #Si si, convierto el arreglo y el valor a cadena para poder imprimirlos. eleccion = str(eleccion) print("\nEl valor "+eleccion+" se encuentra en la/s posiciones "+indices+" de la pila.") print() def Menu(): #Metodo que muestra la interfaz del programa al usuario. global cola #LLamo a mi variable global cola. print ("1 - Crear la cola.\n" #Interfaz... "2 - Insertar valores a la cola.\n" "3 - Eliminar valores de cola.\n" "4 - Mostrar valores de la cola.\n" "5 - Salir.") eleccion = int(input("Que desea realizar?: ")) print() if eleccion == 1: #Si el usuario elige esta opcion llama al metodo Crear() y regresa la cola cola = Crear() #inicializada en ceros. print("Cola creada...\n") Menu() #LLamo a Menu() para seguir con recursividad. else: if eleccion == 2: #Si el usuario elige esta opcion... if len(cola) > 0: #Averiguo si la cola tiene valores para saber si ha sido creada. lugaresdisponibles = [cont for cont,x in enumerate(cola) if x == 0] #Ingreso a una variable todos los ceros que tenga la cola ya que indicecola = len(lugaresdisponibles) #estos me indican cuantos lugares disponibles hay en la cola. indiceciclo = 0 #Cuento los ceros y asi determinar cuantos valores puedo ingresar. try: #Para saber donde iniciar a ingresar valores a la cola busco el primer cero, dondeiniciar = cola.index(0) #de esta manera me regresa el indice del primer cero y de ahi inicio. except: #Si no hay ningun valor con 0 significa que esta llena, para corregir este error pass #utiliza un catch - except. while (indiceciclo) < len(lugaresdisponibles): #Mientras que el indice sea menor a los lugares disponibles... valor = int(input("Ingrese valores enteros (Espacios disponibles: "+str(indicecola)+") : ")) #Le pido un valor entero y le muestro dondeiniciar = push(valor,dondeiniciar) #cuantos lugares disponibles hay. indicecola = indicecola -1 #Llamo al metodo push() e ingreso el valor que ingreso al usuario indiceciclo = indiceciclo +1 #en la posicion donde se debe iniciar segun los lugares disponibles. #Me regresa el indice aumentado y resto los lugares disponibles. print("La cola esta llena.\n") Menu() #LLamo a Menu() para seguir con recursividad. else: print("La cola no ha sido creada, favor de crearla...\n") #Si la cola no tiene indices es porque no ha sido creada. Menu() #LLamo a Menu() para seguir con recursividad. else: if eleccion == 3: #Si el usuario eligio esta opcion quiere eliminar un valor de la cola... if len(cola) > 0: #Si la cola tiene valores... pop() else: print("La cola no ha sido creada, favor de crearla...\n") #Si la cola no tiene indices es porque no ha sido creada. Menu() else: if eleccion == 4: #Si el usuario eligio esta opcion salgo del programa llamando a este metodo reservado. if len(cola) >0: #Se compara si la pila tiene valores, si si se le pregunta el indice del valor que desea ver, o eleccion = str(input("Teclee 'T' para mostrar TODOS los valores de la cola,\nteclee 'U' para mostrar el ULTIMO valor de la cola,\nteclee 'P'" "para mostrar el PRIMER valor de la cola,\no ingrese el valor que desea buscar en la cola: ")) print() peek(eleccion) #Si desea ver todos los valores y se llama al metodo. else: print ("La cola esta vacia.\n") #Si no, se sabe que la pila esta vacia y no hay valores para mostrar. Menu() else: if eleccion == 5: sys.exit() else: print ("Opcion incorrecta...\n") #SI no es ninguna de las opciones le muestro opcion incorrecta. Menu() #LLamo a Menu() para seguir con recursividad. Menu() #LLamo a Menu() para empezar la recursividad.
1c2dfba6786bb367598814842bffc92d0717846c
EduardoMJ99/EstructuraDDatos
/U3_EstructurasLineales/Practica21-U3-ListaEnlazadaCircularPeek().py
5,112
3.84375
4
import sys class Nodo(): #Esta clase crea los Nodos de la lista con 2 atributos, el valor y el enlace vacio. def __init__(self,datos): self.datos = datos self.siguiente = None def Enlazar(): #Este metodo se encarga de enlazar los nodos que se vayan creando. global raiz global p #Declaro e inicializo mis variables. global q p=Nodo(str(input("Ingrese el elemento a enlazar: "))) #Creo un Nodo y le mando el valor ingresado. q.siguiente = p #Como es lista circular, el nodo que vaya creando necesita estar enlazado con la raiz. p.siguiente = raiz #Para esto la propiedad de enlace del nodo creado le asigno la raiz. q=p #Al final muevo ambos punteros al ultimo nodo. def Peek(eleccion): #Metodo para mostrar nodos de la lista. global raiz bandera = True q=raiz #Declaro e inicializo mis variables p=raiz if eleccion == "T": #SI eligio esta opcion es para mostrar todos los valores de la lista. while (bandera): print(q.datos) #Imprimo el valor del nodo en el que estoy. if q.siguiente == raiz: #Si su atributo de enlaze es Nulo significa que llegue al final de la lista y termino el ciclo. bandera = False else: #Si no, avanzo al siguiente nodo con ayuda de los punteros. p = q.siguiente #Muevo un puntero al sig nodo que esta en el enlace y luego muevo el otro puntero a este nodo. q=p elif eleccion == "U": #Si eligio esta opcion utilizo exactamente el ciclo anterior solo que solo imprimo el ultimo while (bandera): #nodo en el que se quedaron los punteros al salir del ciclo. if q.siguiente == raiz: #Si el siguiente Nodo es la raiz, es porque llego al final de las listas. bandera = False else: #SI no, continua al sig Nodo p = q.siguiente q=p print("Ultimo valor de la lista: "+ p.datos+"\n") elif eleccion == "R": #SI eligio esta opcion es para imprimir la raiz. print("La raiz es: "+raiz.datos+"\n") else: #Si no fue ninguno de los anteriores significa que esta buscando un nodo por su valor. contador=1 while (bandera): #Para esto utilizo el mismo ciclo anterior para moverme a traves de toda la lista y me detengo if eleccion == q.datos: #hasta que encuentro el valor deseado o hasta que llegue al final de la lista sin encontrarlo. print("El dato "+str(eleccion)+" se encuentra en el nodo "+str(contador)+" de la lista...") #Encontro el valor en la lista. bandera = False elif q.siguiente == raiz: print("El dato "+str(eleccion)+" no existe en la lista...") #NO encontro el valor en la lista. bandera = False else: contador=contador+1 p = q.siguiente q=p print() def Menu(): #Menu... print ("1.- Crear y enlazar nodo.\n" "2.- Mostrar los nodos.\n" "3.- Salir.") eleccion = int(input("Que desea realizar?: ")) if eleccion ==1: Enlazar() #Si eligio esta opcion llamo al metodo enlazar. print("\nNodo creado y enlazado...\n") Menu() elif eleccion ==2: #Si eligio esta opcion es para mostrar los valores de la eleccion = str(input("\nTeclee 'T' para mostrar TODA la lista circular,\n" "teclee 'U' para mostrar el ULTIMO nodo enlazado,\n" "teclee 'R' para mostrar la RAIZ,\n" "o ingrese el valor que desea buscar en la lista: ")) print() Peek(eleccion) Menu() elif eleccion ==3: sys.exit() #Utilizo esta libreria para cerrar el programa. else: print("\nValor ingresado invalido...\n") Menu() raiz = Nodo("Raiz") #AL inicio del programa creo la Raiz con el valor Raiz como unico. p=raiz #Y mi puntero lo igualo a la raiz para de ahi comenzar la lista. q=raiz Menu() #LLamo al metodo Menu para iniciar la recursividad...
b74582b044926e0d37563f292f3d97e1f3dd42c0
barnabycollins/cipher
/letterfreq.py
1,348
3.875
4
key = {} alphabet = ['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'] commonletters = ['e','t','a','o','i','n','s','h','r','d','l','c','u','m','w','f','g','y','p','b','v','k','j','x','q','z'] letters = {} cipher = input("Cipher:\n") print("\nAnalysing...\n") total = 0 totalconnie = 0 for letter in alphabet: letters[letter] = cipher.count(letter) sortedletters = sorted(letters, key=letters.get, reverse=True) for char in sortedletters: print(char + ": Frequency " + str(letters[char]) + " | n2-n " + str(letters[char]*letters[char]-letters[char])) total = total + letters[char] totalconnie = totalconnie + (letters[char]*letters[char]-letters[char]) print("\nTotal: " + str(total) + ", TotalConnie: " + str(totalconnie/(total*total-total))) if(input("\nWould you like to attempt to decrypt the cipher using this data? (y/n)\n--> ") == "y"): print("\nAttempting decryption based on letter frequency...\n") j = 0 for i in sortedletters: key[i] = commonletters[j].upper() j += 1 plain = '' for character in cipher: if(character in key): plain = plain + key[character] else: plain = plain + character print(plain) print("\nKey: " + str(key))
b46aba74d16c03fefb468fb7282cb978022d740f
barnabycollins/cipher
/keyword.py
1,354
3.71875
4
#By AARON GILCHRIST ( https://agilchrist0.github.io ) def createKey(keyword): alphabet = ['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'] cyphertext_alphabet = [] for letter in keyword: if letter.upper() not in cyphertext_alphabet: cyphertext_alphabet.append(letter.upper()) last_letter = cyphertext_alphabet[-1] letter_number = alphabet.index(last_letter) for burger in range(letter_number+1, len(alphabet)): cake = alphabet[burger] if cake not in cyphertext_alphabet: cyphertext_alphabet.append(cake) for chip in range(0, len(alphabet)): rice = alphabet[chip] if rice not in cyphertext_alphabet: cyphertext_alphabet.append(rice) for x in range(0,26): alphabet[x] = alphabet[x].lower() key = dict(zip(cyphertext_alphabet,alphabet)) return key def encode(code,msg): for k,v in code.items(): msg = msg.replace(k, v) return msg def crackKeyword(): keyword = input('Please enter a suitable keyword:\n--> ') key = createKey(keyword) cyphertext = input('\nPlease enter your cyphertext:\n--> ').upper() result = encode(key,cyphertext) print('This is the result:\n{}'.format(result)) crackKeyword()
e0be6624b307bc25db6f7647228f2f4fdc594415
barnabycollins/cipher
/caesar2.py
713
3.546875
4
alphabet = ['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'] counts = {} key = {} curmax = 0 plain = '' cipher = input("Cipher:\n").upper() printnums = int(input("How many results do you want to output?\n--> ")) for i in alphabet: counts[i] = cipher.count(i) counts = sorted(counts, key=counts.get, reverse=True) for i in range(printnums): plain = '' curmax = alphabet.index(counts[i]) for j in range(len(alphabet)): key[alphabet[(curmax + j)%26]] = alphabet[(4 + j)%26] for j in cipher: if j in alphabet: plain += key[j] else: plain += j print("\nGuess "+ i +":\n" + plain)
f86e49a04c6fb3e410bc9b5324aec78bfe9d4c22
barnabycollins/cipher
/box.py
1,169
3.578125
4
# BARNABY'S BOX CIPHER SOLVER V1.0 https://github.com/barnstorm3r # 10/11/2016 DEVELOPED IN PYTHON 3.5.2 cipher = input("Cipher:\n") boxnum = int(input("How wide are the boxes?\n--> ")) boxes = [] currentstr = "" move = [] rearranged = [] condensed1 = [] condensed2 = "" if len(cipher) % boxnum != 0: procede = input('Hmm. You are going to have characters left over. Do you want to procede? (y/n) ') if procede == 'y' or procede == 'Y': boxes = [cipher[i:i+boxnum] for i in range(0, len(cipher), boxnum)] else: print('Bye.') import sys sys.exit() else: boxes = [cipher[i:i+boxnum] for i in range(0, len(cipher), boxnum)] print(boxes) for i in range(boxnum): move.append(int(input("Where should character " + str(i+1) + " go?\n--> ")) - 1) for i in range(len(boxes)): rearranged.append([]) for j in range(boxnum): rearranged[i].append("") for j in range(boxnum): rearranged[i][move[j]] = boxes[i][j] for i in range(len(boxes)): condensed1.append("".join(rearranged[i])) condensed2 = "".join(condensed1) print("Plaintext: " + condensed2)
676a5ad604903e33cc48e6f9535ccb49fb0c4559
vgtgayan/algorithms
/dynamic_programming/can_sum/how_sum.py
1,537
3.71875
4
""" /******************************************************* * Project : DP_MASTER * Summary : Master Dynamic Programming Concepts * Author(s) : VGT GAYAN * Date : 2021/07/24 * Copyright (C) 2020-2021 {VGT GAYAN} <{[email protected]}> * * This code cannot be copied and/or distributed without the express * permission of {VGT GAYAN} ** ** ******** ********** /** /** **//////**/////**/// /** /** ** // /** //** ** /** /** //** ** /** ***** /** //**** //** ////** /** //** //******** /** // //////// // *******************************************************/ """ def how_sum(n, arr): if n == 0: return [] if n < 0: return None for i in arr: res = how_sum(n-i, arr) if res != None: return [res[:], n] return None def how_sum_memo(n, arr, memo={}): if n in memo: return memo[n] if n == 0: return True for i in arr: if i<=n: memo[n] = how_sum_memo(n-i, arr, memo) return memo[n] memo[n] = False return memo[n] return False def main(): # print(how_sum_memo(5,[5,3,4,7])) # print(how_sum(7,[5,3,4,7])) # # print(how_sum_memo(4,[5,3])) # print(how_sum(4,[5,3])) # # print(how_sum_memo(500,[5,3,4,7])) # # print(how_sum(500,[5,3,4,7])) # # print(can_sum(50,50)) # Hang if __name__ == "__main__": main()
23c56a6242beb05236ad8ece5a356125adc58a0e
pk1510/Inductions
/RMI/Basic/Duplicate element.py
448
4.09375
4
arr = [] dict={} duplicate = [] n = int(input("enter the number of elements")) for i in range(0,n): element = int(input("enter elementwise")) arr.insert(i, element) for i in arr: if i in dict.keys(): duplicate.append(i) else: dict[i] = i if arr[i] not in dict.keys(): dict[arr[i]] = 1 else: duplicate.append(arr[i]) print("the duplicate elements are: ", duplicate) #time complexity is 0(n)
afeafaf591cbffa8b98cd0b4cd072f3946957ad8
TomersHan/CMRL
/cmrg/data_process/gen_data.py
777
3.5625
4
# print("w") # def create_data_generator(shuffle=True, infinite=True): # print("1212") # while True: # if shuffle: # pass # for i in range(10): # print("this is inside", i) # yield i # if not infinite: # break # create_data_generator() import random data = list(range(237)) def next_batch(batch_size, data, shuffle=True, infinite=True): batch = (len(data) - 1) // batch_size + 1 print(batch) while True: if shuffle: random.shuffle(data) for i in range(batch): yield data[i::batch] if not infinite: break import numpy as np # random.shuffle(data) # print(data) g = next_batch(15,data) for i in range(20): print(next(g))
73f585596248ef1b48fab824d5d8204911acf857
ssong86/UdacityFullStackLecture
/Python/Drawing_Turtles/draw_shapes_no_param.py
701
4.125
4
import turtle def draw_square(): window = turtle.Screen() window.bgcolor("pink") # creates a drawing GUI with red background color brad = turtle.Turtle() # drawing module brad.shape("turtle") brad.color("blue") brad.speed(2) for x in range (0,4): # runs from 0 to 3 (4-1) brad.forward(100) brad.right(90) x = x+1 angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) scott = turtle.Turtle() scott.shape("turtle") scott.color("blue") scott.speed(2) for y in range (0,3): scott.forward(100) scott.left(120) y=y+1 window.exitonclick() draw_square()
00195c0135e3dc939de792a7fb66b26e6c563727
Failproofshark/simple-MUD
/mudroom.py
1,371
3.640625
4
''' Bryan Baraoidan mudroom.py This file contains the definition for a room in the game world ''' class MudRoom: def __init__(self, name, description, contents, exits): """ str: name, description str list: contents str dict: exits """ self.name = name self.description = description self.contents = contents self.exits = exits def __str__(self): """String version of Room Object""" stringForm = self.name + "\n===========\n" + \ self.description + "\n\n" stringForm += "Items that are currently in the room: " if len(self.contents) > 0: for item in self.contents: stringForm += item + " " else: stringForm += "None" stringForm += "\n\nPaths out of this room: " for path in self.exits.keys(): stringForm += path + " " stringForm += "\n" return stringForm def addItem(self, item): """ Add an item to the room, whether it be a character entering it or an item left behind """ self.contents.append(item) def removeItem(self, item): """ When a character picks up (takes) an item remove it from the room """ if item in self.contents: self.contents.remove(item)
cee753287bd21c7e222a6acfdc3e34412241a52f
vaishnav-nk/vaishanv-nk.github.io
/binarysearch.py
442
3.953125
4
def binarysearch(item_list,item): first = 0 last = len(item_list) - 1 found = False while(first<=last and not found): mid = (first+last)//2 if item_list[mid] == item: found = True else: if item< item_list[mid]: last = mid-1 else: first = mid+1 return found print(binarysearch([1,2,3,4,5,6],6)) print(binarysearch([1,2,3,4,5,6],7))
8617172f973154a1da17ff103ca0d7dcb55246aa
PavanjDot/pythonbible
/while.py
158
4
4
L=[] while len(L) <3: new_name = input("Add name: ").strip() L.append(new_name) if len(L)==3: print(L)
0d204a13c441bb6ab2f42670d5e8f1caccd41b12
paulinaflorezg/-INTRO-PROGAMACION-2021
/clases/inputclase.py
303
3.859375
4
PREGUNTA_NOMBRE = "Como te llamas? : " MENSAJE_SALUDO = "un gusto conocerte :" PREGUNTA_EDAD = "Cuantos años tienes? :" PREGUNTA_ESTATURA = "Cuanto mides?" nombre = input (PREGUNTA_NOMBRE) edad = int (input (PREGUNTA_EDAD)) print (MENSAJE_SALUDO,nombre) estatura = float (input(PREGUNTA_ESTATURA))
7c5824da6d1e600f1d072deb73c22ed48b2ec659
paulinaflorezg/-INTRO-PROGAMACION-2021
/examenes/quiz3graficos.py
1,963
3.515625
4
#PUNTO 1 import matplotlib.pyplot as plt snacks = ['jumbo','palito de queso','galletas oreo','perro','helado'] precio = [2000,4000,3500,5000,4000] plt.bar(snacks,precio) ######### plt.title('Snacks favoritos') plt.xlabel('snacks') plt.ylabel ('precio') plt.savefig ('graficos snacksfavoritos.png') ######### plt.show() #PUNTO2 cuidad1 = input("Ingresa tu cuidad favorita: ") poblacion1 = int(input("Ingresa la poblacion de esta cuidad: ")) cuidad2 = input("Ingresa tu cuidad favorita: ") poblacion2 = int(input("Ingresa la poblacion de esta cuidad: ")) cuidad3 = input("Ingresa tu cuidad favorita: ") poblacion3 = int(input("Ingresa la poblacion de esta cuidad: ")) cuidad4 = input("Ingresa tu cuidad favorita: ") poblacion4 = int(input("Ingresa la poblacion de esta cuidad: ")) cuidad5 = input("Ingresa tu cuidad favorita: ") poblacion5 = int(input("Ingresa la poblacion de esta cuidad: ")) lista_cuidades = [cuidad1, cuidad2, cuidad3, cuidad4, cuidad5] lista_poblaciones = [poblacion1, poblacion2, poblacion3, poblacion4, poblacion5] plt.pie(lista_poblaciones,labels=lista_cuidades) plt.title("grafica de torta") plt.savefig("torta.png") plt.show() #PUNTO 3 print("Definicion ecg: El electrocardiograma es la representación visual de la actividad eléctrica del corazón en función del tiempo, que se obtiene.") print("Definicion ppg; La fotopletismografía o fotopletismograma es una técnica de pletismografía en la cual se utiliza un haz de luz para determinar el volumen de un órgano.") import pandas as pd ecgdata = pd.read_csv("ecg.csv", sep=";") print(ecgdata) valor_ecg = ecgdata["valor"] plt.plot(valor_ecg) plt.title("Grafica ECG") plt.xlabel("tiempo") plt.ylabel("mV") plt.savefig("ecg.png") plt.show() import pandas as pd ecgdata2 = pd.read_csv("ppg.csv", sep=";") print(ecgdata2) valor_ppg = ecgdata2["valor"] plt.plot(valor_ppg) plt.title("Grafica PPG") plt.xlabel("tiempo") plt.ylabel("volumen") plt.savefig("ppg.png") plt.show()
32477b008d75266da42df96abeda03ae23d63718
RelioXx/MyWorks
/ParadigmasProg/14_async_generators.py
347
3.734375
4
import asyncio async def cuadrados(): for i in range(10): pass yield i ** 2 await asyncio.sleep(0.1) # Operación de IO que tarda async def main(): r1 = [i async for i in cuadrados()] r2 = [i for i in [1,2,3]] print(r1) print(r2) if __name__ == '__main__': asyncio.run(main())
fb1795c96050d29340251a3dc328b14e70f3b7bf
jiazekun/Py
/ds_using_dict.py
403
3.625
4
ab={ 'Swaroop':'[email protected]', 'Larry':'[email protected]', 'Mali':'[email protected]', 'Spa':'[email protected]' } print('Swaroop \'s address is ',ab['Swaroop']) del ab['Spa'] print('\nThere are{}contents in the address-book\n'.format(len(ab))) for name,address in ab.items(): print('Contact {} at {}'.format(name,address)) ab['Guido']='[email protected]' if 'Guido' in ab: print('\nGuido\'s address is',ab['Guido'])
e09ff03629e07c3a3600f676f5545e34e717e83f
michael7ulian/training_python
/pertemuan ke6/module.py
477
3.90625
4
class person(object): def __init__(self,name,age,nama_lawan): self.name = name self.age = age self.nama_lawan = nama_lawan def sapa(self): print("halo namaku: "+self.name) print("namamu siapa?") def salamkenal(self): print("halo namaku: "+self.nama_lawan) print("senang bertemu denganmu. sampai jumpa kebali") p3 = person("michael",23,"dodi") p3.sapa() p3.salamkenal()
984658d5a0192e275cf8bdea9cd91db7d150b445
J0sueTM/DSA
/Implementation/Mathematics/BasicMath/python/armstrongNumbers.py
188
3.59375
4
def isArNum(n, s): c = 0 t = n while t > 0: r = t % 10 c += r ** s t //= 10 return (c == n) n = int(input()) s = len(str(n)) print(isArNum(n, s))
957bf35ebf75e8ba66062dcd42ef9d908f7024fc
J0sueTM/DSA
/Implementation/Mathematics/BasicMath/python/gcd.py
387
3.796875
4
import math def gcdpf(a, b): if a == 0: return b if b == 0: return a if a == b: return a if a > b: return gcdpf(a - b, b) else: return gcdpf(a, b - a) def gcdea(a, b): if b == 0: return a return gcdea(a, a % b) a = int(input()) b = int(input()) print(gcdpf(a, b)) print(gcdea(a, b)) print(math.gcd(a, b))
cbfdccb80a6d6feb89d9e3a9edfd120d200e8637
VATSALagrawal/Bitcoin-price-Detection-Using-Neural-Networks
/bitcoin.py
3,102
3.609375
4
import numpy as np import pandas as pd from matplotlib import pyplot as plt # read the data , convert timestamp values to date and then group them according to their date df = pd.read_csv('coinbaseUSD.csv') df['Date'] = pd.to_datetime(df['Timestamp'],unit='s').dt.date #df=pd.read_csv('BTC-USD.csv') group = df.groupby('Date') Price = group['Close'].mean() # number of days defined to test model days_to_predict = 90 df_train= Price[:len(Price)-days_to_predict] df_test= Price[len(Price)-days_to_predict:] print("Training data") print(df_train.head()) print("Testing data") print(df_test.head()) # Data preprocessing to feature scale data to fit in range (0,1) which helps NN converge faster training_set = df_train.values training_set = np.reshape(training_set, (len(training_set), 1)) from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) X_train = training_set[0:len(training_set)-1] y_train = training_set[1:len(training_set)] X_train = np.reshape(X_train, (len(X_train), 1, 1)) #print(X_train[0:5]) #print(y_train[0:5]) # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # Initialising the RNN model = Sequential() # Adding the input layer and the LSTM layer # input_shape(x,y) x is number of time steps and y is number of features model.add(LSTM(units = 7, activation = 'sigmoid', input_shape = (None, 1))) #model.add(Dropout(0.2)) #model.add(LSTM(units = 5, activation = 'sigmoid', input_shape = (None, 1),return_sequences=False)) # Adding the output layer model.add(Dense(units = 1)) # Compiling the RNN model.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fitting the RNN to the Training set model.fit(X_train, y_train, batch_size = 5, epochs = 100) test_set = df_test.values inputs = np.reshape(test_set, (len(test_set), 1)) inputs = sc.transform(inputs) print("inputs before reshape ",inputs[0:5]) inputs = np.reshape(inputs, (len(inputs), 1, 1)) print("inputs after reshape ",inputs[0:5]) #input to every LSTM layer must be 3 dimentional predicted_BTC_price = model.predict(inputs) predicted_BTC_price = sc.inverse_transform(predicted_BTC_price) #calculating root mean squared error valid = np.reshape(test_set, (len(test_set), 1)) rms=np.sqrt(np.mean(np.power((valid-predicted_BTC_price),2))) print("root mean error is :",rms) # Visualising the results plt.figure(figsize=(25,15), dpi=80, facecolor='w', edgecolor='k') ax = plt.gca() plt.plot(test_set, color = 'red', label = 'Real BTC Price') plt.plot(predicted_BTC_price, color = 'green', label = 'Predicted BTC Price') plt.title('Bitcoin Price Prediction', fontsize=25) df_test = df_test.reset_index() x=df_test.index labels = df_test['Date'] plt.xticks(x, labels, rotation = 'vertical') for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(10) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(10) plt.xlabel('Time', fontsize=30) plt.ylabel('BTC Price(USD)', fontsize=20) plt.legend(loc=2, prop={'size': 20}) plt.show()
9378de6f71d668ea2a9d250d78d19fb64b385ef0
igorpejic/nx
/c.py
6,253
3.5
4
import math import networkx as nx import ast def euclidean(node1, node2): return math.sqrt((node2['x'] - node1['x']) ** 2 + (node2['y'] - node1['y']) ** 2) def get_direction_codes(nodes_list): """ Codes: 1 up 2 down 3 right 4 left Return list of directions viewed from the sky not from cart direction """ directions = [] for index, node in enumerate(nodes_list): try: next_node = nodes_list[index + 1] except IndexError: break if R.node[node]['x'] == R.node[next_node]['x']: if R.node[node]['y'] < R.node[next_node]['y']: directions += [1] else: directions += [2] elif R.node[node]['y'] == R.node[next_node]['y']: if R.node[node]['x'] < R.node[next_node]['x']: directions += [3] else: directions += [4] return directions def add_coordinates_to_node(node): """ Add coordinates to node with notation (id, (a, b), %) a - node closer to (0,0) b - node farther from (0,0) $ - relative percent of total length of (a, b) edge from a return (id, (a, b), %, {'x': 3, 'y': 2}) node """ k = node[2] neighbor1 = node[1][0] neighbor2 = node[1][1] node += ( { 'x': B.node[neighbor1]['x'] + (B.node[neighbor2]['x'] - B.node[neighbor1]['x']) * k, 'y': B.node[neighbor1]['y'] + (B.node[neighbor2]['y'] - B.node[neighbor1]['y']) * k }, ) return node def add_products_to_graph(products, B): """ Insert nodes with notation (id, (a, b) %) Recieves dictionary: {('a', 'b'): ((2741, ('a', 'b',) 0.5),), ('d', 'c'): ((..),(..),)} a - node closer to (0,0) b - node farther from (0,0) $ - relative percent of total length of (a, b) edge from a """ for k, v in products.items(): previous_node = k[0] # sort by % v = sorted(v, key=lambda tup: tup[2]) B.remove_edge(k[0], k[1]) for product in v: product = add_coordinates_to_node(product) id, (abs_prev_node, forward_node), percent, coordinates = product # calculate here which is the closest B.add_node(id, x=coordinates['x'], y=coordinates['y']) B.add_edge(previous_node, id, weight=euclidean(B.node[previous_node], coordinates)) # imitate node on edge previous_node = id B.add_edge(id, forward_node, weight=euclidean(B.node[forward_node], coordinates)) def add_products_to_corridor(product): """Recieves {(4, 1): ((2743, {'y': 8.2, 'x': 2.0}), (2744, {'y': 7.4, 'x': 2.0}), (2745, {'y': 10.6, 'x': 2.0})), (3, 2): ((2742, {'y': 9.0, 'x': 10.0}),), (3, 4): ((2740, {'y': 3.0, 'x': 5.2})))} kind of dictionary andd adds those nodes to graph populates R graph """ for k, v in product.items(): R.remove_edge(k[0], k[1]) node_has_same = 'y' if R.node[k[0]]['y'] == R.node[k[1]]['y'] else 'x' node_has_different = 'y' if node_has_same != 'y' else 'x' # start adding nodes previous = k[0] for node in sorted(v, key=lambda tup: tup[1][node_has_different]): data = {} data[node_has_same] = R.node[k[0]][node_has_same] data[node_has_different] = node[1][node_has_different] R.add_node(node[0], **data) R.add_edge(previous, node[0], weight=euclidean(R.node[previous], node[1])) previous = node[0] R.add_edge(previous, k[1], weight=euclidean(R.node[previous], R.node[k[1]])) def clamp(x, xmin, xmax): return min(max(x, xmin), xmax) def epn_distance(x, y, p1x, p1y, p2x, p2y): # vector a = p - p1 ax = x - p1x ay = y - p1y # vector b = p2 - p1 bx = p2x - p1x by = p2y - p1y # dot product a*b dot = ax * bx + ay * by # squared length of vector b len_sq = bx * bx + by * by # normalized projection of vector a to vector b epn = float(dot) / float(len_sq) if len_sq != 0 else -1 epn = clamp(epn, 0.0, 1.0) xx = p1x + epn * bx yy = p1y + epn * by dx = x - xx dy = y - yy distance = math.hypot(dx, dy) return (epn, distance) def graphlocation_from_location(graph, location): edges = graph.edges() nodes = graph.nodes() closest_edge = None epn_on_closest = 0.0 distance_to_closest = 0.0 for node1, node2 in edges: epn, dist = epn_distance( location['x'], location['y'], graph.node[node1]['x'], graph.node[node1]['y'], graph.node[node2]['x'], graph.node[node2]['y'], ) if (dist < distance_to_closest) or (closest_edge is None): distance_to_closest = dist closest_edge = (node1, node2) return closest_edge # Blue graph B = nx.Graph() R = nx.Graph() with open('map.txt', 'r') as f: gr = f.read() gr = ast.literal_eval(gr) for key, value in gr.items(): for k, v in value.items(): if key == "corridors": graph = R elif key == "shelves": graph = B for i, l in enumerate(v, start=1): if k == "nodes": graph.add_node(i, x=l[0], y=l[1]) elif k == "edges": graph.add_edge(l[0], l[1], weight=euclidean(graph.node[l[0]], graph.node[l[1]])) p0 = (2738, (16, 15), 0.3) p1 = (2739, (60, 61), 0.3) l = [p0, p1] d = {} for p in l: if p[1] in d.keys(): d[p[1]] += (p,) else: d[p[1]] = (p,) add_products_to_graph(d, B) products_in_corridor = {} for product in B.nodes(data=True): if isinstance(product[0], basestring): continue k = graphlocation_from_location(R, product[1]) if k in products_in_corridor.keys(): products_in_corridor[k] += (product,) else: products_in_corridor[k] = (product,) add_products_to_corridor(products_in_corridor)
4bded11527826b9b2c978c2828fe22423d2f7435
nemesmarci/Advent-of-Code-2019
/17/common.py
1,357
3.5
4
from sys import stdout from intcode import Intcode def read_data(): with open('input.txt') as program: return [int(code) for code in program.read().strip().split(',')] class Scaffolding: def __init__(self): self.ic = Intcode(read_data()) self.area = dict() self.x_size = self.y_size = 0 def scan(self): IC = self.ic.run() try: IC.send(None) except StopIteration: pass x, y = 0, 0 for c in self.ic.output: if c != 10: self.area[(x, y)] = chr(c) x += 1 else: if x != 0: self.x_size = x x = 0 y += 1 self.y_size = y - 1 def get_neighbours(self, current): if current[0] == 0 or current[0] == self.x_size - 1: return None if current[1] == 0 or current[1] == self.y_size - 1: return None up = (current[0], current[1] - 1) left = (current[0] - 1, current[1]) right = (current[0] + 1, current[1]) down = (current[0], current[1] + 1) return [up, left, right, down] def display(self): for y in range(self.y_size): for x in range(self.x_size): stdout.write(self.area[(x, y)]) print()
8981eef3f9fa9b9b245bfc45f77818bcbbbd0acf
nemesmarci/Advent-of-Code-2019
/3/3_1.py
183
3.5625
4
from path import manhattan, read_data, parse wires = read_data() pathes = parse(wires) distances = [manhattan(p, (0, 0)) for p in pathes[0] if p in pathes[1]] print(min(distances))
c46fc22351db7e3fdafadde09aea6ae45b7c6789
rajatthosar/Algorithms
/Sorting/qs.py
1,682
4.125
4
def swap(lIdx, rIdx): """ :param lIdx: Left Index :param rIdx: Right Index :return: nothing """ temp = array[lIdx] array[lIdx] = array[rIdx] array[rIdx] = temp def partition(array, firstIdx, lastIdx): """ :param array: array being partitioned :param firstIdx: head of the array :param lastIdx: tail of the array :return: index of pivot element after sorting """ pivot = array[lastIdx] # Counter i is used as a marker to fill the array with all # elements smaller than pivot. At the end of the loop # pivot is swapped with the next position of i as all the # elements before pivot are smaller than it lowIdx = firstIdx - 1 # Note that range function stops the sequence generation at # lastIdx. This means that there will be # (lastIdx - firstIdx) - 1 elements in the sequence. # The last item generated in the sequence will be lastIdx - 1 for arrayIdx in range(firstIdx, lastIdx): if array[arrayIdx] <= pivot: lowIdx += 1 swap(lowIdx, arrayIdx) swap(lowIdx + 1, lastIdx) return lowIdx + 1 def quickSort(array, firstIdx, lastIdx): """ :param array: Array to be sorted :param firstIdx: head of the array :param lastIdx: tail of the array :return: sorted array """ if firstIdx < lastIdx: pivot = partition(array, firstIdx, lastIdx) quickSort(array, firstIdx, pivot - 1) quickSort(array, pivot + 1, lastIdx) print(array) if __name__ == "__main__": array = [10, 80, 30, 90, 40, 50, 70] firstIdx = 0 lastIdx = len(array) - 1 quickSort(array, firstIdx, lastIdx)
2bb59194c7433002d4d3ab50ae6abb2a5344fa20
5yaaz/d
/palindrome.py
197
3.65625
4
def main(): s=int(input("")) temp=s rev=0 while(s>0): dig=s%10 rev=rev*10+dig s=s//10 if(temp==rev): print("Yes") else: print("No") if __name__ == '__main__': main()
c4ec220c4abfbe6534537ea03b7029dfaa1b3e18
v-antech/adventofcode
/src/main/python/similar1/solution.py
3,355
4.03125
4
#!/usr/bin/python global alphabet alphabet = "abcdefghijklmnopqrstuvwxyz" def generate_matrix(input_string, size_of_matrix): print "Size: {0}".format(size_of_matrix) matrix = [[0 for x in range(size_of_matrix)] for x in range(size_of_matrix)] location_in_word = 0; for y in range(size_of_matrix): for x in range(size_of_matrix): matrix[y][x] = input_string[location_in_word] location_in_word = (location_in_word + 1) % len(input_string) return matrix def print_matrix(matrix): for y in range(len(matrix)): for x in range(len(matrix)): print matrix[y][x], print def lexicographically_superior_word(current, applicant): if len(applicant) > len(current): return applicant if len(applicant) == len(current): lexicographical_applicant = 0 lexicographical_current = 0 for i in range(len(applicant)): lexicographical_applicant += alphabet.index(applicant[i]) lexicographical_current += alphabet.index(current[i]) if(lexicographical_applicant < lexicographical_current): return applicant return current def get_longest_for_line_both_directions(line): longest_word = "" longest_horizontal_positive = get_longest_for_line(line) inverted = list(line) inverted.reverse() longest_horizontal_negative = get_longest_for_line(inverted) longest_word = lexicographically_superior_word(longest_word, longest_horizontal_positive) longest_word = lexicographically_superior_word(longest_word, longest_horizontal_negative) print "positive longest: {0}, negative longest: {1}".format(longest_horizontal_positive, longest_horizontal_negative) return longest_word def get_longest_for_line(line): current_longest = "" longest_word = "" for i in range(len(line)): current_char = line[i] current_index = alphabet.index(current_char) if len(current_longest) == 0: current_longest = current_char else: last_char = current_longest[len(current_longest)-1] last_index = alphabet.index(last_char) if last_index < current_index: current_longest = current_longest + current_char else: longest_word = lexicographically_superior_word(longest_word, current_longest) current_longest = current_char longest_word = lexicographically_superior_word(longest_word, current_longest) return longest_word def column(matrix, i): return [row[i] for row in matrix] def get_longest(matrix): longest_word = "" current_longest = "" for row in matrix: longest_word = get_longest_for_line_both_directions(row) for col_index in range(len(matrix[0])): col = column(matrix, col_index) column_longest = get_longest_for_line_both_directions(col) longest_word = lexicographically_superior_word(longest_word, column_longest) return longest_word def main(): input_string = raw_input("What is the string? ") size_of_matrix = raw_input("What is the size of the matrix? ") matrix = generate_matrix(input_string, int(size_of_matrix)) longest_vertical = get_longest(matrix) print_matrix(matrix) print longest_vertical if __name__ == "__main__": main()
b5130d19dedec998008d90a4cbb7aaefe626d7f6
Shayennn/ComPro-HW
/6-Second-HW/L03P5.py
381
3.671875
4
# -*- coding: utf-8 -*- #std35: Phitchawat Lukkanathiti 6110503371 #date: 22AUG2018 #program: L03P5.py #description: display positive and negative of input posneg=[0,0] while True: number = int(input("Please input number : ")) if number > 0: posneg[0]+=1 elif number<0: posneg[1]+=1 else: break print("Positive :",posneg[0]) print("Negative :",posneg[1])
564f6a56d42373ee2e4440bf13dd23304144f632
Shayennn/ComPro-HW
/6-Second-HW/L03P3.py
462
3.84375
4
# -*- coding: utf-8 -*- #std35: Phitchawat Lukkanathiti 6110503371 #date: 22AUG2018 #program: L03P3.py #description: if and no elif ..... status={90:'Senior Status',60:'Junior Status',30:'Sophomore Status',0:'Freshman Status'} while True: credit = int(input("Enters the number of college credits earned : ")) for credit_rule,std_status in status.items(): if credit>credit_rule or credit_rule==0: print(std_status) break
16da508f62ddb353409ef723a4e6a6a3360ae592
Shayennn/ComPro-HW
/2-First LAB/L01M1.py
262
3.546875
4
# -*- coding: utf-8 -*- #std25: Phitchawat Lukkanathiti 6110503371 #date: 09AUG2018 #program: L01M1.py #description: hello name and lastname name = input("What is your name? ") lastname = input("What is your lastname? ") print("Hello",name,lastname) print("Welcome to Python!")
603238d29b70b8d5c882d4cd32bf77e3ed01c10e
Shayennn/ComPro-HW
/8-TEST02/01_primeNDigit.py
505
3.8125
4
# -*- coding: utf-8 -*- #std35: Phitchawat Lukkanathiti 6110503371 #date: 30AUG2018 quiz02 #program: 01_primeNDigit.py #description: count prime that have n digits n = int(input('n: ')) number_range = [True for _ in range(10**n)] count=0 for number in range(10**n): if number_range[number]==False or number < 2: number_range[number]=False continue if number>=(1+10**(n-1)): count+=1 for not_prime in range(number*2,10**n,number): number_range[not_prime]=False print(count)
c9a9fb8c6dd77916be383007a69350bff4cc3f70
Shayennn/ComPro-HW
/6-Second-HW/L03M2.py
921
3.84375
4
unit=['K','C','F','R'] def temp2kelvin(temp,inunit): if inunit == 0: return temp elif inunit == 1: return temp+273.15 elif inunit == 2: return ((temp+459.67)*5/9) elif inunit == 3: return ((temp-7.5)*40/21+273.15) return -999 def kelvin2temp(kelvin,outunit): if outunit == 0: return kelvin elif outunit == 1: return kelvin-273.15 elif outunit == 2: return (kelvin*9/5-459.67) elif outunit == 3: return ((kelvin-273.15)*21/40+7.5) return -999 print("Temperature choices are") for unitnumber in range(len(unit)): print(unitnumber,").",unit[unitnumber]) inunit = int(input("Choose input unit number : ")) intemp = float(input("Input temperature : ")) outunit = int(input("Choose output unit number : ")) print("Temperature in ",unit[outunit],' is ',format(kelvin2temp(temp2kelvin(intemp,inunit),outunit),'.2f'))
969e6b9efc208367d623176c3681af8869f2deac
Avery246813579/cs-diagnostic-avery-durrant
/Linked List Reversal.py
1,371
4
4
class LinkedList: head = None def add(self, element): if self.head is None: self.head = Node(element) return new_start = Node(element) new_start.pointer = self.head self.head = new_start def pop(self): if self.head is None: return self.head = self.head.next() def reverse(self): if self.head is None: return next = self.head.next() self.head.pointer = None while True: if next is None: break current = next next = current.next() current.pointer = self.head self.head = current def __str__(self): if self.head is None: return "Empty" to_return = "" current = self.head while True: to_return += str(current.value) + " " next_node = current.next() if next_node is None: break current = next_node return to_return class Node: pointer = None def __init__(self, value): self.value = value def next(self): return self.pointer list = LinkedList() list.add(1) list.add(2) list.add(3) list.add(4) print(list) list.reverse() print(list)
032cf9c4c13c608b7053e6af651481ee673b0500
Mhmdabed11/CrackingtheCodingInterviewExcercisesTypeScript
/threeInOne.py
1,777
3.796875
4
class ThreeInOne: def __init__(self, stackSize): self.__stackCapaity = stackSize self.__array = [None]*3*stackSize self.__sizes = [0]*3 def push(self, stackNum, value): if(int(stackNum) > 2): print("Stack number should be less than 3") return if(self.__sizes[stackNum] >= self.__stackCapaity): print("%s is full" % stackNum) return index = stackNum*self.__stackCapaity + self.__sizes[stackNum] self.__sizes[stackNum] = self.__sizes[stackNum] + 1 self.__array[index] = value def pop(self, stackNum): if(self.__sizes[stackNum] > 0): index = self.__stackCapaity * stackNum + (self.__sizes[stackNum]-1) else: index = self.__stackCapaity * stackNum + self.__sizes[stackNum] item = self.__array[index] self.__array[index] = None if(self.__sizes[stackNum] > 0): self.__sizes[stackNum] = self.__sizes[stackNum]-1 return item def peek(self, stackNum): if(self.__sizes[stackNum] > 0): index = self.__stackCapaity*stackNum + self.__sizes[stackNum]-1 else: index = self.__stackCapaity*stackNum + self.__sizes[stackNum] return self.__array[index] def isEmpty(self, stackNum): return self.__sizes[stackNum] == 0 def print(self): print(self.__array) MyArrayStack = ThreeInOne(5) MyArrayStack.push(0, 'a') MyArrayStack.push(0, 'b') MyArrayStack.push(0, 'c') MyArrayStack.push(0, 'd') MyArrayStack.push(0, 'e') MyArrayStack.push(1, 'a') MyArrayStack.push(1, 'b213123123') MyArrayStack.push(2, 'a') MyArrayStack.push(2, '898989') MyArrayStack.push(2, '10293946') MyArrayStack.pop(1) MyArrayStack.print()
a54e726b3a4c8ef2d26769fb60a86948089627e4
Mhmdabed11/CrackingtheCodingInterviewExcercisesTypeScript
/returnKthtoLast.py
560
4
4
from linkedList import LinkedList def returnKthToLast(linkedList, k): ptr1 = linkedList.head ptr2 = linkedList.head for i in range(0, k-1): try: ptr2 = ptr2.next except Exception as exception: return exception while(ptr1.next and ptr2.next): ptr1 = ptr1.next ptr2 = ptr2.next return ptr1.value myLinkedList = LinkedList(1) myLinkedList.append(2) myLinkedList.append(3) myLinkedList.append(4) myLinkedList.append(5) myLinkedList.append(6) print(returnKthToLast(myLinkedList, 3))
3d1a886b8d61f6175cc9376dfddae520c822f8ba
Mhmdabed11/CrackingtheCodingInterviewExcercisesTypeScript
/sumLists.py
2,511
3.796875
4
from linkedList import LinkedList import math def sumLists(linkedList1, linkedList2): number1 = "" number2 = "" current1 = linkedList1.head while(current1): print(current1) number1 = number1+str(current1.value) current1 = current1.next current2 = linkedList2.head while(current2): number2 = number2 + str(current2.value) current2 = current2.next number1 = number1[::-1] number2 = number2[::-1] return int(number1) + int(number2) def sumListsTwo(linkedList1, linkedList2): myLinkedList3 = LinkedList(None) carriage = 0 current1 = linkedList1.head current2 = linkedList2.head while(current1 or current2): if(current1 and current2): sum = current1.value + current2.value + carriage sumWithoutCarriage = sum if(sum >= 10 and current1.next != None and current2.next != None): carriage = math.floor(sum/10) sumWithoutCarriage = sum % 10 elif(sum < 10 and current1.next != None and current2.next != None): carriage = 0 myLinkedList3.append(sumWithoutCarriage) current1 = current1.next current2 = current2.next elif(current1 == None): myLinkedList3.append(current2.value) current2 = current2.next elif(current2 == None): myLinkedList3.append(current1.value) current1 = current1.next myLinkedList3.print() class PartialSum: sum = LinkedList() carry = 0 def sumTwoListsTwo(node1, node2): if(node1 == None and node2 == None): sum = PartialSum() return sum sum = sumTwoListsTwo(node1.next, node2.next) val = node1.value + node2.value + sum.carry sum.sum.prepend(val % 10) sum.carry = math.floor(val / 10) return sum def addLists(linkedList1, linkedList2): l1 = linkedList1.length() l2 = linkedList2.length() if(l1 > l2): for i in range(0, l1-l2): linkedList2.prepend(0) elif(l2 > l1): for i in range(0, l2-l1): linkedList1.prepend(0) sum = sumTwoListsTwo(linkedList1.head, linkedList2.head) sum.sum.prepend(sum.carry) return sum.sum myLinkedList1 = LinkedList(9) myLinkedList1.append(9) myLinkedList1.append(9) myLinkedList2 = LinkedList(9) myLinkedList2.append(9) myLinkedList2.append(9) myLinkedList2.append(7) myLinkedList2.append(6) addLists(myLinkedList1, myLinkedList2).print()
1b035eebd1088a5b976e5cd1c72f6d1d3706ad7a
petermchale/algorithms_and_data_structures_Python
/queues and stacks/queue built from stacks.py
982
3.71875
4
# https://www.youtube.com/watch?v=7ArHz8jPglw&index=31&list=PLOuZYwbmgZWXvkghUyMLdI90IwxbNCiWK from stack import Stack class Queue: def __init__(self): self.stack_newest_on_top = Stack() self.stack_oldest_on_top = Stack() def shift_stacks(self): if self.stack_oldest_on_top.is_empty(): while self.stack_newest_on_top.is_empty() is False: self.stack_oldest_on_top.push(self.stack_newest_on_top.pop()) def peek(self): self.shift_stacks() return self.stack_oldest_on_top.peek() def enqueue(self, data): self.stack_newest_on_top.push(data) def dequeue(self): self.shift_stacks() return self.stack_oldest_on_top.pop() def test_queue(): queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print queue.peek() print queue.dequeue() print queue.dequeue() print queue.dequeue() if __name__ == "__main__": test_queue()
985fa1c907017b8a3ed95d6a50e2fdcf3693ad54
Aetos19/PDJ2
/Imp_Py/3_ex_contains.py
464
3.53125
4
class CaseInsensitive: def __init__(self, **kwargs): for key, value in kwargs.items(): self[key.lower()] = value def __contains__(self, key): return super(CaseInsensitive, self).__contains__(key.lower()) def __getitem__(self, key): return super(CaseInsensitive, self).__getitem__(key.lower()) def __setitem__(self, key, value): super(CaseInsensitive, self).__setitem__(key.lower(), value) d = CaseInsensitive(SpAm = 'eggs') #print('spam' in d)
bbc5ef85630d09469c0a64186d6c27d95d3a9c88
DanielEstrada971102/Implementaciones_FPGA
/Interfaces/firstW_designer/firstW_onlyCode.py
1,274
3.609375
4
import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QMainWindow, QApplication class Simple_window(QMainWindow): """ This is a simple examplo about how generate a GUI whith PyQt5 """ def __init__(self): super(Simple_window, self).__init__() self.setGeometry(300, 300, 320, 300) # x, y, w, h self.setWindowTitle("Venta sencilla de prueba") self.initUI() def initUI(self): self.label1 = QtWidgets.QLabel(self) self.label1.setGeometry(60,50,200,90) self.label1.setText("This is the first Simple GUI") self.boton1 = QtWidgets.QPushButton(self) self.boton1.setText("Press to Change the label") self.boton1.setGeometry(50, 110, 200, 30) self.boton1.clicked.connect(lambda: self.changeLabel(1)) self.boton2 = QtWidgets.QPushButton(self) self.boton2.setText("Press to ReChange the label") self.boton2.setGeometry(50, 160, 250, 30) self.boton2.clicked.connect(lambda: self.changeLabel(2)) def changeLabel(self, opt): if opt==1: self.label1.setText("This is a test") else: self.label1.setText("This is the first Simple GUI") def main(): app = QApplication(sys.argv) window = Simple_window() window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
a5531b6d065ff94953c67c60efe74d2f16cb44f2
KulataevKanat/PythonData
/structures/cycles/comparisonOfNumbers.py
867
4.09375
4
#! Программа Сравнение чисел print("Для выхода нажмите exit") while True: try: value1 = input("Введите первое число: ") if value1.lower().__eq__("exit"): break # выход из цикла value2 = input("Введите второе число: ") if value2.lower().__eq__("exit"): break # выход из цикла if int(value1) > int(value2): print(value1 + " больше " + value2) elif int(value1) == int(value2): print(value1 + " и " + value2 + " равны.") else: print(value1 + " меньше " + value2) except: print("Просьба ввести числа, или 'exit' для окончания") print("сравнение чисел окончено")
67dd07b7ffa31b09e4e7a667464da4a121741572
KulataevKanat/PythonData
/structures/oop/object/str.py
1,110
3.828125
4
class Car: def __init__(self, id, mark, color, model, dateOfManufacture) -> None: self.id = id self.mark = mark self.color = color self.model = model self.dateOfManufacture = dateOfManufacture def display_info(self): print(self.__str__) def __str__(self) -> str: return "\n id: {} \n Марка: {} \n Цвет: {} \n Модель: {} \n Дата начала-окончания производства: {}" \ .format(self.id, self.mark, self.color, self.model, self.dateOfManufacture) class Main: car1 = Car("10", "Tesla", "Белый", "X 100D", "Январь 2015 - В производстве") print(car1.__str__()) car2 = Car("36", "Toyota", "Чёрный", "Camry", "Январь 2014 - Январь 2017") print(car2.__str__()) car3 = Car("43", "Ford", "Серый", "Mustang Shelby GT 500", "Январь 2009 - Январь 2011") print(car3.__str__()) car4 = Car("16", "Nissan", "Красный", "GT-R", "Январь 2016 - В производстве") print(car4.__str__())
a7ed1cdd3e87253358419d20e5d1c6ffd4cae683
KulataevKanat/PythonData
/GUI/button.py
859
3.78125
4
from tkinter import * clicks = 0 def click_button(): global clicks clicks += 1 root.title("Clicks {}".format(clicks)) root = Tk() root.title("Графическая программа на Python") root.geometry("400x300+300+250") btn = Button(text="Hello GUI", # текст кнопки background="#5DB11E", # фоновый цвет кнопки foreground="#000000", # цвет текста padx="20", # отступ от границ до содержимого по горизонтали pady="8", # отступ от границ до содержимого по вертикали font=("Verdana", 15, "bold"), # высота шрифта command=click_button # хранение кол-во кликов ) btn.pack() root.mainloop()
9b36ee11bf5740fecaa7e197ad9b3b03478f5c8f
KulataevKanat/PythonData
/structures/exceptions/valueError.py
251
3.6875
4
try: number = int(input("Введите число: ")) print("Введенное число:", number) except ValueError: print("Преобразование прошло неудачно") print("Завершение программы")
7b6b3d10531a4a5676472bbc7bc2280b2b07d1b0
KulataevKanat/PythonData
/GUI/elements/entry/entryMethods.py
1,841
3.828125
4
from tkinter import * from tkinter import messagebox def clear(): name_entry.delete(0, END ) surname_entry.delete(0, END ) def display(): messagebox.showinfo("GUI Python", name_entry.get() + " " + surname_entry.get() ) root = Tk() root.title("GUI на Python") root.geometry("250x100+300+250") name_label = Label(text="Введите имя:") surname_label = Label(text="Введите фамилию:") name_label.grid(row=0, column=0, sticky="w" ) surname_label.grid(row=1, column=0, sticky="w" ) name_entry = Entry() surname_entry = Entry() name_entry.grid(row=0, column=1, padx=5, pady=5 ) surname_entry.grid(row=1, column=1, padx=5, pady=5 ) # вставка начальных данных name_entry.insert(0, "Kanat" ) surname_entry.insert(0, "Kulataev" ) display_button = Button(text="Display", command=display ) clear_button = Button(text="Clear", command=clear ) clear_button.grid(row=2, column=0, padx=5, pady=5, sticky="" ) display_button.grid(row=2, column=1, padx=5, pady=5, sticky="e" ) root.mainloop()
a0cb7e54077531cbcdf6ae61b9c846de87d68a37
KulataevKanat/PythonData
/GUI/elements/elementPositioning/pack/fill.py
776
3.5
4
from tkinter import * root = Tk() root.title("Fill Method") root.geometry("500x500") btn1 = Button(text="CLICK ME", background="#555", foreground="#ccc", padx="15", pady="6", font="15" ) btn1.pack(side=RIGHT, fill=Y ) btn2 = Button(text="!-?", bg="#555", fg="#ccc", padx="15", pady="6", font="15" ) btn2.pack(side=TOP, fill=X ) btn3 = Button(text="CLICK ME(2)", background="#555", foreground="#ccc", padx="15", pady="6", font="15" ) btn3.pack(side=RIGHT, fill=Y) root.mainloop()
84554e996c2ddf3894fff2a1112cd5318995ffb9
KulataevKanat/PythonData
/structures/modules/randomModule.py
610
3.875
4
import random print("random() - (0.0 до 1.0)): ") number = random.random() print(number) print("\nrandom() - (0.0 до 100.0)): ") number = random.random() * 100 print(number) print("\nrandint(min, max): ") number = random.randint(1, 13) print(number) print("\nrandrange(start, stop, step): ") number = random.randrange(10, 50, 5) print(number) print("\nchoice(): ") string = "I write in language {pl}" pl = list() pl.append("Java") pl.append("Python") pl.append("C++") pl.append("C") pl.append("Go") pl.append("PHP") random.shuffle(pl) plChoice = random.choice(pl) print(string.format(pl=plChoice))
51e1776e41d1f4f0a02a23eec982b9ef948430c0
alessioserra/Data_Science_Lab04
/default/__init__.py
2,101
3.5625
4
import numpy as np import matplotlib.pyplot as plt # using class import """ from default.KMeans import KMeans """ from sklearn.cluster import KMeans # EXERCISE 1 # read data set with numpy data = np.loadtxt("gauss_clusters.txt", delimiter=",", skiprows=1) x = [x for x, y in data] # saving all x and y in different vectors y = [y for x, y in data] # scanner plot colors = np.random.rand(len(data)) plt.scatter(x, y, c=colors, alpha=0.5) plt.show() """ # GO function klusters = KMeans(15, 100) k = klusters.fit_predict(data) klusters.dump_to_file("result.csv", k, x, y) # EXERCISE 2 data2 = np.loadtxt("camaleon_clusters.txt", delimiter=",", skiprows=1) x2 = [x for x, y in data2] # saving all x and y in different vectors y2 = [y for x, y in data2] # scanner plot colors = np.random.rand(len(data2)) plt.scatter(x2, y2, c=colors, alpha=0.5) plt.show() # GO function klusters = KMeans(15, 100) k2 = klusters.fit_predict(data2) klusters.dump_to_file("result.csv", k2, x2, y2) """ """ # Update: using Sci-Kit """ n = 15 n_clusters = n km = KMeans(n_clusters) pred = km.fit_predict(data) klusters = {} # empty dictionary # create index for klusters for i in range(n): klusters[str(i)] = [] # Union data and respective clusters: for point, k in zip(data, pred): klusters[str(k)].append(point) fig1, ax2 = plt.subplots(figsize=(8, 5)) cmap = plt.cm.get_cmap("hsv", n) for key in klusters.keys(): xx = [xx for xx, yy in klusters[key]] yy = [yy for xx, yy in klusters[key]] ax2.scatter(xx, yy, cmap(klusters[key])) """ Exercise 1.6 """ centroids = [] for key in klusters.keys(): xx = [x for x, y in klusters[key]] yy = [y for x, y in klusters[key]] xc = np.average(xx) yc = np.average(yy) centroid = [xc, yc] centroids.append(centroid) xc = [xx for xx, yy in centroids] yc = [yy for xx, yy in centroids] area = 30 ax2.scatter(xc, yc, c="black", s=area, marker="*") plt.show()
13ad5d8eadfd88a79fc51d5d5fb9ad808e735904
Mouzouris/AI-project
/AI.py
24,739
3.515625
4
#This is the part 1 Assignment of Foundations of AI COMP #initialised the board in the state that each location within the baord had a corresponding value such as # ---- ---- ---- ---- # | 0 | 1 | 2 | 3 | # ---- ---- ---- ---- # | 4 | 5 | 6 | 7 | # ---- ---- ---- ---- # | 8 | 9 | 10 | 11 | # ---- ---- ---- ---- # | 12 | 13 | 14 | 15 | # ---- ---- ---- ---- import math import random #Starting positions of the tiles and the agent TileA = 5 TileB = 9 TileC = 12 Agent = 15 #creating and inputting the values that are corresponding to the tiles and agent 1=Tile1, 2=Tile2, 3=Tile3, 9=Agent StartState = [] for i in range(0,16): if i==TileA: StartState.append(1) elif i==TileB: StartState.append(2) elif i==TileC: StartState.append(3) elif i==Agent: StartState.append(9) else: StartState.append(0) print(StartState) #This are the different situatins that a goal state has been identified #where the agent is in all the positions beside the ones where the tiles should be GoalState0 = [9,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0] GoalState1 = [0,9,0,0,0,1,0,0,0,2,0,0,0,3,0,0] GoalState2 = [0,0,9,0,0,1,0,0,0,2,0,0,0,3,0,0] GoalState3 = [0,0,0,9,0,1,0,0,0,2,0,0,0,3,0,0] GoalState4 = [0,0,0,0,9,1,0,0,0,2,0,0,0,3,0,0] GoalState5 = [0,0,0,0,0,1,9,0,0,2,0,0,0,3,0,0] GoalState6 = [0,0,0,0,0,1,0,9,0,2,0,0,0,3,0,0] GoalState7 = [0,0,0,0,0,1,0,0,9,2,0,0,0,3,0,0] GoalState8 = [0,0,0,0,0,1,0,0,0,2,9,0,0,3,0,0] GoalState9 = [0,0,0,0,0,1,0,0,0,2,0,9,0,3,0,0] GoalState10 = [0,0,0,0,0,1,0,0,0,2,0,0,9,3,0,0] GoalState11 = [0,0,0,0,0,1,0,0,0,2,0,0,0,3,9,0] GoalState12 = [0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,9] # Class for Node to reference aupon within the algorithm # the necessary variables are state,its parent, action, cost of movement and depth of node class Node: def __init__( self, state, parent, action, cost, depth): self.state = state self.parent = parent self.action = action self.cost = cost self.depth = depth #Special case for A * - same as class Node plus storing the result of the heuristic function class AstarNode: def __init__( self, state, parent, action, cost, depth, h_cost): self.state = state self.parent = parent self.action = action self.cost = cost self.depth = depth self.h_cost = h_cost #Function for movement def movement (state, direction): NEW_STATE=list(state) # generate the list of the tiles AgentPos = NEW_STATE.index(9) #identify the agent position and assign it #if the agent goes up if direction == "up": if AgentPos not in [0,1,2,3]: # if it's not in the top range do AgentNewPos = NEW_STATE[AgentPos - 4] # assign new positions # move agent up NEW_STATE[AgentPos - 4] = NEW_STATE[AgentPos] # Replace the tile that the agent was located with NewPostion NEW_STATE[AgentPos] = AgentNewPos return NEW_STATE #return the new state of the agent # if the agent goes down if direction == "down": if AgentPos not in [12,13,14,15]: # if it's not in the bottom range do AgentNewPos = NEW_STATE[AgentPos + 4] # assign new positions # move agent down NEW_STATE[AgentPos + 4] = NEW_STATE[AgentPos] # Replace the tile that the agent was located with NewPostion NEW_STATE[AgentPos] = AgentNewPos return NEW_STATE #return the new state of the agent #if the agent goes left if direction == "left": if AgentPos not in [0,4,8,12]: # if it's not in the left-most range do AgentNewPos = NEW_STATE[AgentPos - 1] # assign new positions #move agent left NEW_STATE[AgentPos - 1] = NEW_STATE[AgentPos] # Replace the tile that the agent was located with NewPostion NEW_STATE[AgentPos] = AgentNewPos return NEW_STATE #return the new state of the agent # if the agent moves right if direction == "right": if AgentPos not in [3,7,11,15]: # if it's in the right-most range do AgentNewPos = NEW_STATE[AgentPos + 1] # assign new positions #move agent right NEW_STATE[AgentPos + 1] = NEW_STATE[AgentPos] # if it's not in the bottom range do NEW_STATE[AgentPos] = AgentNewPos return NEW_STATE #return the new state of the agent #else do nothing else: return None #define the board state and accordingly the positions def Board(state): #copy the current list Copylist = state[:] #identify locations of tiles and agent tilea = Copylist.index(1) tileb = Copylist.index(2) tilec = Copylist.index(3) agent = Copylist.index(9) #where tiles and agent found replace visually Copylist[tilea] = 'A' Copylist[tileb] = 'B' Copylist[tilec] = 'C' Copylist[agent] = '*' Copylist = [ x if x!= 0 else " " for x in Copylist ] #print the board print ("-----------------") print ("| %s | %s | %s | %s |" % (Copylist[0], Copylist[1], Copylist[2], Copylist[3])) print ("-----------------") print ("| %s | %s | %s | %s |" % (Copylist[4], Copylist[5], Copylist[6], Copylist[7])) print ("-----------------") print ("| %s | %s | %s | %s |" % (Copylist[8], Copylist[9], Copylist[10], Copylist[11])) print ("-----------------") print ("| %s | %s | %s | %s |" % (Copylist[12], Copylist[13], Copylist[14], Copylist[15])) print ("-----------------") #Visualise the sequence of movement for the agent in order to reach the solution def visualiase_movement(move,state): #copy the list of the state new_list_state = list(state) #initialise new position NewPosition = list(new_list_state) #set the new state, depending on the movement if move == "up": NewPosition = movement( new_list_state, "up" ) elif move == "down": NewPosition = movement( new_list_state, "down" ) elif move == "left": NewPosition = movement( new_list_state, "left" ) elif move == "right": NewPosition = movement( new_list_state, "right" ) #return the new state return NewPosition #Expand node with the possible movements #append to the list the several nodes that will be displayed on expandsion based on the movement used based on the values (state,parent,action,cost,depth) #for each movement towards the goal expand the node and alter the successors in order to find the solution and also increase the depth and cost by 1 def ExpandNode (node): Expanded=[] #Initilise list of succesors Expanded.append( Node( movement(node.state, "up" ), node, "up", node.cost + 1, node.depth + 1 )) Expanded.append( Node( movement(node.state, "down" ), node, "down",node.cost + 1, node.depth + 1 )) Expanded.append( Node( movement(node.state, "left" ), node, "left",node.cost + 1, node.depth + 1 )) Expanded.append( Node( movement(node.state, "right" ), node, "right",node.cost + 1, node.depth + 1 )) Expanded = [node for node in Expanded if node.state != None] #remove the ones with no movement return Expanded #randmisation function def shuffle (node): random.shuffle(node) return node #Expand node while include the heuristic cost for astar2 def ExpandNodeAstar2( node,goal ): Expanded = [] Expanded.append( AstarNode( movement( node.state, "up" ), node, "up", node.cost + 1, node.depth + 1, h2(movement( node.state, "up" ), goal) ) ) Expanded.append( AstarNode( movement( node.state, "down" ), node, "down", node.cost + 1, node.depth + 1, h2(movement( node.state, "down" ), goal) ) ) Expanded.append( AstarNode( movement( node.state, "left" ), node, "left", node.cost + 1, node.depth + 1, h2(movement( node.state, "left" ), goal) ) ) Expanded.append( AstarNode( movement( node.state, "right" ), node, "right", node.cost + 1, node.depth + 1, h2(movement( node.state, "right" ), goal) ) ) Expanded = [node for node in Expanded if node.state != None] return Expanded #Expand node while include the heuristic cost for astar1 def ExpandNodeAstar (node): Expanded=[] Expanded.append(AstarNode(movement( node.state, "up"),node, "up", node.cost + 1, node.depth+1, AddDepth(node,h1(node.state)))) Expanded.append(AstarNode(movement( node.state, "down"),node, "down", node.cost + 1, node.depth+1, AddDepth(node,h1(node.state)))) Expanded.append(AstarNode(movement( node.state, "left"),node, "left", node.cost + 1, node.depth+1, AddDepth(node,h1(node.state)))) Expanded.append(AstarNode(movement( node.state, "right"),node, "right", node.cost + 1, node.depth+1, AddDepth(node,h1(node.state)))) Expanded = [node for node in Expanded if node.state != None] return Expanded def Comparison(child, explored, Fringe): for i in range(0,len(explored)): if child.state == explored[i].state: return True for i in range(0,len(Fringe)): if child.state == Fringe[i].state: return True return False def bfs(start): #initialise the list of the nodes to be expanded Fringe = [] #initilise list of explored nodes. explored = [] #initilise list to input moves if solution found. moves = [] #set boolean for braking loop bottom = 1 #Append Initial State Fringe.append( Node( start, None, None, 0, 0 ) ) while bottom != 0: #if bottom has been reached and no more nodes to left to use if len( Fringe ) == 0: bottom = 0 # brake loop return None, len(explored) #return the length of the explored values. #use the first node of the Fringe node = Fringe.pop(0) #check if it's in any state of a goal(s) if node.state == GoalState0 or node.state == GoalState1 or node.state == GoalState2 or node.state == GoalState3 or node.state == GoalState4 or node.state == GoalState5 or node.state == GoalState6 or node.state == GoalState7 or node.state == GoalState8 or node.state == GoalState9 or node.state == GoalState10 or node.state == GoalState11 or node.state == GoalState12: #if goal as been reached do while True: # insert into list the action taken moves.insert(0, node.action) # if the state is right after initialstate if node.depth == 1: # brake loop break # swap place of the child with the parent node = node.parent # terminate while loop bottom = 0 # return moves plus nodes expanded/explored return moves, len(explored) # append the explored to the list explored explored.append(node) #explore the children and for each child append to Fringe children = ExpandNode(node) for child in children: #if not Comparison(child, explored, Fringe): #for graph search Fringe.append(child) print('nodes expanded', len(explored)) print("BFS with depth: " + str(child.depth)) actionsdone = [] actionsdone.insert(0, child.action) print(actionsdone) Board(child.state) #For Depth First Search def dfs(start): #same logic with breadth first search,although the function used to insert into the fringe i used insert #this was done in order to choose the initial position to append the childs in order to enable Depth-First-Search #in this case, the last node of the stack must be expanded Fringe = [] explored = [] moves = [] bottom = 1 Fringe.append( Node( start, None, None, 0, 0 ) ) #implimented a user input algorithm to enable the user wether he/she wants to choose the randomisation function or not. rndmchoices = input("1) Without Randomisation 2) With Randomisation:") while rndmchoices not in ['1','2']: print("you have not inputted the correct choice valid input is 1/2") rndmchoices = input("1) Without Randomisation 2) With Randomisation:") else: while bottom!= 0: if len( Fringe ) == 0: bottom = 0 return None, len(explored) # use the first node of the lstack (LIFO) node = Fringe.pop(0) if node.state == GoalState0 or node.state == GoalState1 or node.state == GoalState2 or node.state == GoalState3 or node.state == GoalState4 or node.state == GoalState5 or node.state == GoalState6 or node.state == GoalState7 or node.state == GoalState8 or node.state == GoalState9 or node.state == GoalState10 or node.state == GoalState11 or node.state == GoalState12: while True: moves.insert(0, node.action) if node.depth == 1: break node = node.parent bottom = 0 return moves, len(explored) explored.append(node) if rndmchoices == '1': children = ExpandNode(node) if rndmchoices == '2': children = shuffle(ExpandNode(node)) #i is the indicator where the child will be saved and iterates through it until all childs are inserted. i = 0 for child in children: #if not Comparison(child, explored, Fringe): for Graph search Fringe.insert(i,child) i+=1 print('nodes expanded', len(explored)) print("DFS with depth: " + str(child.depth)) Board(child.state) def dls( start, depth ): #depth limited search implimented with a value supplied at the call of the function of 5000 limit = depth Fringe = [] explored = [] moves =[] bottom = 1 Fringe.append( Node( start, None, None, 0, 0 ) ) while bottom != 0: if len( Fringe ) == 0: bottom = 0 return None, len(explored) node = Fringe.pop(0) if node.state == GoalState0 or node.state == GoalState1 or node.state == GoalState2 or node.state == GoalState3 or node.state == GoalState4 or node.state == GoalState5 or node.state == GoalState6 or node.state == GoalState7 or node.state == GoalState8 or node.state == GoalState9 or node.state == GoalState10 or node.state == GoalState11 or node.state == GoalState12: while True: moves.insert(0, node.action) if node.depth == 1: break node = node.parent bottom = 0 return moves, len(explored) #until the limit has been reached iterate through the following if node.depth < limit: explored.append(node) children = ExpandNode(node) for child in children: #if not Comparison(child, explored, Fringe): #for graph search Fringe.insert(0,child) print('nodes expanded', len(explored)) print("With depth: " + str(child.depth)) Board(child.state) def ids( start, depth ): #Keep the expansion of the nodes even though displaying otherwise AllExpanded = 0 #iterate the dls function for each depth until it reaches the limit that the user gives for i in range( depth + 1 ): #adding one since it starts from 0 to reach the approrpiate depth result, amount = dls( start, i ) #increment by amount AllExpanded += amount #if the goal has beeen reached present the if result != None: return result, AllExpanded break #if the goal is not reached, when the depth is reached present the following expansion if result == None: return result, AllExpanded #faster algorithm for astar def astar1(start): Fringe = [] moves = [] explored = [] bottom = 1 Fringe.append(AstarNode(start, None,None,0,0,h1(start))) #similar to normal Node although we also supply heauristics cost. while bottom!= 0: #iterative loop for the end of the expansion. if len(Fringe)== 0: bottom = 0 return None, len(explored) Fringe = sorted(Fringe, key=lambda node: node.h_cost) # sorting according to the heurstics provided h_cost node = Fringe.pop(0) #using the first(lowest) value possible to fid the answer. if node.state == GoalState0 or node.state == GoalState1 or node.state == GoalState2 or node.state == GoalState3 or node.state == GoalState4 or node.state == GoalState5 or node.state == GoalState6 or node.state == GoalState7 or node.state == GoalState8 or node.state == GoalState9 or node.state == GoalState10 or node.state == GoalState11 or node.state == GoalState12: while True: #following the same routine as the other algorythms to expand the nodes and append the output. moves.insert(0, node.action) if node.depth == 1: break node = node.parent bottom = 0 return moves, len(explored) explored.append(node) children = ExpandNodeAstar(node) # using specialised expansion that includes the first heurstic h1 for child in children: # if not Comparison(child, explored, Fringe): #for graph search Fringe.append(child) print('nodes expanded', len(explored)) print("astar1 with depth: " + str(child.depth)) Board(child.state) # heuristic one function takes the values of the current state and based on their goal position a heuristic is drawn # from the tiles that are misplaces so 0 is goal state 1,2,3 #alsong with the distance of the tile from its goal state #these values are then added to produce a heursitic score to use for helping the algorithm. def h1(state): Misplaced = 0 Distance = 0 if state[5] != 1: Misplaced+=1 Distance += math.fabs(state.index(1)-5) if state[9] != 2: Misplaced+=1 Distance += math.fabs(state.index(2)-9) if state[13] != 3: Misplaced+=1 Distance += math.fabs(state.index(3)-13) Heuristic=Distance+Misplaced print(Heuristic) return Heuristic #function used to incorporate depth within algorithm1 def AddDepth(node, heuristic): AddDepth = (node.depth + heuristic) return AddDepth def astar2(start, goal): Fringe = [] moves = [] explored = [] bottom = 1 #insert the initial state Fringe.append( AstarNode( start, None, None, 0, 0, h2( start, goal ) ) ) while bottom!= 0: if len(Fringe)== 0: return None, len(explored) #same as previously although this time also incorporating the depth and the heursitic cost of the state of the algorithm Fringe = sorted(Fringe, key=lambda node: node.depth + node.h_cost) node = Fringe.pop(0) if node.state == GoalState0 or node.state == GoalState1 or node.state == GoalState2 or node.state == GoalState3 or node.state == GoalState4 or node.state == GoalState5 or node.state == GoalState6 or node.state == GoalState7 or node.state == GoalState8 or node.state == GoalState9 or node.state == GoalState10 or node.state == GoalState11 or node.state == GoalState12: while True: moves.insert(0, node.action) if node.depth == 1: break node = node.parent bottom = 0 return moves, len(explored) explored.append(node) children = ExpandNodeAstar2(node,goal) for child in children: #if not Comparison(child, explored, Fringe): #for grah search Fringe.append(child) print('nodes expanded', len(explored)) print("astar2 with depth: " + str(child.depth)) Board(child.state) def h2( state, goal ): #if no state identified if state == None: return None else: Heuristic = 0 #find position of current and goal state Currentstate = find_index( state ) ar,ac,br,bc, cr, cc = find_index( state ) print(Currentstate) #for debug Setgoal = find_index( goal ) gar,gac,gbr,gbc, gcr, gcc = find_index( goal ) print(Setgoal) #for debug #for i in range(len(Currentstate)): multiplies and enhances algorithm Heuristic += abs(gar-ar) + abs(gac-ac) #for tilea Heuristic += abs(gbr-br) + abs(gbc-bc) #for tileb Heuristic += abs(gcr-cr) + abs(gcc-cc) #for tilec print(Heuristic) return Heuristic #find the place of each tile in the board in order to ssist the heuristic2 def find_index(node): TileA = node.index(1) TileB = node.index(2) TileC = node.index(3) #set the row and the colum for each tile RowA, ColumnA = FindRowColumn( TileA ) RowB, ColumnB = FindRowColumn( TileB ) RowC, ColumnC = FindRowColumn( TileC ) return list([RowA, ColumnA, RowB, ColumnB, RowC, ColumnC]) def FindRowColumn(state): #initialise row and column row = 0 column = 0 #if the tile is in the first row if state in [0,1,2,3]: row = 0 #if the tiles is in the second row elif state in [4,5,6,7]: row = 1 #if the tiles is in the third row elif state in [8,9,10,11]: row = 2 #if the tiles is in the fourth row elif state in [12,13,14,15]: row = 3 if state in [0,4,8,12]: column = 0 elif state in [1,5,9,13]: column = 1 elif state in [2,6,10,14]: column = 2 elif state in [3,7,11,15]: column = 3 #return the number of the row and column return row, column goal = GoalState12 depth = 14 nodes =[] choices = "" choices = input("Which Algorithm: 1) BFS 2) DFS 3) DLS 4) IDS 5) A* 6) A*-2 7) Exit :") while choices not in ['1','2','3','4','5', '6', '7']: print("you have not inputted the correct choice valid input is 1/2/3/4/5/6 or 7 for Exit") choices = input("Which Algorithm: 1) BFS 2) DFS 3) DLS 4) IDS 5) A* 6) A*-2 7) Exit :") else: if choices == '1': result, amount = bfs(StartState) print("the moves are ", (result)) print("the amount of iterations ", amount ) elif choices == '2': result, amount = dfs(StartState) print("the moves are ", (result)) print("the amount of iterations ", amount ) elif choices == '3': result, amount = dls(StartState, depth) #print("the moves are ", (result)) #for debug print("the amount of iterations ", amount ) elif choices == '4': result, amount = ids(StartState, depth) print("the moves are ", (result)) print("the amount of iterations ", amount ) elif choices == '5': result, amount = astar1(StartState) print("the moves are ", (result)) print("the amount of iterations ", amount ) elif choices == '6': result, amount = astar2(StartState, goal) print("the moves are ", (result)) print("the amount of iterations ", amount ) elif choices == '7': print("See Ya!") if choices in ['1','2','4','5','6']: nodes.append(amount) if result == None: print("This search method didn't solve the problem") else: print(len(result), "moves") Board(StartState) for iter in range(len(result)): if iter == 0: a = visualiase_movement(result[iter],StartState) Board(a) elif iter == 1: temp = a b = visualiase_movement(result[iter], temp) c = b Board(c) else: temp = c b = visualiase_movement(result[iter], temp) c = b Board(c) print("the moves are ", (result)) print("the amount of iterations ", amount ) print('the solution is visualised above')
7418a205641f3a6c09c71b3d8bd5c95b6947fae5
chrhsmt/system_programming
/3/match_ends.py
334
3.609375
4
def match_ends(li): # resultList = filter(lambda w: # (len(w) >=2 and w[0] == w[-1]), li) # return len(resultList) return len([x for x in li if len(x) >= 2 and x[0] == x[-1]]) print match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']) print match_ends(['', 'x', 'xy', 'xyx', 'xx']) print match_ends(['aaa', 'be', 'abc', 'hello'])
ed57fc7bbf77ac2f9439bd2905a4a59fa7d8d93a
new-silvermoon/RecreationalMaths
/sumofcubes.py
2,005
4.03125
4
""" There is a popular conjecture in Maths which states that numbers that can be expressed as a sum of three cubes of integers, allowing both positive and negative cubes in the sum. Refer https://en.wikipedia.org/wiki/Sums_of_three_cubes Andrew Booker wrote an algorithm in March 2019 in order to find the result for number 33. Refer https://www.youtube.com/watch?v=ASoz_NuIvP0 This code takes stab at Andrew's algorithm in a Pythonic way. """ import threading import itertools import math value = 3 bound = 10**3 xy_list = [] xy_lock = threading.RLock def generate_xy_combinations(): """ |x|, |y| <= bound :return: Generates all the possible integer combination for x and y """ global xy_list data = list(range(-(bound),bound+1)) xy_list = [p for p in itertools.product(data, repeat=2)] print("Length of permutation "+str(len(xy_list))) iLen = math.floor(len(xy_list) / 4) threading.Thread(target=calculate_z,args=(xy_list[0:iLen],1,)).start() threading.Thread(target=calculate_z, args=(xy_list[iLen:iLen+iLen], 2,)).start() threading.Thread(target=calculate_z, args=(xy_list[iLen + iLen:iLen + iLen + iLen], 3,)).start() threading.Thread(target=calculate_z, args=(xy_list[iLen + iLen +iLen:len(xy_list)], 4,)).start() def calculate_z(xy_list,i): """ :param xy_list: List of x,y tuples :param i: Thread index :return: Calculates z and prints the result if it matches with value """ print("Running thread "+str(i)) global value for item in xy_list: x, y = item d = x + y if d == 0: continue interm_val = x**2 - (x*y) + y**2 for z in range(-(bound),bound+1): if (value - z**3)/d == interm_val: print("Result found using x= "+str(x)+" y= "+str(y)+" z= "+str(z)+" in thread "+str(i)) print("Thread "+str(i)+" completed.") if value % 9 == 4 or value % 9 == 5: print("Not possible") exit() generate_xy_combinations()
18567c0c63270e54bc8a42310dea5f2c58baca18
manjulive89/JanuaryDailyCode2021
/DailyCode01282021.py
500
4.03125
4
# --------------------------------------------------------- # Daily Code 01/28/2021 # "Convert Minutes into Seconds" Lesson from edabit.com # Coded by: Banehowl # --------------------------------------------------------- # Write a function that takes an integer minutes and converts it to seconds # convert(5) -> 300 # convert(3) -> 180 # convert(2) -> 120 def convert(minutes): seconds = minutes * 60 return(seconds) print convert(5) print convert(3) print convert(2)
68fc5fd6c86607595d5eb547218c7a55781f3389
manjulive89/JanuaryDailyCode2021
/DailyCode01092021.py
1,381
4.5625
5
# ------------------------------------------- # Daily Code 01/09/2021 # "Functions" Lesson from learnpython.org # Coded by: Banehowl # ------------------------------------------- # Functions are a convenient way to divide your code into useful blocks, allowing order in the code, make it # more readable, reuse it, and save some time. Also fuctions are a key way to define interfaces so # programmers can share their code. # How to write functions in Python def my_function(): # Functions are define using the block keyword "def" print("Hello From My Function!") # Functions may also receive arguments (variables passed from the caller to the function) def my_function_with_args(username, greeting): print("Hello, %s, From My Function! I wish you %s" % (username, greeting)) # Fuctions may return a value to the caller, using the keyword "return" def sum_two_number(a, b): return a + b # To call functions in Python, simply write teh function's the name followed by (), placing any required # arguments within the bracket. Using the previous functions we defined: # print(a simple greeting) my_function() # prints - "Hello, Joe Doe, From My Function! I wish you a great year!" my_function_with_args("John Doe", "a great year!") # after this line x will hold the value 3 x = sum_two_number(1, 2) print(x)
9d1b835fd8b5e6aeadb4ff23d54c2bc0b5435b2f
manjulive89/JanuaryDailyCode2021
/DailyCode01202021.py
1,831
4.3125
4
# ----------------------------------------------- # Daily Code 01/20/2021 # "Serialization" Lesson from learnpython.org # Coded by: Banehowl # ----------------------------------------------- # Python provides built-in JSON libraries to encode and decode JSON # Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module is used. # In order to use the json module, it must be imported: import json # There are two basic formats for JSON data. Either in a string or the object datastructure. # The object datastructure, in Python, consists of lists and dictionaries nested inside each other. # The object datastructure allows one to use python methods (for lists and dictionaries) to add, list, # search and remove elements from the datastructure. # # The String format is mainly used to pass the data into another program or load into a datastructure. # To load JSON back to a data structure, use the "loads" method. This method takes a string and turns # it back into the json object datastructure. To encode a data structure to JSON, use the "dumps" method. # This method takes an object and returns a String: json_string = json.dumps([1, 2, 3, "a", "b", "c"]) print(json.loads(json_string)) # Sample Code using JSON: # import json #it's already imported so... # fix this function, so it adds the given name # and salary pair to salaries_json, and return it def add_employee(salaries_json, name, salary): salaries = json.loads(salaries_json) salaries[name] = salary return json.dumps(salaries) # test code salaries = '{"Alfred" : 300, "Jane" : 400 }' new_salaries = add_employee(salaries, "Me", 800) decoded_salaries = json.loads(new_salaries) print(decoded_salaries["Alfred"]) print(decoded_salaries["Jane"]) print(decoded_salaries["Me"])
5cac576e1c3b2e1ecd67bfd71ab20bc765b4eee3
jtm192087/Assignment_8
/ps1.py
960
4.46875
4
#!/usr/bin/python3 #program for adding parity bit and parity check def check(string): #function to check for a valid string p=set(string) s={'0','1'} if s==p or p=={'0'} or p=={'1'}: print("It is a valid string") else: print("please enter again a valid binary string") if __name__ == "_main_" : string=input("please enter a valid binary string\n") check(string) #calling check function substring='1' count=string.count(substring) print("count is:",count) if count%2==0: #to add parity bit at the end of the binary data if no. one,s is even string=string+'1' print("The parity corrected data is: ",string) #print corrected data else: string=string+'0' print("The parity corrected data is: ",string) print("\n") string2=string.replace("010","0100") #replacing the '010' substring by '0100' print("The transmitting data is: ",string2)
078ca69e4955028b2c0cedc634b1d3ec0353cc62
VishwasShetty/Python
/cal.py.py
5,354
3.96875
4
#Auther:Vishwas Shetty #Programming Language:Python 3 #Progarm:To Create Simple Calculator #Start Date:30-11-2019 #End Date:1-12-2019 import tkinter from tkinter import* from tkinter import messagebox val="" num1=0 num2=0 operator="" res=0 flag=0; def button_clicked(n): global val val=val+str(n) value.set(val) def operator_clicked(op): global operator global val global num1 global flag # if flag==0: operator=op num1=int(val) flag=1 val=val+op value.set(val) # else: # equal_clicked() # flag=0 # operator="" # return operator_clicked(op) #operator="" #operator=op #num1=int(val) #val=val+operator #value.set(val) def equal_clicked(): global val global operator global num1 global num2 global res #global flag if operator=="+": num2=int(val.split("+")[1]) res=num1+num2 val="" val=str(res) value.set(val) if operator=="-": num2=int(val.split("-")[1]) res=num1-num2 val="" val=str(res) value.set(val) if operator=="/": num2=int(val.split("/")[1]) if num2==0: messagebox.showerror("Error","cannot devisible by zero") num1="" #flag=0 val="" value.set(val) else: #res=round(num1/num2,2) res=int(num1/num2) val="" val=str((res)) value.set(val) if operator=="*": num2=int(val.split("*")[1]) res=num1*num2 val="" val=str(res) value.set(val) def clearButton_clicked(): global num1 global val global flag #flag=0 num1="" val="" value.set(val) root=tkinter.Tk() root.geometry("250x400+300+300") root.title("Calculator") root.resizable(10,10) value=StringVar() label1=Label( root, text="", anchor=SE, bg="#ffffff", fg="#000000", font=("verdana",20), textvariable=value, ) label1.pack(expand=True,fill="both") btnrow1=Frame(root,bg="cyan") btnrow1.pack(expand=True,fill="both") btnrow2=Frame(root) btnrow2.pack(expand=True,fill="both") btnrow3=Frame(root,bg="cyan") btnrow3.pack(expand=True,fill="both") btnrow4=Frame(root) btnrow4.pack(expand=True,fill="both") #button row 1 buttons btn1=Button( btnrow1, text="1", font=("verdana",22) ,border="0",bg="cyan", relief=GROOVE, command=lambda:button_clicked(1) ) btn1.pack(side=LEFT,expand=True,fill="both") btn2=Button( btnrow1, text="2", font=("verdana",22) ,border="0",bg="cyan", command=lambda:button_clicked(2), ) btn2.pack(side=LEFT,expand=True,fill="both") btn3=Button( btnrow1, text="3", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(3), ) btn3.pack(side=LEFT,expand=True,fill="both") btn4=Button( btnrow1, text="4", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(4), ) btn4.pack(side=LEFT,expand=True,fill="both") #button row 2 buttons btn5=Button( btnrow2, text="5", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(5), ) btn5.pack(side=LEFT,expand=True,fill="both") btn6=Button( btnrow2, text="6", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(6), ) btn6.pack(side=LEFT,expand=True,fill="both") btn7=Button( btnrow2, text="7", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(7), ) btn7.pack(side=LEFT,expand=True,fill="both") btn8=Button( btnrow2, text="8", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(8), ) btn8.pack(side=LEFT,expand=True,fill="both") #btnrow3 buttons btn9=Button( btnrow3, text="9", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(9), ) btn9.pack(side=LEFT,expand=True,fill="both") btn10=Button( btnrow3, text="0", font=("verdana",22),border="0",bg="cyan", command=lambda:button_clicked(0), ) btn10.pack(side=LEFT,expand=True,fill="both") btnplus=Button( btnrow3, text="+", font=("verdana",19),border="0",bg="cyan", command=lambda:operator_clicked("+"), ) btnplus.pack(side=LEFT,expand=True,fill="both") btnminus=Button( btnrow3, text="-", font=("verdana",24),border="0",bg="cyan" ,command=lambda:operator_clicked("-"), ) btnminus.pack(side=LEFT,expand=True,fill="both") #btnrow4 buttons btndiv=Button( btnrow4, text="/", font=("verdana",23),border="0",bg="cyan" ,command=lambda:operator_clicked("/"), ) btndiv.pack(side=LEFT,expand=True,fill="both") btnmul=Button( btnrow4, text="x", font=("verdana",22),border="0",bg="cyan" ,command=lambda:operator_clicked("*"), ) btnmul.pack(side=LEFT,expand=True,fill="both") btneq=Button( btnrow4, text="=", font=("verdana",18),border="0",bg="cyan", command=lambda:equal_clicked() ) btneq.pack(side=LEFT,expand=True,fill="both") btncls=Button( btnrow4, text="c", font=("verdana",22),border="0",bg="cyan", command=lambda:clearButton_clicked(), ) btncls.pack(side=LEFT,expand=True,fill="both") root.mainloop()
4a20648cdf7d4e19c953d7cc067392742788d8f9
huairenxiao99/myedu-1902
/day02/yunsuanfu.py
330
3.78125
4
def jisuan(a,b): print(a + b) print(a - b) print(a * b) print(a / b) # 取余 print(a % b) def dyu(a,b,c): print(a > b) print(a < b) print(a == b) print(a == c) print(a >= b) print(a <= b) print(a != b) if __name__ == '__main__': a = 10 b = 6 c = 10 pass
22b799170338c2e388892893eb7a9a8aa36f4082
saurabh-konpratiwar/heroku-st1
/penguins-app.py
1,559
3.609375
4
import streamlit as st import pandas as pd import pickle as pk import numpy as np pickle_in = open('model_pickle','rb') svc = pk.load(pickle_in) def prediction(Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age): prediction = svc.predict([[Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age]]) print(prediction) return prediction st.title("Diabetes Symptoms ") html_temp = """ <div style="background-color:orange; padding:10px"> <h2 style="color:red;text-align:center;">Streamlit Diabetes Predictor </h2> </div> """ st.markdown(html_temp, unsafe_allow_html=True) Pregnancies = st.number_input("Pregnancies") Glucose = st.number_input("Glucose") BloodPressure = st.number_input("BloodPressure") SkinThickness = st.number_input("SkinThickness") Insulin = st.number_input("Insulin") BMI = st.number_input("BMI") DiabetesPedigreeFunction = st.number_input("DiabetesPedigreeFunction") Age = st.number_input("Age") result = "" if st.button("Predict"): result = prediction(int(Pregnancies),int(Glucose),int(BloodPressure),int(SkinThickness),int(Insulin),float(BMI),float(DiabetesPedigreeFunction),int(Age)) print('result',result[0]) if result[0] == 1: result2 = 'patient has diabities' st.success('its seem {} and recommended you to go to your doctor '.format(result2)) else: result2 = 'patient does\'nt have diabities' st.error('The output is {}'.format(result2))
266b2250dbbc45c22395f3542f587a1a575dc4d8
Stengaffel/kattis
/heirsdilemma.py
999
3.59375
4
import sys # Checks if the digit dig apppears in the number x def check_digit(x, dig): while x > 0: if x % 10 == dig: return True x = x // 10 return False def find_nums(upper, lower, cur_num, nums, dec): if dec == 0: nums.append(cur_num) return for i in range(1,10): if check_digit(cur_num,i) == False and \ cur_num + i*dec >= ( lower // dec ) * dec: if cur_num + i*dec <= ( upper // dec ) * dec: find_nums(upper,lower,cur_num+i*dec,nums,dec//10) else: break return nums bounds = [int(x) for x in sys.stdin.readline().split()] upper = bounds[1] lower = bounds[0] nums = find_nums(upper,lower,0,[],10**5) count = 0 for n in nums: temp_num = n while temp_num > 0: if n % ( temp_num % 10 ) != 0: break temp_num = temp_num // 10 if temp_num == 0: count = count + 1 print('{}'.format(count))
c5d38f28962bbe6c0d4de9c12d16ff0be77fac3c
Stengaffel/kattis
/apaxiaaans.py
221
3.546875
4
import sys name = str( sys.stdin.readline() ).strip() new_name = '' cur_char = '' for ch in name: if cur_char == ch: continue else: new_name = new_name + ch cur_char = ch print(new_name)
1bcabc3abf05c755d74e36055f9a435b82cb2a32
Stengaffel/kattis
/reversebinary.py
741
3.859375
4
import sys # Returns an array containing the binary representation of the integer 'x' def create_binary(x): bin = [] cur_dig = 2**29 while cur_dig > 0: if x >= cur_dig: bin.append(1) x = x - cur_dig else: if len(bin) > 0: bin.append(0) cur_dig = cur_dig // 2 return bin # Returns an integer that is represented in binary in the array 'x' def binary_to_num(x): bi_num = 0 cur_dig = 2**( len(x)-1 ) for i in range(0,len(x)): bi_num = bi_num + x[i] * cur_dig cur_dig = cur_dig // 2 return bi_num num = int( sys.stdin.readline() ) bi_arr = create_binary(num) bi_arr.reverse() print(binary_to_num(bi_arr))
7f1558ee13bd336adda19c4750a3aaf0be4dd1e5
Stengaffel/kattis
/last_factorial_digit.py
284
3.6875
4
import sys def factorial(x): if x == 1: return 1 else: return x * factorial(x-1) limit = int(sys.stdin.readline()) nums = [] for i in sys.stdin: nums.append(int(i)) if len(nums) == limit: break for n in nums: print( factorial(n) % 10)
286682527cf109dfab6d8c42ae80616d3592623b
Gabrielgjs/python
/SalarioFuncionario.py
436
3.8125
4
salario = float(input('Qual é o salário do funcionário? R$')) aumento = salario * 0.10 aumento1 = salario * 0.15 if salario <= 1250: print(f'Quem ganhava R${salario:.2f} passa a ganhar R${salario+aumento1:.2f} agora') else: print(f'Quem ganhava R${salario:.2f} passa a ganhar R${salario+aumento:.2f} agora') '''if salario <= 1250: novo = salario + (salario * 15 / 100) else: novo = salario + (salario * 10 / 100)'''
71180623d83500bc518dfd6483fecc5e0149e25d
Gabrielgjs/python
/InteragindoComNome.py
408
3.96875
4
'''n = str(input('Digite seu nome completo: ')).strip() nome = n.split() print('Muito prazer em te conhecer!') print(f'Seu primeiro nome é {nome[0]}') print(f'Seu ultimo nome é {nome[len(nome)-1]}')''' n=str(input('Digite seu nome completo: ')).strip() nome=n.split() print('Muito prazer em te conhecer!') print('Seu primeiro nome é {}'.format(nome[0])) print('Seu último nome é {}'.format(nome[-1]))
a0c94fff02953dd66974b2476f299a4417e7605c
Gabrielgjs/python
/AnoAlistamento.py
600
4.1875
4
from datetime import date ano = int(input('Ano de nascimento: ')) atual = date.today().year alistamento = 18 idade: int = atual - ano print(f'Quem nasceu em {ano} tem {idade} anos em {atual}.') if idade == 18: print('voê tem que se alistar IMEDIATAMENTE!') elif idade > alistamento: saldo = idade - alistamento print(f'você deveria ter se alistado há {saldo} anos.') print(f'Seu alistamento foi em {atual - saldo}') elif idade < alistamento: saldo = alistamento - idade print(f'Seu alistamento será em {saldo} anos') print(f'Seu alistamento será em {atual + saldo}')
c6d6c93a737c4c29f95d7ab9310329ec65dfbd66
Gabrielgjs/python
/teste.py
1,359
3.984375
4
print('PESQUISA ESCOLA TRÂNSITO SEGURO') contador = 0 r1 = input('Se o farol está vermelho. você pode avançar com o carro ? (sim ou não)') if r1 == 'sim': print('Errou, pesquise o assunto!') elif r1 == 'não' : print('Acertou, vamos para a proxima pergunta') contador += 1 r2 = (input('se o farol está amarelo, você deve acelerar o carro para passar ? (sim ou não)')) if r2 == 'sim': print('Errou, pesquise o assunto!') elif r2 == 'não': print('Acertou, vamos para a proxima pergunta') contador += 1 r3 = input('se o farol está verde e não há nenhum pedestre atravessando, você pode avançar ? ( sim ou não)') if r3 == 'sim': print('Acertou, vamos para a proxima pergunta') contador += 1 elif r3 == 'não': print('Errou, pesquise o assunto! ') r4 = input('se o farol está verde e há pedestre atravessando, você pode avançar ? (sim ou não)') if r4 == 'sim': print('Errou, pesquise o assunto!') elif r4 == 'não': print('Acertou, vamos para a proxima pergunta') contador += 1 r5 = input('se o farol está vermelho, você deve parar o carro ? (sim ou não)') if r5 == 'sim': print('Acertou, vamos para a proxima pergunta') contador += 1 elif r5 == 'não': print('Errou, pesquise o assunto!') if contador > 3: print('Parabéns! você conhece as leis de trânsito!') print('FIM')
cdc09fd55f7cf9c6a408287f9fa5d2bec4832880
Gabrielgjs/python
/PrecoPassagem.py
383
4.0625
4
distancia = float(input('Qual é a distância da sua viagem? ')) print(f'Você está prestes a começar uma viagem de {distancia:.1f}km.') if distancia <= 200: print(f'O preço da sua passagem será R${distancia * 0.50}') elif distancia > 200: print(f'O preço da sua passagem será R${distancia * 0.45}') #preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
efca7b2a11ecafad103932c0d5a34335d354e7d8
gvogel03/Pygame
/test.py
9,806
3.5625
4
""" LESSON: 5.1 - Sprites EXERCISE: Code Your Own """ import pygame pygame.init() import tsk import random c = pygame.time.Clock() window = pygame.display.set_mode([1018, 573]) background = tsk.Sprite("SkyScrolling.jpg", 0, 0) image_sheet = tsk.ImageSheet("DragonFlying.png", 4, 6) dragon = tsk.Sprite(image_sheet, 0, 0) dragon.scale = .2 loop = True coin1 = tsk.Sprite("Coin.png", 100, 100) coin2 = tsk.Sprite("Coin.png", 100, 100) coin3 = tsk.Sprite("Coin.png", 100, 100) coin4 = tsk.Sprite("Coin.png", 100, 100) coin5 = tsk.Sprite("Coin.png", 100, 100) coin6 = tsk.Sprite("Coin.png", 100, 100) coin7 = tsk.Sprite("Coin.png", 100, 100) rock1 = tsk.Sprite("BigRock.png", 100, 100) rock2 = tsk.Sprite("BigRock.png", 100, 100) rock3 = tsk.Sprite("BigRock.png", 100, 100) rock4 = tsk.Sprite("BigRock.png", 100, 100) rock5 = tsk.Sprite("BigRock.png", 100, 100) rock6 = tsk.Sprite("BigRock.png", 100, 100) rock7 = tsk.Sprite("BigRock.png", 100, 100) rock8 = tsk.Sprite("BigRock.png", 100, 100) rock9 = tsk.Sprite("BigRock.png", 100, 100) collidable_6 = True collidable_7 = True rock2.scale = .2 rock3.scale = .2 rock4.scale = .2 rock5.scale = .2 coin1.scale = .2 coin2.scale = .2 coin3.scale = .2 coin4.scale = .2 rock5.scale = .2 rock6.scale = .2 rock7.scale = .2 rock8.scale = .2 rock9.scale = .2 rock1.scale = .2 coin6.scale = .2 coin7.scale = .2 collidable_5 = True coin5.scale = .2 inc = 5 count = 1 coins = 0 x = random.randint(0, 50) y = random.randint(20, 550) collidable_1 = True collidable_2 = True collidable_3 = True collidable_4 = True coin1.center_x = dragon.center_x + random.randint(250, 350) coin1.center_y = random.randint(20, 550) coin2.center_x = dragon.center_x + random.randint(550, 650) coin2.center_y = random.randint(20, 550) coin3.center_x = dragon.center_x + random.randint(850, 950) coin3.center_y = random.randint(20, 550) coin4.center_x = dragon.center_x + random.randint(1150, 1250) coin4.center_y = random.randint(20, 550) coin5.center_x = dragon.center_x + random.randint(1450, 1550) coin5.center_y = random.randint(20, 550) coin6.center_x = dragon.center_x + random.randint(1450, 1550) coin6.center_y = random.randint(20, 550) coin7.center_x = dragon.center_x + random.randint(1450, 1550) coin7.center_y = random.randint(20, 550) rock1.center_x = dragon.center_x + random.randint(350, 400) rock1.center_y = random.randint(20, 550) rock2.center_x = dragon.center_x + random.randint(450, 500) rock2.center_y = random.randint(20, 550) rock3.center_x = dragon.center_x + random.randint(550, 600) rock3.center_y = random.randint(20, 550) rock5.center_x = dragon.center_x + random.randint(650, 700) rock5.center_y = random.randint(20, 550) rock6.center_x = dragon.center_x + random.randint(750, 800) rock6.center_y = random.randint(20, 550) rock7.center_x = dragon.center_x + random.randint(850, 900) rock7.center_y = random.randint(20, 550) rock8.center_x = dragon.center_x + random.randint(950, 1000) rock8.center_y = random.randint(20, 550) rock9.center_x = dragon.center_x + random.randint(1050, 1100) rock9.center_y = random.randint(20, 550) game = True while game: while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: loop = False if tsk.is_key_down(pygame.K_UP): dragon.center_y -= 7 if tsk.is_key_down(pygame.K_DOWN): dragon.center_y += 7 if dragon.center_y > 630: dragon.center_y = 0 if dragon.center_y < 0: dragon.center_y = 573 if coins >= 5: inc = 5 + int(coins / 5) * 2 coin1.center_x -= inc coin2.center_x -= inc coin3.center_x -= inc coin4.center_x -= inc coin5.center_x -= inc coin6.center_x -= inc coin7.center_x -= inc rock1.center_x -= inc rock2.center_x -= inc rock3.center_x -= inc rock5.center_x -= inc rock4.center_x -= inc rock6.center_x -= inc rock7.center_x -= inc rock8.center_x -= inc rock9.center_x -= inc background.center_x -= 5 if background.center_x <= 0: background.center_x = 1018 if coin1.center_x < -50: coin1.center_x = dragon.center_x + random.randint(1020, 1050) coin1.center_y = random.randint(20, 550) coin1.visible = True collidable_1 = True if coin2.center_x < -50: coin2.center_x = dragon.center_x + random.randint(1020, 1050) coin2.center_y = random.randint(20, 550) coin2.visible = True collidable_2 = True if coin3.center_x < -50: coin3.center_x = dragon.center_x + random.randint(1020, 1050) coin3.center_y = random.randint(20, 550) coin3.visible = True collidable_3 = True if coin4.center_x < -50: coin4.center_x = dragon.center_x + random.randint(1020, 1050) coin4.center_y = random.randint(20, 550) coin4.visible = True collidable_4 = True if coin5.center_x < -50: coin5.center_x = dragon.center_x + random.randint(1020, 1050) coin5.center_y = random.randint(20, 550) coin5.visible = True collidable_5 = True if coin6.center_x < -50: coin6.center_x = dragon.center_x + random.randint(1020, 1050) coin6.center_y = random.randint(20, 550) coin6.visible = True collidable_6 = True if coin7.center_x < -50: coin7.center_x = dragon.center_x + random.randint(1020, 1050) coin7.center_y = random.randint(20, 550) coin7.visible = True collidable_7 = True if rock1.center_x < -50: rock1.center_x = dragon.center_x + 1018 rock1.center_y = random.randint(20, 550) if rock2.center_x < -50: rock2.center_x = dragon.center_x + 1018 rock2.center_y = random.randint(20, 550) if rock3.center_x < -50: rock3.center_x = dragon.center_x + 1018 rock3.center_y = random.randint(20, 550) if rock4.center_x < -50: rock4.center_x = dragon.center_x + 1000 rock4.center_y = random.randint(20, 550) if rock5.center_x < -50: rock5.center_x = dragon.center_x + 1000 rock5.center_y = random.randint(20, 550) if rock6.center_x < -50: rock6.center_x = dragon.center_x + 1000 rock6.center_y = random.randint(20, 550) if rock7.center_x < -50: rock7.center_x = dragon.center_x + 1000 rock7.center_y = random.randint(20, 550) if rock8.center_x < -50: rock8.center_x = dragon.center_x + 1000 rock8.center_y = random.randint(20, 550) if rock9.center_x < -50: rock9.center_x = dragon.center_x + 1000 rock9.center_y = random.randint(20, 550) if pygame.sprite.collide_rect(dragon, coin1): coin1.visible = False if collidable_1: coins += 1 collidable_1 = False if pygame.sprite.collide_rect(dragon, coin2): coin2.visible = False if collidable_2: coins += 1 collidable_2 = False if pygame.sprite.collide_rect(dragon, coin3): coin3.visible = False if collidable_3: coins += 1 collidable_3 = False if pygame.sprite.collide_rect(dragon, coin4): coin4.visible = False if collidable_4: coins += 1 collidable_4 = False if pygame.sprite.collide_rect(dragon, coin5): coin5.visible = False if collidable_5: coins += 1 collidable_5 = False if pygame.sprite.collide_rect(dragon, coin6): coin6.visible = False if collidable_6: coins += 1 collidable_6 = False if pygame.sprite.collide_rect(dragon, coin7): coin7.visible = False if collidable_7: coins += 1 collidable_7 = False if pygame.sprite.collide_rect(dragon, rock1): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock2): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock3): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock4): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock5): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock6): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock7): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock8): loop = False print("You Lose") if pygame.sprite.collide_rect(dragon, rock9): loop = False print("You Lose") background.draw() dragon.update(c.get_time()) dragon.draw() rock1.draw() rock2.draw() rock3.draw() rock4.draw() rock5.draw() coin1.draw() coin2.draw() coin3.draw() coin4.draw() coin5.draw() rock6.draw() rock7.draw() rock8.draw() rock9.draw() coin6.draw() coin7.draw() pygame.display.flip() c.tick(30) print ("You collected " + str(coins) + " coins!") print ("You made it to level " + str(int(coins/5) + 1)) game = False
bfdbcb6a7e055bae5fd9409e64597c8354af4753
morgulbrut/cookbook
/python/is_even/is_even.py
99
3.609375
4
#!/usr/bin/env python3 import is_odd def is_even(number): return not (is_odd.is_odd(number))
cafccf75a28b5f3c3460e7564a26e452414c86af
sindhu819/Greedy-2
/Problem-136.py
925
3.96875
4
''' Leetcode- 135. Candy - https://leetcode.com/problems/candy/ time complexity - O(N) space complexity - O(N) Approach - first we assign each child one candy each 2) Then we compare left neighbour, if it is greater then then we add 1 candy else it remains the same 3) Sameway we do compare the right neighbour ''' class Solution: def candy(self, nums: List[int]) -> int: m=len(nums) res=[1 for i in range(m)] #left neighbour for i in range(1,m,1): if nums[i]>nums[i-1]: res[i]=res[i-1]+1 print(res) #right neighbour for i in range(m-2,-1,-1): if nums[i]>nums[i+1]: res[i]=max(res[i],res[i+1]+1) print(res) #calulate sum sum=0 for i in range(len(res)): sum+=res[i] return sum
6e46e42ea4205b428807d2b960095074984916b5
tanvir362/Python
/binary_search_tree_traversal.py
2,433
3.6875
4
import sys pre_order_traversal_list = [] post_order_traversal_list = [] in_order_traversal_list = [] bfs_traversal_list = [] class Node: def __init__(self, n): self.value = n self.left = None self.right = None def insert(self, n): if n < self.value: if self.left: self.left.insert(n) else: new_node = Node(n) self.left = new_node else: if self.right: self.right.insert(n) else: new_node = Node(n) self.right = new_node def pre_order(self): # print(self.value, end=' ') pre_order_traversal_list.append(self.value) if self.left: self.left.pre_order() if self.right: self.right.pre_order() def post_order(self): if self.left: self.left.post_order() if self.right: self.right.post_order() # print(self.value, end=' ') post_order_traversal_list.append(self.value) def in_order(self): if self.left: self.left.in_order() # print(self.value, end=' ') in_order_traversal_list.append(self.value) if self.right: self.right.in_order() class BinarySearchTree: def __init__(self): self.root = None def insert(self, n): if self.root: self.root.insert(n) else: new_node = Node(n) self.root = new_node def pre_order_traversal(self): self.root.pre_order() # print() def post_order_traversal(self): self.root.post_order() # print() def in_order_traversal(self): self.root.in_order() # print() def bfs_traversal(self): q = [] q.append(self.root) while(len(q)): cur = q.pop(0) if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) # print(cur.value, end=' ') bfs_traversal_list.append(cur.value) # print() tree = BinarySearchTree() n = input() for i in input().split(): tree.insert(int(i)) tree.pre_order_traversal() tree.in_order_traversal() tree.post_order_traversal() tree.bfs_traversal() print(*pre_order_traversal_list) print(*in_order_traversal_list) print(*post_order_traversal_list) print(*bfs_traversal_list)
e2386b4c6fcb67f02c09f40ba80d3ce778517f9e
tanvir362/Python
/linked_list.py
841
3.953125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add(self, data): if not self.head: self.head = Node(data) return cur = self.head while cur.next: cur = cur.next cur.next = Node(data) def remove(self, data): if not self.head: return cur = self.head prev = self.head while cur: if cur.data == data: if prev: prev.next = cur.next else : prev = cur.next # cur.next = None return prev = cur cur = cur.next def traverse(self): if not self.head: return cur = self.head while cur: print(cur.data, end=" ") cur = cur.next print() linkedlist = LinkedList() for i in range(1, 11): linkedlist.add(i) linkedlist.traverse() linkedlist.remove(1) linkedlist.traverse()
a041b93fec1ef0dbe5051bd7ab62339e9693107b
tanvir362/Python
/bfs.py
617
3.5625
4
n = int(input()) e = int(input()) graph = {} vis = {} for i in range(e): u, v = [int(x) for x in input().split()] if u not in graph: graph[u] = [] if v not in graph: graph[v] = [] graph[u].append(v) graph[v].append(u) s = int(input()) q = [s] vis[s] = True print(graph) print(q) print(vis) print('start traversing bfs ---------') while len(q)>0: node = q.pop(0) print(node) for child in graph[node]: if not vis.get(child, False): print(child, end=" ") q.append(child) vis[child] = True print('\n------------')
60bfafee9e036355bd9c1384d5d48adf8cd805cf
ViFLara/Information-security
/client_tcp/tcpclient.py
814
3.5
4
import socket import sys def main(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) except socket.error as e: print("The connection has failed!") print("Error: {}" .format(e)) sys.exit() print("Socket successfully created") target_host = input("Type the host or Ip to be connected: ") target_port = input("Type the port to be connected: ") try: s.connect((target_host, int(target_port))) print("Tcp client successfully created on Host: " + target_host + " and Port: " + target_port) s.shutdown(2) except socket.error as e: print("Unable to connect to the Host: " + target_host + " - Port: " + target_port) print("Error: {}" .format(e)) sys.exit() if __name__ == '__main__': main()
740ed3e23a6f6d4531ae28fbd1efce9df17aef28
Kunal600/PythonMiniAssignments
/OverSalary.py
313
3.9375
4
#Program to calculate person Salary Hours = raw_input("Enter Hours:") Rate = raw_input("Enter Rate:") if float(Hours) > 40.0: over = float(Hours) - 40.0 Pay = 40.0 * float(Rate) + float(over) * 1.5 * float(Rate) print 'Pay:',Pay else: Pay = 40.0 * float(Rate) + float(over) print 'Pay:',Pay
be982a03905d0ca95fe7e1b8c6bcdf7300b3a0e0
vit050587/Python-homework-GB-2
/lesson4.4.py
847
4.25
4
# 2. Вычисляет урон по отношению к броне. # Примечание. Функция номер 2 используется внутри функции номер 1 для вычисления урона и вычитания его из здоровья персонажа. player_name = input('Введите имя игрока') player = { 'name': player_name, 'health': 100, 'damage': 50, 'armor' : 1.2 } enemy_name = input('Введите врага') enemy = { 'name': enemy_name, 'health': 50, 'damage': 30, 'armor' : 1 } def get_damage(damage, armor): return damage / armor def attack(unit, target): damage = get_damage(unit['damage'], target['armor']) target['health'] -= unit['damage'] attack(player, enemy) print(enemy) attack(enemy, player) print(player)
6350e10279970611dc7596725282d31edb2648a1
lacretelle/beta_bootcamp_python
/day00/ex05/kata03.py
108
3.703125
4
phrase = "The right format" i = len(phrase) while i < 42: print ("-", end='') i += 1 print (phrase)
2d64da9c1ef7e05354edf601ac253ff54f913678
lacretelle/beta_bootcamp_python
/day01/ex01/game.py
955
3.796875
4
class GotCharacter: """A class representing the GOT character with their name and if they are alive or not """ def __init__(self, first_name, is_alive=True): try: if not first_name: self.first_name = None elif isinstance(first_name, str): self.first_name = first_name self.is_alive = is_alive except Exception as err: print (err) class Stark(GotCharacter): """ A class representing the Stark family. Not bad people but a lot of bad luck. """ def __init__(self, first_name=None, is_alive=True): super().__init__(first_name=first_name, is_alive=is_alive) self.family_name = "Stark" self.house_words = "Winter is Coming" def print_house_words(self): """ prints to screen the House words """ print (self.house_words) def die(self): if self.is_alive: self.is_alive = False
4b4f20ebd7680757a8764a77720b31af1cef4c8a
Mahendra710/Number_Pattern
/7.11-Number Pattern.py
241
4
4
num=input("Enter an odd length number:") length=len(num) for i in range(length): for j in range(length): if i==j or i+j==length-1: print(num[i],end=" ") else: print(" ",end=" ") print()
3afebab1061cedb3cd3649c6d9c7aeb920f37ccf
Mahendra710/Number_Pattern
/7.9-Number Pattern.py
202
3.875
4
n=int(input("Enter the number of rows:")) for row in range(n): val=row+1 dec=n-1 for col in range(row+1): print(val,end=" ") val=val+dec dec=dec-1 print()
578f3caf2d4247460b9331ae8f8b2a9cc56a4a74
EgorVyhodcev/Laboratornaya4
/PyCharm/individual.py
291
4.375
4
print("This program computes the volume and the area of the side surface of the Rectangular parallelepiped") a, b, c = input("Enter the length of 3 sides").split() a = int(a) b = int(b) c = int(c) print("The volume is ", a * b * c) print("The area of the side surface is ", 2 * c * (a + b))
c7b567bde9e143c404c3670793576644a26f6142
AhmadQasim/Battleships-AI
/gym-battleship/gym_battleship/envs/battleship_env.py
4,760
3.53125
4
import gym import numpy as np from abc import ABC from gym import spaces from typing import Tuple from copy import deepcopy from collections import namedtuple Ship = namedtuple('Ship', ['min_x', 'max_x', 'min_y', 'max_y']) Action = namedtuple('Action', ['x', 'y']) # Extension: Add info for when the ship is sunk class BattleshipEnv(gym.Env, ABC): def __init__(self, board_size: Tuple = None, ship_sizes: dict = None, episode_steps: int = 100): self.ship_sizes = ship_sizes or {5: 1, 4: 1, 3: 2, 2: 1} self.board_size = board_size or (10, 10) self.board = None self.board_generated = None self.observation = None self.done = None self.step_count = None self.episode_steps = episode_steps self.action_space = spaces.Discrete(self.board_size[0] * self.board_size[1]) # MultiBinary is a binary space array self.observation_space = spaces.MultiBinary([2, self.board_size[0], self.board_size[1]]) # dict to save all the ship objects self.ship_dict = {} def step(self, raw_action: int) -> Tuple[np.ndarray, int, bool, dict]: assert (raw_action < self.board_size[0]*self.board_size[1]),\ "Invalid action (Superior than size_board[0]*size_board[1])" action = Action(x=raw_action // self.board_size[0], y=raw_action % self.board_size[1]) self.step_count += 1 if self.step_count >= self.episode_steps: self.done = True # it looks if there is a ship on the current cell # if there is a ship then the cell is 1 and 0 otherwise if self.board[action.x, action.y] != 0: # if the cell that we just hit is the last one from the respective ship # then add this info to the observation if self.board[self.board == self.board[action.x, action.y]].shape[0] == 1: ship = self.ship_dict[self.board[action.x, action.y]] self.observation[1, ship.min_x:ship.max_x, ship.min_y:ship.max_y] = 1 self.board[action.x, action.y] = 0 self.observation[0, action.x, action.y] = 1 # if the whole board is already filled, no ships if not self.board.any(): self.done = True return self.observation, 100, self.done, {} return self.observation, 1, self.done, {} # we end up here if we hit a cell that we had hit before already elif self.observation[0, action.x, action.y] == 1 or self.observation[1, action.x, action.y] == 1: return self.observation, -1, self.done, {} # we end up here if we hit a cell that has not been hit before and doesn't contain a ship else: self.observation[1, action.x, action.y] = 1 return self.observation, 0, self.done, {} def reset(self): self.set_board() # maintain an original copy of the board generated in the start self.board_generated = deepcopy(self.board) self.observation = np.zeros((2, *self.board_size), dtype=np.float32) self.step_count = 0 return self.observation def set_board(self): self.board = np.zeros(self.board_size, dtype=np.float32) k = 1 for i, (ship_size, ship_count) in enumerate(self.ship_sizes.items()): for j in range(ship_count): self.place_ship(ship_size, k) k += 1 def place_ship(self, ship_size, ship_index): can_place_ship = False while not can_place_ship: ship = self.get_ship(ship_size, self.board_size) can_place_ship = self.is_place_empty(ship) # set the ship cells to one self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y] = ship_index self.ship_dict.update({ship_index: ship}) @staticmethod def get_ship(ship_size, board_size) -> Ship: if np.random.choice(('Horizontal', 'Vertical')) == 'Horizontal': # find the ship coordinates randomly min_x = np.random.randint(0, board_size[0] - 1 - ship_size) min_y = np.random.randint(0, board_size[1] - 1) return Ship(min_x=min_x, max_x=min_x + ship_size, min_y=min_y, max_y=min_y + 1) else: min_x = np.random.randint(0, board_size[0] - 1) min_y = np.random.randint(0, board_size[1] - 1 - ship_size) return Ship(min_x=min_x, max_x=min_x + 1, min_y=min_y, max_y=min_y + ship_size) def is_place_empty(self, ship): # make sure that there are no ships by simply summing the cell values return np.count_nonzero(self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y]) == 0 def get_board(self): return self.board
1077c1381bc2376d9e18cbf9197a2382a31027e1
leenatomar123/functions
/KBC.py
1,186
3.859375
4
print("wELCOME......TO......KBC") Question_list=("how many states are there in India?" "what is the capital of india?" "NG mai konsa course padhaya jata hai?") options_list=[ ["Twenty-four","Twenty-five","Twenty-eight","Twenty-nine"] ["Bhutan","Pakistan","Delhi","China"] ["Software engineering","Graphics","Animation","Architecture"] ] Solution_list=[3,4,1] Ans=["Twenty-eight","Twenty-four","Delhi","Bhutan","Graphics","Software engineering"] i=0 r=1 y=0 count=0 while i<len(question_list): i1=question_list[i] print(i1) j=0 k=i while j<len(option_list[i]): l=option_list[k][j] print(j+1,l) j=j+1 Lifeline1=(input("do u want 50-50 lifelline")) if lifeline1=="yes": print(50-50) if count==0: print(ans([y+i]) print(ans([y+r]) n=int(input("enter answer")) if n==solution[i]: print("Right Anwer") else: print("Wrong Anwer") break count+=1 else: print("Want 50-50 lifeline") m=int(input("enter your answer")) if m==solution[i]: print("you win this challenge") else: print("you lose this challenge") break r+=1 y+=1 i+=1
835133a36e6cd47c8b9f422f9c802262fcb987bf
dselig11235/pyrsa
/pyrsa.py
3,158
3.53125
4
from random import randint from miller_rabin import is_prime import base64 def gcd(x, y): """This function implements the Euclidian algorithm to find G.C.D. of two numbers""" while(y): x, y = y, x % y return x # define lcm function def lcm(x, y): """This function takes two integers and returns the L.C.M.""" lcm = (x*y)//gcd(x,y) return lcm def seq(i, m): while i<m: yield i i = i+1 def factor(n): factors = [] while(n>1): for div in seq(2, n+1): if n % div == 0: n = n/div factors.append(div) break fset = set(factors) return [(x, factors.count(x)) for x in fset] def euler_phi(n): phi = n for f in factor(n): phi = int(phi*(1 - 1.0/f[0])) return phi def getParams(x, y, z): p = primes[x] q = primes[y] tot = lcm(p-1, q-1) e = primes[z] d = (e**(euler_phi(tot) -1)) % tot return { 'p': p, 'q': q, 'tot': tot, 'e': e, 'd': d, 'n': p*q } def random_prime(bits): min = 6074001000 << (bits-33) max = (1<<bits) - 1 while True: p = randint(min, max) if(is_prime(p)): return p def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m class RSAKey: def __init__(self, e = 0, n = 1): self.n = n self.e = e def encrypt(self, msg): return pow(strToInt(msg), self.e, self.n) def decrypt(self, msg): return intToStr(pow(msg, self.e, self.n)) def encrypt64(self, msg): return base64.b64encode(intToStr(self.encrypt(msg))) def decrypt64(self, msg): return self.decrypt(strToInt(base64.b64decode(msg))) def tostr(self): return '{},{}'.format(base64.b64encode(intToStr(self.n)), base64.b64encode(intToStr(self.e))) def fromstr(self, str): (n, e) = str.split(',') self.n = strToInt(base64.b64decode(n)) self.e = strToInt(base64.b64decode(e)) class RSAParams: def generate(self, keysize): e = 65537 while True: p = random_prime(keysize/2) q = random_prime(keysize/2) tot = lcm(p - 1, q - 1) if gcd(e, tot) == 1 and (keysize/2-100 < 0 or (abs(p-q) >> (keysize/2-100)) > 1): self.p = p self.q = q self.n = p*q self.e = e self.d = modinv(e, tot) self.public = RSAKey(e, self.n) self.private = RSAKey(self.d, self.n) return (self.public, self.private) def strToInt(msg): return int(msg.encode('hex'), 16) def intToStr(msg): encoded = format(msg, 'x') l = len(encoded) encoded = encoded.zfill(l + l%2) return encoded.decode('hex') #return hex(msg)[2:].rstrip('L').decode('hex')
2531327f966f606597577132fa9e54f7ed0be407
Rotondwatshipota1/workproject
/mypackage/recursion.py
930
4.1875
4
def sum_array(array): for i in array: return sum(array) def fibonacci(n): '''' this funtion returns the nth fibonacci number Args: int n the nth position of the sequence returns the number in the nth index of the fibonacci sequence '''' if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) def factorial(n): '''' this funtion returns the factorial of a give n intheger args: n it accepts an intger n as its argument returns : the number or the factorial of the given number '''' if n < 1: return 1 else: return n * factorial(n-1) def reverse(word): '''' this funtion returns a word in a reverse order args : word it accepts a word as its argument return: it returns a given word in a reverse order '''' if word == "": return word else: return reverse(word[1:]) + word[0]
c49787ad7badc48c6cdc3ecdd63dbaf3f3e5eb6f
phyokolwin/pythonworkshop
/01/01E12.py
100
3.984375
4
# Choose a question to ask print('What is your name?') name = input() print('Hello, ' + name + '.')
8ce437b775fd8fca2cb0c8ff2843b85a1b8c7265
phyokolwin/pythonworkshop
/01/01E16.py
204
3.546875
4
age = 20 if age >= 18 and age <21: print('At least you can vote') print('Poker will have to wait') if age >= 18: print('You can vote.') if age >= 21: print('You can play poker.')
de7488333bd872a4925fdd261ae08138d1aa7945
phyokolwin/pythonworkshop
/02/02E01.py
130
3.828125
4
shopping = ["bread","milk","eggs"] print(shopping) for item in shopping: print(item) mixed = [365,"days",True] print(mixed)
63dc143aa10a6a0343b440633ebea3f16e5dd745
maokitty/IntroduceToAlgorithm
/docDist/docDistance_listStruct_2.py
6,408
3.625
4
import math class DocDistance(object): def __init__(self): self.file_1 = "../txtFile/javawikipage.txt" self.file_2="../txtFile/pythonwikipage.txt" def read_file(self,filename): try: file=open(filename) return file.readlines() except Exception as e: print(e) def word_split_file(self,records): words=[] for line in records: word_inline = self.get_words_inline(line) words.extend(word_inline)#extend接受一个参数,这个参数总是list 比append要快,如果是string会被拆开成单个 return words def get_words_inline(self,line): words=[] character_list=[] for character in line: if character.isalnum(): character_list.append(character) elif len(character_list)>0: word="".join(character_list) word=word.lower() words.append(word) #append可以是任何类型 character_list=[] if len(character_list)>0: word="".join(character_list) word=word.lower() words.append(word) return words def count_frequency(self,words): w_f=[] for word in words: for wf in w_f: if wf[0] == word: wf[1]=wf[1]+1 break else: # python 语法:循环因为break被终止不会执行以下语句。当循环因为耗尽整个列表而终止时或条件变为假是会执行 w_f.append([word,1]) return w_f def word_frequence(self,filename): records = self.read_file(filename) words = self.word_split_file(records) w_f = self.count_frequency(words) return w_f def inner_product(self,w_f_1,w_f_2): sum = 0.0 for w1,cnt1 in w_f_1: for w2,cnt2 in w_f_2: # 循环都是一样的 if w1 == w2: sum+=cnt1*cnt2 return sum def distance(self): w_f_1 = self.word_frequence(self.file_1) w_f_2 = self.word_frequence(self.file_2) numerator = self.inner_product(w_f_1,w_f_2) denominator = math.sqrt(self.inner_product(w_f_1, w_f_1)*self.inner_product(w_f_2,w_f_2)) dist = math.acos(numerator/denominator) print("%0.6f"%dist) if __name__ == '__main__': import profile docDist = DocDistance() profile.run("docDist.distance()") # 0.803896 # 274277 function calls in 2.099 seconds # Ordered by: standard name # ncalls tottime percall cumtime percall filename:lineno(function) # 1 0.000 0.000 0.000 0.000 :0(acos) # 107145 0.129 0.000 0.129 0.000 :0(append) # 1 0.000 0.000 2.098 2.098 :0(exec) # 108885 0.131 0.000 0.131 0.000 :0(isalnum) # 17180 0.022 0.000 0.022 0.000 :0(join) # 23820 0.028 0.000 0.028 0.000 :0(len) # 17180 0.021 0.000 0.021 0.000 :0(lower) # 2 0.000 0.000 0.000 0.000 :0(nl_langinfo) # 2 0.000 0.000 0.000 0.000 :0(open) # 1 0.000 0.000 0.000 0.000 :0(print) # 2 0.001 0.000 0.001 0.000 :0(readlines) # 1 0.001 0.001 0.001 0.001 :0(setprofile) # 1 0.000 0.000 0.000 0.000 :0(sqrt) # 18 0.000 0.000 0.000 0.000 :0(utf_8_decode) # 1 0.000 0.000 2.098 2.098 <string>:1(<module>) # 2 0.000 0.000 0.000 0.000 _bootlocale.py:23(getpreferredencoding) # 2 0.000 0.000 0.000 0.000 codecs.py:257(__init__) # 2 0.000 0.000 0.000 0.000 codecs.py:306(__init__) # 18 0.000 0.000 0.000 0.000 codecs.py:316(decode) # 2 0.341 0.170 0.667 0.333 docDistance_listStruct.py:14(word_split_file) # 2 0.702 0.351 0.707 0.353 docDistance_listStruct.py:32(count_frequency) # 2 0.000 0.000 1.375 0.687 docDistance_listStruct.py:48(word_frequence) # 3 0.722 0.241 0.722 0.241 docDistance_listStruct.py:54(inner_product) # 1 0.000 0.000 2.097 2.097 docDistance_listStruct.py:63(distance) # 2 0.000 0.000 0.001 0.001 docDistance_listStruct.py:7(read_file) # 1 0.000 0.000 2.099 2.099 profile:0(docDist.distance()) # 0 0.000 0.000 profile:0(profiler) # 使用extend拆分单行和所有行的代码 # 0.803896 # 276003 function calls in 1.866 seconds # Ordered by: standard name # ncalls tottime percall cumtime percall filename:lineno(function) # 1 0.000 0.000 0.000 0.000 :0(acos) # 107145 0.111 0.000 0.111 0.000 :0(append) # 1 0.000 0.000 1.865 1.865 :0(exec) # 863 0.001 0.000 0.001 0.000 :0(extend) # 108885 0.112 0.000 0.112 0.000 :0(isalnum) # 17180 0.019 0.000 0.019 0.000 :0(join) # 23820 0.024 0.000 0.024 0.000 :0(len) # 17180 0.018 0.000 0.018 0.000 :0(lower) # 2 0.000 0.000 0.000 0.000 :0(nl_langinfo) # 2 0.000 0.000 0.000 0.000 :0(open) # 1 0.000 0.000 0.000 0.000 :0(print) # 2 0.001 0.000 0.001 0.000 :0(readlines) # 1 0.001 0.001 0.001 0.001 :0(setprofile) # 1 0.000 0.000 0.000 0.000 :0(sqrt) # 18 0.000 0.000 0.000 0.000 :0(utf_8_decode) # 1 0.000 0.000 1.865 1.865 <string>:1(<module>) # 2 0.000 0.000 0.000 0.000 _bootlocale.py:23(getpreferredencoding) # 2 0.000 0.000 0.000 0.000 codecs.py:257(__init__) # 2 0.000 0.000 0.000 0.000 codecs.py:306(__init__) # 18 0.000 0.000 0.000 0.000 codecs.py:316(decode) # 2 0.003 0.001 0.580 0.290 docDistance_listStruct_2.py:14(word_split_file) # 863 0.296 0.000 0.576 0.001 docDistance_listStruct_2.py:21(get_words_inline) # 2 0.623 0.312 0.628 0.314 docDistance_listStruct_2.py:40(count_frequency) # 2 0.000 0.000 1.209 0.604 docDistance_listStruct_2.py:53(word_frequence) # 3 0.655 0.218 0.655 0.218 docDistance_listStruct_2.py:59(inner_product) # 1 0.000 0.000 1.865 1.865 docDistance_listStruct_2.py:68(distance) # 2 0.000 0.000 0.001 0.000 docDistance_listStruct_2.py:7(read_file) # 1 0.000 0.000 1.866 1.866 profile:0(docDist.distance()) # 0 0.000 0.000 profile:0(profiler)