blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
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))
428fd8714cd7c2542af1000822bf90da9dd58847
linleysanders/algorithms
/Homework Week One (Average of Averages)/Linley Sanders Week One Homework.py
2,609
4.28125
4
# coding: utf-8 # # Lede Algorithms -- Assignment 1 # # In this assignment you will use a little algebra to figure out how to take the average of averages. # In[1]: import pandas as pd import matplotlib.pyplot as plt import requests get_ipython().run_line_magic('matplotlib', 'inline') # First, read in the titanic.csv data set. # In[2]: df = pd.read_csv("titanic.csv") df.head() # Compute the average survival rate (mean of the `survived` column) # In[3]: df['survived'].mean() # Now compute the average survival rates of the male and female 1st, 2nd, and 3rd class passengers (six groups in total) # In[31]: df.groupby(by='gender')['survived'].count() # In[32]: df.groupby(by='gender')['survived'].value_counts() # ## Male Survival Rate: 16.70% # ## Female Survival Rate: 66.30% # In[35]: 142/850 # In[34]: 307/463 # In[37]: df.groupby(by='pclass')['survived'].count() # In[36]: df.groupby(by='pclass')['survived'].value_counts() # ## First Class Survival Rate: 59.93% # ## Second Class Survival Rate: 42.5% # ## Third Class Survival Rate: 19.26% # In[38]: 193/322 # In[39]: 119/280 # In[40]: 137/711 # Compute the average of these six averages. Is it the same as the the overall average? # In[43]: #It's not the same as the overall average—it is higher (34.19+16.70+66.30+59.93+42.5+19.26)/(6) # How would you compute the overall average from the average of averages? Start with the formulas # # $$mean = \frac{\sum_{i=1}^N x_i}{N}$$ # # for the overall mean, where $x_i$ is data value $i$ and $N$ is the total number of values, and # # $$mean_k = \frac{\sum_{i=1}^{N_k} xk_i}{N_k}$$ # # is the mean of group $k$, where $xk_i$ is value $i$ of group $k$ and $N_k$ is the number of values in group $k$, and # # $$N = \sum_{i=1}^M N_k$$ # # relates the total number of values $N$ to the number of values in each of the $M$ groups. # # Your task is to derive a formula that computes $mean$ using only $mean_k$, the $N_k$, and $N$. Note: this question is not asking you to write code! Rather, you must answer two questions: # # - What is the correct formula? # - How can we derive this formula starting from the formulas above? # ## Answer / Response: # # The first formula is the calculation overall for mean. The second formula is the calculation for a group (a column), as the extra variable K. Big N is equal to the sum of the values, and Nk would give the total number of people in a column. I think the solution would be to take 1/6 of each percentage and # Now use this formula to calculate the overall mean. Does it match?
cb01fa3f3fea34c85dd2373c6130478be7cbde25
SuprovoDas/Dream_Work
/multiple_iinheritance.py
1,022
4.03125
4
"""class father: def height(self): print('height is 6 feet') class mother: def color(self): print('color is dark') class child(father,mother): pass c = child() c.height() c.color()""" class A(object): def __init__(self): self.a = 'a' print(self.a) super().__init__() class B(object): def __init__(self): self.b = 'b' print(self.b) super().__init__() class D(object): def __init__(self): self.d = 'd' print(self.d) super().__init__() class E(object): def __init__(self): self.e = 'e' print(self.e) super().__init__() class C(A,B,D,E): def __init__(self): super().__init__() self.c = 'c' print(self.c) o = C() print(C.mro()) #MRO = Method Resolution Order) """ polymorphism :- If a variable,object,method exhibit deffent in diffent context then it is called polymorphism.
cafb9aeb9a9da703325dc2979a1e21a098e56bb7
D-Code-Animal/CTI110
/P2T1_SalesPrediction_EatonStanley.py
311
3.53125
4
# CTI-110 # P2TI-Sales Prediction # Stanley J. Eaton Sr. # June 15, 2018 # Get the projected total sales. total_sales = float (input ('Enter the projected sales:')) # Calculate the profit as 23 precent of total sales. profit = total_sales * 0.23 # Display the profit. print ('The profit is $', format (profit, ',.2f'))
080664c2e54275b4268edb64b140559fa4d07f57
LiouYiJhih/Python
/cheap01_ Basic_operations.py
2,344
3.9375
4
# 註解的重要性 hourly_salary = 125 # 設定時薪 annual_salary = hourly_salary * 8 * 300 # 計算年薪 monthly_fee = 9000 # 設定每月花費 annual_fee = monthly_fee * 12 # 計算每月花費 annual_savings = annual_salary - annual_fee # 計算每年儲存金額 print(annual_savings) # 列出每年儲存金額 print("=====================") print("認識底線開頭或結尾的變數") # 變數名稱有前單底線,例如: _test ### 一種私有變數、函數或方法,可能是在測試中或一般應用在不想直接被調用的方法可以使用。 # 變數名稱有後單底線,例如: dict_ ### 主要目的是避免與Python的關鍵字或內建函數有相同名稱。 ### 舉例: max是求較大值函數、min是求較小值函數,若想建立max和min變數可以命名為max_和min_。 # 變數名稱前後有雙底線,例如: __test__ ### 保留給Python內建的變數或方法使用。 # 變數名稱有錢雙底線,例如: __test ### 這也是私有方法或變數命名,無法直接使用本名存取。 print("=====================") # 基本運算 四則運算 a = 5 + 6 print(a) b = 80 -10 print(b) c = 5 * 9 print(c) d = 9 / 5 print(d) # 餘數和整除 x = 9 % 5 # 餘數設定給變數x print(x) y = 9 // 2 # 整數結果設定給變數y print(y) x = 3 ** 2 # 3的平方 print(x) y = 3 ** 3 # 3的次方 print(y) # 多重指定 x = y = z = 10 print(x, y, z) a, b, c = 10, 20, 30 print(a, b, c) # 變數交換 x, y = 70, 80 print("Before:",x, y) x, y = y, x print("After:",x, y) # divmod(): 一次獲得商和餘數 z = divmod(9, 5) # 獲得元組值(1, 4),元組(Tuple) print(z) x, y = z # 將元組值設定給x和y print(x, y) # 刪除變數 del x # print(x) # 將一個敘述分成多行 a = b = c = 10 x = a + b + c + 12 print(x) y = a + \ b + \ c + \ 12 print(y) z =( a + b + c + 12 ) print(z) print("=====================") # 複利計算 money = 50000 * (1 + 0.015) ** 5 print("本金合是:", money) # 計算園面積和圓周長 PI = 3.14159 r = 5 print("圓面積:單位是平方公分") area = PI * r * r print(area) circumference = 2 * PI * r print("圓周長:單位是公分") print(circumference) print("=====================")
ea09333e3af913cd33bd6df2ecaf7d4b84525a71
pradloff/analysis-framework
/common/node.py
1,290
3.640625
4
class node(): def __init__(self,parents,children,__item__): self.__item__ = __item__ self.parents = [] self.add_parents(*parents) self.children = [] self.add_children(*children) #self.__ancestor__ = {} #self.__decscendants__ = {} def add_parents(self,*parents): for parent in parents: if parent not in self.parents: self.parents.append(parent) parent.add_children(self) def add_children(self,*children): for child in children: if child not in self.children: self.children.append(child) child.add_parents(self) def __call__(self): return self.__item__ """ def getDescendants(self): descendants = {} for child in self.__children__: descendants[child]=0 descendants.update(dict((key,val) for key,val in child.getDescendants().items() if key not in descendants)) #descendants.update( dict((key,val) for key,val child.getDescendants().items() if key not in descendants) ) for descendant in descendants.keys(): descendants[descendant]+= 1 return descendants def getProgenitors(self): progenitors = {} for parent in self.__parents__: progenitors.update( parent.getProgenitors() ) progenitors[parent]=0 for progenitor in progenitors.keys(): progenitors[progenitor]-= 1 return progenitors """
f21fd0a9ca55cf2b6a0d298ff7b25390e3bb5e50
jboenawan/MIS3615
/src/calc.py
1,066
3.96875
4
# print(2017 - 1998) # print(2**10) # minutes = 42 # seconds = 42 # # print('The time duration is', minutes * 60 + seconds, 'seconds.') # # r = 5 # jess = (4 / 3) * r ** 3 * math.pi # print(jess) # len_of_number = len(str(2 ** 1000000)) # How many digits in a really BIG number? # print(len_of_number) # # import random # # print(random.random()) # # print(random.choice(['Jess', 'Andrea', 'Lucy'])) import math def quadratic(a, b, c): discriminant = b ** 2 - 4 * a * c # calculate the discriminant if discriminant >= 0: # equation has solutions x_1 = (-b + math.sqrt(discriminant)) / (2 * a) x_2 = (-b - math.sqrt(discriminant)) / (2 * a) return x_1, x_2 else: print('No real number solution.') return None # solutions = quadratic(1, -2, 5) # # if solutions is not None: # print(solutions) a = float(input('please enter a number:')) b = float(input('please enter a number:')) c = float(input('please enter a number:')) solutions = quadratic(a, b, c) if solutions is not None: print(solutions)
9ac9210e2616b578f13b22d03315cb473e5e0c61
globality-corp/microcosm-resourcesync
/microcosm_resourcesync/toposort.py
1,825
3.765625
4
""" Topological sort. """ from collections import defaultdict def toposorted(resources): """ Perform a topological sort on the input resources. Resources are first sorted by type and id to generate a deterministic ordering and to group resouces of the same type together (which minimizes the number of write operations required when batching together writes of the same type). The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ # sort resources first so we have a deterministic order of nodes with the same partial order resources = sorted( resources, key=lambda resource: (resource.type, resource.id), ) # build incoming and outgoing edges nodes = { resource.uri for resource in resources } incoming = defaultdict(set) outgoing = defaultdict(set) for resource in resources: for parent in resource.parents: if parent not in nodes: # ignore references that lead outside of the current graph continue incoming[resource.uri].add(parent) outgoing[parent].add(resource.uri) results = [] while resources: remaining = [] for resource in resources: if incoming[resource.uri]: # node still has incoming edges remaining.append(resource) continue results.append(resource) for child in outgoing[resource.uri]: incoming[child].remove(resource.uri) if len(resources) == len(remaining): raise Exception("Cycle detected") resources = remaining return results
d333b5c8fa654a867c5e54f599f2ca5a5c68746d
zhezhe825/api_test
/cases/test_1.py
1,297
4.5
4
''' unittest框架:单元测试框架,也可做自动化测试,python自带的 unittest:管理测试用例,执行用例,查看结果,生成 html 报告(多少通过,多少失败 ) 自动化:自己的代码,验证别人的代码 大驼峰命名:PrintEmployeePaychecks() 小驼峰:printEmployeePaychecks() 下划线命名:print_employee_paychecks() 类:大驼峰命名 其他:小驼峰,下划线命名 class:测试的集合,一个集合又是一个类 unittest.TestCase:继承 继承的作用:子类继承父类(TestExample 继承 TestCase),父类有的,子类都有 ''' ''' self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") 断言失败可用:msg="。。。" 给出提示信息 .通过 F 失败:开发的BUG E:你自己的代码的BUG ''' import unittest # print(help(unittest)) # help:查看帮助文档 class TestExample(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) # self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main()
3375441b180ccb3af8ed21c1dc59918f1a9ad339
AMANGUPTA2000/ML_Projects
/Assignment_2/sum_diagonal.py
240
3.546875
4
import numpy as nm arr=nm.array([[1,2,3,4],[3,4,5,6],[6,7,8,9],[9,0,1,2]]) print(arr) arr_diagonal_element = arr.diagonal() print("\nDiagonal element:",arr_diagonal_element) print("\nSum of Diagonal elements:",nm.sum(arr_diagonal_element))
488db3e736f5b837e0dda27689d60d167734a963
jcastiblanco/mintic2022memories
/Reto1.py
1,025
3.8125
4
#Importación de modulos necesarios para librerias matematicas import decimal import math #******************************** #**Código Principal de ejecucion #******************************** # main () #Variables salarioBase=176 pcthorasExtras=1.25 horasExtras=0 pctbonificacion=0.065 salarioBase=0 salarioExtras=0 salarioBonificaciones=0 planDeSalud=0.025 aportePension=0.025 cajaCompensacion=0.04 esbonificiacion=0 salarioBase,horasExtras,esbonificiacion=input().split() salarioBase = float(salarioBase ) horasExtras= int(horasExtras) esbonificiacion= int(esbonificiacion) #Operaciones salarioExtras=horasExtras * ((salarioBase/176) * pcthorasExtras) salarioBonificaciones=esbonificiacion*(salarioBase * pctbonificacion) salarioTotal=round((salarioBase + salarioExtras + salarioBonificaciones),1) salarioDespuesDescuentos=round((salarioBase + salarioExtras + salarioBonificaciones)-(salarioTotal*0.09),1) #Resultado print(f"{salarioTotal} {salarioDespuesDescuentos}") #1000000 5 0
1e77dfff1db0174ed2a6695864eefecae7e1326c
xwj0813/lectcode
/com/xwj/code/No17letterCombinations.py
736
3.6875
4
# -*- coding:utf-8 -*- ''' 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合 ''' def letterCombinations(digits): dict = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} result = [''] for digit in digits: str_digit = [] for char in dict[digit]: str_digit += [x + char for x in result] result = str_digit return result if __name__ == '__main__': digits = '235' result = letterCombinations(digits) print(result)
a7f6a75f106e7d866e56d5f4f2b522d99390d1ee
xwj0813/lectcode
/com/xwj/code/No4_MedianTwoSortedArray.py
2,382
3.546875
4
# -*- coding:utf-8 -*- ''' 给出两个有序的数字列表,长度分别为m,n。找到这两个列表中的中间值 ''' import time def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ # 创建新列表,并将所有元素初始为0 nums3 = [0] * (len(nums1) + len(nums2)) # 指定三个列表的索引,初始值为0 l_i, r_i, i = 0, 0, 0 # 当输入两个列表都还存在元素没进行比较的时候,循环进行对比 # 并将较小值放入新列表,同时较小元素的列表和新列表索引加一 while(l_i < len(nums1)) and (r_i < len(nums2)): if nums1[l_i] < nums2[r_i]: nums3[i] = nums1[l_i] l_i += 1 else: nums3[i] = nums2[r_i] r_i += 1 i += 1 # 当存在某一个列表所有元素已经比较完,即拍好了序 # 剩下那个列表剩下的值直接放入新列表对应位置即可 if l_i != len(nums1): nums3[i:] = nums1[l_i:] else: nums3[i:] = nums2[r_i:] # 小詹有话说:注意‘/’和‘//’的区别 /得到的是float,//得到的是int # 前者结果为float类型,后者为整除,结果为int型 len_3 = len(nums3) #‘%’为取模运算,即看长度是否被2整除,即看偶数还是奇数 if len_3 % 2 != 0: return float(nums3[(len_3 - 1) // 2]) return (nums3[len_3 // 2 - 1] + nums3[len_3 // 2]) / 2 def findMedianSortedArrays_1(nums1, nums2): # 简单粗暴将两个列表合成一个 for i in range(len(nums1)): # if nums1[i] in nums2: # # 如果表1 在表中含有就跳过 # continue # else: nums2.append(nums1[i]) # 重新排序 nums3 = sorted(nums2) len_3 = len(nums3) if len(nums3) % 2 != 0: # 奇数 return float(nums3[(len(nums3) - 1) // 2]) else: return (nums3[len_3 // 2 - 1] + nums3[len_3 // 2]) / 2 if __name__ == '__main__': nums1 = [1, 1] nums2 = [1, 2] start = time.time() result = findMedianSortedArrays(nums1, nums2) end = time.time() print(result, end - start) start_1 = time.time() result_1 = findMedianSortedArrays_1(nums1, nums2) end_1 = time.time() print(result_1, end_1 - start_1)
cbd8f93e9f6e1adbeebe0d612865c3d306ada0a1
ritaly/python-6-instrukcje-warunkowe
/Odpowiedzi/2.py
988
4.125
4
# -*- coding: utf8 -*- """ Do kalkulatora BMI z lekcji "Python 1 zabawy w konsoli" dodaj sprawdzanie czy BMI jest prawidłowe Niedowaga | < 18,5 Waga normaln | 18,5 – 24 Lekka nadwaga | 24 – 26,5 Nadwaga | > 26,5 W przypadku nadwagi sprawdź czy występuje otyłość: Otyłość I stopnia | 30 – 35 Otyłość II stopnia | 30 – 40 Otyłość III stopnia | > 40 """ print("Podaj wagę w kg: ") weight = float(input()) print("Podaj wzrost w cm: ") height = float(input())/100 BMI = weight / (height ** 2) print("Twoje bmi wynosi:", round(BMI, 2)) if (BMI < 18.5): print("Niedowaga") elif (18.5 <= BMI < 24): print("Waga prawidłowa") elif (24 <= BMI < 26.5): print("Lekka nadwaga") else: print("Nadwaga") if (30 >= BMI > 35): print("Otyłość I stopnia") elif (35 >= BMI > 40): print("Otyłość II stopnia") else: print("Otyłość III stopnia")
b7fe479f010694f71b4dbc5df0e07cd3a3c08449
DMRathod/_RDPython_
/Simple_estimation_CrowdComputing.py
894
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 12:53:40 2019 @author: Dharmraj Rathod """ from statistics import mean #from scipy import stats #let we have the bottle filled with marbels and we have to guess how many number of marbles are #there in the bottle """total number of marbles in the bottle is 36""" #implementation of trim_mean function from scipy Guess = [30,35,20,15,40,45,38,45,50,50,70,37,15,55,25,28,26,28,20,30] #for guess we use the trimmed percentage%(should be in 100) def Rdtrim_mean(percentage,Guess): if(percentage > 100 or Guess == []): print("Please Enter the valid Arguments") percentage = percentage/100 Guess.sort() trimmed_value =int( percentage*len(Guess) ) #m = stats.trim_mean(Guess,0.1) Guess = Guess[trimmed_value:] Guess = Guess[:len(Guess)-trimmed_value] print("Actual Value May Near About = ",mean(Guess)) #print(m)
6f3c61f8c2d26f3e112b9853319633d0aa5c2cde
DMRathod/_RDPython_
/Coding Practice/Basic Maths/Factorial.py
179
4.09375
4
def fact(number): if(number <=1): return 1 else: return (number * fact(number-1)) number = int(input("Enter number for factorial:")) print(fact(number))
976f3ae5ea8e924d2fd0838cdfbf5981a0195e48
DMRathod/_RDPython_
/Coding Practice/Basic Maths/FindMeetingRoomlist.py
1,089
3.734375
4
# meeting room details which is dictionary of room number as key and value is list of two values starting and ending time of the meeting # OccupiedRoomDetails = {0 : ["9AM", "11AM"], 1: ["10AM", "12AM"], 2: ["11AM", "12AM"], 3: ["9AM", "10AM"]} # Assuming requested meeting is only of 1 hour. def FindMeetingRoomlist(starttime, endtime): arr = [[1, 1, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0]] hour_dict = {"9AM" : 0, "10AM" : 1, "11AM" : 2, "12AM" : 3, "1PM" : 4, "2PM" : 5, "3PM" : 6, "4PM" : 7, "5PM" : 8, "6PM" : 9} result = [] for i in range(len(arr)): cnt = 0 hours = (hour_dict[endtime] - hour_dict[starttime]) j = hour_dict[starttime] while(cnt < hours and (arr[i][j] == 0)): cnt += 1 if(j < 9): j += 1 else: break if(cnt == hours): result.append(i+1) return result print(FindMeetingRoomlist("1PM", "2PM")) #[3, 4, 6, 8]
61a496dde5f1d6faa1dfb14a79420f3730c0727f
DMRathod/_RDPython_
/Coding Practice/Basic Maths/LeapYear.py
441
4.21875
4
# leap year is after every 4 years, divisible by 4. # Every Century years are not leap years means if it is divisible by 100. # we need to confirm if it is divisible by 400 or not. year = int(input("Enter The Year :")) if(year%4 == 0): if(year%100 == 0): if(year%400 == 0): print(str(year) + "is Leap Year") else: print(str(year)+ "is Leap Year") else: print(str(year) + " is NOT Leap Year")
1d9d07543fdcded06e83687de0279e2660a3c53f
DMRathod/_RDPython_
/Coding Practice/Sorting/SS.py
532
3.671875
4
ns = [4, 5, 1, 22] # selection sort will just find the one element and put that element at its right position # here i have taken max element and putting at its right psition each time in each iteration def SSort(ns): for i in range(len(ns)): mx = ns[0] j = 1 k = 0 while(j < len(ns)-i): if(mx < ns[j]): mx = ns[j] k = j j += 1 temp = ns[j-1] ns[j-1] = ns[k] ns[k] = temp return ns print(SSort(ns))
4e2950045c5f2f36d9655585f48f5d9260ce1a6b
rwinklerwilkes/Python
/knn.py
2,210
3.703125
4
#A short messy implementation of a 2-dimensional kth nearest neighbor algorithm import math class Point: def __repr__(self): return "Point" def __str__(self): return "x1: %d\nx2: %d\ny1: %s\n" %(self.x1,self.x2,self.y1) def __init__(self, x1, x2, y1): self.x1 = x1 self.x2 = x2 self.y1 = y1 def dist(point1, point2): term1 = (point2.x2-point1.x1)**2 term2 = (point2.x2-point1.x1)**2 return math.sqrt(term1+term2) #make sure that I actually understand what's going on here #I mean, I wrote it, but the off-by-one error took a while to fix def knn(k, point, pointset): nnset = [0 for i in range(k)] to_fill = 0 for p in pointset: curdist = dist(point,p) #if the distance is less than the kth closest, put it in order if to_fill < len(nnset): #insert in the proper spot j = to_fill while j > 0 and curdist < nnset[j-1][1]: #shift up by one and decrement nnset[j] = nnset[j-1] j = j-1 nnset[j] = (p,curdist) to_fill = to_fill + 1 elif curdist < nnset[k-1][1]: insert((p,curdist),nnset) return nnset #this doesn't seem to be doing what I want it to def insert(point, pointset): #assume pointset is in decreasing order #assume the values in pointset are stored as (point, distance) #assume point is passed as (point,distance) hole = len(pointset) while hole > 0 and point[1] < pointset[hole-1][1]: hole = hole - 1 if hole > 0: pointset[hole] = pointset[hole - 1] pointset[hole] = point def guesstype(point,k,pointset): k_set = knn(k,point,pointset) types = {} for i in range(len(k_set)): curpoint = k_set[i][0] if curpoint.y1 in types: types[curpoint.y1] = types[curpoint.y1] + 1 else: types[curpoint.y1] = 1 alltypes = [(k,v) for (k,v) in types.items()] sorted(alltypes,key =lambda kv: kv[1]) return alltypes[len(alltypes)-1][0] points = [Point(1,4,"a"),Point(1,3,"a"),Point(-2,6,"b"),Point(3,5,"c"),Point(-1,7,"a"),Point(4,-3,"b")] p = Point(2,3,"u")
406a2927197d804de0300c98c678d44d90d8155d
cpowicki/Settlers-Of-Catan-Generator
/devcards.py
591
3.5
4
from random import shuffle class developmentCard: def __init__(self, type): self.type = type class deck: def __init__(self): self.cards = [] for i in range(19): self.cards.append(developmentCard('Knight')) for i in range(5): self.cards.append(developmentCard('Victory Point')) for i in range(2): self.cards.append(developmentCard('Year of Plenty')) self.cards.append(developmentCard('Monopoly')) self.cards.append(developmentCard('Road Builder')) shuffle(self.cards)