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
0dbfe08ed9fd0f87544d12239ca9505083c85986
mpsacademico/pythonizacao
/parte1/m004_lacos.py
1,641
4.15625
4
# codig=UTF-8 print("FOR") # repete de forma estática ou dinâmica animais = ['Cachorro', 'Gato', 'Papagaio'] # o for pode iterar sobre uma coleção (com interador) de forma sequencial for animal in animais: # a referência animal é atualizada a cada iteração print(animal) else: # executado ao final do laço (exceto com break) print("A lista de animais terminou no ELSE") # contando pares: passando para a próxima iteração em caso de ímpar for numero in range(0, 11, 1): if numero % 2 != 0: #print(numero, "é ímpar") continue # passa para a próxima iteração print(numero) else: print("A contagem de pares terminou no ELSE") ''' range(m, n, p) = retorna uma lista de inteiros - começa em m - menores que n - passos de comprimento p ''' # saldo negativo: parando o laço em caso de valor negativo saldo = 100 for saque in range(1, 101, 1): resto = saldo - saque if resto < 0: break # interrompe o laço, o ELSE não é executado saldo = resto print("Saque:", saque, "| Saldo", saldo) else: print("ELSE não é executado, pois o laço sofreu um break") # -------------------------------------------------------------------- print("WHILE") # repete enquanto a codição for verdadeira idade = 0 while idade < 18: escopo = "escopo" # variável definida dentro do while idade += 1 # incrementar unitariamente assim if idade == 4: print(idade, "anos: tomar vacina") continue # pula o resto e vai para próxima iteração if idade == 15: print("Ops! :( ") break # interrompe o laço completamente!!! print(idade) else: print("ELSE: Você já é maior de idade | ESCOPOS:", idade, escopo)
3c1cb160109928256565bf8da415a600d56c41f1
ghostlypi/thing
/CeasarCypher.py
540
3.9375
4
def encrypt(user_input): myname = user_input bigstring = "" for x in range (len(myname)): bigstring = bigstring + str(ord(myname[x])+3).zfill(3) x = 0 encrypted = "" while x < len(bigstring): charnumber = bigstring[x:x+3] x = x + 3 charnumber = int(charnumber) encrypted = encrypted + chr(charnumber) return encrypted def decrypt(ui): x = 0 uo = "" while x < len(ui): char = chr(ord(ui[x])-3) uo = uo + char x += 1 return(uo)
c55551fc0fb4c59bfed84131f404f9b462487691
PhenixI/programing-foundation-with-python
/useclasses/drawflower.py
707
4.03125
4
import turtle def draw_rhombus(some_turtle,length,angel): for i in range(1,3): some_turtle.forward(length) some_turtle.left(180-angel) some_turtle.forward(length) some_turtle.left(angel) def draw_flower(): window = turtle.Screen() window.bgcolor('white') angie = turtle.Turtle() angie.shape('arrow') angie.color('yellow') angie.speed(10) for i in range(1,73): draw_rhombus(angie,100,140) angie.right(5) angie.right(90) angie.forward(300) # angie.right(150) # draw_rhombus(angie,150,140) # angie.right(60) # draw_rhombus(angie,150,140) angie.hideturtle() window.exitonclick() draw_flower()
52830b84ae5750d5f1b39142770c8efaba5e8f41
fastestmk/python_basics
/list_comprehension.py
2,374
3.625
4
# multiple input using list comprehension # a, b, c = [int(i) for i in input().split()] # print(a, b, c) # List as input using list comprehension # my_list = [int(i) for i in input().split()] # print(my_list) # for x in my_list: # print(x, end=" ") # 4*4 Matrix as input # matrix = [[int(j) for j in input().split()] for i in range(4)] # seq = [2, 3, 5, 1, 6, 7, 8] # squares_of_even = [i**2 for i in seq if i%2==0] # print(squares_of_even) # charlist = ['A', 'B', 'C'] # ans = [x.lower() for x in charlist] # print(ans) # s = 'aaa bbb ccc ddd' # print(''.join(s.split())) # s = 'aaa bbb ccc ddd' # s1 = str(''.join([i for i in s if i != ' '])) # s2 = [i for i in s if i != ' '] # print(s1) # print(s2) # li = [1, 2, 4, 0, 3] # print_dict = {i:i*i for i in li} # print(print_dict) # print_list = [[i,i*i] for i in li] # print(print_list) word = 'CatBatSatFatOr' print([word[i:i+3] for i in range(len(word))]) print([word[i:i+3] for i in range(0, len(word), 3)]) # towns = [{'name': 'Manchester', 'population': 58241}, # {'name': 'Coventry', 'population': 12435}, # {'name': 'South Windsor', 'population': 25709}] # town_names = [] # for town in towns: # town_names.append(town.get('name')) # print(town_names) # # List comprehensions... # town_names = [town.get('name') for town in towns] # print(town_names) # # Map function... # town_names = map(lambda town: town.get('name'), towns) # print(town_names) # # For loops... # town_names = [] # town_populations = [] # for town in towns: # town_names.append(town.get('name')) # town_populations.append(town.get('population')) # print(town_names) # print(town_populations) # # List comprehensions... # town_names = [town.get('name') for town in towns] # town_populations = [town.get('population') for town in towns] # print(town_names) # print(town_populations) # # Zip function... # town_names, town_populations = zip(*[(town.get('name'), town.get('population')) for town in towns]) # print(town_names) # print(town_populations) # # For loops... # total_population = 0 # for town in towns: # total_population += town.get('population') # # Sum function... # total_population = sum(town.get('population') for town in towns) # print(total_population) # import reduce # Reduce function... # total_population = reduce(lambda total, town: total + town.get('population'), towns, 0)
5cc5a1970d143188e1168d521fac27f4534f3032
fastestmk/python_basics
/dictionaries.py
441
4.375
4
# students = {"Bob": 12, "Rachel": 15, "Anu": 14} # print(students["Bob"]) #length of dictionary # print(len(students)) #updating values # students["Rachel"] = 13 # print(students) #deleting values # del students["Anu"] # print(students) my_dict = {'age': 24, 'country':'India', 'pm':'NAMO'} for key, val in my_dict.items(): print("My {} is {}".format(key, val)) for key in my_dict: print(key) for val in my_dict.values(): print(val)
aedfec35a3c19b30bc0ec285d7a652b4b340da89
Temesgenswe/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
1,302
3.953125
4
#!/usr/bin/python3 """Module creates class Student""" class Student: """Student class with public instance attributes Instance Attributes: first_name: first name of student last_name: last name of student age: age of student """ def __init__(self, first_name, last_name, age): """Instantiates public instance attributes""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Returns dictionary representation of instance Params: attrs: attributes to retrieve. if not a list of strings, retrieve all attributes """ if type(attrs) is not list: return self.__dict__ filtered = {} for a in attrs: if type(a) is not str: return self.__dict__ value = getattr(self, a, None) if value is None: continue filtered[a] = value return filtered def reload_from_json(self, json): """Replace all attributes of instance with those in json Params: json: dictionary with attributes to use """ for key, value in json.items(): self.__dict__[key] = value
07cd0f2a3208e04dd0c34a501b68de19f692c35a
Temesgenswe/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
364
4.3125
4
#!/usr/bin/python3 """Module defines append_write() function""" def append_write(filename="", text=""): """Appends a string to a text file Return: the number of characters written Param: filename: name of text file text: string to append """ with open(filename, 'a', encoding="UTF8") as f: return f.write(str(text))
86e76c7aa9c052b23b404c05f57420750a5029b7
Temesgenswe/holbertonschool-higher_level_programming
/0x06-python-classes/103-magic_class.py
751
4.4375
4
#!/usr/bin/python3 import math class MagicClass: """Magic class that does the same as given bytecode (Circle)""" def __init__(self, radius=0): """Initialize radius Args: radius: radius of circle Raises: TypeError: If radius is not an int nor a float """ self.__radius = 0 if type(radius) is not int and type(radius) is not float: raise TypeError('radius must be a number') self.__radius = radius def area(self): """Returns the calculated area of circle""" return self.__radius ** 2 * math.pi def circumference(self): """Returns the calculated circumference of circle""" return 2 * math.pi * self.__radius
d7378fd0f3ba0e609add78cc4e57919029736c9e
craymontnicholls/Booklet-3-
/Save-the-Change/main.py
370
3.765625
4
def SaveTheChange(Amount): NearestPound = int(Amount) + 1 if int(Amount) != Amount: return NearestPound - Amount else: NearestPound = Amount Price = 1.20 Savings = SaveTheChange(Price) print("Debit -purchase: £{:.2f}".format(Price)) print("Debit - Save the change: £{:.2f}".format(Savings)) print("Credit - Save the changes: £{:.2f}".format(Savings))
5a42b0695ea0a6d04e00ebce4a443f10dd0a6a61
SeniorJunior/Tic-Tac-Toe
/Board.py
1,417
3.953125
4
#Tic Tac Toe class Board: def __init__(self, square1 =' ', square2=' ', square3=' ', square4=' ', square5=' ', square6=' ', square7=' ', square8=' ', square9=' '): self.square1 = square1 self.square2 = square2 self.square3 = square3 self.square4 = square4 self.square5 = square5 self.square6 = square6 self.square7 = square7 self.square8 = square8 self.square9 = square9 def grid(self): message = '\nSQUARES ARE 0-8, TOP LEFT TO BOTTOM RIGHT, TRAVEL HORIZONTALLY\n | | \n ' +self.square1+' | '+self.square2+' | '+self.square3+' \n___|___|___\n | | \n '+self.square4+' | '+self.square5+' | '+self.square6+' \n___|___|___\n | | \n '+self.square7+' | 'self.square8+' | '+self.square9+' \n | | ' print(message) game= Board() print(game.grid) while True: entry = raw_input('Please enter a number\n') if entry == '0': game.square1='X' elif entry == '1': game.square2='X' elif entry == '2': game.square3='X' elif entry == '3': game.square4='X' elif entry == '4': game.square5='X' elif entry == '5': game.square6='X' elif entry == '6': game.square7='X' elif entry == '7': game.square8='X' elif entry == '8': game.square9='X' print(game.grid())
cac6b62dea819d2135dea643743f4ad8ea617888
LorenzoChavez/CodingBat-Exercises
/Logic-1/sorta_sum.py
259
3.734375
4
# Given 2 ints, a and b, return their sum. # However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20. def sorta_sum(a, b): sums = a + b forbidden = 10 <= sums < 20 if forbidden: return 20 else: return sums
d3e203ffb4eac1ffe1bd1776de5f06220b81b6c1
LorenzoChavez/CodingBat-Exercises
/Warmup-1/sum_double.py
231
4.15625
4
# Given two int values, return their sum. Unless the two values are the same, then return double their sum. def sum_double(a, b): result = 0 if a == b: result = (a+b) * 2 else: result = a+b return result
dcdf2af82b901689753f9e158f009d274ce81580
LorenzoChavez/CodingBat-Exercises
/Logic-2/make_chocolate.py
490
4.03125
4
# We want make a package of goal kilos of chocolate. # We have small bars (1 kilo each) and big bars (5 kilos each). # Return the number of small bars to use, assuming we always use big bars before small bars. # Return -1 if it can't be done. def make_chocolate(small, big, goal): big_needed = goal // 5 if big_needed >= big: small_needed = goal - (5*big) else: small_needed = goal - (5*big_needed) if small < small_needed: return -1 else: return small_needed
9ddb20de902048ec957738f121f50212d3f2bd32
LorenzoChavez/CodingBat-Exercises
/Warmup-1/near_hundred.py
276
3.84375
4
# Given an int n, return True if it is within 10 of 100 or 200. # Note: abs(num) computes the absolute value of a number. def near_hundred(n): result = 0 if abs(100 - n) <= 10 or abs(200 - n) <= 10: result = True else: result = False return result
f884cb7d78aca6efb6943ebc2f7ed4194b0357c3
Pradas137/Python
/Uf2/modulos/funciones.py
256
3.859375
4
def division_entera(): try: dividendo = int(input("escrive un dividendo")) divisor = int(input("escrive un divisor")) return dividendo/divisor except ZeroDivisionError: raise ZeroDivisionError("y no puede ser cero")
a39e8f210577397f71242d2b3b841d4fe31e1656
Pradas137/Python
/Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio4.py
113
3.609375
4
def suma(l): if (len(l) == 0): return 0 return l[0] + suma(l[1:]) lista = [1,2,2,2] print(suma(lista))
9fd1b66731c91a03576bb198733f7b6e803210ef
Pradas137/Python
/Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio2.py
174
4.125
4
def producto(num1, num2): if num2 == 1: return num1 elif num2 == 0 or num1 == 0: return 0 else: return(num1+producto(num1, (num2-1))) print(producto(0, 3))
13e493fdf614c4d1f92f8db7cdddeee4fcc79b32
Pradas137/Python
/Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio3.py
353
3.921875
4
def fibonacci(n): if n>2: return fibonacci(n-2)+fibonacci(n-1) else: return 1 print(fibonacci(12)) def fibonacci1(n): if n>=10: b=0 while (n>0): b=b+n%10 n=n//10 return fibonacci1(b) else: return n print(fibonacci1(1523))
7ce2d175697104c3df72fd437f9fe01fc0ed5053
alxanderapollo/HackerRank
/WarmUp/salesByMatchHR.py
1,435
4.3125
4
# There is a large pile of socks that must be paired by color. Given an array of integers # representing the color of each sock, determine how many pairs of socks with matching colors there are. # Example # There is one pair of color and one of color . There are three odd socks left, one of each color. # The number of pairs is . # Function Description # Complete the sockMerchant function in the editor below. # sockMerchant has the following parameter(s): # int n: the number of socks in the pile # int ar[n]: the colors of each sock # Returns # int: the number of pairs # Input Format # The first line contains an integer , the number of socks represented in . # The second line contains space-separated integers, , the colors of the socks in the pile. def sockMerchant(n, ar): mySet = set() #hold all the values will see count = 0 #everytime we a see a number we first check if it is already in the set #if it is delete the number for i in range(n): if ar[i] in mySet: mySet.remove(ar[i]) count+=1 else: mySet.add(ar[i]) return count #add one to the count #otherwise if we've never seen the number before add it to the set and continue #once we are done with the array #return the count n = 9 ar = [10,20 ,20, 10, 10, 30, 50, 10, 20] print(sockMerchant(n, ar))
c9b5f7671742610dc86e6812456e9f645d4188e5
hliaskost2001/hliaskost
/ask8.py
493
3.5
4
import urllib.request import json url="https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,LTC&tsyms=EUR&e=CCCAGG" r=urllib.request.urlopen(url) html=r.read() html=html.decode() d=json.loads(html) file = input("File name: ") f = open(file, 'r') f = f.read() f = json.loads(f) thisdict = { "BTC": "54267.673556", "ETH": "10797,677999999998", "LTC":"182.01" } print('Your portofolio is:') print(f) print('Which in Euros is: ') print(thisdict)
ecd071980258a704fcae77516c9dbc10a45cc99b
PinkyJangir/Loop.py
/strongnumber.py
221
3.9375
4
num=int(input('enter the number')) sum=0 temp=num while temp>0: f=1 i=1 rem=temp%10 while i<=rem: f=f*i i=i+1 sum=sum+f temp=temp//10 if sum==num: print('yes it is strong number',num) else: print('not strong')
145a65c095d3414341ca36072b3dd527bca51d75
PinkyJangir/Loop.py
/len.py
73
3.59375
4
name=input('ebter the nimber') i=0 c=0 while i<len(name): c=c+1 i=i+1 print(c)
34bd3210423fd7cbfceeea84b10aa34785aeaf6f
archanaburra/adventOfCode
/day-2/day-2-solution.py
1,338
3.65625
4
from functools import reduce ## part 1 f=open("input-day-2.txt", "r") phrases = f.read().split("\n")[:-1] # for testing only # phrases = ['abcdef','bababc','abbcde','abcccd','aabcdd','abcdee','ababab'] final_counts = {} final_counts['2'] = 0 final_counts['3'] = 0 def update_final_counts(value): if value in list(d.values()): final_counts[str(value)] += 1 return; for p in phrases: d = {} for c in p: if c in d: d[c] += 1 else: d[c] = 1 update_final_counts(2) update_final_counts(3) print(reduce(lambda x, y: x*y, list(final_counts.values()))) # part 2 # for testing only # phrases = ['abcde','fghij','klmno','pqrst','fguij','axcye','wvxyz'] f=open("input-day-2.txt", "r") phrases = f.read().split("\n")[:-1] word_len = len(phrases[0]) size = len(phrases) - 1 def determine_repeat(phrases, word_len, size): for index, word in enumerate(phrases): for i in range(index + 1, size): ## iterate thru all other words below comparison_word = phrases[i] for c in range(0, word_len): first = word[:c] + word[c+1:] second = comparison_word[:c] + comparison_word[c+1:] if first == second: return first; print(determine_repeat(phrases, word_len, size))
65f21dd571f901d1331499a0554c82229d24674f
vitor-santos430/aprendendo_ia
/rede_neural_perceptron.py
796
3.8125
4
# para o basilisco no futuro from random import * peso1 = random() peso2 = random() pesoBias = random() entrada1 = int(input("Entrada 1 => ")) entrada2 = int(input("Entrada 2=> ")) bias = 1 erro = 1 while erro != 0: if entrada1 == 1 and entrada2 == 1: resultadoEsperado = 1 else: resultadoEsperado = 0 somatoria = entrada1 * peso1 somatoria += entrada2 * peso2 somatoria += bias * pesoBias if somatoria < 0: resultado = 0 elif somatoria >= 0: resultado = 1 erro = resultadoEsperado - resultado peso1 = peso1 + (0.1 * entrada1 * erro) peso2 = peso2 + (0.1 * entrada2 * erro) pesoBias = pesoBias + (0.1 * bias * erro) print(f'peso 1 => {peso1}') print(f'peso 2 => {peso2}') print(f"O resultado é => {resultado}")
3b38c1507501d451d741da0daa812a4f63152941
kushagra65/Python-CLock-Project
/ANALOG CLOCK.py
2,034
4.28125
4
#import the essential modules import time# importing the time module import turtle #importing the turtle module from the LOGO days #---------------------------------------------------------------- #creating the screen of the clock wn = turtle.Screen()#creating a screen wn.bgcolor("black")#setting the backgroung color wn.setup(width=600, height=600)#setting the size of the screen wn.title("analog clock @ kushagra verma") wn.tracer(0)#sets the animation time ,see in the while loop #--------------------------------------------------------------------------- #creating our drawing pen pen = turtle.Turtle()# create objects pen.hideturtle() pen.speed(0) # animation speed pen.pensize(5) # widht of the pens the pen is drawing def DrawC(h,m,s,pen):# creates min,hr,sec hands #drawing a clock face pen.penup() #means dont draw a line pen.goto(0, 210) pen.setheading(180)#pen facing to the left pen.color("orange")#color of the circle pen.pendown() pen.circle(210) #now drawing lines for the hours pen.penup() pen.goto(0, 0) pen.setheading(90) for _ in range(12): pen.fd(190) pen.pendown() pen.fd(20) pen.penup() pen.goto(0,0) pen.rt(30) # Drawing the hour hand pen.penup() pen.goto(0,0) pen.color("blue") pen.setheading(90) angle = (h / 12) * 360 pen.rt(angle) pen.pendown() pen.fd(100) #drawing the minite hand pen.penup() pen.goto(0,0) pen.color("gold") pen.setheading(90) angle=( m / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(180) # Drawing the sec hand pen.penup() pen.goto(0,0) pen.color("yellow") pen.setheading(90) angle=( s / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(50) while True: h=int(time.strftime("%I")) m=int(time.strftime("%M")) s=int(time.strftime("%S")) DrawC(h,m,s,pen) wn.update() time.sleep(1) pen.clear() #after exiting the loop a error will show ignore the error
71035e7d048dc71de2a400dcc9202dc8e571ee5f
07Irshad/python
/positivenumbers.py
190
3.9375
4
list1 = [12, -7, 5, 64,-14] list2 = [12, 14,-95,3] for number1 in list1: if number1 >= 0: print(number1, end = " ") for number2 in list2: if number2 >= 0: print(number2, end = " ")
06916a4349bdad38c95c99a3ecd91ffcec916c22
ivanrojo07/Python
/Generador de codigo intermedio.py
253
3.8125
4
def esOperador(c): if(c=='+'or c=='-' or c=='/' or c=='*'): return True else: return False fpos="ab*cd*+" pila=[] for c in fpos: print c if fpos[c]== esOperador(c): print pila: e
b59aa904adda89dbb88e022b3173a1d19efbcc58
ivanrojo07/Python
/Ébola Cinco punto uno.py
4,617
3.515625
4
# -*- coding: cp1252 -*- from Tkinter import * from time import sleep from math import * from random import * def distancia(x1, y1, x2, y2): return sqrt( pow( (x2 - x1), 2) + pow( (y2 - y1), 2) ) class Persona(): def __init__(self, c): self.numero = c self.sano = True self.vacunado = False self.contactos = [] self.posicionX = 0 self.posicionY = 0 self.infecciosidad = 0 def creaPoblacion(): poblacion = [] for c in range(1600): poblacion.append(Persona(c)) return poblacion def dibujaPoblacion(poblacion): for c in range(len(poblacion)): x = c % 40 y = c / 40 poblacion[c].posicionX = x poblacion[c].posicionY = y if poblacion[c].sano: lienzo.create_oval(x * 10, y * 10, x*10 + 11, y*10 + 11, fill = "blue") if poblacion[c].vacunado: lienzo.create_oval(x * 10, y * 10, x*10 + 11, y*10 + 11, fill = "yellow") elif not poblacion[c].sano: lienzo.create_oval(x * 10, y * 10, x*10 + 11, y*10 + 11, fill = "red") #sleep(0.5) def correSim(): dias = 20 print 'Aqu va el cdigo de la simulacin' dibujaPoblacion(poblacion) # Parte donde se asignan los contactos ms cercanos. for a in range(len(poblacion)): for b in range(len(poblacion)): d = distancia(poblacion[a].posicionX, poblacion[a].posicionY, poblacion[b].posicionX, poblacion[b].posicionY) if d < 1.5 and not(int(d) == 0): poblacion[a].contactos.append(poblacion[b].numero) aleatorio = 0 # Parte donde se hacen los contactos aleatorios. for c in range(len(poblacion)): while len(poblacion[c].contactos) < 10: aleatorio = randint(0, len(poblacion) - 1) if not (aleatorio in poblacion[c].contactos): poblacion[c].contactos.append(aleatorio) poblacion[c].contactos.sort() aleatorio = randint(0, len(poblacion) - 1) # Se hace al primer infectado. poblacion[aleatorio].sano = False poblacion[aleatorio].infecciosidad = randint(1, 50) print 'El primer habitante infectado es el nmero', aleatorio dibujaPoblacion(poblacion) # Parte donde se hace la simulacin por das. numeroInfectivo = 0 infeccionPoblacion = 0 habitante = 0 vacuna = 0 poblacionInfectada = [] poblacionInfectada.append(aleatorio) for i in range(dias): # Aqu debe ir el nmero de das de la simulacin. print 'Da', i + 1, 'de', dias sleep(0.5) ventana.update() dibujaPoblacion(poblacion) for k in range(int(7.5 *(len(poblacion) / 100)) ): vacuna = randint(0, len(poblacion) - 1) if poblacion[vacuna].sano: poblacion[vacuna].vacunado = True for j in range(len(poblacion)): numeroInfectivo = randint(0, 100) if poblacion[j].sano == False and numeroInfectivo < poblacion[j].infecciosidad:# and not (poblacion[j].contactos in poblacionInfectada): for k in range(len(poblacion[j].contactos)): if not (poblacion[j].contactos[k] in poblacionInfectada): infeccionPoblacion = randint(0, len(poblacion[j].contactos) - 1) habitante = poblacion[j].contactos[infeccionPoblacion] poblacion[habitante].sano = False poblacion[habitante].infecciosidad = randint(1, 100) poblacionInfectada.append(habitante) dibujaPoblacion(poblacion) print 'Fin de la simulacin.' infectados = 0 vacunados = 0 sanos = 0 for c in range(len(poblacion)): if poblacion[c].vacunado: vacunados += 1 if poblacion[c].sano and poblacion[c].vacunado == False: sanos += 1 infectados = len(poblacion) - vacunados - sanos print 'Nmero de sanos:', sanos print 'Nmero de vacunados:', vacunados print 'Nmero de infectados:', infectados #Seccin de la lgica del programa. poblacion = creaPoblacion() # Seccin de la interfaz grfica. ventana = Tk() lienzo = Canvas(ventana, width = 404, height = 404) lienzo.pack() botonSalir = Button(ventana, text = "Salir", fg = "black", command = ventana.quit) botonSalir.pack(side = LEFT) boton1 = Button(ventana, text = "Corre simulacin", command = correSim)# state = DISABLED) boton1.pack(side = LEFT) #etiquetaN = Text(ventana, selectborderwidth = 40) #nDias = etiquetaN. #etiquetaN.pack(side = LEFT) mainloop() ventana.destroy()
a45f6b8edd8e288b56ea0fb3c8e36aabac6057b0
bvinothraj/progp
/p7/source/p7.py
234
3.75
4
def createMyList(arr1): ''' #P7: Given an array of integers, which may contain duplicates, create an array without duplicates. ''' n_obj = {} for i in arr1: n_obj[i] = 0 return list(n_obj.keys())
16705cb5b02ce15d7fa6f30db54514a32af07d06
stevencfree/raspberryPi
/python/trafficLight.py
690
3.828125
4
from time import sleep import RPi.GPIO as GPIO #gives us access to the GPIO pins GPIO.setmode(GPIO.BCM) #sets the pin numbering system we want to use green = 27 #set variables for the pin numbers driving each LED yellow = 22 red = 17 GPIO.setup(green, GPIO.OUT) #configure GPIO pins to output mode GPIO.setup(yellow, GPIO.OUT) GPIO.setup(red, GPIO.OUT) while True: GPIO.output(red, False) #turn on green light for 2 seconds GPIO.output(green, True) sleep(2) GPIO.output(green, False) #turn on yellow light for 1 second GPIO.output(yellow, True) sleep(1) GPIO.output(yellow, False) #turn on red light for 3 seconds GPIO.output(red, True) sleep(3)
4255bda81982abadac9f18f2cbeddd4650140c55
whalespotterhd/YAPC
/YAPC.py
1,394
3.96875
4
#!/usr/bin/python import time #####VARIABLES##### """ list of pokemon you which to evolve format: pokemon, # of pokemon, # of candies, candy needed to evolve """ pokemon_list =[ ["Pidgey", 23, 99, 12], ["Rattata", 25, 87, 25] ] #####FUNCTIONS##### def pidgey_calc(pokemon_name, pokemon_amount, pokemon_candy, candy_needed): amount_of_evolutions = 0 pokemon_transfered = 0 a = pokemon_name b = pokemon_amount c = pokemon_candy d = candy_needed # as long as their are pokemon left while b > 0: # transfer 1 pokemon if c < d: b -= 1 c += 1 pokemon_transfered += 1 # else, evolve 1 pokemon else: c -= d amount_of_evolutions += 1 b -= 1 #gain 1 candy from evolving c += 1 return (amount_of_evolutions, pokemon_transfered) #####MAIN FUNCTION##### def main(): total_XP = 0 approx_time = 0 for i in pokemon_list: answer = (pidgey_calc(i[0], i[1], i[2], i[3])) total_XP += answer[0] * 500 approx_time += (answer[0] * 30) print ( "You need to transfer " + str(answer[1]) + " " + i[0] + ". Then you can evolve " + str(answer[0]) + " for a total of" + str(answer[0] *500) + " XP. \n" ) print( "This grands a total of " + str(total_XP) + " XP" + " and takes roughly " + str(approx_time) + " seconds" ) if __name__ == "__main__": main()
6dd0fdc233200217feb75ed152f99c8ac3b7c34f
morganstanley/testplan
/examples/PyTest/pytest_tests.py
4,724
3.671875
4
"""Example test script for use by PyTest.""" # For the most basic usage, no imports are required. # pytest will automatically detect any test cases based # on methods starting with ``test_``. import os import pytest from testplan.testing.multitest.result import Result class TestPytestBasics: """ Demonstrate the basic usage of PyTest. PyTest testcases can be declared as either plain functions or methods on a class. Testcase functions or method names must begin with "test" and classes containing testcases must being with "Test". Classes containing testcases must not define an __init__() method. The recommended way to perform setup is to make use of Testplan's Environment - see the "TestWithDrivers" example below. Pytest fixtures and the older xunit-style setup() and teardown() methods may also be used. """ def test_success(self): """ Trivial test method that will simply cause the test to succeed. Note the use of the plain Python assert statement. """ assert True def test_failure(self): """ Similar to above, except this time the test case will always fail. """ print("test output") assert False @pytest.mark.parametrize("a,b,c", [(1, 2, 3), (-1, -2, -3), (0, 0, 0)]) def test_parametrization(self, a, b, c): """Parametrized testcase.""" assert a + b == c class TestWithDrivers: """ MultiTest drivers are also available for PyTest. The testcase can access those drivers by parameter `env`, and make assertions provided by `result`. """ def test_drivers(self, env, result): """Testcase using server and client objects from the environment.""" message = "This is a test message" env.server.accept_connection() size = env.client.send(bytes(message.encode("utf-8"))) received = env.server.receive(size) result.log( "Received Message from server: {}".format(received), description="Log a message", ) result.equal( received.decode("utf-8"), message, description="Expect a message" ) class TestWithAttachments: def test_attachment(self, result: Result): result.attach(__file__, "example attachment") class TestPytestMarks: """ Demonstrate the use of Pytest marks. These can be used to skip a testcase, or to run it but expect it to fail. Marking testcases in this way is a useful way to skip running them in situations where it is known to fail - e.g. on a particular OS or python interpreter version - or when a testcase is added before the feature is implemented in TDD workflows. """ @pytest.mark.skip def test_skipped(self): """ Tests can be marked as skipped and never run. Useful if the test is known to cause some bad side effect (e.g. crashing the python interpreter process). """ raise RuntimeError("Testcase should not run.") @pytest.mark.skipif(os.name != "posix", reason="Only run on Linux") def test_skipif(self): """ Tests can be conditionally skipped - useful if a test should only be run on a specific platform or python interpreter version. """ assert os.name == "posix" @pytest.mark.xfail def test_xfail(self): """ Tests can alternatively be marked as "xfail" - expected failure. Such tests are run but are not reported as failures by Testplan. Useful for testing features still under active development, or for unstable tests so that you can keep running and monitoring the output without blocking CI builds. """ raise NotImplementedError("Testcase expected to fail") @pytest.mark.xfail(raises=NotImplementedError) def test_unexpected_error(self): """ Optionally, the expected exception type raised by a testcase can be specified. If a different exception type is raised, the testcase will be considered as failed. Useful to ensure that a test fails for the reason you actually expect it to. """ raise TypeError("oops") @pytest.mark.xfail def test_xpass(self): """ Tests marked as xfail that don't actually fail are considered an XPASS by PyTest, and Testplan considers the testcase to have passed. """ assert True @pytest.mark.xfail(strict=True) def test_xpass_strict(self): """ If the strict parameter is set to True, tests marked as xfail will be considered to have failed if they pass unexpectedly. """ assert True
68cfe56e1f5d2712f20888f05fe1fdf222fea993
WuLC/Beauty_OF_Programming
/python/chapter 2/2_2.py
1,904
3.734375
4
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2016-05-14 01:31:44 # @Last modified by: WuLC # @Last Modified time: 2016-10-24 12:51:56 # @Email: liangchaowu5@gmail.com ############################################################### # problem1: caculate the number of 0 at the end of the number n! ############################################################### # solution1,count the 0 that each number can generate from 1 to n def solution1_1(n): count = 0 for i in xrange(1,n+1): while i!=0 and i%5==0 : count += 1 i /= 5 return count # solution2,the number equal to pow(5,n) can generate n 0 def solution1_2(n): count = 0 while n >= 5: n /= 5 count += n return count ############################################################ # problem2: find the index of the first 1 of number n! # from lower to higer order in the form of binary ############################################################# # solution1,count the 0 that each number can generate in the form of binary def solution2_1(n): count = 0 for i in xrange(1,n+1): while i%2==0 and i!=0: i >>= 1 # i /= 2 count += 1 return count # solution2,the number equal to pow(2,n) can generate n 0 def solution2_2(n): count = 0 while n>=2: n >>= 1 count += n return count ######################################## # problem3: judge if a number is pow(2,n) # as pow(2,n) in bianry form must be 100000000... # thus,pow(2,n)&(pow(2,n)-1)=0 ######################################## def solution3_1(n): return n == 0 or (n&(n-1))==0 # lowbit def solution3_2(n): return (n^(-n)) == 0 if __name__ == '__main__': print solution1_1(100) print solution1_2(100) print solution2_1(12) print solution2_2(12) for i in xrange(1000): if solution3(i): print i,
1a503d1fa00f78450cce1cbaada145745ea5d17b
AaravAgarwal1/Project-110
/pro 110.py
2,013
3.546875
4
import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import pandas as pd import plotly.express as px df=pd.read_csv("medium_data.csv") #reading the file data= df["temp"].tolist() #converting to list # fig= ff.create_distplot([data],["temp"],show_hist=False) # fig.show() population_mean=statistics.mean(data) #rando name std_dev=statistics.stdev(data) print(f"Population mean: {population_mean}") print(f"Standard Deviation: {std_dev}") def show_fig(mean_list): df=mean_list #data is now mean_list mean=statistics.mean(df) #mean fig=ff.create_distplot([df],["temp"],show_hist=False) #creating dist_plot fig.add_trace(go.Scatter(x=[mean,mean],y=[0,1],mode="lines",name="MEAN"))#adding trace line fig.show() dataset=[] for i in range(0,100): random_index=random.randint(0,len(data)) value=data[random_index] dataset.append(value) mean=statistics.mean(dataset) std_deviation=statistics.stdev(dataset) print(f"Mean of sample: {mean}") print(f"Standard Deviation of sample: {std_deviation} ") def random_set_mean(counter): dataset=[] for i in range(0,counter): #counter u can put--> check line 52 random_index=random.randint(0,len(data)-1) value=data[random_index] dataset.append(value) mean=statistics.mean(dataset) return mean def setup(): mean_list=[] for i in range(0,1000): set_of_means=random_set_mean(30) #taking 100 rando values from 1000 to see the mean mean_list.append(set_of_means) show_fig(mean_list) mean=statistics.mean(mean_list) print(f"Mean of sampling distribution: {mean}") setup() def standard_dev(): #gives std_dev mean_list=[] for i in range(0,1000): set_of_means=random_set_mean(100) mean_list.append(set_of_means) std_devi=statistics.stdev(mean_list) print(f"Standard deviation of sampling distribution: {std_devi}") standard_dev()
3ed3977bb968cc017b63049c9a9ea879d0184308
FDSGAB/Python-HackerRank
/Print Function.py
144
3.546875
4
if __name__ == '__main__': n = int(input()) for i in range (n+1): if (i==0): continue print(str(i), end="")
5f03a74b3ba7d060785ee6e329a428f52ed7188e
neung20402/Python
/week3/test2.py
311
4.0625
4
loop = int(input("กรุณากรอกจำนวนครั้งการรับค่า\n")) total = 0 for x in range(0,loop): num = int(input("กรอกตัวเลข : ")) total = total + num print("ผลรวมค่าที่รับมาทั้งหมด = ",total)
ab76e546874b2bce5ecd02890e8a1db5d44125eb
neung20402/Python
/week2/test7.py
1,491
3.65625
4
print(" โปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์ ") print("---------------------------------------") print(" รถยนต์ 4 ล้อ กด 1 ") print(" รถยนต์ 6 ล้อ กด 2 ") print(" รถยนต์มากกว่า 6 ล้อ กด 3 ") choose = int(input("\n เลือกประเภทยานภาหนะ : ")) four = [25 , 30 , 45 , 55 , 60] six = [45 , 45 , 75 , 90 , 100] mostsix = [60 , 70 , 110 , 130 , 140] if choose==1: clist=list(four) print("\n ค่าบริการรถยนต์ประเภท 4 ล้อ \n") if choose==2: clist=list(six) print("\n ค่าบริการรถยนต์ประเภท 6 ล้อ \n") if choose==3: clist=list(mostsix) print("\n ค่าบริการรถยนต์ประเภทมากกว่า 6 ล้อ \n") print("ลาดกระบัง-->บางบ่อ.....",clist[0],".....บาท") print("ลาดกระบัง-->บางประกง..",clist[1],".....บาท") print("ลาดกระบัง-->พนัสคม....",clist[2],".....บาท") print("ลาดกระบัง-->บ้านบึง.....",clist[3],".....บาท") print("ลาดกระบัง-->บางพระ....",clist[4],".....บาท")
56b57bdd2fc048bd1f4feec420779d3193dc305a
ikramulkayes/University_Practice
/practice107.py
426
3.8125
4
def function_name(word): dic = {} count = 0 for k in word: if k.isdigit() or k.isalpha(): if k not in dic.keys(): dic[k] = [count] else: temp = dic[k] temp.append(count) dic[k] = temp count += 1 return dic print(function_name("this is my first semester.")) print(function_name("my student id is 010101."))
1ff6938b2332ff63f21894b59e39795061b8486c
ikramulkayes/University_Practice
/practice16.py
698
3.765625
4
dict1 = input("Enter a number: ") dict2 = input("Enter another number: ") dict1 = dict1[1:-1] dict1 = dict1.split(", ") dict2 = dict2[1:-1] dict2 = dict2.split(", ") lst = [] final = {} flag = True for i in dict1: m = i.split(": ") for k in dict2: j = k.split(": ") if m[0] == j[0]: lst.append(m[1].strip("'")) lst.append(j[1].strip("'")) flag = False if flag: lst.append(m[1].strip("'")) f = m[0] f = f[1:-1] final[f] = lst flag = True lst = [] for k in dict2: j = k.split(": ") m = j[0] m = m.strip("'") if m not in final.keys(): final[m] = [j[1].strip("'")] print(final)
77bfa9039336ed579826500626f2018bc272bf7a
ikramulkayes/University_Practice
/practice74.py
252
3.921875
4
word1 = input("Enter a word: ") word2 = input("Enter a word: ") final = "" for i in word1: if i in word2: final += i for i in word2: if i in word1: final += i if final =="": print("Nothing in common.") else: print(final)
70becfda5c39f6de278654fb9a5e5b8d35c40f3f
ikramulkayes/University_Practice
/practice69.py
240
3.6875
4
def convert_to_list(square_matrix_dict): lst = [] for k,v in square_matrix_dict.items(): lst.append(v) return lst square_matrix_dict = {1 : [1,2,3] , 2 : [4,5,6] , 3 : [7,8,9] } print(convert_to_list(square_matrix_dict))
213049edd2f0c0e10bd8b781ae666840f44b6f09
ikramulkayes/University_Practice
/practice14.py
341
3.6875
4
color = input("Enter a number: ") sumr = 0 sumg = 0 sumb = 0 lst = [] for i in color: if i == "R": sumr += 1 elif i == "G": sumg += 1 elif i == "B": sumb += 1 if sumr > 1: lst.append(("Red",sumr)) if sumg > 1: lst.append(("Green",sumg)) if sumb > 1: lst.append(("Blue",sumb)) print(tuple(lst))
27e40e90c22bd82f2b6b15c0522872277926cf95
ikramulkayes/University_Practice
/practice86.py
1,159
3.90625
4
try: word = input("Enter your equation: ") lst = ["+","-","/","%","*"] flag = True op = "" sum1 = 0 for i in word: if i in lst: op = i word = word.split(i) flag = False break if len(word) > 2: raise IndexError if flag: raise RuntimeError if op == "+": for i in word: i = int(i.strip()) sum1 += i elif op == "-": sum1 = int(word[0].strip()) - int(word[1].strip()) elif op == "/": sum1 = int(word[0].strip()) / int(word[1].strip()) elif op == "%": sum1 = int(word[0].strip()) % int(word[1].strip()) elif op == "*": sum1 = int(word[0].strip()) * int(word[1].strip()) else: raise RuntimeError print(sum1) except IndexError: print("Input does not contain 3 elements/Wrong operator") except ValueError: print("Input does not contain numbers.") except RuntimeError: print("Input does not contain 3 elements/Wrong operator") except ZeroDivisionError: print("You cannot devide anything by Zero") except Exception: print("There are some errors")
fb2aab5142dbb35c7e8ed8da1b5db79ca4c52f79
ikramulkayes/University_Practice
/practice98.py
303
3.609375
4
rotate = int(input("Enter a number: ")) lst = [] for i in range(rotate): k = (input("Enter ID: ")) lst.append(k) dic = {} for i in lst: k = i[0:2] + "th" if k not in dic.keys(): dic[k] = [i] else: temp = dic[k] temp.append(i) dic[k] = temp print(dic)
20103fee91c007c5ae2bf3f744484d8439373bae
ikramulkayes/University_Practice
/practice65.py
603
3.625
4
def function_name(word): word = word.split() word = sorted(word) lst =[] for i in word: if i not in lst: lst.append(i) dic = {} for i in lst: count = 0 for k in word: if i == k: count += 1 dic[i] = count fdic = {} lst = [] for k,v in dic.items(): newtemp = (v,k) #best thing you can do with dic and tuple combo lst.append(newtemp) lst = sorted(lst) for v,k in lst: fdic[k] = v return fdic print(function_name("go there come and go here and there go care"))
e3adaf7cbc084bc3f4582e57ba9229ab200c1639
ikramulkayes/University_Practice
/practice115.py
412
3.890625
4
#que no 3 def function_name(num1): count = 0 sum1 = "" for i in range(num1): if count == 0: sum1 += "A"*num1 + "\n" elif count == num1-1: sum1 += "#"*(num1-1) + "A"*num1 else: sum1 += "#"*count +"A" +"*"*(num1-2) + "A"+'\n' count += 1 return sum1 print(function_name(4)) #print(function_name(3)) print(function_name(5))
9df9246de021e02e56c66a6bd0de75e216927c6a
ikramulkayes/University_Practice
/practice63.py
321
3.5625
4
def function_name(word): #word = word.split() lst = [] for i in word: if i not in lst: lst.append(i) flst = [] num = 0 for i in lst: num = ord(i) temp = str(num)+str(i)+str(num) flst.append(temp) return(flst) print(function_name("pythonbook"))
96eaaf367f434255625e9daf04e5e6ccc4cdb22b
ikramulkayes/University_Practice
/practice70.py
1,316
3.953125
4
def convert_to_diagonal(square_matrix_dict): lst = [] final = "" for k,v in square_matrix_dict.items(): lst.append(v) for i in range(len(v)): if i == len(v) - 1: final += str(v[i]) + "\n" else: final += str(v[i]) + " " print("Non-diagonal matrix:") print("In list of list format:",lst) print("in orginal square format:") print(final,end="") print("================") dlst = [] dfinal = "" count = 0 for i in range(len(lst)): temp = [] for k in range(len(lst[i])): if k == count: temp.append(lst[i][k]) if k == len(lst[i])-1: dfinal += str(lst[i][k]) + "\n" else: dfinal += str(lst[i][k]) + " " else: temp.append(0) if k == len(lst[i])-1: dfinal += str(0) + "\n" else: dfinal += str(0) + " " dlst.append(temp) count += 1 print("Diagonal matrix:") print("In list of list format:",dlst) print("in orginal square format:") print(dfinal,end="") square_matrix_dict = {1 : [1,2,3] , 2 : [4,5,6] , 3 : [7,8,9] } convert_to_diagonal(square_matrix_dict)
1d46299408c1ab7d7d20edd1ba4b262d89e8c69b
lucaslima2018/LinguagemdeProgramacaoPython
/Desafio/usuario.py
520
3.546875
4
class Usuario: # matricula, nome, tipo (leitor ou redator), email (CRUD) def __init__(self, matricula, nome, tipo, email): self.matricula = matricula self.nome = nome self.tipo = tipo # Leitor ou Redator self.email = email # sobreescrevendo o __str__ - equivalente ao toString() do Java def __str__(self): return "%s - %s" % (self.matricula, self.nome) # return f"{self.matricula} - {self.nome}" # return "{self.matricula} - {self.nome}".format()
22a96b0956aa4837591b645997a2651743da88dd
sanketmodi6801/first-project-
/fifteenth_health_managment.py
1,741
3.953125
4
# This is a Health managment program, which stores my diet and exercise details..!! from typing import TextIO def getdate(): import datetime return datetime.datetime.now() def logging_deit(): with open("sanket_diet.txt","a") as f: diet = input("Add some space before entering your diet : ") f.write(diet + " : "+ str(getdate())) f.write("\n") def logging_exercise(): with open("sanket_exercise.txt","a") as f : exer = input("Add some space before entering your exercise : ") f.write(exer + " : "+ str(getdate())) f.write("\n") def retrive_diet(): with open("sanket_diet.txt") as f: for item in f: print(item,end="") def retrive_exercise(): with open("sanket_exercise.txt") as f: for item in f: print(item,end="") while(True): print("This is your health record file..!!") print("For logging details press [ 1.]\n " "For retriving details press [ 2.] \n " "For exit press [ 0.]" ) l = int(input()) if l==1: n = int(input("select 1 or 2 for logging details of :" " \n\t\t 1.) diet \n\t\t 2.) exercise\n")) if n==1 : logging_deit() elif n==2 : logging_exercise() else : print("Enter valid value ..!! ") continue elif l==2 : n = int(input("select 1 or 2 for retriving details of :" " \n\t\t 1.) diet \n\t\t 2.) exercise\n")) if n==1 : retrive_diet() elif n==2 : retrive_exercise() else : print("Enter valid value ..!! ") continue elif l==0: break print("Thank you..!!\n\t Have a nice day..!!")
ee4492b84507e8311614c571f5df40c17b170ad7
kleyton67/algorithms_geral
/uri_1032.py
855
3.796875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ''' Kleyton Leite Problema do primo jposephus, deve ser considerado a primeira troca Arquivo uri_1032.py ''' import math def isprime(n): flag = True if n == 2: return flag for i in range(2, int(math.sqrt(n))+1, 1): if(n % i == 0): flag = False break return flag def primo(pos): for i in range(2, 32000, 1): if(isprime(i)): pos = pos - 1 if (not pos): return i n = 0 n = input("") pulo = 0 posicao = 0 if n > 0: lista = list(range(1, n+1, 1)) p_primo = 1 while(len(lista) > 1): pulo = primo(p_primo)-1 while (pulo): posicao = (posicao+1) % len(lista) pulo = pulo - 1 del(lista[posicao]) p_primo = p_primo + 1 print (lista)
b5e6a2ce6513df4d043cb5fe149d5573a5f2fb8c
hmhudson/user-signup
/crypto/caesar.py
762
3.953125
4
from sys import argv, exit from helpers import alphabet_position, rotate_character def encrypt(text, rot): rot_message = "" for i in text: if i.isalpha(): x = rotate_character(i, rot) rot_message += str(x) else: rot_message += str(i) return(rot_message) def user_input_is_valid(cl_args): if len(cl_args) != 2: return False if cl_args[1].isdigit()== True: return True else: return False def main(): if user_input_is_valid(argv) == False: print("usage: python3 caesar.py n") exit() text = input("Type a message:") rot = int(argv[1]) user_input_is_valid(argv) print(encrypt(text, rot)) if __name__ == '__main__': main()
fd8bf7ff5152280eb9942b2128ab29082df84432
ndtands/MachineLearning
/8.Logistic_Regression/test.py
188
3.5
4
import numpy as np x = np.array([[0, 3], [4, 3], [6, 8]]) print(np.linalg.norm(x, axis = 1, keepdims = True)) print(np.linalg.norm(x)) print(np.linalg.norm(x, axis = 0, keepdims = True))
4c8965f39e33753729e96142fa6e71c90d24b728
ililk/CUGSE
/数据结构课设/DataStructure/LintCode_easy/LinearList/insertionSortList.py
1,452
3.984375
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param: head: The first node of linked list. @return: The head of linked list. """ def insertionSortList(self, head): # write your code here if head == None: return head #first 为未排序链表的头节点 first = head.next head.next = None #设置一个dummy链接在head的前面 dummy = ListNode(0) dummy.next = head #设置一个尾节点和新值比较 tail = head while first: #新值比尾节点要大则直接接上 if tail.val < first.val: tmp = first tail.next = tmp first = first.next tail = tail.next tail.next = None #新值要是比尾节点小则从头开始遍历 else: pre = dummy cur = dummy.next while cur: if cur.val < first.next: pre = pre.next cur = cur.next else: tmp = first first = first.next tmp.next = cur pre.next = tmp break return dummy.next
e77ae27829c9f25024d0326b03503913dff0c543
Laurilao/cs50
/pset8/mario.py
700
4.03125
4
def main(): # Get user input while True: height = int(input("Height: ")) if height < 24 and height > 0: break rownumber = 1 # Keep track of current row, initially 1st # Iterate over desired height for i in range(height): # Print the pyramid structure print(" " * (height - rownumber), end="") print("#" * (i + 1), end="") printgap() print("#" * (i + 1), end="") # Print a newline print() # Increment row number on each iteration rownumber += 1 def printgap(): print(" ", end="") if __name__ == "__main__": main()
962a51fe87a6f273d69b4c3ba5792fc7835ef55a
hayatbayramolsa/Yapay-Zeka-Proje-Ekibi-Gt-
/UygulamaDersi1.py
4,712
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 18 13:02:27 2020 @author: Hp 840 """ Uygulama1: 1 ile 50 arasındaki tüm çift sayıları bir listede topla. # liste.append() listeye eleman ekleme *** Basit düşün! *** liste = [] for i in range(50): if(i % 2 == 0): liste.append(i) Uygulama2: Haftanın günlerini sayı ve isim olarak tutan bir sözlük yazın. Kullanıcı bir sayı girdiğinde hangi gün olduğunu yazdırsın. Örnek: 2 -> Salı gunlerSozluk = {1 : "Pazartesi", 2: "Salı", 3 : "Çarşamba", 4 : "Perşembe", 5: "Cuma", 6: "Cumartesi", 7: "Pazar"} sayi = input("Bir sayı gir") print(gunlerSozluk[int(sayi)]) Uygulama3: Bir listenin içindeki sayılardan en büyüğünü döndüren fonksiyonu yazın. Integer değer verecek. def enBuyuk(liste): enBuyukSayi = liste[0] for i in liste: if (i > enBuyukSayi): enBuyukSayi = i return enBuyukSayi liste = [1, 9, 5, 15, 82, 2, 150, 19, 7] enBuyuk(liste) Uygulama4: Listedeki sayılardan en küçüğünü döndüren fonksiyonu yazın. def enKucuk(liste): enKucukSayi = liste[0] for i in liste: if (i < enKucukSayi): enKucukSayi = i return enKucukSayi liste = [-10, 9, 5, 15, 82, 2, 150, 19, 7] enKucuk(liste) Uygulama5: Bir listenin içinde kaç tane unique(benzersiz) değer olduğunu döndüren fonksiyonu yazın. Unique: Sadece bir kez tekrarlanan değer. İpucu: İç içe for döngüsü. def kacUnique(liste): uniqueSayisi = 0 for i in liste: say = 0 for j in liste: if (i == j): say = say + 1 if (say == 1): uniqueSayisi = uniqueSayisi + 1 return uniqueSayisi liste = [1, 9, 5, 15, 1, 2, 9, 4, 19, 15] kacUnique(liste) Uygulama6: Bir listede belirli bir elemanın kaç kez geçtiğini döndüren fonksiyonu yazın. Fonksiyon liste ve eleman şeklinde 2 parametre almalı. def kacKezGeciyor(liste, eleman): say = 0 for i in liste: if (i == eleman): say = say + 1 return say liste = [1, 3, 5, 2, 4, 1, 1, 4] kacKezGeciyor(liste, 4) Genel kültür: Bir veri setinde verilerden birinin kaç kez yer aldığına sıklık(frequency) denir. Uygulama 7: Bir listedeki en çok tekrar eden değeri döndüren fonksiyonu yazın. İpucu: Bir önceki yazdığınız fonksiyondan faydalanın. def tekrarlanan(liste): tekrarEtmeSayisi = 0 for i in liste: sayi = kacKezGeciyor(liste, i) if (sayi > tekrarEtmeSayisi): tekrarEtmeSayisi = sayi enCokTekrarEden = i return enCokTekrarEden liste = [1, 3, 5, 2, 4, 1, 1, 5, 3, 3, 3] tekrarlanan(liste) Genel kültür: Bir veri setinde sıklık(frequency) değeri en yüksek olana matematikte mod değeri, veri biliminde top veri denir. Uygulama 8: Bir listenin medyan değerini veren fonksiyonu yaz. Veriler küçükten büyüğe sıralandığında ortada kalan değerdir. Çift sayıda olursa ortadaki 2 değer. liste.sort() Küçükten büyüğe sıralı hale getirir. liste.sort() 1,2,3 -> Tek sayıdaysa direk ortadaki 1,2,3,4 -> Ortadaki 2 tane 1,2,3,4,5 def medyanBul(liste): liste.sort() # Eğer tek sayıysa if(len(liste) % 2 == 1): elemanSayisi = len(liste) ortaindex = int((elemanSayisi - 1) / 2) return liste[ortaindex] # Eğer çift sayıysa else: index = int(len(liste) / 2) return [liste[index - 1], liste[index]] medyanBul([1,2,3,4,5,6,7,8]) Uygulama 9: Listedeki değerlerin aritmetik ortalamasını veren fonksiyonu yazın. def ortalama(sayilar): a = 0 b = len(sayilar) for i in sayilar: a = a + i return a / b ortalama([3,4,5,6]) Uygulama 10: Verilen listeyi detaylıca analiz eden bir fonksiyon yaz. Min değer, max değer, medyan, aritmetik ortalama, kaç tane unique değer var, en çok tekrar eden hangisi ve bu kaç kez tekrar ediyor. def analiz(liste): print("Minimum değer:") print(enKucuk(liste)) print("Maximum değer:") print(enBuyuk(liste)) print("Medyan:") print(medyanBul(liste)) print("Aritmetik Ortalama:") print(ortalama(liste)) print("Kaç unique değer var?") print(kacUnique(liste)) print("Top value:") print(tekrarlanan(liste)) print("Kaç kez tekrar ediyor") print(kacKezGeciyor(liste, tekrarlanan(liste))) liste= [1,2,3,4,5,6,7] analiz(liste)
f7cf5485d6767b504de12f472d9a4d5cf9035e6b
jgarciakw/virtualizacion
/ejemplos/ejemplos/comprehension1.py
386
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #____________developed by paco andres____________________ toys = ['Buzz', 'Rex', 'Bo', 'Hamm', 'Slink', ] len_map1 = {} for toy in toys: len_map1[toy] = len(toy) len_map = {toy: len(toy) for toy in toys} if __name__ == "__main__": print (len_map1) print (len_map) edad=18 a="mayor" if edad>20 else "nemor" print(a)
0a4c81ea0d6e66f6290e55978e9b3400d421ccd3
jgarciakw/virtualizacion
/ejemplos/ejemplos/texto.py
151
3.5625
4
cad1="a caballo regalado" cad2="no le mires el diente " cad1=cad1.upper() cad2=cad2.strip() cad1=cad1+" "+cad2.upper() print(cad1)
e783154304256165ff443159d4181209454d2e08
kanishk333gupta/Elementary-Signals-in-continuous-and-discrete-time
/Exponential signal.py
1,765
4.34375
4
#EXPONENTIAL SIGNAL import numpy as np #Importing all definitions from the module and shortening as np import matplotlib.pyplot as mplot #Shortening as mplot ,an alias to call the library name ###CONTINUOUS x = np.linspace(-1, 2, 100) # 100 linearly spaced numbers from -1 to 2 xCT = np.exp(x) # Exponent function mplot.plot(x , xCT) # Plot a exponential signal mplot.xlabel('x') # Give X-axis label for the Exponential signal plot mplot.ylabel('exp(x)') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Continuous Time')#Give a title for the Exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the Exponential signal ###DISCRETE #Defining a function to generate DISCRETE Exponential signal # Initializing exponential variable as an empty list # Using for loop in range # and entering new values in the list # Ends execution and return the exponential value def exp_DT(a, n): exp = [] for range in n: exp.append(np.exp(a*range)) return exp a = 2 # Input the value of constant n = np.arange(-1, 1, 0.1) #Returns an array with evenly spaced elements as per the interval(start,stop,step ) x = exp_DT(a, n) # Calling Exponential function mplot.stem(n, x) # Plot the stem plot for exponential wave mplot.xlabel('n') # Give X-axis label for the Exponential signal plot mplot.ylabel('x[n]') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Discrete Time') # Give a title for the exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the exponential signal
26864be554f52e6a3dc2cee5455de74599228579
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
355
4.15625
4
#!/usr/bin/python3 """ number_of_lines function module """ def number_of_lines(filename=""): """Get the numbers of lines into a text file Keyword Arguments: filename {str} -- [text file] """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: lines += 1 return lines
687e728de6afc1a57f322db9204a20957055b25c
angellovc/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,770
4.125
4
#!/usr/bin/python3 """ Matrix_divided functions module """ def matrix_divided(matrix, div): """ Make a division of all the elements into the matrix by a div number returns a new result list Args: matrix: matrix of dividends, just floats or integers are allowed div: that's represent the divisor, you cannot use 0, because division by zero in imposible """ is_matrix = all(isinstance(element, list) for element in matrix) if is_matrix is False: # check if matrix is really a matrix errors("no_matrix_error") length = len(matrix[0]) # check the corrent length for row in matrix: if length != len(row): errors("len_error") for row in matrix: # check if the elements into the matrix are numbers if len(row) == 0: errors("no_number_error") for element in row: if type(element) not in [int, float]: errors("no_number_error") if div == 0: errors("zero_error") if type(div) not in [int, float]: errors("div_not_number") new_matrix = [] def division(dividend): return round((dividend / div), 2) for i in range(0, len(matrix)): # make the matrix division new_matrix.append(list(map(division, matrix[i]))) return new_matrix def errors(error): # errors list if error == "len_error": raise TypeError("Each row of the matrix must have the same size") if error in ["no_number_error", "no_matrix_error"]: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") if error == "zero_error": raise ZeroDivisionError("division by zero") if error == "div_not_number": raise TypeError("div must be a number")
0665247c33469b1d96396ba065085a5a36b6f6d5
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
240
3.703125
4
#!/usr/bin/python3 """ sate_to_json_file module """ import json def save_to_json_file(my_obj, filename): """ save the json obj into a json file """ with open(filename, mode="w", encoding="UTF8") as f: json.dump(my_obj, f)
f0c1ca32d74b47203d48ebe82b5520069a1bdacc
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
515
4.21875
4
#!/usr/bin/python3 """ read_lines module """ def read_lines(filename="", nb_lines=0): """read and print n number of lines into a text file Keyword Arguments: filename {str} -- [text file] (default: {""}) nb_lines {int} -- [n lines to read] (default: {0}) """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: print(line, end="") lines += 1 if nb_lines > 0 and lines >= nb_lines: break
60cc05902d464fbde315cef67dc852e5612a0849
angellovc/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
360
3.734375
4
#!/usr/bin/python3 """[MyList class module]""" class MyList(list): """[it Inherit from list the ability to make list and his methods] Arguments: list {[list class]} """ def print_sorted(self): """[this method print the list in a sorted way] """ sorted = self.copy() sorted.sort() print(sorted)
13ecec23ce620311c11f33da1ba3bba90cbd7fec
angellovc/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
241
4.4375
4
#!/usr/bin/python3 """ print the ascii alphabet in reverse using upper and lower characters""" for lower, upper in zip(range(122, 96, -2), range(89, 64, -2)): print("{}{}".format(chr(lower), chr(upper)), end='') # print ascii numbers
7047a0e23e92e6a4fb43261c0e303bec4582f49c
jatkin-wasti/python_sparta_task
/sets.py
664
3.78125
4
# What are sets? # There is no indexing in sets therefore # Sets are UNORDERED # Syntax for sets is {"value1", "value2", "value3"} # Use cases: Data that needs to be stored for long periods of time but there is low demand to access it # Also useful for random sets of data e.g. lottery numbers # car_parts = {"wheels", "doors", "engine", "radio", "steering wheel"} print(car_parts) # This does not return the values in the same order that it was input # managing data with sets car_parts.add("seatbelts") # Can add items with add() print(car_parts) car_parts.remove("wheels") # Can remove items with remove() print(car_parts) # Look up frozen sets as a task
6aa9dfeb5ede40c08928e9244464db2babe22967
KMSkelton/leetcode
/PY/977-squares-of-sorted-arrays.py
340
3.515625
4
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: return(sorted([i*i for i in A])) #this is the kind of question list comprehensions excel at. # the list comprehension is essentially a compressed version of a for loop # and it doesn't require a separate list for storage
b430ec91b412c2e2896f303314d0bfb484356b80
peg-ib/Algorithms-and-data-structures
/module 5/BinarySearchTree.py
7,722
3.703125
4
import fileinput from collections import deque import re class TreeNode: def __init__(self, key, value): self.key = key self.value = value self.left = None self.right = None self.parent = None class BinarySearchTree: def __init__(self): self.root = None def add(self, key, value): add_node = TreeNode(key, value) parent_node = None current_node = self.root while current_node is not None: parent_node = current_node if current_node.key < key: current_node = current_node.right elif current_node.key > key: current_node = current_node.left elif current_node.key == key: raise Exception('error') add_node.parent = parent_node if parent_node is None: self.root = add_node elif parent_node.key < add_node.key: parent_node.right = add_node elif parent_node.key > add_node.key: parent_node.left = add_node def delete(self, key): del_node = self.search_node(key) if del_node is None: raise Exception('error') left_child = del_node.left right_child = del_node.right if left_child is None and right_child is None: if del_node == self.root: self.root = None elif del_node.parent.left == del_node: del_node.parent.left = None elif del_node.parent.right == del_node: del_node.parent.right = None elif left_child is None and right_child is not None: if del_node == self.root: self.root = right_child right_child.parent = None elif del_node.parent.left == del_node: del_node.parent.left = right_child right_child.parent = del_node.parent elif del_node.parent.right == del_node: del_node.parent.right = right_child right_child.parent = del_node.parent elif left_child is not None and right_child is None: if del_node == self.root: self.root = left_child left_child.parent = None elif del_node.parent.left == del_node: del_node.parent.left = left_child left_child.parent = del_node.parent elif del_node.parent.right == del_node: del_node.parent.right = left_child left_child.parent = del_node.parent else: current_node = left_child while current_node.right is not None: current_node = current_node.right del_node.key = current_node.key del_node.value = current_node.value if current_node.left is None: if current_node.parent.left == current_node: current_node.parent.left = None elif current_node.parent.right == current_node: current_node.parent.right = None elif del_node == self.root: del_node.left = None elif current_node.left is not None: if current_node.parent == del_node: del_node.left = current_node.left current_node.left.parent = del_node else: current_node.parent.right = current_node.left current_node.left.parent = current_node.parent def set(self, key, value): element = self.search_node(key) if element is None: raise Exception('error') element.value = value def search_node(self, key): current_node = self.root while current_node is not None and key != current_node.key: if key < current_node.key: current_node = current_node.left else: current_node = current_node.right return current_node def search(self, key): current_node = self.search_node(key) if current_node is None: return 0 return '1 ' + current_node.value def max(self): current_node = self.root if self.root is None: raise Exception('error') while current_node.right is not None: current_node = current_node.right return current_node def min(self): current_node = self.root if self.root is None: raise Exception('error') while current_node.left is not None: current_node = current_node.left return current_node def print_tree(tree, queue=None): if tree.root is None: print('_') return if queue is None: queue = deque() queue.append(tree.root) new_queue = deque() answer = '' has_children = False while len(queue) != 0: queue_element = queue.popleft() if queue_element == '_': new_queue.append('_') new_queue.append('_') answer += "_ " continue elif queue_element.parent is None: answer += '[' + str(queue_element.key) + ' ' + queue_element.value + '] ' elif queue_element.parent is not None: answer += '[' + str(queue_element.key) + ' ' + queue_element.value + ' ' + str( queue_element.parent.key) + '] ' if queue_element.left is not None: has_children = True new_queue.append(queue_element.left) else: new_queue.append('_') if queue_element.right is not None: has_children = True new_queue.append(queue_element.right) else: new_queue.append('_') print(answer[:-1]) if not has_children: return print_tree(tree, new_queue) if __name__ == '__main__': binary_search_tree = BinarySearchTree() for line in fileinput.input(): line = line.strip('\n') if re.match(r'^add [+-]?\d+ \S+$', line): try: command, element_key, element_value = line.split() binary_search_tree.add(int(element_key), element_value) except Exception as msg: print(msg) elif re.match(r'^delete [+-]?\d+$', line): try: command, element_key = line.split() binary_search_tree.delete(int(element_key)) except Exception as msg: print(msg) elif re.match(r'^set [+-]?\d+ \S+$', line): try: command, element_key, element_value = line.split() binary_search_tree.set(int(element_key), element_value) except Exception as msg: print(msg) elif re.match(r'^search [+-]?\d+$', line): command, element_key = line.split() print(binary_search_tree.search(int(element_key))) elif re.match(r'^max$', line): try: node = binary_search_tree.max() print(node.key, node.value) except Exception as msg: print(msg) elif re.match(r'^min$', line): try: node = binary_search_tree.min() print(node.key, node.value) except Exception as msg: print(msg) elif re.match(r'^print$', line): print_tree(binary_search_tree) else: print('error')
4a39a59715d3e675e47fa9e0639a3a42963319d8
AugustRush/Python-demos
/demo.py
380
3.65625
4
#! /usr/bin/env python import urllib import urllib2 def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getHtml2(url): request = urllib2.Request(url) page = urllib2.urlopen(request) html = page.read() return html html = getHtml("http://tieba.baidu.com/p/2738151262") html2 = getHtml2("http://www.baidu.com/") print html print html2
3ffc3da5daf3cff90d1edec928c96603f3c3137c
Tangogow/googleFormBot
/rd.py
2,758
4
4
import random def rd(choice, weight=[100], required=True): ''' Return random value in provided list. By default, if the default weight is [100] or if not any weight provided, it will the chance of outcome equally for each choice: ex: rd(['A', 'B', 'C']) => 100% / 3 => weight = ['33', '33', '33'] ex: rd(['A', 'B', 'C', 'D']) => 100% / 4 => weight = ['25', '25', '25', '25'] The number of weight value need to match the same number of choice values provided, except if required is False, then you need to provide the non choice weight. ex: rd(['A', 'B'], [60, 40], True) => Correct: the question is required, so 60% for A and 40% for B ex: rd(['A', 'B'], [50, 40], True) => Incorrect: since the sum of the weight is below 98% ex: rd(['A', 'B'], [50, 50], False) => Incorrect: the question is not required, so the none choice is enabled and you need to provide it's weight ex: rd(['A', 'B'], [30, 50, 20], False) => Correct: 30% for A, 50% for B, 20% for the none choice ex: rd(['A', 'B'], [100], False) => Correct: 33% for A, 33% for B, 33% for the none choice ex: rd(['A', 'B'], [100], True) => Correct: 50% for A, 50% for B and no none choice since it's a required question The sum of amount need to be around 100% (with a tolerance for about +/- 2% for rounded values) Weight values are rounded up, so it doesn't matter if you add the exact decimals or not. ''' if not required: # add the none choice if not required choice.append("") print(choice, len(choice), len(weight)) weight = [int(round(x)) for x in weight] # rounded up if floats if sum(weight) <= 98 or sum(weight) > 102: print("Error: Need 100% weight. (with +/- 2% if not rounded)") exit(1) if len(choice) != len(weight) and weight == [100]: # if weight not set (by default setted at 100) percent = 100 / len(choice) # dividing 100 by nb of elements in choice weight = [percent for i in range(len(choice))] # set same weight for all choices elif len(choice) != len(weight) and not required: print("Error: Choice and weight lists doesn't contains the same numbers of elements") print("Don't forget to add the percentage for the none choice at the end.") print("The none choice is enabled since it's a 'not required' question") exit(1) elif len(choice) != len(weight): print("Error: Choice and weight lists doesn't contains the same numbers of elements") exit(1) res = [] for i in choice: # filling up the list : choice[0] * weight[0] + choice[1] * weight[1]... for j in range(weight[choice.index(i)]): res.append(i) return random.choice(res)
70a97b65e8cb2c963b0ae981b52ae5b191743d57
emmaAU/CSC280
/Random.py
575
4.125
4
#import random #print(random.random) import math print(math) a = int(input('enter coefficient for x**2 ')) b = int(input('enter b: ')) c = int(input('what is c?: ')) disc = b**2 - 4*a*c if disc > 0: root1 = -b + math.sqrt(disc) / 2*2 print(root1) root2 = -b - math.sqrt(disc) / 2*2 print(root2) elif disc == 0: root1 = root2 = -b / 2*2 else: print('no roots') product = 1 n = int(input('please enter a value you want to compute its factorial')) for i in range(2, n+1): product = product * i print('the factorial of', n, 'is, product')
78c1ab180bc7cf08dd7af9a28bcb49377840eaeb
madhan99d/python
/list implementation.py
2,159
3.859375
4
class node: def __init__(self,d): self.addr=None self.data=d class oper: def __init__(self): self.head=None def display(self): temp=self.head while (temp!=None): print(temp.data,"-->",end="") temp=temp.addr print("none") def count(self): temp=self.head c=0 while(temp!=None): c=c+1 temp=temp.addr print(c) def insert(self): print("enter the data of the new node to be inserted") dat=input() newnode=node(dat) print("enter the position to be inserted ") i=input() if(i=='0' or i=="first" or i=="First" or i== "FIRST"): newnode.addr=self.head self.head=newnode print("insertion successfull") elif(i=="last" or i=="Last" or i=="LAST"): temp=self.head while(temp!=None): if temp.addr==None: break temp=temp.addr temp.addr=newnode print("insertion successfull") else: c=1 temp=self.head while(c<int(i)): c=c+1 temp=temp.addr prev=temp.addr temp.addr=newnode newnode.addr=prev print("insertion successfull") def delete(self): print("enter the node to be deleted") dat=int(input()) if self.head.data==dat: self.head.next=head self.head.addr=None print("deletion successfull") else: temp=self.head while(temp!=None): if temp.addr.data==dat: break temp=temp.addr ne=temp.addr temp.addr=ne.addr ne.addr=None print("deletion successfull") obj=oper() ch=0 while(ch!=5): ch=int(input("enter the value 1.display 2.count 3.insert 4.delete")) if ch==1: obj.display() elif ch==2: obj.count() elif ch==3: obj.insert() elif ch==4: obj.delete()
57eb63f9f063deda592db8a58ebf420737f5f37c
etridenour/digitalCrafts
/classNotes/python/class7-2.py
2,516
4.3125
4
# class MyClass: # def SayHello(): # print("Hello there!") # MyClass.SayHello() class Person: def greet (self): #self points to object you are creating (ex. me, matt) print("Hello") me = Person() me.greet() matt = Person() matt.greet() # class MyClass: # Greeting = " " # lcass variable, available to all objects # def __init__(self): # print("Upon Initialization: Hello!") # def instance_method(self): #creates space to be filled in, self has to be there to let it know what to reference # print("Hello {0}".format(self.Greeting)) # def class_method(): # this is a class method because it doesn't have self # print("Hello {0}".format(self.Greeting)) # digitalCrafts = MyClass() # flatIrons = MyClass() # flatIrons.instance_method() # MyClass.Greeting = 'Eric' #set global variable equal to greeting, can change the name and will change in output # digitalCrafts.instance_method() # utAustin = MyClass() # utAustin.instance_method() # # digitalCrafts.instance_method() # # # MyClass.class_method() #calling a class method, this needs myClass before # # test.class_method() # class Person: # GlobalPerson = "Zelda" # global variable # def __init__ (self, name): # self.name = name #set instance variable # print(name) # def greet (self, friend): # instance method # print("Hello {} and {} and {}".format(self.name, friend, self.GlobalPerson)) # matt = Person('Fisher') # matt.greet("Travis") # person1 = Person('Hussein') # person1.greet("Skyler") # Person.GlobalPerson = 'Eric' # matt.greet('Travis') # person1.greet('Skyler') # class Person: # def __init__ (self, name): #constructor # self.name = name # self.count = 0 # def greet (self): # self._greet() # def _greet (self): # self.count += 1 # if self.count > 1: # print("Stop being so nice") # self.__reset_count() # else: # print("Hello", self.name) # def __reset_count(self): # self.count = 0 # matt = Person('Fisher') # matt.greet() #calling function # matt.greet() # matt.greet() # travis = Person('Ramos') #only prints hello ramos because it is it's own thing, even though went through same class # travis.greet() # class Animal: # def __init__ (self, name): # self.name = name # class Dog (Animal): #what you inherit goes in (), in this case animal # def woof (self): # print("Woof") # class Cat (Animal): # def meow (self): # print("Meow") super().__init__(power, health)
4db455f6dbb5e56a4453f50f967c122e0e9d3c03
etridenour/digitalCrafts
/test files/test4.py
143
3.6875
4
a = [1,2,3,4] b = [2,3,4,5] ab = [] #Create empty list for i in range(0, len(a)): ab.append(a[i]*b[i]) print(ab)
6d1e1a539c20dc7f23d9ac88c6bf61a5f4204153
Peteous/Web-API-Interaction
/Encode.py
3,799
4.21875
4
#urlEncode method encodes input following url encode rules for characters # url is the string you would like to encode # apiURL is an optional parameter for a string of the url of a web api, if you want to use one # paramNames is an optional list parameter containing the names of the parameters you want to encode # paramData is an optional list parameter containing the values for the parameters you want to encode # NOTE: indexes of paramNames values and paramData values should match up def urlEncode(url,apiURL=None,paramNames=None,paramData=None): #Establish an initial null output output = '' #Encode the input url, and then add the expected url parameter before it url = _urlCharShift(url) url = 'url='+url #Logic for parameters # if there are parameters to encode and an apiURL if not paramNames == None and not paramData == None and not apiURL == None: #start the output with the apiURL, since that doesn't need encoding, and add a ? output += apiURL output += '?' #find length of the paramNames list for iteration length = len(paramNames) #iterate through the paramNames list and paramData list, encoding paramData values for index in range(length): paramData[index] = _urlCharShift(paramData[index]) #choose seperate character encoding sequences if it's the first value or not if index < 1: output += paramNames[index] + '=' + paramData[index] else: output += '&' + paramNames[index] + '=' + paramData[index] #add & character to end of string, then add the encoded url value, and return output output += '&' output += url return output # if there are not parameters, but there is an apiURL elif paramNames == None and not apiURL == None: output += apiURL output += '?' output += url return output # if there isn't an apiURL but there is paramNames and paramData elif apiURL == None and not paramNames == None and not paramData == None: #follow steps of first if statement, but skip encoding the apiURL length = len(paramNames) for index in range(length): paramData[index] = _urlCharShift(paramData[index]) if index < 1: output += paramNames[index] + '=' + paramData[index] else: output += '&' + paramNames[index] + '=' + paramData[index] output += url return output # if there is just a url elif apiURL == None and paramNames == None and paramData == None: output += url return output # if there is not a url, but there is all of the other things elif url == None and not (apiURL == None and paramNames == None and paramData == None): output += apiURL output += '?' length = len(paramNames) for index in range(length): paramData[index] = paramData[index].replace(' ','+') if index < 1: output += paramNames[index] + '=' + paramData[index] else: output += '&' + paramNames[index] + '=' + paramData[index] return output # Handle edge cases else: print('\n\nAn error occured. Please check your input parameters.') return output #End logic for parameters def htmlEncode(text): text = str(text) text.replace('&','&amp;') text.replace('\"','&quot;') text.replace('\'','&apos;') text.replace('<','&lt;') text.replace('>','&gt;') text.replace('~','&tilde;') return text #internal method containing character rules for url encoding def _urlCharShift(text): url = str(text) url.replace('%','%25') url.replace('!','%21') url.replace('#','%23') url.replace('$','%24') url.replace('&','%26') url.replace('\'','%27') url.replace('(','%28') url.replace(')','%29') url.replace('*','%2A') url.replace('+','%2B') url.replace(',','%2C') url.replace('/','%2F') url.replace(':','%3A') url.replace(';','%3B') url.replace('=','%3D') url.replace('?','%3F') url.replace('@','%40') url.replace('[','%5B') url.replace(']','%5D') return url
f2ebfe3e808503702bcb7adf24b76b4e6ac8efe7
samarthjj/Tries-1
/longestWordinDict.py
1,625
4
4
from collections import deque class TrieNode(object): def __init__(self): self.word = None self.branches = [None] * 26 class Solution(object): # Time Complexity : O(nl) where n is the number of words and l is the average length of the words # Space Complexity : O(nl), where n is the number of words in the trie and l is the average length of the words # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach # The given words are first inserted in the trie, then searched. # A BFS is performed to search all nodes level by level while also maintaining # smaller lexicographical order, In the end the longest word is returned. def __init__(self): self.root = TrieNode() def insert(self, word): curr = self.root for i in word: temp = ord(i) - ord('a') if curr.branches[temp] == None: curr.branches[temp] = TrieNode() curr = curr.branches[temp] curr.word = word def longestWord(self, words): # adding to the trie for i in words: self.insert(i) # queue init q = deque() q.appendleft(self.root) curr = None # BFS with small lexicographical order while len(q) != 0: curr = q.pop() for j in range(25, -1, -1): level = curr.branches[j] if level != None and level.word != None: q.appendleft(level) return curr.word
4738eefb49f7f4f759f3d2752aaf4bfb777d1242
ashrafatef/Prims-Task
/app.py
1,588
3.703125
4
import functools def get_all_prime_numbers_in_list (prime_numbers): p = 2 limit = prime_numbers[-1] + 1 while p*p < limit: if prime_numbers[p] != 0 : for i in range(p*p , limit , p): prime_numbers[i] = 0 p+=1 return prime_numbers def get_max_prime_sum_previous_prims(prims): prims_sum =[0] * len(prims) total = 0 target = 0 for i in range(len(prims)): total+=prims[i] prims_sum[i] = total for i in range(len(prims_sum)): single_prim_sum = prims_sum[i] target = search_for_prim_number(prims , single_prim_sum) or target return target def search_for_prim_number(list_of_prims , number): start = 0 end = len(list_of_prims) -1 while start <= end : mid = int((end + start) /2) if (list_of_prims[mid] == number): return list_of_prims[mid] elif (list_of_prims[mid] > number): end = mid - 1 elif (list_of_prims[mid] < number): start = mid + 1 return False def main(): limit = int(input()) all_numbers = list(range(limit)) prime_numbers = get_all_prime_numbers_in_list(all_numbers) filtered_prim_numbers = list(filter(lambda x : x != 0 and x != 1 , prime_numbers)) print(filtered_prim_numbers) print ("sum of all prims" , functools.reduce(lambda a,b : a+b,filtered_prim_numbers)) prim_of_all_sum_of_prims = get_max_prime_sum_previous_prims(filtered_prim_numbers) print ("THE Prime" , prim_of_all_sum_of_prims) main()
6e6a78384301f229455a7b76dcd4e7f7d9ba9f25
reuben-dutton/random-color-memes-2
/themes/select_theme.py
661
3.5625
4
import sys import json import random ''' This file selects a random theme from the available ones and sets it to be the current theme. This does not take into account a theme vote. ''' name = sys.argv[1] # Load the themes. themes = json.loads(open(sys.path[0] + '/../json/themes.json').read()) # Select a random theme. If the random theme is 'None', continue # selecting a random theme until it isn't. if name in list(themes.keys()): theme = name else: print("Not a theme, please try another.") # Save the randomly selected theme as the current theme. with open(sys.path[0] + "/current.txt", "w") as currentfile: currentfile.write(theme)
4f7ff64e0ec87b80e8689e8d484f9c0cefd3fbdf
ParkerCS/ch18-19-exceptions-and-recursions-aotoole55
/recursion_lab.py
1,152
4.78125
5
''' Using the turtle library, create a fractal pattern. You may use heading/forward/backward or goto and fill commands to draw your fractal. Ideas for your fractal pattern might include examples from the chapter. You can find many fractal examples online, but please make your fractal unique. Experiment with the variables to change the appearance and behavior. Give your fractal a depth of at least 5. Ensure the fractal is contained on the screen (at whatever size you set it). Have fun. (35pts) ''' import turtle color_list = ['red', 'yellow', 'orange', 'blue'] def circle(x, y, radius, iteration): my_turtle = turtle.Turtle() my_turtle.speed(0) my_turtle.showturtle() my_screen = turtle.Screen() #Color my_turtle.pencolor(color_list[iteration % (len(color_list[0:4]))]) my_screen.bgcolor('purple') #Drawing my_turtle.penup() my_turtle.setposition(x, y) my_turtle.pendown() my_turtle.circle(radius) #Recursion if radius <= 200 and radius > 1: radius = radius * 0.75 circle(25, -200, radius, iteration + 1) my_screen.exitonclick() circle(25, -200, 200, 0)
faf2835b5d09232c872f836318aebd7234eabff7
ThePhiri/league-table-calc
/table_generator.py
2,658
3.671875
4
class TableGenerator(object): def readFile(self, file): self.results = {} self.file = file with open(self.file, 'r') as file: for line in file: self.splitLine = line.split() self.team1 = self.splitLine[0] self.team2 = self.splitLine[-2] if (int(self.splitLine[1][0]) > int(self.splitLine[-1])): if self.team1 in self.results: self.results[self.team1] += 3 else: self.results.update({self.team1: 3}) if self.team2 in self.results: self.results[self.team2] += 0 else: self.results.update({self.team2: 0}) if int(self.splitLine[1][0]) == int(self.splitLine[-1]): if self.team1 in self.results: self.results[self.team1] += 1 else: self.results.update({self.team1: 1}) if self.team2 in self.results: self.results[self.team2] += 1 else: self.results.update({self.team2: 1}) if int(self.splitLine[1][0]) < int(self.splitLine[-1]): if self.team1 in self.results: self.results[self.team1] += 0 else: self.results.update({self.team1: 0}) if self.team2 in self.results: self.results[self.team2] += 3 else: self.results.update({self.team2: 3}) allResults = self.results return allResults class ShowRanking: soccer_results = TableGenerator() sorted_scores = [] def sortResults(self): filePath = input("Please enter file pith of input file") unsorted = self.soccer_results.readFile(filePath) self.sorted_scores = sorted( unsorted.items(), key=lambda x: (-x[1], x[0])) print(self.sorted_scores) return self.sorted_scores def writeResults(self): sorted_results = self.sortResults() with open('output.txt', 'w') as f: for idx, team in enumerate(sorted_results): f.write('{0}. {1}, {2} pts\n'.format( idx + 1, team[0], team[1])) f.truncate() print("File generated as output.txt in current folder") def main(): finalTable = ShowRanking() finalTable.writeResults() if __name__ == "__main__": main()
1a34eee26a90e17c5732db0d309769ab6e1c31ac
eliza3c23/CS325-Algorithm-HW2
/quickselect.py
1,312
3.984375
4
# Eliza Nip # Summer 2020 CS325 # 07/07/2020 # HW2 Q2 Quick select # Quick select # Ref from http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html?highlight=%28CategoryAlgorithmNotes%29 # Ref from https://stackoverflow.com/questions/36176907/implementation-of-the-quick-select-algorithm-to-find-kth-smallest-number import random # Set array. # k -> kth smallest element of the array def quick_select(k,array): if array == [] : return [] # Let index be chosen in random, in range of array length index = random.randint(0,len(array)-1) # Pivot- A position that partitions the list into 2 parts. Left element < pivot and right element > pivot # Let pivot = array[index] pivot = array[index] # Set side array[0],pivot = pivot,array[0] # set Left element in array < pivot left = [i for i in array if i < pivot] # set Right element in array >= pivot right = [i for i in array[1:] if i >= pivot] # 3 if case: k = pivot; k> pivot; k< pivot if len(left) == k-1: return pivot elif len(left) < k-1: return quick_select(k-len(left)-1,right) else: return quick_select(k,left) def main(): print (quick_select(2,[1,2,3,4,5,6])) print (quick_select(3,[2,6,7,1,3,5])) if __name__ == '__main__': main()
33d66c910897318e4f4241d719d936b3b2455d2f
peluza/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
394
3.953125
4
#!/usr/bin/python3 """ finds a peak in a list of unsorted integers. """ def find_peak(list_of_integers): """find_peak Args: list_of_integers (list): list of unsorted integers. Returns: list: number peak in a list """ if len(list_of_integers) is not 0: list_of_integers.sort() return list_of_integers[-1] else: return None
5cfbd40a1f22c41890c8078c6b4d801c0844627c
peluza/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
147
3.671875
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): f = [] for i in matrix: f.append(list(map(lambda i: i*i, i))) return f
5bc5d1e5f51ce709331003e42ee710ed60a25b69
peluza/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,585
4.09375
4
#!/usr/bin/python3 """[2-matrix_divided] """ def matrix_divided(matrix, div): """matrix_divided(matrix, div) Arguments: matrix {list} -- the value is the list div {int]} -- the value is the int Raises: TypeError: matrix must be a matrix (list of list) of integers/floats TypeError: matrix must be a matrix (list of list) of integers/floats TypeError: matrix must be a matrix (list of list) of integers/floats TypeError: Each row of the matrix must have the same size TypeError: div must be a number ZeroDivisionError: division by zero Returns: list -- returns div of the value the betwen the lists """ str1 = "matrix must be a matrix (list of list) of integers/floats" str2 = "Each row of the matrix must have the same size" str3 = "div must be a number" str4 = "division by zero" if type(div) not in (int, float): raise TypeError(str3) if len(matrix) == 0 or len(matrix) == 1: raise TypeError(str2) if div == 0: raise ZeroDivisionError(str4) if type(matrix) is not list: raise TypeError(str1) len1 = len(matrix[0]) for row in matrix: if len(row) != len1: raise TypeError(str2) if len(row) == 0: raise TypeError(str1) if type(row) != list: raise TypeError(str1) for column in row: if type(column) not in (int, float): raise TypeError(str1) return [[round(column / div, 2)for column in row]for row in matrix]
6efd603459989c8fa85b848c52d05a96a2ff8a74
peluza/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
719
4.5625
5
#!/usr/bin/python3 """3-say_my_name """ def say_my_name(first_name, last_name=""): """say_my_name Arguments: first_name {str} -- the value is the first_name Keyword Arguments: last_name {str} -- the value is the las_name (default: {""}) Raises: TypeError: first_name must be a string TypeError: last_name must be a string Returns: str -- My name is <first name> <last name> """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") result = print("My name is {} {}".format(first_name, last_name)) return result
2d9b4b049e01cc81b5f69f1bf874926b0548433b
362515241010/MyScript
/arithmetic.py
407
3.921875
4
a = 8 b = 2 print("Addition:\t" , a , "+" , b , "=" , a + b ) print("Subtraction:\t" , a , "-" , b , "=" , a - b ) print("Multiplication:\t" , a , "x" , b , "=" , a * b ) print("Division\t:\t" , a , "" , b , "=" , a / b ) print("Floor Division:\t" , a , "" , b , "=" , a // b ) print("Modulus:\t" , a , "%" , b , "=" , a % b ) print("Exponent:\t" , a , " = " , a ** b , sep = " " )
598e5975a8494d9626ef46c69df30aefbae48efd
knareshk/Assignments
/try.py
401
3.8125
4
#print("iam trying how to use github") #print("iam try to add content from my meachine") #7. Write the higher order function reduce to calculate the total sum of first 30 odd values in the range of 1 to 100. import functools res = list(filter(lambda x: x % 2 == 1, list(range(0, 101)))) print(res) res = functools.reduce(lambda x, y: x + y, filter(lambda x: x % 2 == 1, range(1, 100))) print(res)
198bc20bda17400236842baaf1457b030d07b724
jhorowitz16/CTCI_python
/BitManipulation.py
7,362
3.765625
4
# 5.1 - bit insertion with masks def bit_insertion(N, M, i, j): """ :param N: :param M: :param i: :param j: :return integer: 11 with 5 on M 2 10000010000 10011 insert at index 2 10000010000 10011 build right mask, and left mask 1s on the left ... and 1s on the right 11110000011 and the mask, then or with the shifted small """ all_ones = 0xffffffff right_mask = (1 << i) - 1 left_mask = all_ones << (j + 1) mask = right_mask | left_mask clean_n = N & mask sol = clean_n | (M << i) return bin(sol) # 5.2 - print the binary representation of a double def bin_rep(double): """ :param double: :return bin: build a string ... then convert double the number ... is >= 0.5 0.125 ... double it to .25 -- small? so no 0.5s - append 0 0.25 ... small so no 0.25s - append 0 0.5 ... yes so subtract 0.5 and continue break when double == 0 keep a counter - counter gets too high return impossible """ ctr = 0 sol = "" EPSILON = 0.0001 while ctr < 32: if double <= EPSILON: return sol if double >= 0.5: double -= 0.5 sol += str(1) else: sol += str(0) double *= 2 ctr += 1 return sol + "ERROR" # 5.3 same number of bits def next_largest(n): """ :param n (integer): :return bin: 11010101 11010110 find 01 and swap it with 10 10000000000000 append a 0 to the beginning then 100000000000000 """ if n <= 0: return 0 bin_form = bin(n) bin_form = bin_form[0] + bin_form[2:] for j in range(1, len(bin_form)): i = len(bin_form) - j if bin_form[i] == '1' and bin_form[i - 1] == '0': # we found a 01 bin_form = bin_form[:i - 1] + '10' + bin_form[i + 1:] break return int(bin_form, 2) def next_smallest(n): if n <= 1: return 0 bin_form = bin(n) bin_form = bin_form[0] + bin_form[2:] for j in range(1, len(bin_form)): i = len(bin_form) - j if bin_form[i] == '0' and bin_form[i - 1] == '1': # we found a 01 bin_form = bin_form[:i - 1] + '01' + bin_form[i + 1:] break return int(bin_form, 2) # 5.4 explain this number # n & (n - 1) == 0 - power of 2 # 5.5 number of bis to convert a number into another def num_bits_to_convert(x, y): count = 0 while x > 0 or y > 0: x_one = x % 2 y_one = y % 2 if x_one != y_one: count += 1 x = x // 2 y = y // 2 return count # 5.6 - swap even and odd bits def swap_even_odd(x): """ all = XXXXXXXX odd = X.X.X.X. even = .X.X.X.X shift odd to the right shift even to the left :param x: :return: """ odd = 0xAAAA & x even = 0x5555 & x return (odd >> 1) | (even << 1) # 5.7 - find missing number """ even odd cases 0000 0001 0010 ---- 0100 0101 0110 0111 ==== 0433 last bit - more zeros than ones and should be balanced ... 1 remove bits that aren't relevant next bit - more zeros than ones and should be balanced Observation equal or less 0s? add a 0 only add a 1 when more 0s than ones """ def find_missing(bin_nums): n = len(bin_nums) + 1 k = len(bin_nums[-1]) # everything is the same length now bin_strs = [] for num in bin_nums: s = '0' * (k - len(num)) + num[2:] bin_strs.append(s) def find_missing_helper(sub_set, col): if col < 0: return '' zero_ending, one_ending = [], [] for num in sub_set: if num[col] == '1': one_ending.append(num) else: zero_ending.append(num) s = None if len(zero_ending) <= len(one_ending): # we removed a zero s = find_missing_helper(zero_ending, col - 1) + '0' else: # we removed a one s = find_missing_helper(one_ending, col - 1) + '1' return s return int(find_missing_helper(bin_strs, k - 3), 2) #5.8 Draw a horizontal line across screen class Screen(): # draw horizontal line def __init__(self, arr, width): """ width in bytes """ self.arr = arr self.width = width // 8 # in bytes def __str__(self): full_s = '' for i in range(len(self.arr) // self.width): s = '' for j in range(self.width): val = bin(self.arr[(self.width * i) + j])[2:] s += '0' * (8 - len(val)) + val + ' ' full_s += s + '\n' return full_s """ 16 bytes width 16 bits 00000000 00000000 """ def draw_horizontal_line(self, x1, x2, y): row_bit_width = self.width start = self.width * 8 * y i = start + x1 print(i) while i < start + x2 + 1: curr = self.arr[i // 8] mask = '0' * (i % 8) + '1' + '0' * (7 - i % 8) self.arr[i // 8] = int(mask, 2) | self.arr[i // 8] print(x1, x2, y, i) print(self.arr) i += 1 # ================== utils =================== # def test(call, result=True): if call != result: print("got: " + str(call)) print("expected: " + str(result)) raise ValueError("test failed") # ================== tests =================== # # 5.1 - bit insertion N = int('10000000000', 2) M = int('10011', 2) i = 2 j = 6 output = bin(int('10001001100', 2)) test(bit_insertion(N, M, i, j), output) # 5.2 - binary representation of double test(bin_rep(0.5), "1") test(bin_rep(0.125), "001") test(bin_rep(0.25), "01") test(bin_rep(0.75), "11") test(bin_rep(0.875), "111") test(bin_rep(0.875001), "111") # test(bin_rep(0.875000000000000000000001), "ERROR") # 5.3 - test(next_largest(1), 2) test(next_largest(4), 8) test(next_largest(5), 6) test(next_largest(7), 11) test(next_largest(17), 18) # 5.3 - test(next_smallest(2), 1) test(next_smallest(8), 4) test(next_smallest(6), 5) test(next_smallest(11), 7) test(next_smallest(18), 17) # 5.5 test(num_bits_to_convert(1, 0), 1) test(num_bits_to_convert(5, 0), 2) test(num_bits_to_convert(4, 0), 1) test(num_bits_to_convert(7, 0), 3) test(num_bits_to_convert(7, 4), 2) test(num_bits_to_convert(7, 1), 2) test(num_bits_to_convert(16, 1), 2) test(num_bits_to_convert(274, 274), 0) test(num_bits_to_convert(0, 0), 0) # 5.6 test(swap_even_odd(3), 3) test(swap_even_odd(1), 2) test(swap_even_odd(2), 1) test(swap_even_odd(8), 4) test(swap_even_odd(4), 8) test(swap_even_odd(7), 11) test(swap_even_odd(9), 6) test(swap_even_odd(6), 9) # 5.7 nums = [0] bin_nums = [bin(n) for n in nums] test(find_missing(bin_nums), 1) nums = [1] bin_nums = [bin(n) for n in nums] test(find_missing(bin_nums), 0) nums = [1, 2, 3, 4, 5, 6] bin_nums = [bin(n) for n in nums] test(find_missing(bin_nums), 0) nums = [0, 1, 2, 3, 5, 6] bin_nums = [bin(n) for n in nums] test(find_missing(bin_nums), 4) # 5.8 arr = [0x00 for _ in range(16)] width = 16 screen = Screen(arr, width) # 8 rows of 16 pixels print(str(screen)) screen.draw_horizontal_line(1, 6, 1) screen.draw_horizontal_line(3, 15, 4) screen.draw_horizontal_line(1, 3, 5) print(str(screen))
bdec82bb0afa429bf2ace52c1d339294e7e12007
misaka-umi/Software-Foundamentals
/01 混杂/17 print the longest word in file.py
329
4.09375
4
filename = input("Enter a filename: ") f = open(filename,'r') pockage = f.readlines() num = [] for i in pockage : a = i.split() for j in a : num.append(j) len = len(num) max = 0 maxname = 0 for i in len : if max < len(num[i]) : max = len(num[i]) maxname = num[i] print("The longest word is",)
bbd1072f2a5f859b44c7b4acd7daa5a7ae8b6c48
misaka-umi/Software-Foundamentals
/07 stacks/64 stacks-reverse sentence.py
1,846
4.125
4
class Stack: def __init__(self): self.__items = [] def pop(self): if len(self.__items) > 0 : a= self.__items.pop() return a else: raise IndexError ("ERROR: The stack is empty!") def peek(self): if len(self.__items) > 0 : return self.__items[len(self.__items)-1] else: raise IndexError("ERROR: The stack is empty!") def __str__(self): return "Stack: {}".format(self.__items) def __len__(self): return len(self.__items) def clear(self): self.__items = [] def push(self,item): self.__items.append(item) def push_list(self,a_list): self.__items = self.__items + a_list def multi_pop(self, number): if number > len(self.__items): return "False" else: for i in range(0,number): self.__items.pop() return "True" def copy(self): a=Stack() for i in self.__items: a.push(i) return a def __eq__(self,other): if not isinstance(other,Stack): return "False" else: if len(other) != len(self): return "False" else: a = other.copy() b = self.copy() #self调用的就是栈本身 for i in range(len(a)): if a.pop() != b.pop(): return "False" return "True" def reverse_sentence(sentence): a = Stack() b = sentence.split(" ") c = '' for i in range(len(b)): a.push(b[i]) for i in range(len(b)): if c == '': c= a.peek() else: c = c+" " + a.peek() a.pop() return c print(reverse_sentence('Python programming is fun '))
389e3a18586388528e2c765e39c52c74ab4f0b2b
misaka-umi/Software-Foundamentals
/10 Hash Tables/82 LinkedListHashTable.py
3,959
3.75
4
class Node: def __init__(self, data, next_data = None): self.__data = data self.__next = next_data def __str__(self): return self.__data def get_data(self): return self.__data def get_next(self): return self.__next def set_data(self,data): self.__data = data def set_next(self,next_data): self.__next = next_data def add_after(self, value): tmp = self.__next a = Node(str(value)) self.__next = a a.set_next(tmp) def remove_after(self): tmp = self.get_next().get_next() self.__next = tmp def __contains__(self, value): if self.__next == None and self.__data != value: return False else: if self.__data == value : return True tmp = self.__next while tmp != None: if tmp.get_data() == value: return True else: tmp = tmp.get_next() return False def get_sum(self): #此处假设仅有整数值 num = self.__data tmp = self.__next while tmp != None: num +=tmp.get_data() tmp = tmp.get_next() return num class LinkedList(): def __init__(self): self.__head = None def add(self, value): new_node = Node(value) new_node.set_next(self.__head) self.__head = new_node def size(self): tmp = self.__head num = 0 while tmp != None: num += 1 tmp = tmp.get_next() return num def get_head(self): return self.__head def clear(self): self.__head = None def is_empty(self): if self.__head == None: return True else: return False def __len__(self): return self.size() def __str__(self): tmp = self.__head s = '[' while tmp != None: if tmp.get_next() ==None: s = s + str(tmp.get_data()) break s = s + str(tmp.get_data()) + ', ' tmp = tmp.get_next() s = s+']' return s def __contains__(self, search_value): # 用法 print('hello' in values) tmp = self.__head while tmp != None: if tmp.get_data() == search_value: return True tmp = tmp.get_next() return False def __getitem__(self, index): #print(my_list[0]) tmp = self.__head while index != 0: tmp = tmp.get_next() index -= 1 return tmp.get_data() def add_all(self, a_list): num = len(a_list) for i in range(num): self.add(a_list[i]) def get_min_odd(self): min_ = 999 if self.__head == None: return min_ tmp = self.__head while tmp != None: num=tmp.get_data() if num %2 != 0 and num < min_: min_ = num tmp = tmp.get_next() return min_ class LinkedListHashTable: def __init__(self,size=7): self.__size = size self.__slots = [] for i in range(size): self.__slots.append(LinkedList()) def get_hash_code(self,key): return key%self.__size def __str__(self): for i in range(self.__size-1): print(str(self.__slots[i])) return str(self.__slots[self.__size-1]) def put(self, key): index = self.get_hash_code(key) self.__slots[index].add(key) def __len__(self): num = 0 for i in self.__slots: num += len(i) return num hash_table = LinkedListHashTable(5) hash_table.put(3) hash_table.put(6) hash_table.put(9) hash_table.put(11) hash_table.put(21) hash_table.put(13) print(hash_table) print("The linked list hash table contains {} items.".format(len(hash_table)))
a6f963560d6427aae4c60dc4ae9f9cb71669ac0d
misaka-umi/Software-Foundamentals
/05 class/57 class1-QuadraticEquation.py
1,275
3.671875
4
import math class QuadraticEquation: def __init__(self, coeff_a = 1, coeff_b = 1, coeff_c = 1): self.__a=coeff_a self.__b=coeff_b self.__c=coeff_c def get_coeff_a(self): return self.__a def get_coeff_b(self): return self.__b def get_coeff_c(self): return self.__c def get_discriminant(self): d = self.__b * self.__b - 4*self.__a*self.__c return d def has_solution(self): if self.get_discriminant()<0: return "False" else: return "True" def get_root1(self): i=self.get_discriminant() return (math.sqrt(i)-self.__b)/(2*self.__a) def get_root2(self): i=self.get_discriminant() return (-math.sqrt(i)-self.__b)/(2*self.__a) def __str__(self): i = self.get_discriminant() if i < 0: return "The equation has no roots." if i==0: return "The root is {:.2f}.".format(self.get_root1()) if i > 0: return "The roots are {:.2f} and {:.2f}.".format(self.get_root1(),self.get_root2()) equation1 = QuadraticEquation(4, 4, 1) print(equation1) equation2 = QuadraticEquation() print(equation2) equation3 = QuadraticEquation(1, 2, -63) print(equation3)
eefc00ea54d6cb22976e3951ce51cf4b82d8d7b8
misaka-umi/Software-Foundamentals
/03 排序/42 选择排序.py
987
3.890625
4
def my_selection_sort(data): length = len(data) for i in range(0,length-1): min = data[i] number = i for j in range(i+1,length): if min > data[j] : number = j min = data[j] if i != number: tmp = data[number] data[number] = data[i] data[i] = tmp # data[i] = return data letters = ['e', 'd', 'c', 'b', 'a','f','g','h','k'] my_selection_sort(letters) print(letters) ''' def selectionSort(arr): for i in range(len(arr) - 1): # 记录最小数的索引 minIndex = i for j in range(i + 1, len(arr)): if arr[j] < arr[minIndex]: minIndex = j # i 不是最小数时,将 i 和最小数进行交换 if i != minIndex: arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr letters = ['e', 'd', 'c', 'b', 'a','f','g','h','k'] selectionSort(letters) print(letters) '''
1adbe782bd5800c2b48fd9e73979f0a1b5d672dd
misaka-umi/Software-Foundamentals
/01 混杂/25 访问元组并写入字典.py
660
3.59375
4
def get_tags_frequency(list_of_tuples) : dictionary = {} length = len(list_of_tuples) for i in range(0,length): if list_of_tuples[i][1] not in dictionary : dictionary[list_of_tuples[i][1]] = 1 else : num = dictionary[list_of_tuples[i][1]] num += 1 dictionary[list_of_tuples[i][1]] = num return dictionary list_of_tuples = [('a', 'DT'), ('and', 'CC'), ('father', 'NN'), ('his', 'PRP$'), ('mother', 'NN'), ('shoemaker', 'NN'), ('was', 'VBD'), ('washerwoman', 'NN')] freq_dict = get_tags_frequency(list_of_tuples) for key in sorted(freq_dict.keys()): print(key, freq_dict[key])
0449c5b72a12527c1f9aadd46f490ddb6c93cd9e
misaka-umi/Software-Foundamentals
/01 混杂/18 句子中的单词按长度排序.py
459
3.5625
4
a=input("Enter a sentence: ") sentence = a.split() zidian={} keys=[] for i in sentence: if len(i) not in zidian: zidian[len(i)] = i.lower() elif i.lower() in zidian[len(i)]: pass else: zidian[len(i)]=zidian[len(i)]+" "+i.lower() for i in zidian: keys.append(i) keys.sort() for i in zidian: words=zidian[i].split() words.sort() zidian[i]=" ".join(words) for i in keys: print("{} {}".format(i,zidian[i]))
10e6235e1bffab9da6771291cff1706fb1980882
misaka-umi/Software-Foundamentals
/01 混杂/19 删除字符串中的字母.py
214
4.09375
4
def remove_letters(word1, word2): result = list(word2) for letter in word1: if letter in result: result.remove(letter) return ''.join(result) print(remove_letters('hello', 'world'))
31b9ceee52b271c41e05fa745910b64a109f299d
kailashsinghparihar/HangmanGame
/Problems (13)/Party time/task.py
232
3.578125
4
try: my_list = [] while True: my_list.append(input()) except EOFError: my = [] for i in my_list: if i != '.': my.append(i) else: break print(my) print(len(my))
4970527d3c2c27270e52c75435caf8bfe34707c3
chefong/8-Puzzle
/helpers.py
818
3.890625
4
# Prints the board state in a nice format def printState(board): for row in board: for tile in row: print(tile, end=" ") print() # Locates and returns a pair of (row, col) indices where the blank space is found def findEmptyIndices(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == '0': return [i, j] # Converts the 2D board state into a tuple def tupifyState(board): return tuple(map(tuple, board)) # Message to print once the goal state is achieved def printGoalMessage(num_nodes, max_num_frontier_nodes): print("Goal!!!\n") print("To solve this problem the search algorithm expanded a total of {} nodes.".format(num_nodes)) print("The maximum number of nodes in the queue at any one time: {}.\n".format(max_num_frontier_nodes))
ae31e06304c3bb248cca14eacb43d62ecec55433
inktechnkikov/Python
/Beginer/Lists/reverse.py
163
3.78125
4
towns = ["Berlin","Zurich","Sofia"] numbers = [2,3,4,1,0] # towns.reverse() numbers.sort() print(towns) print(numbers) sortTowns = sorted(towns) print(sortTowns)
5f34f34a2b3a138ca17f461d13d3e5de37886ffa
risentveber/Old-code
/combinatorics_with_python/py3.py
1,406
3.796875
4
# -*- coding: utf-8 -*- mass = [1, 1] #инициализируем для p(0) и p(1) def calculate_p(n): #функция для индуктивного вычисления p(n) global mass result = 0 i = 0 #счетчик суммы k = -1 #множитель отвечающий за (-1)^(i + 1) в началее рекуррентной суммы while True: k *= -1 #изменяем множитель i += 1 #и счетчик tmp = n - (3*i*i - i)//2 # аргумент первого рекурсивного слагаемого if (tmp >= 0): #прибавляем его если нужно result += k*mass[tmp] tmp = n - (3*i*i + i)//2 # аргумент второго рекурсивного слагаемого if (tmp >= 0): #прибаляем его если нужно result += k*mass[tmp] else: #больше нечего прибавлять return result def p(n): global mass if n < 0: raise ValueError("unexpected n < 0") if n + 1 > len(mass): for i in range(len(mass), n + 1): #добавляем нужные для вычисления элементы mass += [calculate_p(i)] return mass[n] num = int(input("Please enter the number ")) print("the number of unordered partitions of", num, "is", p(num))