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
55c5746789509bff263142b162e84ff4fb33bda9
ImJoaoPedro/RaspArd-FireFighter
/TestStuff/Rasp+ArdComms.py
1,364
3.53125
4
import smbus import time import io import fcntl # for RPI version 1, use “bus = smbus.SMBus(0)” bus = smbus.SMBus(1) # This is the address we setup in the Arduino Program address = 0x04 def writeNumber(value): bus.write_byte(address, value) # bus.write_byte_data(address, 0, value) return -1 def readNumber(): # I'm not familiar with the SMbus library, so you'll have to figure out how to # tell if any more bytes are available and when a transmission of integer bytes # is complete. For now, I'll use the boolean variable "bytes_available" to mean # "we are still transmitting a single value, one byte at a time" byte_list = [] while bytes_available: # build list of bytes in an integer - assuming bytes are sent in the same # order they would be written. Ex: integer '123' is sent as '1', '2', '3' byte_list.append(bus.read_byte(address)) # now recombine the list of bytes into a single string, then convert back into int number = int("".join([chr(byte) for byte in byte_list])) return number while True: var = input('Enter 1 – 9: ') if not var: continue writeNumber(var) print 'RPI: Hi Arduino, I sent you ', var # sleep one second time.sleep(1) number = readNumber() print 'Arduino: Hey RPI, I received a digit ', number print
74322d334ba92809d050b0fd960880622597e5de
LeonMac/Principles-of-Data-Science_forPython3
/Test_Matrix.py
476
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np x=np.array([3,6,8]) y=np.array([4,7,0]) multi=x*y add =x+y sub =x-y dot =x.dot(y) dot_1=y.dot(x) cross=np.cross(x,y) cross_1=np.cross(y,x) print ('x = ',x) print ('y = ',y) print ('\n') print ('x+y = ',add) print ('x-y = ',sub) print ('x*y = ',multi) print ('\n') print ('x.y = ',dot) print ('y.x = ',dot_1) print ('xXy = ',cross) print ('yXx = ',cross_1)
09b9854b9578e862107747778f65e94e36455bd0
tiagosouza1984/ADS_2D_LPII
/com/tiago/hackerRank01.py
565
3.90625
4
import re for i in range (int(input())): var_1 = input() passUpper = 0 passNum = 0 flag = False if var_1.isalnum() and len(var_1) == 10 : for i in var_1: if i.isupper(): passUpper+=1 if i.isnumeric(): passNum+=1 if var_1.count(i) <= 1: pass else: flag = True if passUpper >= 2 and passNum >=3 and flag == False: print('Valid') else: print('Invalid') else: print('Invalid')
48f81ee68b1150c34bb8d7b99c4148723c2e8334
gtoutin/gt6422-coe332
/midterm/generate_animals.py
1,512
3.640625
4
#!/usr/bin/env python3 # Author: Gabrielle Toutin # Date: 1/27/2021 # Homework 1 import petname import random import json import uuid import datetime #animals = { "animals": [] } # initialize animals dictionary animals = [] heads = ["snake", "bull", "lion", "raven", "bunny"] # get head choices bodies = petname.names # get body choices #while len(animals["animals"]) < 20: while len(animals) < 20: head = random.choice(heads) # choose a random head from heads list body1 = random.choice(bodies) # choose 2 animals for the body body2 = random.choice(bodies) while (body1 == body2): body2 = random.choice(bodies) # can't choose the same 2 animals body = body1 + '-' + body2 # format the body correctly numarms = 2 * random.randint(1,5) # choose a number of arms numlegs = 3 * random.randint(1,4) # choose a number of legs numtails = numarms + numlegs animal = { "head": head, "body": body, "arms": str(numarms), "legs": str(numlegs), "tail": str(numtails), "uid" : str(uuid.uuid4()), "created_on": str(datetime.datetime.now()) } #if (animal in animals["animals"]): # no duplicates if (animal in animals): continue else: #animals["animals"].append(animal) # add new animal to dictionary animals.append(animal) with open('animals.json', 'w') as out: json.dump(animals, out, indent=2)
48796c87e55fa3f45b0f90334b4b38f49f4e3675
Ksaur12/Link_finder
/links in links.py
1,313
4.09375
4
import urllib.request, urllib.parse, urllib.error import re import ssl #Made by Ksaur12 print('''You can use this program to find links in a webpage, the links can be used for downloading For example:''') print(' If you want to download something but') print(' the website keep your see ads, ') print(' then can use this for retrieving the downloadable link\n\nEnter the full URL link like ---> https://www.google.com') # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE #empty list for storing the url, one by one lst = [] #Prompt for the url url = input('Enter the url- ') print(url) print('\n\nFinding the url.....') try: #Open the url in it's source code html = urllib.request.urlopen(url, context=ctx).read() except: print('\nError in network or in URL\nTry again') exit() print('\n\nFinding the links in the url entered......') links = re.findall(b'href="(http[s]?://.*?)"', html) for link in links: link = link.decode() + '\n' lst.append(link) file = open('links_retrieved.txt', 'w') for i in lst: #Append every link into the links_retrieved.txt file.write(i + '\n') print("\nAll the links are saved in the links_retrieved.txt file\nPlease check your current folder")
ae0a22b8754a7bb813605c0ec2c1eee29fef6263
bimalka98/Data-Structures-and-Algorithms
/Mini-xtreme-2021/Answers/Drone.py
1,080
3.59375
4
def check_order(dest, order): countL=0 countR=0 countU=0 countD=0 for i in order: if i=='L': countL+=1 if i=='R': countR+=1 if i=='U': countU+=1 if i=='D': countD+=1 # print("CountD = ",countD) # print("CountU = ",countU) # print("CountL = ",countL) # print("CountR = ",countR) status = True if dest[0]<0: if (countL<abs(dest[0])): status = False # print(status) elif dest[0]>0: if (countR<dest[0]): status = False # print(status) if dest[1]<0: if (countD<abs(dest[1])): status = False # print(status) elif dest[1]>0: if (countU<dest[1]): status = False # print(status) if status: print("YES") else: print("NO") queries=int(input()) for i in range (0,queries): dest = list(map(int, input().split())) order = input() check_order(dest, order)
b4bde21241f2bb9e7ef018f4a480ff3ba601584c
4ON91/MathNotes_and_3D-related-scripts
/Linux/Python/Math Notes/Basic Square Root Algorithm.py
810
3.921875
4
#https://youtu.be/rAuoJCiPiGU #based on this youtube video on how to do square roots without a calculator #Only works with integer values def SquareRootAlgorithm(VARIABLE): for i in range(0, VARIABLE+1): if( pow(i,2) >= VARIABLE): MULTIPLE = i-1 PROBLEM = VARIABLE-pow(i-1,2) FINAL_ANSWER = MULTIPLE break for i in range(1, 100): PROBLEM = PROBLEM*100 MULTIPLE = (MULTIPLE+(MULTIPLE%10))*10 for x in range(0, 10): if( (MULTIPLE+x)*x > PROBLEM): PROBLEM = PROBLEM - (MULTIPLE+(x-1))*(x-1) MULTIPLE = (MULTIPLE+(x-1)) FINAL_ANSWER = FINAL_ANSWER + ((x-1) * pow(10,-i)) break return(FINAL_ANSWER) print(SquareRootAlgorithm(2)) #1.414213562373
0281da2e0ae0faf2a060eab924d71a1e37ebfe51
JamesALin/2020-Classes
/edxbasics/problems2.py
162
3.953125
4
print('Please enter a number from the hex number system: ') user = input() output_sentence = 'The decimal number for ' + str(int(user, 16)) print(output_sentence)
529992c5ac16bfefa9db7b50d35ae0b45541975f
Oindry/Pythin-Basics
/L20_practice.py
159
3.609375
4
numbs=[1,2,3,4,5,6,7,8,9,10] square=numbs.copy() for i in numbs: print(numbs[i]) square[i] = numbs[i]**2 print(square[i]) print("s",square)
2bf1624de15ab8bffac86c21b49709b541143681
theXYZT/codejam-2018
/Practice Session/steed-2-cruise-control.py
858
3.734375
4
# Codejam 2018, Practice Session: Steed 2: Cruise Control class Horse(): """Class for Horse.""" def __init__(self, position, speed, destination): self.position = position self.speed = speed self.time_to_destination = (destination - self.position) / self.speed def find_max_speed(horses): """Finds max speed to reach destination.""" max_time = max([horse.time_to_destination for horse in horses]) return destination / max_time # I/O Code num_cases = int(input()) for case in range(1, num_cases + 1): destination, num_horses = map(int, input().split()) horses = [] for _ in range(num_horses): position, speed = map(int, input().split()) horses.append(Horse(position, speed, destination)) max_speed = find_max_speed(horses) print('Case #{}: {:.6f}'.format(case, max_speed))
db6d2b8ef699f5b36d9af4be7cd3e047915ff962
RyanLongRoad/Functions
/Currency converter.py
1,061
4.09375
4
#Ryan Cox #02/12/14 #Currency converter def information(): print("Please enter the currency you have out of: GBP, USD or EURO: ") currency = input("Please enter the currency you have that you wish to convert: ") amount = int(input("how much do you have?")) return currency, amount def choice(currency, amount): if currency == "GBP": converterGBP(amount) elif currency == "USD": converterUSD(amount) elif currency == "EURO": converterEURO(amount) def converterGBP(amount): USD = amount * 1.601 Euro = amount * 1.229 return Euro, USD def converterUSD(amount): USD = amount * 0.625 Euro = amount * 0.768 return Euro, USD def converterEURO(amount): USD = amount * 0.814 Euro = amount * 1.302 return Euro, USD def output(Euro, USD): print("You have {0} USD or {1} Euro".format(USD, Euro)) def engine(): currency, amount = information() choice(currency, amount) output(USD, Euro) #main program engine()
c75ed9f79dd1cecf3fe937751a11f0ac5493407a
daliborstakic/randwiki-python
/gui_rand.py
510
3.78125
4
""" Importing Tkinter """ import tkinter as tk from tkinter import Button, Label from wiki_app import * # Main root window root = tk.Tk() root.title("Randow Wikipedia Article") # Label button_label = Label(root, text="Press the button to generate a Wikipedia page") # Button gen_button = Button(root, text="Generate", command=gen_rand, bg="#F9E178") # Grid button_label.grid(row=0, column=0, padx=5, pady=5) gen_button.grid(row=1, column=0, pady=5, padx=5) if __name__ == '__main__': root.mainloop()
651ab949cb32a9428fee502ff5c5e7d0232e6401
saemideluxe/adventofcode_2017
/9.py
645
3.515625
4
with open('input') as f: _in = f.read().strip() score = 0 level = 0 ignorenext = False ingarbage = False garbage = 0 for c in _in: if not ingarbage: if c == '{': level += 1 elif c == '}': score += level level -= 1 elif c == '<': ingarbage = True else: if not ignorenext: if c == '>': ingarbage = False elif c == '!': ignorenext = True else: garbage += 1 else: ignorenext = False print('solution 1: %s' % score) print('solution 2: %s' % garbage)
380f26309294df9ec90109b61b57c4353c2d4d72
Mpendulo1/Error-Handling
/main.py
1,672
3.71875
4
from tkinter import * root = Tk() root.title('Login Center') root.geometry("600x600") root.config(bg="OrangeRed2") # Creating a widgets l1 = Label(root, text='Login Details:', bg='OrangeRed2', fg='honeydew', font=('Arial', 20, 'bold')) l1.place(x=120, y=10) # Username l2 = Label(root, text='Enter Username : ', bg='OrangeRed2', fg='honeydew', font=('Arial', 20, 'bold')) l2.place(x=200, y=100) e1 = Entry(root, bg='honeydew', fg='gray20', width=14, font=('Arial', 20, 'bold')) e1.place(x=220, y=150) # Password l3 = Label(root, text='Enter Password : ', bg='OrangeRed2', fg='honeydew', font=('Arial', 20, 'bold')) l3.place(x=200, y=250) e2 = Entry(root, bg='honeydew', fg='gray20', width=14, font=('Arial', 20, 'bold'), show='*') e2.place(x=220, y=300) # Defining a Function fr logging in def login(): # importing message box from tkinter import messagebox username = ["Zipho", "Masi", "Lihle", "Thandokazi"] password = ["555", "333", "200", "221"] amount = [1000, 4000, 3000, 2900] found = False for x in range(len(username)): if e1.get()==username[x] and e2.get()==password[x] and amount[x]: found = True if found==True: messagebox.showinfo("PERMISSION", "ACCESS GRANTED") root.destroy() import Exception_Page else: messagebox.showinfo("ERROR INFO", "ACCESS DENIED") return # Defining a function for clearing def clear(): e1.delete(0, END) e2.delete(0, END) # Button b1 = Button(root, text='Login', bg='gray80', fg='gray12', font=('Georgia', 20, 'bold'), cursor='hand2', command=login) b1.place(x=250, y=400) root.mainloop()
ffe24156489d5063ee564b1b5c558585363a7944
directornicm/python
/Project_4.py
572
4.28125
4
# To calculate leap year: # A leap year is a year which is divisible by 4 but ... # if it is divisible by 100, it must be divisible by 400. # indentation matters - take care of it year = int(input("Give the year to be checked for leap year")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(f"The year {year} is a leap year") else: print(f"The year {year} is not a leap year") else: print(f"The year {year} is a leap year") else: print(f"The year {year} is not a leap year")
e0d2ea85430376143f9401e1742311bf4f5e6c1e
sthapliyal37/my_Programs
/repetitions.py
190
3.71875
4
string=input() maximum=0 count=1 for i in range(len(string)-1): if string[i]==string[i+1]: count+=1 else: maximum=max(count,maximum) count=1 #print(count) print(max(maximum,count))
a03f5cdd70d061ba507a45d3560e624349146e5c
sthapliyal37/my_Programs
/binary.py
616
3.625
4
def count_changes(string,n): count=0 sum_s=0 #for i in range(n): # sum_s+=int(string[i]) x=int(string,2) sum_s=int(bin(x).count('1')) if(sum_s==0): count=(len(string)/n) elif(sum_s!=len(string)): p=string[0:n] x=int(p,2) sum_s=int(bin(x).count('1')) if(sum_s==0): count+=1 sum_s=1 string=string[:n-1] + '1' +string[n:] for i in range(n-1,len(string)-1): sum_s-=int(string[i-n+1]) sum_s+=int(string[i+1]) if(sum_s==0): count+=1 sum_s=1 string=string[:i+1] + '1' +string[i+2:] print(count) #driver Function string="00100" n=2 count_changes(string,n)
2ddaf7038f2a8c696f36d55c4ecaa6e740b415c8
RayanSt/SingletonMultiHilos
/Hilos.py
675
3.859375
4
import threading class Singleton(object): _instance = None def __new__(self): self.lock.acquire() if not self._instance: self._instance = super(Singleton, self).__new__(self) return self._instance self.lock.release() def Accion(accion): for vuelta in range(5): print("Accion: " + accion + "\n") #mientras A este en funcionamiento, B no puede acceder al metodo y asi por el mumero de peticiones A = threading.Thread(target=Singleton.Accion("camina")) B = threading.Thread(target=Singleton.Accion("salta")) C = threading.Thread(target=Singleton.Accion("descansa")) A.start() B.start() C.start()
e7f908a2eb4199049c3e408ee9f97bceb0356966
ally17/assignments
/assignment6.py
226
3.65625
4
n = 100 prime_list = [] for i in range(1, n + 1): count = 0 for j in range(1, i + 1): if i % j == 0: count += 1 if (count < 3) and (i != 1): prime_list.append(i) print(prime_list)
a9c78ffcc211b5250aca8ce492dab0cabfb0a4be
msa190/pydraw
/Circle.py
483
3.5
4
from Vector import * from Curve import Curve class Circle(Curve): #Center C=Vector([0.0,0.0]) #Radius r=0.0 def __init__(self,r=1.0,C=None,NP=0): if (C): self.C=C if (NP): self.NP=NP self.r=r self.Closed=True return def R(self,t): return self.C+e(t)*self.r def PMin(self): return Vector([-self.r,-self.r]) def PMax(self): return Vector([self.r,self.r])
918c516681dbcf0a4bfcca706a7037a0fef2f97b
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo02/Ejercicio10.py
125
3.765625
4
""" Ejemplo17 """ nombre = str(input("Ingrese el nombre de la persona: ")) print("El nombre ingresado es %s\n" % nombre)
f4f5cc063109a82ef9d6183ef1a8478544533574
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo05/Ejemplo09.py
299
3.703125
4
""" Ejemplo13 """ numerador = 1 denominador = 1 contador = 1 while(contador <= 5): if((contador % 2)==0): print("%s%d/%d" % ("-", numerador,denominador) else: print("%s%d/%d" % ("+", numerador,denominador) contador = contador + 1 denominador = denominador + 2
7e5f120cc287f73d161a88e62f972df9d1676b13
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo05/Ejemplo10.py
201
3.765625
4
""" Ejemplo14 """ bandera = True salir = "" while(bandera): salir = str(input("Desea salir del ciclo; digite: si: ")) salir = salir.lower() if(salir == "si"): bandera = False
6b477349143e3f91d8e85698faa71af16e0d1ab0
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo04/Ejemplo07.py
223
3.703125
4
""" Ejemplo12 """ contador = 1 while contador <= 10: if (contador%2)==0: print("El número %d es par\n" % contador) else: print("El número %d es impar\n" % contador) contador = contador + 1
6ed204b50af3dd7d8058e0abafe05449ba6c28e2
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo05/Ejemplo22.py
196
3.65625
4
""" Ejemplo22 """ tabla = int(input("Ingrese la tabla a generar: ")) for i in range(5,30,contador++): operacion = tabla * contador print("%d * %d = %d\n" % (tabla,contador,operacion))
e14e55d0194aa92952b05410d8ffffd19ee0fe94
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo02/Ejemplo05.py
215
3.609375
4
""" Ejemplo10 """ nombreEstudiante = str("Arianna Marikrys") apellidoEstudiante = str("Ramón Ramón") nacimiento = str("2001") print(nombreEstudiante+"\n\n"+apellidoEstudiante) print(nombreEstudiante+"\t"+apellidoEstudiante)
3fcb2c95de85a8103b36d601c8f555401b7008e0
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-Arianna0206
/Trabajo01/Ejercicio10.py
122
3.625
4
""" Ejercicio10 Salida de datos """ import math print((math.sqrt(25)*10)>=100 and (True) or (False) or (10/5 >=2))
f505b186498a023cfd306f319ce810150b45f175
elioenas/Python
/Estrutura de repeticao/For e Range/Votos.py
733
4.09375
4
"""Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato.""" """criar a variavel""" eleitores = int(input('numero de eleitores:')) votos =[] """um for onde o ira contar numero de eleitores e determinar quantos votos tera""" for i in range(eleitores): voto = votos.append(int(input('Digite o numero do seu candidato [1,2,3] :'))) print('') print('Quantidade de eleitores',eleitores) print('O candidato1 teve um total de ',votos.count(1), 'votos') print('O candidato2 teve um total de ',votos.count(2), 'votos') print('O candidato3 teve um total de ',votos.count(3), 'votos')
ffed5af17f0fad7393a2928b9e545d415ab8f83e
peruguanvesh/Assignment
/divisible.py
210
3.515625
4
def func_multiples(begin,end): output_values=[] for j in range(begin,end+1): if j%7 == 0 and j%5 != 0: output_values.append(str(j)) return ','.join(output_values) print(func_multiples(3000,5300))
b0beed001a2b92c2770e863690799397ce682581
kkowalsks/CS362-Homework-7
/leapyear.py
603
4.1875
4
def leapCheck(int): if int % 4 != 0: int = str(int) print(int + " is not a leap year") return False else: if int % 100 != 0: int = str(int) print(int + " is a leap year") return True else: if int % 400 != 0: int = str(int) print(int + " is not a leap year") return False else: int = str(int) print(int + " is a leap year") return True leapCheck(2020) leapCheck(2021) leapCheck(1900) leapCheck(2000)
60a933754cf205750439a80ab4357dd3e60ce389
CruzerNexus/Repo
/pythonFullStack/simpleCalculator.py
414
4.09375
4
def calculator(x, y, z): if x == ("+"): return y + z elif x == ("-"): return y - z elif x == ("*"): return y * z else: return y / z x = input("Welcome! What opperation would you like to preform (+, -, *, /)? ") y = input("What is the first number? ") y = float(y) z = input("What is the second number? ") z = float(z) print(f"{y} {x} {z} = {calculator(x, y, z)}")
96a99e284e212fdc90eb117a02849b60e8fb451d
CruzerNexus/Repo
/pythonFullStack/pick6.py
965
3.609375
4
import random def pick6(): randCount = 0 lotto = [] while randCount < 6: lotto.append(random.randint(1,99)) randCount += 1 return lotto def num_matches(lotto, ticket): winnings = 0 for i in range(len(lotto)): if lotto[i] == ticket[i]: winnings += 1 return winnings balance = 0 winBalance = 0 tryCount = 0 lotto = pick6() while tryCount < 100000: balance -= 2 ticket = pick6() winnings = num_matches(lotto, ticket) if winnings == 1: winBalance += 4 elif winnings == 2: winBalance += 7 elif winnings == 3: winBalance += 100 elif winnings == 4: winBalance += 50000 elif winnings == 5: winBalance += 1000000 elif winnings == 6: winBalance += 25000000 tryCount += 1 balance += winBalance ROI = (winBalance - 200000)/200000 print(f"After buying 100,000 lotto tickets (costing $200,000 total) your final account balance is ${balance}.") print(f"You won a total of ${winBalance}") print(f"Your ROI is {ROI}. Congratulations!")
0a1fc80a2fafb907673599e2b4d42939d6aec372
CruzerNexus/Repo
/pythonFullStack/rotCipher.py
947
3.53125
4
userLetter = ['a', 'b', 'c', 'd', "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] cipherLetter = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", 'a', 'b', 'c', 'd', "e", "f", "g", "h", "i", "j", "k", "l", "m"] def encode(userInput): pcOutput = "" for char in (userInput): if char in (userLetter): idx = userLetter.index(char) pcOutput += cipherLetter[idx] else: pcOutput += char return pcOutput def decode(userInput): pcOutput = "" for char in (userInput): if char in cipherLetter: idx = cipherLetter.index(char) pcOutput += userLetter[idx] else: pcOutput += char return pcOutput userInput = input("Give me a secret message and I'll encode it: ") print(encode(userInput)) print(f"and {encode(userInput)} decoded is {decode(userInput)}.")
92f0e2b6757f6b812e9e7c5e6477ee121507b440
CruzerNexus/Repo
/pythonFullStack/spythonMadLib.py
1,599
3.734375
4
madlib = "" a = input("Verb ending in 'ing': ") madlib += f"Espionage is the formal word for {a}. " b = input("Adjective: ") madlib += f"In the shadowy world of spies, a/an {b} organization like the US government " c = input("Adjective: ") madlib += f"uses spies to infiltrate {c} groups " d = input("Plural Noun: ") madlib += f"for the purpose of obtaining top secret {d}. " e = input("Adjective: ") madlib += f"For example, spies might have to crack the code for acessing confidential, {e} files, " f = input("Person in Room: ") madlib += f"or their mission could be far more dangerous - like stealing the key ingredient for making {f}'s " g = input("Plural Noun: ") madlib += f"award-winning Explosive Fudgy {g}. " h = input("A Place: ") madlib += f"Spies are found all over (the) {h} " i = input("Adjective: ") madlib += f"but they are not allowed to reveal their {i} identities. " j = input("Celebrity: ") madlib += f"A teacher, {j}, " k = input("Noun: ") madlib += f"or even the little old {k} with the cane " l = input("Plural Noun: ") madlib += f"and fifteen pet {l} who lives next door to you could be a spy. " m = input("Adjective: ") madlib += f"The world of spying might seem glamorous and {m} " n = input("Plural Noun: ") madlib += f"but it is filled with risks and {n}! " o = input("Plural Noun: ") madlib += f"Sure, spies have a never-ending supply of supercool electronic {o}, " p = input("Noun: ") madlib += f"but they can't trust any {p} " q = input("Plural Noun: ") madlib += f"which is why the number one rule of spies is to keep friends close... and {q} closer!" print (madlib)
d0c948552ba6d559aac56c2970d3dc110ad40a9c
CruzerNexus/Repo
/pythonFullStack/numberToPhrase.py
1,058
3.953125
4
ones = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"} tens = {2: "twenty", 3: "thirty", 4: "fourty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"} def intToEng(x): word = "" if x == "10": return("ten") elif x == "11": return("eleven") elif x == "12": return("twelve") elif x == "0": return("zero") else: number = int(x) if 12 < number < 20: if x[-1] == "3": return "thirteen" elif x[-1] == "4": return "fourteen" elif x[-1] == "5": return "fifteen" elif x[-1] == "6": return "sixteen" elif x[-1] == "7": return "seventeen" elif x[-1] == "8": return "eighteen" else: return "nineteen" else: for i in range(len(x)): if len(x) == 2 and number % 10 !=0: word = (f"{tens[number // 10]}-{ones[number % 10]}") elif len(x) == 2: word = (tens[number // 10]) else: word = (ones[number%10]) return word x = input("Enter a number between 0 and 99: ") print(f'You have entered {intToEng(x)}.')
a7852816dd48f6c67888180eb9be6489fa8b2c78
mahack-gis/GISProgramming6345_WK5
/Exercise 9.1_redo.py
592
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: file = open('words.txt', 'r') #locates the file and 'r' reads each line f = file.readlines() #print(f) # In[4]: newList = [] #creates an empty list for line in f: if line[-1] == '\n': newList.append(line[:-1]) else: newList.append(line) #print(newList) # In[5]: longWords = [] #creates an empty list for word in newList: #traverse each word in newList if len(word) >= 20: #if word is > 20 char add to new list longWords.append(word) print(longWords)
76262d582cce4a4d8cd821ea35b0ff9cea1b7a17
mahack-gis/GISProgramming6345_WK5
/Exercise 9.2_redo.py
1,794
3.953125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: def has_no_e(word): #creates a function called has_no_e for letter in word: #traverses each letter in word if letter == 'e': #if the letter is 'e' returns False return False return True #else it returns true # In[2]: has_no_e('star') #'star' has no E so it should return True # In[3]: has_no_e('hello') #'hello' has an E so it should return False # In[4]: file = open('testWords.txt', 'r') #locates the file and 'r' reads each line f = file.readlines() # In[5]: wordList = [] #creates an empty list for line in f: if line[-1] == '\n': wordList.append(line[:-1]) else: wordList.append(line) print(wordList) # In[6]: ##This attempt did not do what I expected: noEWords = [] #creates an empty list for word in wordList: #traverse each word in newList for letter in word: #traverses each letter in word if letter != 'e': #if the letter is not 'e' add it to list noEWords.append(word) print(noEWords) # In[7]: ###found this solution online after several attempts on my own. word = open('words.txt') def words(word): # function that takes a str wordCount = 0 #variable to hold the word count lineCount = 0 #variable to hold the line count for line in word: #traverse each line in word if line.find('e') == -1: #if the line has 'e' print(line) #print it wordCount += 1 #incremeent word count by 1 lineCount += 1 #increment line count by 1 for every line percent = (float(wordCount) / float(lineCount)) * 100.0 print(percent, '%') words(word)
a168748c4be85b53e6f97007b0b6e20d332833dd
pokoli/adventofcode2020
/day1/resolve.py
645
3.53125
4
import os from itertools import combinations expenses = [] with open(os.path.join('.', 'input.txt')) as f: for line in f.readlines(): expenses.append(int(line)) for a, b in combinations(expenses, 2): if a + b == 2020: print('Found two numbers ({a}, {b}) that sum 2020'.format(**locals())) print('Its multiplication is {mul}'.format(mul=a * b)) break for a, b, c in combinations(expenses, 3): if a + b + c == 2020: print('Found three numbers ({a}, {b}, {c}) that sum 2020'.format( **locals())) print('Its multiplication is {mul}'.format(mul=a * b * c)) break
76759518bd53b697e0b7592d04df04ed5b1af2aa
goldandelion/learn-python
/ex3.py
812
4.0625
4
# -*- coding:utf-8 -*- # 每个程序媛都有把程序写优雅的义务 print "I will now count my chickens:" print "Hens",25+30/6 # 30除以6是5 25加5是30 print "Roosters",100-25*3%4 # 25乘3是75 75除4的余数是3 100减3是97 print "Now I will count the eggs:", 3+2+1-5+4%2-1/4+6 print "Is it true that 3+2<5-7 ?" print 3+2 < 5-7 print "What is 3+2?",3+2 print "What is 5-7?",5-7 print "Oh, that's why it's False." print "How about some more." print "Is it greater? 5>-2,",5>-2 print "Is it greater or equal? 5>=-2,", 5>=-2 print "Is it less or equal? 5<=-2," ,5<=-2 print "what is 7/4?", 7/4 print "what is 7.0/4.0?", 7.0/4.0 print "try floating number" print "Hens",25.0+30.0/6.0 # 30除以6是5 25加5是30 print "Roosters",100.0-25.0*3.0%4.0 # 25乘3是75 75除4的余数是3 100减3是97
67eb2e0043b1c1d63395df0de8f4e39a98930a7e
luthraG/ds-algo-war
/general-practice/17_09_2019/p16.py
996
4.1875
4
''' Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) ''' def can_construct_string(str1): length = len(str1) i = 1 limit = length // 2 while i <= limit: if length % i == 0: times = length // i if str1[:i] * times == str1: return True i += 1 return False str1 = str(input('Enter input string :: ')) print('can this string be constructed by sub strings :: {}'.format(can_construct_string(str1)))
a5a7621f089aeef12a7b1d304f904a012a90d5db
luthraG/ds-algo-war
/general-practice/10_09_2019/p10.py
528
3.890625
4
import operator import re ops = { '+': operator.add, '-': operator.sub } pattern = re.compile(r'([0-9]+)([+-]*)') expression = str(input('Enter mathematical expression containing plueses and minues :: ')) stack = 0 operation = None for number, operator in re.findall(pattern, expression): if operation: stack = operation(int(stack), int(number)) if operation is None: stack = number if operator: operation = ops[operator] print('Expression resolves to : {}'.format(stack))
2e0b50d0d233545a278ca3874bf2523da2d2ddbd
luthraG/ds-algo-war
/problems/leet/string/p1.py
1,573
3.75
4
''' https://leetcode.com/problems/roman-to-integer/ Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. ''' from timeit import default_timer as timer import operator ops = { '+': operator.add, '-': operator.sub } translate = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } def roman_to_integer(roman): i = len(roman) - 1 operator = ops['+'] stack = 0 handledPrev = False while i >= 0: if handledPrev is False: current = roman[i] if (i - 1) >= 0: prev = roman[i - 1] else: prev = None if (prev == 'I' and current in ['V', 'X']) or (prev == 'X' and current in ['L', 'C']) or (prev == 'C' and current in ['D', 'M']): current = ops['-'](translate[current], translate[prev]) handledPrev = True if current in translate: current = translate[current] stack = operator(current, stack) else: handledPrev = False i -= 1 return stack roman = str(input('Enter roman number :: ')).upper() start = timer() integer = roman_to_integer(roman) end = timer() print('Integer form of roman number {} is {}'.format(roman, integer)) print('Time taken is {}'.format(end - start))
b5a690bcf29a1d7227d20a1db56e5ce1afee3fc1
luthraG/ds-algo-war
/general-practice/22_08_2019/p6.py
1,412
3.953125
4
# coding: utf-8 ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? Algorithm is based on idea that prime numbers are always of the form 6*k + 1 So we would only check those numbers which can be expressed in 6*k + 1 form ''' from timeit import default_timer as timer import math def isPrime(number): if number % 2 == 0: return number == 2 if number % 3 == 0: return number == 3 x = 5 limit = int(math.sqrt(number) + 1) while x <= limit: if number % x == 0: return False if number % (x + 2) == 0: return False x += 6 return True def nthPrime(number): n = 0 # Keeps the nth prime number c = 2 # Keeps the counter of prime number if number == 1: n = 2 elif number == 2: n = 3 while c < number: n += 6 if isPrime(n - 1): c += 1 if c == number: return n - 1 if isPrime(n + 1): c += 1 if c == number: return n + 1 return n if __name__ == '__main__': number = int(input('Enter the number :: ')) start = timer() print('{} prime number is {}'.format(number, nthPrime(number))) end = timer() print('Time taken is {}'.format(end - start))
3316019f3994b8404396a16cfeac53ce0bb3a82d
luthraG/ds-algo-war
/general-practice/28_08_2019/p6.py
1,340
3.703125
4
from timeit import default_timer as timer import math def rwh_prime(upper_bound, number): primes = [True] * upper_bound primes[0] = False primes[1] = False i = 3 limit = int(upper_bound ** 0.5) + 1 while i <= limit: if primes[i]: primes[i*i::2*i] = [False] * ((upper_bound-i*i- 1)//(2*i) + 1) i += 2 i = 3 count = 1 nthPrime = -1 if number == 1: nthPrime = 2 while i < upper_bound and nthPrime == -1: if primes[i]: count += 1 if count == number: nthPrime = i break i += 2 return nthPrime if __name__ == '__main__': test_cases = int(input('Enter the number of test_cases :: ')) for t in range(test_cases): number = int(input('Enter the number :: ')) start = timer() firstPrimes = [2, 3, 5, 7, 11, 13] primes = -1 if number < 7 and number > 0: prime = firstPrimes[number - 1] else: upper_bound = (number * math.log(number)) + (number * math.log(math.log(number))) + 3 upper_bound = int(upper_bound) prime = rwh_prime(upper_bound, number) print('{} prime number is {}'.format(number, prime)) end = timer() print('Time taken is : {}'.format(end - start))
dd67cc4be7876eb5b448ca6cb7d1e9b1263d0eb0
luthraG/ds-algo-war
/general-practice/28_08_2019/p1.py
708
3.859375
4
from timeit import default_timer as timer if __name__ == '__main__': test_cases = int(input('Enter test cases :: ')) for t in range(test_cases): number = int(input('Enter number :: ')) start = timer() # since we need multiples below number -= 1 mux3 = number // 3 mux5 = number // 5 mux15 = number // 15 mux3 = 3 * ((mux3 * (mux3 + 1)) // 2) mux5 = 5 * ((mux5 * (mux5 + 1)) // 2) mux15 = 15 * ((mux15 * (mux15 + 1)) // 2) sum = mux3 + mux5 - mux15 print('Sum of multiples of 3 and 5 below {} is {}'.format(number + 1, sum)) end = timer() print('Time taken is {}'.format(end - start))
fea3eb8962250ac66a1d519c751f53e1f5119379
luthraG/ds-algo-war
/general-practice/11_09_2019/p6.py
1,163
3.9375
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' from timeit import default_timer as timer import math def prime_rwh(upper_limit, number): primes = [True]* upper_limit primes[0] = False primes[1] = False i = 3 limit = int(upper_limit ** 0.5) + 1 while i <= limit: primes[i*i::2*i] = [False]*((upper_limit-i*i-1)//(2*i) + 1) i += 2 count = 1 i = 3 nthPrimeNumber = -1 while i < upper_limit: if primes[i]: count += 1 if count == number: nthPrimeNumber = i break i += 2 return nthPrimeNumber number = int(input('Enter which prime number is required :: ')) start = timer() primes = [2,3,5,7,11,13] if number < 7: nthPrimeNumber = primes[number - 1] else: upper_limit = int((number * math.log(number)) + (number * math.log(math.log(number))) + 3) nthPrimeNumber = prime_rwh(upper_limit, number) end = timer() print('{} prime number is {}'.format(number, nthPrimeNumber)) print('Time taken is {}'.format(end - start))
31ea62752ea462b775c16a6a7a1f0fb61d8eecc8
luthraG/ds-algo-war
/general-practice/24_08_2019/p5.py
1,069
4.0625
4
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes not greater than given N. Input Format The first line contains an integer T i.e. number of the test cases. The next T lines will contains an integer N. Constraints 1 <= T <= 10^4 1 <= N <= 10^6 Output Format Print the value corresponding to each test case in separate line. Algorithm 2: Here we use sieve of Eratosthenes ''' from timeit import default_timer as timer def sumOfPrimes(number): sum = 0 primes = [True] * (number + 1) x = 2 while x <= number: y = x if primes[y]: sum += x y = 2 * x while y <= number: primes[y] = False y += x x += 1 return sum if __name__ == '__main__': number = int(input('Enter the number : ')) start = timer() print('Sum of primes not greater than {} is {}'.format(number, sumOfPrimes(number))) end = timer() print('Time taken is : {}'.format(end - start))
c970b948cc1ceaff2b10aedd36807e277b69ff98
luthraG/ds-algo-war
/general-practice/11_09_2019/p22.py
509
3.84375
4
import operator import re ops = { '+': operator.add, '-': operator.sub } expression = str(input('Enter mathematical expression(containing pluses and minues) :: ')) pattern = re.compile(r'([0-9])+([+-])*') operation = None stack = 1 for number, op in re.findall(pattern, expression): if operation: stack = operation(int(stack), int(number)) if op: operation = ops[op] if operation is None: stack = number print('Expression value is {}'.format(stack))
9ad1b5b8b960b7a144624a8f77de063b758fe7a7
luthraG/ds-algo-war
/general-practice/22_08_2019/p13.py
1,200
3.90625
4
# coding: utf-8 ''' n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! Algorithm 4:: Use prime decompositions ''' from timeit import default_timer as timer def calculateFactorial(number): primes = [True] * (number + 1) primes[0] = False primes[1] = False i = 2 fact = 1 while i <= number: if primes[i]: j = i + i while j <= number: primes[j] = False j += i sum = 0 t = i while t <= number: sum += number // t t *= i fact *= i**sum i += 1 return fact if __name__ == '__main__': number = int(input('Enter the number :: ')) start = timer() sum = 0 fact = calculateFactorial(number) while fact != 0: sum += fact % 10 fact //= 10 print('Sum of digits of factorial of {} is {}'.format(number, sum)) end = timer() print('Time taken is {}'.format(end - start))
bd48564a03e15ec4c6f2d287ec3b651947418118
luthraG/ds-algo-war
/general-practice/20_08_2019/p1.py
861
4.125
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 10 Million. from timeit import default_timer as timer if __name__ == '__main__': start = timer() number = 1000 # Since we want below hence number -= 1 # Sum of multiple of 3s upper3 = number // 3 sum3 = 3 * upper3 * (upper3 + 1) // 2 # Sum of multiple of 5s upper5 = number // 5 sum5 = 5* upper5 * (upper5 + 1) // 2 # Sum of multiple of 15s upper15 = number // 15 sum15 = 15 * upper15 * (upper15 + 1) // 2 sum = sum3 + sum5 - sum15 print("sum3 {}, sum5 {} and sum15 {}".format(sum3, sum5, sum15)) print("Overall sum = {}".format(sum)) end = timer() print("Time taken is {}".format(end - start))
2232e32a65b40db29c0004e11d449da832d2cf39
luthraG/ds-algo-war
/problems/euler/p10/solution.py
603
4.0625
4
from timeit import default_timer as timer import math def isPrime(number): if number % 2 == 0 and number != 2: return False for x in range(3, int(math.sqrt(number)) + 1, 2): if number % x == 0: return False return True if __name__ == '__main__': start = timer() number = 2000000 addition = 0 for x in range(2, number + 1): isP = isPrime(x) if isP: addition = addition + x print("Sum of prime numbers below {} is {}".format(number, addition)) end = timer() print("Time taken is {}".format(end - start))
3ec6fd0dcd97904b08c95fe17cac67b03a75a61f
luthraG/ds-algo-war
/general-practice/11_09_2019/p11.py
648
4.15625
4
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' from timeit import default_timer as timer power = int(input('Enter the power that needs to be raised to base 2 :: ')) start = timer() sum_of_digits = 0 number = 2 << (power - 1) number = str(number) length = len(number) i = 0 while i < length: sum_of_digits += int(number[i]) i += 1 # while number != 0: # sum_of_digits += (number % 10) # number //= 10 end = timer() print('Sum of digits of 2 raised to power {} is {}'.format(power, sum_of_digits)) print('Time taken is {}'.format(end - start))
ddc31bfd69d17e5f07a602d330ed39b644d0a372
luthraG/ds-algo-war
/problems/hackerrank/competition/euler/solution2.py
733
3.96875
4
from timeit import default_timer as timer if __name__ == '__main__': number = int(input("Enter the upper limit of number :: ")) start = timer() addition = 0 sequence = [1, 2] term = 0 if number <= 1: sequence = [] # Let us add value of 2 addition = addition + 2 while term <= number and len(sequence) == 2: term = sequence[0] + sequence[1] if term <= number: sequence[0] = sequence[1] sequence[1] = term if term % 2 == 0: addition = addition + term end = timer() print("Sum of even valued terms for Fibonacii series below {} is {}".format(number, addition)) print("Time taken is {}".format(end - start))
56a73740d003c13f2c8f0ad569fd6afbfd2c6b78
luthraG/ds-algo-war
/problems/euler/p2/solution.py
735
3.78125
4
from timeit import default_timer as timer def additionFabonacii(limit): sequence = [1, 2] term = 0 addition = 0 if limit > 0: addition = addition + 2 while term < limit: length = len(sequence) term = sequence[length - 1] + sequence[length - 2] if term < limit: if term % 2 == 0: addition = addition + term sequence.append(term) return addition if __name__ == '__main__': limit = 10**16 addition = 0 start = timer() addition = additionFabonacii(limit) end = timer() print("Addition of even valued terms in Fabonacii series upto {} is {}".format(limit, addition)) print("Time taken is {}".format(end - start))
33f5c2d803562730098d3b4393d5843d9d2f9d4a
luthraG/ds-algo-war
/general-practice/14_09_2019/p18.py
1,586
4.34375
4
''' https://leetcode.com/problems/unique-email-addresses/ Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.) It is possible to use both of these rules at the same time. Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails? ''' import re def unique_emails_count(emails): unique_emails = [] for email in emails: email_split = email.split('@') email = re.sub(r'\.', '', email_split[0]) email = email + '@' + email_split[1] email = re.sub(r'\+(.*?)(?=@)', '', email) unique_emails.append(email) return len(set(unique_emails)) emails = str(input('Enter list of emails : ')).split(',') emails = list(map(str, emails)) print('Total unique emails count is {}'.format(unique_emails_count(emails)))
743148624d001ae5c9bbea10f8d70b7074e9ddb0
luthraG/ds-algo-war
/general-practice/10_09_2019/p20.py
450
4.0625
4
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' from timeit import default_timer as timer number = int(input('Enter power :: ')) start = timer() exp = 2 << (number - 1) sum = 0 while exp != 0: sum += (exp % 10) exp //= 10 end = timer() print('Sum of digits of 2 raised to {} is {}'.format(number, sum)) print('Time taken is : {}'.format(end - start))
72fd0e2052800e60a55b2bfeca7a54eee9aa59f6
luthraG/ds-algo-war
/general-practice/11_09_2019/p16.py
481
3.8125
4
class ArraySetOps: def mean(self, items): length = len(items) sum_of_items = 0 for item in items: sum_of_items += item return (sum_of_items / length) if __name__ == '__main__': arraySetOps = ArraySetOps() numbers = str(input('Enter list of numbers(separated by comma). Press enter to stop :: ')).split(',') numbers = list(map(int, numbers)) print('Mean of numbers is : {}'.format(arraySetOps.mean(numbers)))
2016817647c32c5e148437225c826b39f2ce8ee4
luthraG/ds-algo-war
/general-practice/10_09_2019/p3.py
2,228
4.125
4
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.start_node = Node() def add_to_start(self, data): node = Node(data) node.next = self.start_node.next self.start_node.next = node def add_to_end(self, data): node = Node(data) n = self.start_node while n.next is not None: n = n.next n.next = node def remove_from_begining(self): node = self.start_node.next if node is None: print('List is empty. Nothing to delete') else: self.start_node.next = node.next node = None def remove_from_end(self): node = self.start_node if node.next is None: print('List is empty. Nothing to delete') else: while node.next.next is not None: node = node.next node.next = None def traverse_list(self): node = self.start_node while node is not None: if node.data is not None: print(node.data) node = node.next def count(self): c = 0 node = self.start_node while node is not None: if node.data is not None: c += 1 node = node.next return c if __name__ == '__main__': linkedList = LinkedList() number = int(input('Enter number of items to add in list :: ')) for i in range(number): data = int(input('Enter data :: ')) # If i is even then add to start, else add to end if i & 1 == 1: linkedList.add_to_end(data) else: linkedList.add_to_start(data) count = linkedList.count() print('Total items in the list :: {}'.format(count)) MAX_ALLOWED = 2 diff = count - MAX_ALLOWED if diff > 0: print('Going to remove {} items from end'.format(diff)) for i in range(diff): linkedList.remove_from_end() print('List items are') linkedList.traverse_list() print('Total items in the list :: {}'.format(linkedList.count()))
07e1d267b9b5d0dadb0e2b797a40ae148ba695a5
luthraG/ds-algo-war
/general-practice/28_08_2019/p8.py
973
3.796875
4
from timeit import default_timer as timer def sumOfPrimes(number): number += 1 # Since we want primes equal to number primes = [True] * number sum = [0] * number i = 3 limit = int(number ** 0.5) + 1 while i <= limit: if primes[i]: primes[i*i::2*i] = [False] * (((number - i*i - 1)//(2*i)) + 1) i += 2 i = 3 sum[2] = 2 prev_sum = 2 while i < number: if primes[i]: prev_sum += i sum[i] = prev_sum sum[i+1] = prev_sum i += 2 return sum if __name__ == '__main__': test_cases = int(input('Enter the test cases :: ')) max_limit = 1000000 sum = sumOfPrimes(max_limit) for t in range(test_cases): number = int(input('Enter the number :: ')) start = timer() print('Sum of primes not greater than {} is {}'.format(number, sum[number])) end = timer() print('Time taken is : {}'.format(end - start))
d331095ee862fa325c24109df312a94f269af343
luthraG/ds-algo-war
/sorting/quickSort.py
1,136
3.875
4
from timeit import default_timer as timer def partition(input, low, high): # print("low {} and high {}".format(low, high)) i = low - 1 # Index of smaller element pivot = input[high] j = low # loop variable while j < high: elem = input[j] if elem <= pivot: # Increment the counter and then replace i with j i += 1 temp = input[j] input[j] = input[i] input[i] = temp j += 1 i += 1 temp = input[i] input[i] = pivot input[high] = temp return i def quickSort(input, low, high): if low < high: partitionIndex = partition(input, low, high) # Now pivot is at correct position, so we will sort left and sort right quickSort(input, low, partitionIndex - 1) quickSort(input, partitionIndex + 1, high) if __name__ == "__main__": input = [4, 1, 3, 7, 9, 8, 2, 6, 5] # input = [10, 7, 8, 9, 1, 5] start = timer() quickSort(input, 0, len(input) - 1) print("Sorted list is {}".format(input)) end = timer() print("Time taken is {}".format((end - start)))
b3aaf2652c1cfda99a9c3b3c8e1d7d47b358abb4
luthraG/ds-algo-war
/general-practice/18_09_2019/p12.py
1,035
4.15625
4
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. ''' def longest_common_prefix(str1, str2): length1 = len(str1) length2 = len(str2) if length1 == 0 or length2 == 0: return '' else: i = 0 while i < length1 and i < length2: if str1[i] != str2[i]: break i += 1 return str1[0:i] if i > 0 else '' def longest_common_prefix_solution(items): length = len(items) common_prefix = items[0] if length > 0 else '' i = 1 while i < length: common_prefix = longest_common_prefix(common_prefix, items[i]) i += 1 return common_prefix
65fa7232117759419f49d208b8bcd19e9c35e064
Throrus/Calculator
/calculator.py
5,876
4
4
import tkinter as tk from tkinter import font # window setup window = tk.Tk() window.title("Calculator") window.geometry('500x500') window.resizable(0, 0) # setting up the grid rows = 0 while rows < 5: window.rowconfigure(rows, weight=1) window.columnconfigure(rows,weight=1) rows += 1 # font font = font.Font(family='Helvetica', size=18, weight='bold') # display field display_text = tk.StringVar() result_field = tk.Label(window, width = 25, height = 3, textvariable = display_text, font=font, fg = "black", bg = "white").grid(row = 0, columnspan = 3) # arithmatic symbol arith_symbol = "default" result = 0 # value groups num_set1 = '' num_set2 = '' float1 = False float2 = False # updating the arithmatic value def update_symbol(sign): global arith_symbol global display_text if arith_symbol == 'default': arith_symbol = sign current = display_text.get() if sign == "add": current += " + " elif sign == "subtract": current += " - " elif sign == "multiply": current += " x " elif sign == "divide": current += " / " display_text.set(current) else: pass # arithmatic functions def calculate(arith_symbol, num_set1, num_set2, float1, float2): global result global display_text if float1 == True: num_set1 = float(num_set1) else: num_set1 = int(num_set1) if float2 == True: num_set2 = float(num_set2) else: num_set2 = int(num_set2) if arith_symbol == "add": result = (num_set1 + num_set2) elif arith_symbol == "subtract": result = (num_set1 - num_set2) elif arith_symbol == "multiply": result = (num_set1 * num_set2) elif arith_symbol == "divide": result = (num_set1 / num_set2) current = display_text.get() current = result display_text.set(current) # functions that add the numbers def add_num(num, arith_symbol): global display_text global num_set1 global num_set2 global float1 global float2 current = display_text.get() current += num display_text.set(current) if arith_symbol == 'default': num_set1 += num if num == ".": float1 = True else: num_set2 += num if num == ".": float2 = True # clear the display def clear(): global display_text global arith_symbol global num_set1 global num_set2 current = display_text.get() current = '' display_text.set(current) arith_symbol = "default" num_set1 = '' num_set2 = '' # button frame class Calculator(tk.Frame): def __init__(self, master=None, **kwargs): tk.Frame.__init__(self, master) self.rowconfigure(0, minsize=kwargs.pop('height', None)) self.columnconfigure(0, minsize=kwargs.pop('width', None)) self.btn = tk.Button(self, **kwargs) self.btn.grid(row=0, column=0, sticky="nsew") self.config = self.btn.config # number buttons one = Calculator(window,text="1",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("1",arith_symbol)).grid(row=1, column=0) two = Calculator(window,text="2",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("2",arith_symbol)).grid(row=1, column=1) three = Calculator(window,text="3",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("3",arith_symbol)).grid(row=1, column=2) four = Calculator(window,text="4",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("4",arith_symbol)).grid(row=2, column=0) five = Calculator(window,text="5",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("5",arith_symbol)).grid(row=2, column=1) six = Calculator(window,text="6",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("6",arith_symbol)).grid(row=2, column=2) seven = Calculator(window,text="7",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("7",arith_symbol)).grid(row=3, column=0) eight = Calculator(window,text="8",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("8",arith_symbol)).grid(row=3, column=1) nine = Calculator(window,text="9",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("9",arith_symbol)).grid(row=3, column=2) zero = Calculator(window,text="0",width=105, height=80 ,font=font, fg = "black", command = lambda: add_num("0",arith_symbol)).grid(row=4, column=1) # math buttons add_button = Calculator(window, width = 105, height = 80, text = "+", font=font, fg = "black", command = lambda: update_symbol("add")).grid(row = 1, column = 3) sub_button = Calculator(window, width = 105, height = 80, text = "-", font=font, fg = "black", command = lambda: update_symbol("subtract")).grid(row = 2, column = 3) mul_button = Calculator(window, width = 105, height = 80, text = "x", font=font, fg = "black", command = lambda: update_symbol("multiply")).grid(row = 3, column = 3) div_button = Calculator(window, width = 105, height = 80, text = "/", font=font, fg = "black", command = lambda: update_symbol("divide")).grid(row = 4, column = 3) dec_button = Calculator(window, width = 105, height = 80, text = ".", font=font, fg = "black", command = lambda: add_num(".", arith_symbol)).grid(row = 4, column = 0) equ_button = Calculator(window, width = 105, height = 80, text = "=", font=font, fg = "black", command = lambda: calculate(arith_symbol, num_set1, num_set2, float1, float2)).grid(row = 4, column = 2) clear_button = Calculator(window, width = 105, height = 80, text = "C", font=font, fg = "black", command = lambda: clear()).grid(row = 0, column = 3) window.mainloop()
06840ed3effeba83a48b27d1b9f5fdce3b940f82
hluaces/cntg-python
/practicas/Ejercicios complementarios 1/programs/ej7.py
603
4
4
#!/usr/bin/env python def _get_input(): words = [] while len(words) == 0: x = input("Imprime una lista de palabras separadas por espacios: ") y = [x.strip() for x in x.split(' ')] if len(y) == 1 and y[0] == '': print("Entrada inválida.") continue words = y return words def main(): words = list(set(_get_input())) words.sort() for word in words: if word == words[0]: print(word, end="") else: print(" " + word, end="") print("") if __name__ == "__main__": main()
95766d349262a1517cd3d4dee2470e92d39011a7
hluaces/cntg-python
/practicas/Ejercicios complementarios 2/ej13.py
188
3.625
4
#!/usr/bin/env python def main(): x = input("Introduce texto:") if x.lower() == "yes": print("Yes") else: print("No") if __name__ == "__main__": main()
0150bb0f24cece88f5dd912701d927e30af20439
kubeflow/testing
/py/kubeflow/testing/yaml_util.py
482
3.515625
4
"""YAML utilities """ import requests import urllib import yaml def load_file(path): """Load a YAML file. Args: path: Path to the YAML file; can be a local path or http URL Returs: data: The parsed YAML. """ url_for_spec = urllib.parse.urlparse(path) if url_for_spec.scheme in ["http", "https"]: data = requests.get(path) return yaml.load(data.content) else: with open(path, 'r') as f: config_spec = yaml.load(f) return config_spec
df6f00a9ec76db2997df11d0e31f7f448bacd7fc
arifaulakh/Competitive-Programming
/DMOJ/dealing_with_knots/main.py
430
3.546875
4
G = {} for i in range(1,1003): G[i] = set() visited = [False for i in range(1003)] def dfs(graph, node): if visited[node]==True: return visited[node] = True for v in G[node]: dfs(graph, v) N = int(input()) for i in range(N): a, b = map(int, input().split()) G[a].add(b) X, Y = map(int, input().split()) dfs(G, X) if (visited[Y]==True): print("Tangled") else: print("Not Tangled")
bc8beb8ee2874764216e03c0467f0ef776a96721
arifaulakh/Competitive-Programming
/DMOJ/bruno_and_trig/brunoandtrig.py
227
3.796875
4
a = int(input()) b = int(input()) c = int(input()) x = [] x.append(a) x.append(b) x.append(c) x.sort() if x[0] + x[1] > x[2]: print("Huh? A triangle?") elif x[0] + x[1] <= x[2]: print("Maybe I should go out to sea...")
5ebb5fe066d3af6b3467c61f030497ae7c889e2f
arifaulakh/Competitive-Programming
/DMOJ/deficient_abundant_perfect/deficientabundantperfect.py
361
3.71875
4
n = int(input()) for i in range(0,n): count = 0 each = int(input()) for j in range(1, each + 1): if each%j == 0 and each != j: count +=j if count == each: print(str(each) + " is a perfect number.") elif count > each: print(str(each) + " is an abundant number.") elif count < each: print(str(each) + " is a deficient number.")
b2657646e162f2ada6cb62bae50bd8e894591865
arifaulakh/Competitive-Programming
/DMOJ/interlace_cypher/main.py
140
3.734375
4
for i in range(10): n = input() if n=="encode": p = input().split(" ") print(p) elif n=="decode": p = input().split(" ") print(p)
6d53601a7fc6a0c2fb2e35f5685770bd5e771798
stollcode/GameDev
/game_dev_oop_ex1.py
2,829
4.34375
4
""" Game_dev_oop_ex1 Attributes: Each class below, has at least one attribute defined. They hold data for each object created from the class. The self keyword: The first parameter of each method created in a Python program must be "self". Self specifies the current instance of the class. Python Directions: Create a Python module on your Z:\GameDev folder named oop_ex1.py. Add the following code to the module. Do not forget to test!!! *** Teacher Class *** 1. Define a class named Teacher containing the following attributes: a. Attributes: i. name ii. gender iii. date_of_birth iv. phone_number b. Set all attributes to default as empty strings (also called null strings). Write the code below the triple quotes below. """ # Your code goes here. """ *** Monkey Class **** 2. Define a class named Monkey containing the following attributes: a. Attributes: i. age ii. species iii. is_rain_forest b. Set the default age to zero, species to an empty string and is_rain_forest to False. Write the code below the triple quotes below. """ # Your code goes here """ *** Fish Class *** 3. Define a class named Fish with the following attributes: a. Attributes: i. is_fresh_water ii. weight iii. age iv. gender b. Set the following defaults for the attributes: is_fresh_water to False, weight to 0.0, age to 0 and gender to an empty string. c. Define a breathe() method that returns the following string: The fish breathes Do not forget to include self as the first parameter of the method. Example: def breathe(self): Write the code below the triple quotes below. """ # Your code goes here """ *** Enemy Class *** 4. Create a class named Enemy with the following attributes: a. Attributes: i. Name = "Goblin" ii. health = 100 Write the code below the triple quotes below. """ # Your code goes here """ *** Testing *** 5. For each class: a. Print a message describing the class being tested (ie. "Testing the Fish Class:") b. Create an object instance. c. Set all attribute values. (be creative, unless otherwise specified) d. Modify the attribute values. e. Print the attribute values using descriptive headings f. Call methods for the class where appropriate. g. Print any values returned by the methods, with descriptive headings. Write the tests below the triple quotes below. """ # Test the Teacher class here # Test the Monkey class here # Test the Fish class here (Don't forget to call the breathe() method) # Test the Enemy class below.
0f227ae102e644024608c93a33dac90b39f2dcb9
greenblues1190/Python-Algorithm
/LeetCode/14. 비트 조작/393-utf-8-validation.py
1,893
4.15625
4
# https://leetcode.com/problems/utf-8-validation/ # Given an integer array data representing the data, return whether it is a valid UTF-8 encoding. # A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: # For a 1-byte character, the first bit is a 0, followed by its Unicode code. # For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, # followed by n - 1 bytes with the most significant 2 bits being 10. # This is how the UTF-8 encoding would work: # Char. number range | UTF-8 octet sequence # (hexadecimal) | (binary) # --------------------+--------------------------------------------- # 0000 0000-0000 007F | 0xxxxxxx # 0000 0080-0000 07FF | 110xxxxx 10xxxxxx # 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx # 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx # Note: The input is an array of integers. # Only the least significant 8 bits of each integer is used to store the data. # This means each integer represents only 1 byte of data. from typing import List class Solution: def validUtf8(self, data: List[int]) -> bool: def check(bytes: int, start: int) -> bool: for i in range(start + 1, start + bytes): if i >= len(data) or (data[i] >> 6) != 0b10: return False return True start = bytes = 0 while start < len(data): code = data[start] if code >> 3 == 0b11110: bytes = 4 elif code >> 4 == 0b1110: bytes = 3 elif code >> 5 == 0b110: bytes = 2 elif code >> 7 == 0b0: bytes = 1 else: return False if not check(bytes, start): return False start += bytes return True
56ead187d3484a44effec2bbe6b3b3835a42e87f
greenblues1190/Python-Algorithm
/LeetCode/18. 다이나믹 프로그래밍/53-maximum-subarray.py
628
3.921875
4
# https://leetcode.com/problems/maximum-subarray/ # Given an integer array nums, find the contiguous subarray(containing at least one number) # which has the largest sum and return its sum. # A subarray is a contiguous part of an array. # Constraints: # 1 <= nums.length <= 3 * 104 # -105 <= nums[i] <= 105 from typing import List import sys class Solution: def maxSubArray(self, nums: List[int]) -> int: best_sum = -sys.maxsize current_sum = 0 for num in nums: current_sum = max(num, current_sum + num) best_sum = max(best_sum, current_sum) return best_sum
d220f727d9ae11f1f6add855328aeb8c98e98aa3
greenblues1190/Python-Algorithm
/LeetCode/18. 다이나믹 프로그래밍/509-fibonacci-number.py
1,147
3.734375
4
# https://leetcode.com/problems/fibonacci-number/ # The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, # such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, # F(0) = 0, F(1) = 1 # F(n) = F(n - 1) + F(n - 2), for n > 1. # Given n, calculate F(n). # Constraints: # 0 <= n <= 30 import collections # memoization (bottom-up) class Solution: dp = collections.defaultdict(int) def fib(self, n: int) -> int: if n <= 1: return n if self.dp[n]: return self.dp[n] self.dp[n] = self.fib(n - 1) + self.fib(n - 2) return self.dp[n] # tabulation (top-down) class Solution: dp = collections.defaultdict(int) def fib(self, n: int) -> int: self.dp[0] = 0 self.dp[1] = 1 for i in range(2, n + 1): self.dp[i] = self.dp[i - 1] + self.dp[i - 2] return self.dp[n] # save memory class Solution: def fib(self, n: int) -> int: x = 0 y = 1 for i in range(0, n): x, y = y, x + y return x
800919799222a6c3a4952517b1ceb6d456e7ed4b
greenblues1190/Python-Algorithm
/LeetCode/16. 그리디 알고리즘/455-assign-cookies.py
994
3.640625
4
# https://leetcode.com/problems/assign-cookies/ # Assume you are an awesome parent and want to give your children some cookies. # But, you should give each child at most one cookie. # Each child i has a greed factor g[i], which is the minimum size of a cookie\ # that the child will be content with; and each cookie j has a size s[j]. # If s[j] >= g[i], we can assign the cookie j to the child i, and the child i # will be content. Your goal is to maximize the number of your content children # and output the maximum number. # Constraints: # 1 <= g.length <= 3 * 104 # 0 <= s.length <= 3 * 104 # 1 <= g[i], s[j] <= 231 - 1 from typing import List class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() greed_idx = size_idx = 0 while greed_idx < len(g) and size_idx < len(s): if g[greed_idx] <= s[size_idx]: greed_idx += 1 size_idx += 1 return greed_idx
94aee979799f19ca2c565a953db0ae0ab2554ffa
greenblues1190/Python-Algorithm
/LeetCode/15. 슬라이딩 윈도우/424-longest-repeating-character-replacement.py
956
3.515625
4
# https://leetcode.com/problems/longest-repeating-character-replacement/ # You are given a string s and an integer k. You can choose any character of # the string and change it to any other uppercase English character. # You can perform this operation at most k times. # Return the length of the longest substring containing the same letter # you can get after performing the above operations. # Constraints: # 1 <= s.length <= 105 # s consists of only uppercase English letters. # 0 <= k <= s.length import collections class Solution: def characterReplacement(self, s: str, k: int) -> int: left = 0 count = collections.defaultdict(int) max_freq = 0 for right in range(len(s)): count[s[right]] += 1 max_freq = max(max_freq, count[s[right]]) if right - left + 1 - max_freq > k: count[s[left]] -= 1 left += 1 return (right + 1) - left
6fa07cdd779d571b36128048ae6bac5412d60885
greenblues1190/Python-Algorithm
/LeetCode/16. 그리디 알고리즘/134-gas-station.py
1,108
3.84375
4
# https://leetcode.com/problems/gas-station/ # There are n gas stations along a circular route, where the amount of gas # at the ith station is gas[i]. # You have a car with an unlimited gas tank and it costs cost[i] of gas to travel # from the ith station to its next (i + 1)th station. You begin the journey with # an empty tank at one of the gas stations. # Given two integer arrays gas and cost, return the starting gas station's index # if you can travel around the circuit once in the clockwise direction, otherwise # return -1. If there exists a solution, it is guaranteed to be unique # Constraints: # gas.length == n # cost.length == n # 1 <= n <= 104 # 0 <= gas[i], cost[i] <= 104 from typing import List class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 start, fuel = 0, 0 for i in range(len(gas)): if gas[i] + fuel < cost[i]: start = i + 1 fuel = 0 else: fuel += gas[i] - cost[i] return start
7c7e14e587885e4e8d7650478e5d984c41f032c9
greenblues1190/Python-Algorithm
/LeetCode/15. 슬라이딩 윈도우/76-minimum-window-substring.py
1,068
3.84375
4
# https://leetcode.com/problems/minimum-window-substring/ # Given two strings s and t of lengths m and n respectively,return the minimum window substring # of s such that every character in t (including duplicates) is included in the window. # If there is no such substring, return the empty string "". # The testcases will be generated such that the answer is unique. # A substring is a contiguous sequence of characters within the string. import collections class Solution: def minWindow(self, s: str, t: str) -> str: need = collections.Counter(t) missing = len(t) left = start = end = 0 for right, char in enumerate(s, 1): missing -= need[char] > 0 need[char] -= 1 if missing == 0: while left < right and need[s[left]] < 0: need[s[left]] += 1 left += 1 if not end or (right - left <= end - start): start, end = left, right return s[start:end]
3e950535ae360cbb9d8f0d7c0b842d150d8c2066
greenblues1190/Python-Algorithm
/LeetCode/13. 이진 검색/167-two-sum-ii-input-array-is-sorted.py
1,446
3.875
4
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ # Given an array of integers numbers that is already sorted in non-decreasing order, # find two numbers such that they add up to a specific target number. # Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, # where 1 <= answer[0] < answer[1] <= numbers.length. # The tests are generated such that there is exactly one solution. # You may not use the same element twice. from typing import List # binary search class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for idx1, num1 in enumerate(numbers): left, right = idx1 + 1, len(numbers) - 1 expected = target - num1 while left <= right: mid = left + (right - left) // 2 if numbers[mid] > expected: right = mid - 1 elif numbers[mid] < expected: left = mid + 1 else: return idx1 + 1, mid + 1 # two-pointer class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left, right = 0, len(numbers) - 1 while left != right: sum = numbers[left] + numbers[right] if sum > target: right -= 1 elif sum < target: left += 1 else: return left + 1, right + 1
7b7e86e454016e2821fac3104c5211372387169a
greenblues1190/Python-Algorithm
/LeetCode/15. 슬라이딩 윈도우/1695-maximum-erasure-value.py
1,064
3.6875
4
# https://leetcode.com/problems/maximum-erasure-value/ # You are given an array of positive integers nums and want to erase a subarray # containing unique elements. The score you get by erasing the subarray is # equal to the sum of its elements. # Return the maximum score you can get by erasing exactly one subarray. # An array b is called to be a subarray of a if it forms a contiguoussubsequence # of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). from typing import List class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: max_sum = 0 current_sum = 0 left = right = 0 subarray = {} while right < len(nums): if nums[right] not in subarray: subarray[nums[right]] = right current_sum += nums[right] right += 1 max_sum = max(max_sum, current_sum) else: del subarray[nums[left]] current_sum -= nums[left] left += 1 return max_sum
c0840913eaaa0126aa39fac8e391c812725196b2
NSatoh/Pascal_triangle_ps
/color.py
1,083
3.59375
4
class Color: def __init__(self, name, r, g, b): """ :param str name: color name :param float r: :param float g: :param float b: """ self.name = name self.r = r self.g = g self.b = b RED = Color(name='red', r=1, g=0, b=0) BLUE = Color(name='blue', r=0, g=0, b=1) GREEN = Color(name='green', r=0, g=1, b=0) MAGENTA = Color(name='magenta', r=1, g=0, b=1) CYAN = Color(name='cyan', r=0, g=1, b=1) YELLOW = Color(name='yellow', r=1, g=1, b=0) HOTPINK = Color(name='hotpink', r=1, g=0.412, b=0.706) TEAL = Color(name='teal', r=0, g=0.5, b=0.5) FORESTGREEN = Color(name='forestgreen', r=0.133, g=0.545, b=0.133) DARKORCHID = Color(name='darkorchid', r=0.6, g=0.196, b=0.8) SKYBLUE = Color(name='skyblue', r=0.529, g=0.808, b=0.922) SLATEBLUE = Color(name='slateblue', r=0, g=0.5, b=1) DARKORANGE = Color(name='darkorange', r=1, g=0.549, b=0) BLACK = Color(name='black', r=0, g=0, b=0) GRAY80 = Color(name='gray80', r=0.8, g=0.8, b=0.8)
1ed53802fa9c216eb6f19a05a67afd19d3abfd69
madhuripr21/day2assignment
/day2/pangram.py
328
4.09375
4
import string def ispangram(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in str.lower(): return False return True string = 'the five boxing wizards jump quickly.' if (ispangram(string) == True): print ("yes") else: print ("no")
bf9cebcb99452aa75d9fa70280aa7f7d2ce2f572
jeffreywugz/code-repository
/python/matplotlib/demo.py
439
3.640625
4
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) while True: pass # ax.plot(np.ravel(x), np.ravel(y), np.ravel(z), color='b') # plt.show()
bf67b98e1c8d67e03db25488893518e5fd2e3a36
GaiBaDan/GBD-GoodMan
/demo1.py
599
4.5625
5
#1.注释:代码中不会被编译执行的部分(不会起到任何程序作用,用来备注用的) #在说明性文字前加#键可以单行注释 ''' ''' """ A.对程序进行说明备注 B.关闭程序中的某项功能 """ #建议:写程序多写注释 print("HELLO world") ;print("hello python") #每条语句结束后可以没有分号r如果一行要写多条语句,那么每条语句之间用分号隔开 # print("hello world") print("hello world") # print("hello world") print('dandan') # print('hahahahahaha')\ list1 = [2,4,6] num = [3*x for x in list1] print(num)
d565e04077e8f1f14b75375a35df836e09f70c15
SomeStrHere/HauntedHouse
/CharacterCreator.py
1,489
3.78125
4
import random from Character import Character class CharacterCreator : def createCharacter() : print('Please enter the following information to setup your character...\n') firstName = input('What is your first name? ') heightInFeet = float(input('What is your height in feet approx? ')) age = int(input('What is your age in whole years? ')) fitnessLevel = input('What is your fitness level (Poor, Okay, Great)? ') character = Character(firstName, heightInFeet, age, fitnessLevel) return(character) def createRandomCharacter() : firstNameData = ['Gareth', 'Dan', 'Rachel', 'Ethereal', 'Raby', 'Carrie', 'Erika', 'Nathan'] heightInFeetData = [4.5, 5.3, 5.7, 5.7, 5.9, 5,11, 6, 6, 6.1, 6.2, 6.9] fitnessLevelData = ['Poor', 'Okay', 'Great'] firstName = random.choice(firstNameData) age = random.randint(18, 45) heightInFeet = random.choice(heightInFeetData) fitnessLevel = random.choice(fitnessLevelData) # This method is called in HauntedHouse.py at the character creation. # You can access the object from there. randomCharacter = Character(firstName, heightInFeet, age, fitnessLevel) print("Name: " + firstName) print("Age: {0}".format(age)) print("Height: {0} ft".format(heightInFeet)) print("Fitness: " + fitnessLevel) print("") return(randomCharacter)
02bd64d1871d08a5ef5354e4962074dc01363b8e
darrenthiores/PythonTutor
/Learning Python/level_guessing.py
2,170
4.125
4
# membuat app number guessing dengan level berbeda import random def low_level() : number = random.randint(1,10) chances = 3 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def med_level() : number = random.randint(1,25) chances = 5 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def high_level() : number = random.randint(1,50) chances = 8 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def pick_level() : print ('='*10,'Number Guessing Game','='*10) print ('[1] Low Level (1 - 10, 3 chances)') print ('[2] Medium Level (1 - 25, 5 chances)') print ('[3] High Level (1 - 50, 8 chances)') print ('[4] EXIT') menu = int(input('Pick level (index) : ')) if (menu == 1) : low_level() elif (menu == 2) : med_level() elif (menu == 3) : high_level() elif (menu == 4) : exit() else : print ('Which level did you picked?') if __name__ == "__main__": while (True) : pick_level()
6fb53f0a54f65a983132e65fac54d9f6f29deff0
darrenthiores/PythonTutor
/Learning Python/CRUD_learn_2.py
1,417
3.5625
4
#CRUD (3) materi_bio = [] #function def list_materi() : if (len(materi_bio) <= 0) : print ('MATERI KOSONG') else : for i in range(len(materi_bio)) : print (i,'.', materi_bio[i]) def input_materi() : materi = str(input('Materi Bio : ')) materi_bio.append(materi) def ralat_materi() : list_materi() index = int(input('Masukkan index yang mau diubah : ')) if (index >= len(materi_bio)) : print ('MATERI TIDAK DITEMUKAN!!') else : ralat = str(input('Materi baru : ')) materi_bio[index] = ralat def delete_materi() : list_materi() index = int(input('Masukkan index yang mau dihapus : ')) if (index >= len(materi_bio)) : print ('MATERI TIDAK DITEMUKAN!!') else : del materi_bio[index] #UI def show_menu() : print ('-'*10, 'MENU', '-'*10) print ('-'*30) print ('[1] LIST MATERI') print ('[2] TAMBAH MATERI') print ('[3] UBAH MATERI') print ('[4] HAPUS MATERI') print ('[5] EXIT') menu = int(input('Pilih menu : ')) if (menu == 1) : list_materi() elif (menu == 2) : input_materi() elif (menu == 3) : ralat_materi() elif (menu == 4) : delete_materi() elif (menu == 5) : exit() else : print ('MENU TIDAK DITEMUKAN!!') #main looping if __name__ == "__main__": while (True) : show_menu()
3d0b17e4a0dab5efa5d148901600acd6ea19cfc3
darrenthiores/PythonTutor
/Learning Python/Max.py
1,181
3.953125
4
# Max() function # untuk mencari angka tertinggi angka = [1, 2, 4, 5, 34, 45, 23, 31] tertinggi = max(angka) terendah = min(angka) print (tertinggi) print (terendah) # Contoh programnya (mencari pendapatan tertinggi dan terendahdidalam suatu bulan) bulan = { 'januari' : 0, 'februari' : 0, 'maret' : 0, 'april' : 0, 'mei' : 0, 'juni' : 0 } #Input penghasilan for i in bulan : bulan[i] = int(input(f'penghasilan pada bulan {i} : Rp. ')) #Mencari penghasilan tertinggi penghasilan_tertinggi = max(bulan['januari'], bulan['februari'], bulan['maret'], bulan['april'], bulan['mei'], bulan['juni']) #Mencari penghasilan terendah penghasilan_terendah = min(bulan['januari'], bulan['februari'], bulan['maret'], bulan['april'], bulan['mei'], bulan['juni']) #cari dan cetak bulan serta penghasilan tertinggi for i in bulan : if (bulan[i] == penghasilan_tertinggi) : print (f'penghasilan tertinggi berada pada bulan : {i}, yaitu : {bulan[i]}') #cari dan cetak bulan serta penghasilan terendah for i in bulan : if (bulan[i] == penghasilan_terendah) : print (f'penghasilan terendah berada pada bulan : {i}, yaitu : {bulan[i]}')
40be613671a47f1dff0d5378527ffe929c583221
ramatssm47/Python
/Stocks/Stocks/test.py
96
3.75
4
mylist = [["a","b"],["a1","b1"]] for x in mylist: print "flower of "+ x[0]+" is "+x[1]
c1df1f9642c7fa669bfeaf69632813ad8a6f0237
henneyhong/Python_git
/python수업내용/test0521.py
1,137
3.890625
4
print("Hello VSCode") a=1 b=2 c=a+b print(c) t=[1,2,3] a,b,c=t print(t,a,b,c) #if score = 92 if score >=90 : print('합격') else : print('불합격') #for문 for i in[0,1,2,3,4,5,6,7,8,9,10] : print(i) for i in range(0,11): print(i) favorite_hobby = ['reading','fishing','shopping'] for hobby in favorite_hobby : print('%s is my favorite hobby' % hobby) wish_travel_city = {'bankok' : 'Thao','Los Angeles' : 'USA','Manila' : 'Philiphines'} for city, country in wish_travel_city.items(): print('%s in %s' % (city,country)) t=(1,2,3) print(t+t,t*2) for x in range(2,-1,-1): print(x) prices = [2.50, 3.50, 4.50] for price in prices: print('price is',price) #while문 count = 0 if count < 5: print ("Hello, I am an if statement and count is", count) while count < 5: print ("Hello, I am a while and count is", count) count += 1 num = 0 while num <= 10: if num % 2 == 1: print (num) num += 1 num = 0 while 1: print(num) if num == 10: break num +=1 num = 0 while num < 10: num += 1 if num == 5: continue print (num)
103ef065e932aeecb8c7d9e414ec4a64689cbe72
mehmettuzcu/measurement_problems
/rating_product_and_sorting_reviews.py
3,749
3.5625
4
################ Data Understanding ################ ##### Importing Libraries import pandas as pd import math import scipy.stats as st # Making the appearance settings pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) pd.set_option('display.width', 500) pd.set_option('display.expand_frame_repr', False) pd.set_option('display.float_format', lambda x: '%.5f' % x) ##### Importing Data df = pd.read_csv("datasets/amazon_review.csv") df.shape # Dimension of dataframe df.dtypes # Data type of each variable df.info() # Print a concise summary of a DataFrame df.head() # First 5 observations of dataframe df.tail() # Last 5 observations of dataframe ##### Data Preparation df.isnull().sum() # Get number of Null values in a dataframe # Remove missing observations from the data set df.dropna(inplace=True) ################# Task-1 ################# # Let's check the number of rating awarded to product df["overall"].count() # Let's check how many of each rating there df["overall"].value_counts() # Distributions in variable "day_diff" df["day_diff"].quantile([0, 0.05, 0.25, 0.50, 0.75, 0.95, 0.99, 1]) df["day_diff"].mean() # There is no difference between mode and median. It is seen that the distribution is in a regular way. # Since the data is regularly distributed, I divided the days into quarters and multiplied according to these intervals. df['days_segment'] = pd.qcut(df["day_diff"], 4, labels=["A", "B", "C", "D"]) df.loc[df["days_segment"] == "A", "overall"].mean() * 28 / 100 + \ df.loc[df["days_segment"] == "B", "overall"].mean() * 26 / 100 + \ df.loc[df["days_segment"] == "C", "overall"].mean() * 24 / 100 + \ df.loc[df["days_segment"] == "D", "overall"].mean() * 22 / 100 df["overall"].mean() # When we calculate the Time-Based and Average rating scores, the rating score in the Time-Based method is observed a little more. ################# Task-2 ################# # Sorting Reviews df = pd.read_csv("datasets/amazon_review.csv") # Since there is no information about those who do not like the comment in the data set, we create it ourselves. df["down_rating"] = df["total_vote"] - df["helpful_yes"] df.head() # We'll cover 3 methods for sorting reviews. # 1-) Score # 2-) Average rating # 3-) Wilson Lower Bound Score # 1-) Score = (up ratings) − (down ratings) def score_up_down_diff(up, down): return up - down # 2-) Score = Average rating = (up ratings) / (down ratings) def score_average_rating(up, down): if up + down == 0: return 0 return up / (up + down) # 3-) Wilson Lower Bound Score def wilson_lower_bound(up, down, confidence=0.95): n = up + down if n == 0: return 0 z = st.norm.ppf(1 - (1 - confidence) / 2) phat = 1.0 * up / n return (phat + z * z / (2 * n) - z * math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n) # Case Study: # Score Different df["score_pos_neg_diff"] = df.apply(lambda x: score_up_down_diff(x["helpful_yes"], x["down_rating"]), axis=1) df.sort_values("score_pos_neg_diff", ascending=False) # Average rating df["score_average_rating"] = df.apply(lambda x: score_average_rating(x["helpful_yes"], x["down_rating"]), axis=1) df.sort_values("score_average_rating", ascending=False) # Wilson Lower Bound Score df["wilson_lower_bound"] = df.apply(lambda x: wilson_lower_bound(x["helpful_yes"], x["down_rating"]), axis=1) df.sort_values("wilson_lower_bound", ascending=False) final_df = df.loc[:, ["reviewText", "total_vote", "down_rating", "score_pos_neg_diff", "score_average_rating", "wilson_lower_bound"]] final_df.head() # Top 20 sorted by Wilson Lower Bound score final_df.sort_values("wilson_lower_bound", ascending=False).head(20)
44882456dbccb64858e28b41f745624cb75546ec
yahusun/p0427
/13_Numpy/generals.py
594
3.890625
4
import numpy as np ''' mat1 = np.zeros((3,4)) #3*4的矩陣 print(mat1) print(mat1.ndim) print(mat1.shape) mat2 = np.ones((2,3)) * 2 mat2_2 = mat2 * 2 mat2_3 = mat2 * mat2_2 print(mat2) print(mat2_2) print(mat2_3) #對角矩陣 mat3 = np.eye(3,4) print(mat3) #真的矩陣運算 #print(np.matmul(mat2, mat3)) ''' #亂數矩陣 import matplotlib.pyplot as plt arr_x = np.arange(10) a = np.random.rand(10) # uniform in [0, 1],不會等於1 b = np.random.randint(5, 10, 10) # uniform in [5, 10] with 10 elements plt.plot(arr_x, a, '-r^', arr_x, b, '--go') plt.show()
ec1ffc53f6f1a71fc3989a28770c4aa3566e9dec
JosefinaMedina/EjerciciosComputacion-Python
/p3_10c.py
350
3.9375
4
import math m1=int(input("Pendiente de la recta 1: ")) b1=int(input("Ordenada al origen de la recta 1: ")) m2=int(input("Pendiente de la recta 2: ")) b2=int(input("Ordenada al origen de la recta 2: ")) if m1!=m2: x=(b2-b1)/(m1-m2) print(f"El punto de interseccion es {x}") if m1==m2: print(f"Las rectas no se intersecan")
468bd59a2638ecc6487f0c9850fc9880262b35ed
JosefinaMedina/EjerciciosComputacion-Python
/p3_8c.py
364
3.703125
4
x1=int(input("Elemento x del primer vector: ")) y1=int(input("Elemento y del primer vector: ")) x2=int(input("Elemento x del segundo vector: ")) y2=int(input("Elemento y del segundo vector: ")) def resta1 (x1,x2): return x2-x1 def resta2 (y1,y2): return y2-y1 x=x2-x1 y=y2-y1 def modulo(x,y): return (x**2+y**2)**(1/2) print(modulo(x,y))
c8926c80c5c408c06aaf769c2729afb8e3bd8e62
PrasadGinnarapu/python_automation
/10.webscraping.py
551
3.90625
4
"""imported the requests library""" import requests DATA_URL = "https://simple.wikipedia.org/wiki/Rose" # URL of the image to be downloaded is defined as image_url OBJECT= requests.get(DATA_URL) # create HTTP response object # send a HTTP request to the server and save # the HTTP response in a response object called r with open("webcontent.txt", 'wb') as f: # Saving received content as a png file in # binary format # write the contents of the response (r.content) # to a new file in binary mode. f.write(OBJECT.content)
1fa509ec2b939331f18a1b41496e81023572a7de
PrasadGinnarapu/python_automation
/6.morning_setup.py
569
3.609375
4
"""importing webbrowswer module""" import sys import webbrowser def opensetup(): """function for open user specified website""" var = input("Enter g-google, 'd'-darwin, o-office: ").strip() if var == 'g': webbrowser.open("www.google.com") elif var == 'd': webbrowser.open("https://ojasit.darwinbox.com/user/login") elif var == 'o': webbrowser.open("https://www.office.com/?auth=2") while True: yesno = input("Do you want to play(Y/N): ").upper() if yesno == 'Y': opensetup() else: sys.exit()
e385c0d52b417af217ce978a978c66f0e3a395f0
stefanulloa/skL_tutor
/main.py
9,859
4.15625
4
#from tutorial: https://www.dataquest.io/blog/pandas-python-tutorial/ # %% import pandas as pd import matplotlib.pyplot as plt import math import numpy as np def pandasPart1(): #read data on DataFrame type reviews = pd.read_csv(".\data\ign.csv") #shape of dataframe shape = reviews.shape #obtain certain rows and/or columns using iloc method (by position) reviews = reviews.iloc[:,1:] #obtain certain rows and/or columns using loc method (by label) reviewst2 = reviews.loc[0:4,"score"] reviewst3 = reviews.loc[0:4,["score","release_year"]] #obtain certain rows and/or columns (by label) #this is of type Series reviewst4 = reviews[["url", "release_day"]] #series type seriesTest1 = pd.Series([1,2]) seriesTest2 = pd.Series(["juan","mario"]) #making a dataframe from two series dftest1 = pd.DataFrame([seriesTest1,seriesTest2]) #making a dataframe from scratch dftest2 = pd.DataFrame( [ [1,2], ["juan","mario"] ], index=["row1","row2"], columns=["col1","col2"] ) #making dataframe like dic dftest3 = pd.DataFrame( { "col1": [1,"juan"], "col2": [2,"mario"] } ) #head can also be used for series type seriesTest3 = reviews["title"].head() #mean for direct mean calculation on column meanscore = reviews["score"].mean() #finds all numerical columns and computes mean for each allmeansCol = reviews.mean() #finds all numerical values on each row and computes mean for each allmeansRow = reviews.mean(axis=1) #corr computes correlation between numerical columns #corrtest = reviews.corr() #other methods: max, min, count, std, median maxtest = reviews.max() counttest = reviews.count() #math operations on series type #other operations: +, -, *, ^ dividetest = reviews["score"] / 2 #boolean filter booleantestFilter = reviews["score"] > 7 filteredReview = reviews[booleantestFilter] #boolean filter with more conditions booleantestFilter2 = (reviews["score"] > 7) & (reviews["platform"]=="Xbox One") filteredReview2 = reviews[booleantestFilter2] #check histograms on column on condition to make visual comparisons reviews[reviews["platform"]=="Xbox One"]["score"].plot(kind="hist") reviews[reviews["platform"]=="PlayStation 4"]["score"].plot(kind="hist") def pandasPart2(): #scaping because \t produces error polling = pd.read_csv(".\\data\\thanksgiving-2015-poll-data.csv") #output only the different possible values for a given column uniqueValuesOfColumns = polling["Do you celebrate Thanksgiving?"].unique() #get the name of columns by position someColumnNames = polling.columns[50:] ##FUNCTIONS## #check how many values there of the unique values for a given column #dropna also counts nan values countValuesOfColumn = polling["What is your gender?"].value_counts(dropna=False) #apply transformation method to each row individually #new column added polling["new_gender"] = polling["What is your gender?"].apply(fromGenderToNumeric) #count values after transformation countValuesOfNGenderCol = polling["new_gender"].value_counts(dropna=False) #apply a lambda operation with apply. it will work on clumns by default #to work on row level, use axis=1 as argument #dtype will output the type of each column lambdaoperation = polling.apply(lambda x: x.dtype).head() #check unique values for given column moneyOfHouseholdLastYear = polling["How much total combined money did all members of your HOUSEHOLD earn last year?"].value_counts(dropna=False) #apply transformation on income and create new column polling["newIncomeCol"] = polling["How much total combined money did all members of your HOUSEHOLD earn last year?"].apply(clean_income) ##GROUPING## #check (and count) unique value of type of sauce column countValuesOnSauceCol = polling["What type of cranberry saucedo you typically have?"].value_counts() #new dataframes on condition of type of sauce homemade = polling[polling["What type of cranberry saucedo you typically have?"] == "Homemade"] canned = polling[polling["What type of cranberry saucedo you typically have?"] == "Canned"] #mean for each type of sauce meanHomemade = homemade["newIncomeCol"].mean() meanCanned = canned["newIncomeCol"].mean() #instead of the previous process, we can directly make groups of dataframes depending on sauce grouped = polling.groupby("What type of cranberry saucedo you typically have?") #to check set of row indices for each sauce case setOnSauceGroups = grouped.groups #how many rows for each group countRowsOnSauceGroups = grouped.size() #get info of groups for name, group in grouped: print(name,group.shape,type(group)) #create groups of series (each series depeds on the sauce type) incomeOnSauceGroups = grouped["newIncomeCol"] ##AGREGATION## #IMPORTANT: agg() only works for functions that return one value, if it returns more we have to use apply() #agg() lets use many functions at the same time, apply() does not #agg applies the same function to a group of series in parallel avgForSauceGroupSeries = grouped["newIncomeCol"].agg(np.mean) #if no column specified, agg will perform on every column #in this case, mean only works on data with numeric values avgForSauceGroupDataFrames = grouped.agg(np.mean) #to visually compare avgForSauceGroupSeries.plot(kind="bar") #groups using two columns for groupby grouped2 = polling.groupby(["What type of cranberry saucedo you typically have?","What is typically the main dish at your Thanksgiving dinner?"]) #mean depending on combinations of two types (from the two columns) meanGroups2Col = grouped2.agg(np.mean) #calculate mean, sum and std on income column for the grouped object operationsGroups2Col = grouped2["newIncomeCol"].agg([np.mean, np.sum, np.std]) #apply is a different way of using methods on groups #we get groups by type of location, from those we choose just the dishes column for each group grouped3 = polling.groupby("How would you describe where you live?")["What is typically the main dish at your Thanksgiving dinner?"] #we will count every instance #because value_counts returns 2 or more values, we cannot use agg() #so we have to use apply which will combine the results countGroup3 = grouped3.apply(lambda x:x.value_counts()) #method transforms string values to 0 (male) or 1 (female), nan is the same #each row will be applied this method individually def fromGenderToNumeric(genderString): #isnan only works on numeric values, so we need to check first the type is float (nan is float) if isinstance(genderString, float): if math.isnan(genderString): return genderString #in case it is female, casting comparison to int transforms to 1. for male, it is 0 return int(genderString == "Female") #if 200000 on upwards: 200000 #if prefer not to answer or nan: nan #if range: avg def clean_income(value): if value == "$200,000 and up": return 200000 elif value == "Prefer not to answer": return np.nan elif isinstance(value,float): if math.isnan(value): return np.nan #getting rid of commas and $ value = value.replace(",", "").replace("$", "") low, high = value.split(" to ") #return avg value return (int(low)+int(high))/2 def haversineFormula(lon1, lat1, lon2, lat2): R_earth = 6371 #km lon1, lat1, lon2, lat2 = [float(lon1), float(lat1), float(lon2), float(lat2)] lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) dlon = lon2-lon1 dlat = lat2-lat1 a = math.sin(dlat/2)**2 + math.cos(lat1)*math.cos(lat2)*math.sin(dlon/2)**2 c = 2*math.asin(math.sqrt(a)) d = R_earth*c return d def calc_distance(row, airports): dist = 0 try: #we get the airport data for a given route (source airport and dest airport) #we use iloc[0] to get rid of unnecessary info, otherwise we #would also get index, col name and type, we just need value source = airports[airports["id"] == row["source_id"]].iloc[0] dest = airports[airports["id"] == row["dest_id"]].iloc[0] dist = haversineFormula(dest["longitude"], dest["latitude"], source["longitude"], source["latitude"]) #we need exception in case there is data that cannot be processed except (ValueError, IndexError): pass return dist def dataVisualization(): airports = pd.read_csv(".\data\\airports.csv", header=None, dtype=str) #the data doesnt have headers, so we need to add them airports.columns = ["id", "name", "city", "country", "code", "icao", "latitude", "longitude", "altitude", "offset", "dst", "timezone", "more1", "more2"] #skiprows to ignore the first row which doesnt have useful info airlines = pd.read_csv(".\data\\airlines.csv", skiprows=[0], header=None, dtype=str) airlines.columns = ["id", "name", "alias", "iata", "icao", "callsign", "country", "active"] routes = pd.read_csv(".\data\\routes.csv", header=None, dtype=str) routes.columns = ["airline", "airline_id", "source", "source_id", "dest", "dest_id", "codeshare", "stops", "equipment"] #in the airline_id there are rows with a value "\N", so we need to take them out routes = routes[routes["airline_id"] != "\\N"] #axis=1 to apply on row level route_lengths = routes.apply(calc_distance, args=(airports,), axis=1) plt.hist(route_lengths, bins=20) print('hey') dataVisualization()
ff6d900694a6fa4d85f1fec76496abfc36d9779d
Kunal-Kumar-Sahoo/PyWeather
/weather.py
1,605
3.65625
4
import tkinter as tk import requests import time def getWeatherInfo(window): city = textField.get() API = "" # To get your API visit: https://openweathermap.org/ jsonData = requests.get(API).json() weatherCondition = jsonData["weather"][0]["main"] temperature = int(jsonData["main"]["temp"] - 273.15) minTemperature = int(jsonData["main"]["temp_min"] - 273.15) maxTemperature = int(jsonData["main"]["temp_max"] - 273.15) pressure = jsonData["main"]["pressure"] humidity = jsonData["main"]["humidity"] windSpeed = jsonData["wind"]["speed"] sunrise = time.strftime("%H:%M%S", time.gmtime(jsonData["sys"]["sunrise"] + 6*60*60)) sunset = time.strftime("%H:%M%S", time.gmtime(jsonData["sys"]["sunset"] + 6*60*60)) finalInfo = weatherCondition + "\n" + str(temperature) + "°C" finalData = "\n" + "Maximum Temperature: " + str(maxTemperature) + "°C" + "\n" +"Minimum Temperature: " + str(minTemperature) + "°C" + "\n" + "Pressure: " + str(pressure) + "\n" + "Humidity: " + str(humidity) + "\n" + "Wind Speed: " + str(windSpeed) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset label1.config(text=finalInfo) label2.config(text=finalData) window = tk.Tk() window.geometry("600x500") window.title("PyWeather") f = ("ubuntu", 15, "bold") t = ("ubuntu", 35, "bold") textField = tk.Entry(window, justify="center",font=t) textField.pack(pady=20) textField.focus() textField.bind("<Return>", getWeatherInfo) label1 = tk.Label(window, font=t) label1.pack() label2 = tk.Label(window, font=f) label2.pack() window.mainloop()
60ec4bc36f8b1c57135e68b7a645e414a33a01d2
jdvalenzuelah/VacationDestination
/Fase2/Destino.py
759
3.859375
4
class Destino(object): """ Destino posible al que se puede ir. Attributes: nombre (String): nombre del destino. ubicacion (String): ubicacion deonde se encuentra. tags (list): categorias a las cuales puede ser asignado el destino. clima (String): clima del destino. """ def __init__(self, nombre, ubicacion, clima, tags=[]): """ Constructor de la clase """ self.nombre = nombre.upper() self.ubicacion = ubicacion.upper() self.tags = tags self.clima = clima.upper() def __str__(self): """ toString """ listStr = "" for element in self.tags: listStr = listStr + str(element) + ', ' listStr = listStr[:-2] return "Nombre: %s Ubicacion: %s Clima: %s Tags: %s" %(self.nombre, self. ubicacion, self.clima, listStr)
9d181fdb0694acfd6d1fe06f91666e8881612bb0
goodsosbva/BOJ_Graph
/11724.py
1,205
3.515625
4
def DFS(num): # print(num, end=' ') # 처음 방문한 그 지점을 출력 visited[num] = 1 # 방문했을 때 그 방문리스트에 0으로 되어있을 텐데, 그것을 1로 바꾸어준다. for i in range(N): if visited[i] == 0 and connectList[num][i] == 1: DFS(i) import sys N, M = map(int, sys.stdin.readline().split()) connectList = [[0] * (N) for _ in range(N)] #matrix visited = [0 for _ in range(N)] # check notVisitede = [0 for _ in range(N)] # print(notVisitede) for i in range(M): a, b = map(int, sys.stdin.readline().split()) if i == 0: V = a connectList[a - 1][b - 1] = 1 connectList[b - 1][a - 1] = 1 DFS(V) # print("\n") # print(connectList) # print(V) print(notVisitede) cnt = 0 print(connectList) for i in range(N): for j in range(N): # print(j, end="") # print("order:", order) if connectList[i][j] == 1: # print(j) notVisitede[j] = 1 print(notVisitede) # print("check") # print(visited) print(notVisitede) for i in notVisitede: if i == 0: cnt += 1 sys.stdout.write(str(cnt))
9b39f95066e6bf5919683302f61adc5f40300a60
younism1/Checkio
/Password.py
1,673
4.15625
4
# Develop a password security check module. # The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least # one digit, as well as containing one uppercase letter and one lowercase letter in it. # The password contains only ASCII latin letters or digits. # Input: A password as a string. # Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean. # In the results you will see the converted results. # checkio('A1213pokl') == False # checkio('bAse730onE') == True # checkio('asasasasasasasaas') == False # checkio('QWERTYqwerty') == False # checkio('123456123456') == False # checkio('QwErTy911poqqqq') == True def checkio(data: str) -> bool: upper = False lower = False digit = False if not len(data) >= 10: # print("Your password needs to be 10 characters long or more") return False for i in data: if i.isdigit(): digit = True if i.isupper(): upper = True if i.islower(): lower = True return upper and digit and lower if __name__ == '__main__': #self-checking and not necessary for auto-testing assert checkio('A1213pokl') == False, "1st example" assert checkio('bAse730onE4') == True, "2nd example" assert checkio('asasasasasasasaas') == False, "3rd example" assert checkio('QWERTYqwerty') == False, "4th example" assert checkio('123456123456') == False, "5th example" assert checkio('QwErTy911poqqqq') == True, "6th example" print("Passed all test lines ? Click 'Check' to review your tests and earn cool rewards!")