blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
b7a777c05fd37642a487677bad4542d064850dc1 | MarcoASB/python-challenge | /PyPoll/poll_results.py | 2,245 | 3.703125 | 4 | # Import dependecies
import pandas as pd
data = pd.read_csv('Resources/election_data.csv')
# A complete list of candidates who received votes
def candidates (data):
list_candidates = data.Candidate.unique()
return list_candidates
# Count and percentage of candidates
def votes (data):
data['Count'] = 1
votes = data[['Count','Candidate']].groupby('Candidate').count()
votes['Percentage'] = round(votes.Count/number_votes*100,2)
return votes
# The winner of the election based on popular vote.
def winner (data):
data['Count'] = 1
votes = data[['Count','Candidate']].groupby('Candidate').count()
votes['Percentage'] = round(votes.Count/number_votes*100,2)
max_votes = votes['Count'].max()
winner_row = votes.loc[votes['Count'] == max_votes]
winner = winner_row.index[0]
return winner
def report(data):
candidates_list = candidates(data)
can_votes = votes(data)
can_winner = winner(data)
print("Election Results")
print("-------------------------")
print(f"Total Votes: ",len(data))
print("-------------------------")
print("{}: {}% ({})".format(candidates_list[0],
can_votes.loc[can_votes.index == candidates_list[0]]['Percentage'][0],
can_votes.loc[can_votes.index == candidates_list[0]]['Count'][0]))
print("{}: {}% ({})".format(candidates_list[1],
can_votes.loc[can_votes.index == candidates_list[1]]['Percentage'][0],
can_votes.loc[can_votes.index == candidates_list[1]]['Count'][0]))
print("{}: {}% ({})".format(candidates_list[2],
can_votes.loc[can_votes.index == candidates_list[2]]['Percentage'][0],
can_votes.loc[can_votes.index == candidates_list[2]]['Count'][0]))
print("{}: {}% ({})".format(candidates_list[3],
can_votes.loc[can_votes.index == candidates_list[3]]['Percentage'][0],
can_votes.loc[can_votes.index == candidates_list[3]]['Count'][0]))
print("-------------------------")
print(f"Winner: ",can_winner)
print("-------------------------")
report(data) |
26a07246153352e984b2a9742c2d0390b53c9c2c | AlexKaracaoglu/Cryptography | /PS5/AKaracaoglu_HW5.py | 10,813 | 3.90625 | 4 | #Alex Karacaoglu
#Crypto_HW5
#I completed problems 1,2,4,6,7,8
import conversions
import euclid_etc
#After using the hex(number) -> string method it puts '0x' at the front and 'L'
#at the end because it is a long and in order to convert back to ASCII using the
#conversions methods provided you need to have those gone
def hex_string_to_hex(s):
length = len(s)
if (s[length-1] == 'L'):
s = s[:length-1]
if (s[:2] == '0x'):
s = s[2:]
return s
#Taken from Professor's solutions to previous HW
def kthroot(N,k):
low=2
high=N
while high-low>1:
mid=(high+low)/2
if mid**k<=N:
low=mid
else:
high=mid
return low
#Problem 1: Short message, small exponent
# problem1("BOPsNWUf4Wlq0x7slBtDBKBAm8/7DZipepU3kklFB2GcurrqQNuouHpxocau3D5otveYhBw7z2AbETcKMuMkWZdToWSo92mK+UhNeP8wXNqVW7I7Fiy/", 89925312925763822584710378409033190578053125728910169871227932983692156412020390339531051155939673506480017767823980121411205241896041063847997991270201142150794495706134903691987753153769920552199651886672073876514247298569925380985174185832099311517867889120692301373911817723374815064908214018503193857221)
def problem1(cipher_b64, N):
cipher_hex = conversions.b64_to_hex(cipher_b64)
cipher_b10 = int(cipher_hex,16)
plaintext_b10 = kthroot(cipher_b10,3)
plaintext_hex_string = hex(plaintext_b10)
plaintext_hex = hex_string_to_hex(plaintext_hex_string)
plaintext_as = conversions.hex_to_as(plaintext_hex)
return plaintext_as
#Problem 2: Small exponent
# problem2("PBq5gXUhUHA9odbER2Oow3aBRX5VzEPPRCPdcFPZisJSDtoDQtCGiDdcD4q5qNWtA7dMRZxktHzO1kQy1HNmgg6jjUnxuXPIihJgTG4rAQaAFVJrj9THVoaNb+QxovCU61c7N49H+tekr6xyGyGSok6wNnLZtE0GQd8p3zbyIAg=", "a11Wynb/5BbzR2+gfZ5vgyJvlk0VHAUP08F2tvEZKCsS4Q0zaHok9FBf3QSJxn7X+e9+bADoV0aycZpXh/8hchNE5jER156vamjQm/9cmLwVcQeK/IFJOOmvuFEWYwOg3L8r2Jsii6cn/XrStNZ4JypnOhzbyhR5Jd8hsC2pPIo=", "HlPEAzFjvc1ipxHIaig2o6WwpHfsHmIuS07lM0uKmY0VzcxyiOyB8Q0f4yjo8mu5yPYteO5Kiz5W3sk2j/d5ClmU7yUOVRxm5Q8LXymjpkhLK/I+cxO5P3WRjXF6tUiS/7cz+Koox/r1zC0W4BdfCzr3LSjM/khFHyRyxsmW9Ec=", 116352696909960426025864851693810318405618117771451092066454825684677043175680039111752172705287741166921435658711582887107841565748470707915492808066623281928343866378761016071751094691691153177015920723800541267192488702040046723176890027878282090184778778793686252497241689941158021804171328580092708776333, 113159069239053057823530426012762733579195323934158077138440185385412667833688850511263203419882218256057634130377557866771685834979020529147973323837633935391154851580497106210797073916815264166772985134768913514820393183935763151959349642321950865577799563213986693573189083682991881468336071564883866833467, 84645091220488904665996303582605230466879862527671219768265030555132951506114250139685118956675414529710122137796339176130460114790081203074349445462593477716603703644138088562638660083014885373629701703614641595720381677601897924624948376232277832479665238039958287396790532376148968417689500200999461168369)
def problem2(cipher1_b64, cipher2_b64, cipher3_b64, N1, N2, N3):
a1_hex = conversions.b64_to_hex(cipher1_b64)
a2_hex = conversions.b64_to_hex(cipher2_b64)
a3_hex = conversions.b64_to_hex(cipher3_b64)
a1_b10 = int(a1_hex,16)
a2_b10 = int(a2_hex,16)
a3_b10 = int(a3_hex,16)
N2N3inv = euclid_etc.extended_euclid(N2*N3,N1)
N2N3inv = N2N3inv[1][0] #This is all just plug and chug
N1N3inv = euclid_etc.extended_euclid(N1*N3,N2) #into the CRT equation in the
N1N3inv = N1N3inv[1][0] #Lecture notes #7. x = ... see notes for full equation
N1N2inv = euclid_etc.extended_euclid(N1*N2,N3)
N1N2inv = N1N2inv[1][0]
parta = a1_b10 * ((N2N3inv) % N1) * (N3*N2)
partb = a2_b10 * ((N1N3inv) % N2) * (N1*N3)
partc = a3_b10 * ((N1N2inv) % N3) * (N1*N2)
x = (parta + partb + partc) % (N1*N2*N3)
cubeRootx = kthroot(x,3)
x_hex = hex(cubeRootx)
x_hex = hex_string_to_hex(x_hex)
plain = conversions.hex_to_as(x_hex)
return plain
#Problem 4: Common Factor
# problem4("Ur/BIau7ZZBdwxD8P3xDJFJGMfkJDXNU5rbY7GlvlRkGae4NEMo3pMq9r8Jk2akGSj47SZ00L+eTmeMIIfis3RoG7jjBdj03p5lLtgrLwnjP0lzr31fasl5+NVZIvmnoEt56Figi54lIAXEj4ig06MHFG2KfotLYJTnwabangS4=", "CPEXorDgegEqM6UttzFLaccAN/t4QB1FTDS+NL3TSofQlq3Rs/BebbNn4Qj/Vo4FmTwV3P0+n+hlIhjXzOgEgdgV3BmiBE3rIBHqUc+q0FoVvWJU1+jvFpEeellYZMX8vG7O9us5JKfDAHjPaHWZSwv++BSX4rh+5O01flxzlJA=", 87750187518907655534583445808737942078016029371855217057442341331127022016930461105786023716013285380470222803872626192434912740863485532564125627646878636545449869643527771922181597178447982975143657375859594541373428795038041796818858805812228886812351199020336314262507362189851970680226889619203804537151, 59077605606399909603607705484000546044333045357566473814158491087439387780574866766800852465743470772146755309189078604396507686696592563062056700875467732286553829707195406383141965288479916793429869646143662227281782900822010619445408818002981548245734527538573941174294649831309213962935858200869524073603)
def problem4(cipher1_b64, cipher2_b64, N1, N2):
cipher1_hex = conversions.b64_to_hex(cipher1_b64)
cipher2_hex = conversions.b64_to_hex(cipher2_b64)
cipher1_b10 = int(cipher1_hex,16)
cipher2_b10 = int(cipher2_hex,16)
common_factor = euclid_etc.euclid(N1, N2)
if (common_factor ==1): #Returning an error as requested if there is no common factor
return "error: there is no common factor"
else:
p1 = N1 / common_factor #N1 = common_factor * p1 N1,N2 are the 2 different moduli
p2 = N2 / common_factor #N2 = common_factor * p2
M1 = (p1 - 1) * (common_factor - 1) #definition of M as in the notes
M2 = (p2 - 1) * (common_factor - 1)
d1 = euclid_etc.extended_euclid(65537, M1)
d2 = euclid_etc.extended_euclid(65537, M2)
d1 = d1[1][0] #Need to access the desired part bc we get a tuple and then a tuple within it in the second (technically [1]) so i need to access the actual wanted part
d2 = d2[1][0] + M2 #Added M2 because I was getting an error bc originally it was negative and we know that a = b(mod n) -> a+n = b(mod n)
plaintext1_b10 = euclid_etc.repeated_squaring(cipher1_b10, d1, N1) #message = c^d(mod n), equation from class and from notes, plug and chug
plaintext2_b10 = euclid_etc.repeated_squaring(cipher2_b10, d2, N2)
plaintext1_hex = hex(plaintext1_b10)
plaintext2_hex = hex(plaintext2_b10)
plaintext1_hex = hex_string_to_hex(plaintext1_hex)
plaintext2_hex = hex_string_to_hex(plaintext2_hex)
plaintext1 = conversions.hex_to_as(plaintext1_hex)
plaintext2 = conversions.hex_to_as(plaintext2_hex)
return (plaintext1, plaintext2) #I returned a tuple of the plaintexts bc I decrypted both of them
#Problem 6: Diffie Hellman
# problem6(191147927718986609689229466631454649812986246276667354864188503638807260703436799058776201365135161278134258296128109200046702912984568752800330221777752773957404540495707852046983, 5, 176478319826764259370406117740489882944142268114222243573886354279989450112247437716236796057251798300509450763347865746885560883563075519833320667906000345397226327059751213369961, 42694797205671621659845608467948077104282354898632405210027867058530843815065930986742716022222447350595400603633273172816767784236961837688169657044396569579700949515830214254992, 73982478796308483406582889587923018499575337266536017447507799702797406257043632101045569763590982806403627704785985032506296784648293661856246199184245278019913797261546316759270, 1227561673735205443986782574414500194775280963876704725208507831364630528829422611287956320336912905023628854115065478249082243473610928313596901712034514819305660036543382454852)
def problem6(p, g, gx_mod_p, x, firstComponent, secondComponent):
gxy = euclid_etc.repeated_squaring(firstComponent,x,p) #gxy = g^xy (mod p)
plaintext = euclid_etc.extended_euclid(gxy,p)
plaintext = plaintext[1][0] #Just like problem 4, need to get the desired part
plaintext_b10 = (plaintext * secondComponent) % p
plaintext_hex_string = hex(plaintext_b10)
plaintext_hex = hex_string_to_hex(plaintext_hex_string)
plaintext_as = conversions.hex_to_as(plaintext_hex)
return plaintext_as
#Problem 7:
# problem7(191147927718986609689229466631454649812986246276667354864188503638807260703436799058776201365135161278134258296128109200046702912984568752800330221777752773957404540495707852046983, 5, 176478319826764259370406117740489882944142268114222243573886354279989450112247437716236796057251798300509450763347865746885560883563075519833320667906000345397226327059751213369961, 104862672745740711919811315922065122010281934991422240638097533405207971405689057652673577043484488015740722326384001808611695005135028713487234715202873484670021923322009761545457, 17606878671981551311137298337848994393797765223509173646178261989274226953505667592410786573428076963287971811161509360601971410344413313700739795932040261074709506491861567699546, "Now my charms are all o'erthrown and what strength I have's mine own.", 116115839773157782821329377087409766815814624668492668098672866213651171163182813304753241741593566110843721045751605192482170477996370202802973966889697676265503034822908949368607)
def problem7(p, g, gx_mod_p, firstComponent, first_secondComponent, m, second_secondComponent):
m_hex = conversions.as_to_hex(m)
m_b10 = int(m_hex,16)
gxy = euclid_etc.extended_euclid(m_b10,p)
gxy = gxy[1][0]
gxy = (first_secondComponent * gxy) % p
gxy_inverse = euclid_etc.extended_euclid(gxy, p)
gxy_inverse = gxy_inverse[1][0]
plaintext_b10 = (gxy_inverse * second_secondComponent) % p
plaintext_hex_string = hex(plaintext_b10)
plaintext_hex = hex_string_to_hex(plaintext_hex_string)
plaintext_as = conversions.hex_to_as(plaintext_hex)
return plaintext_as
#Problem 8: We are given the discrete log info, y
# problem8(191147927718986609689229466631454649812986246276667354864188503638807260703436799058776201365135161278134258296128109200046702912984568752800330221777752773957404540495707852046983, 5, 176478319826764259370406117740489882944142268114222243573886354279989450112247437716236796057251798300509450763347865746885560883563075519833320667906000345397226327059751213369961, 68188080109582330879868861330998506151774854600403700625797299927558995162740321112260973638619757922646242302104885437536745080299248852065080008358309735875192480724496530325927, 112018886720018236580229932176683955946063514397085867696250318378121351302079624330821244744748925197792097406122146093507280201522804485024833199924734248052247065779216659451112, 138670566126823584879625861326333326312363943825621039220215583346153783336272559955521970357301302912046310782908659450758549108092918331352215751346054755216673005939933186397777)
def problem8(p, g, gx_mod_p, firstComponent, secondComponent, y):
gxy = euclid_etc.repeated_squaring(gx_mod_p, y, p)
plaintext = euclid_etc.extended_euclid(gxy, p)
plaintext_b10 = plaintext[1][0]
plaintext_b10 = (plaintext_b10 * secondComponent) % p
plaintext_hex_string = hex(plaintext_b10)
plaintext_hex = hex_string_to_hex(plaintext_hex_string)
plaintext_as = conversions.hex_to_as(plaintext_hex)
return plaintext_as
|
95e792e1275a44e99bd4e7051d94b7776a3527e9 | PrakashBorade022/PythonPrograms | /Programs to Understand the Control Structures of Python/sum of first n odd numbers.py | 362 | 4.3125 | 4 | # Python program to print sum of a first n odd numbers
sum =0
n = int(input("Enter a value of n "))
for i in range(1,n+1):
if i%2!=0:
sum+=i
print("Sum of first {} odd numbers = {}".format(n,sum))
# Test case 1
'''
Enter a value of n 5
Sum of first 5 odd numbers = 9
'''
# Test Case 2
'''
Enter a value of n 10
Sum of first 10 odd numbers = 25
''' |
86c4d9b01511502c80cf77ce48c82173d0571fc2 | Ivan-Voroshilov/1_lesson | /4.py | 133 | 3.9375 | 4 | x = int(input('Input number... '))
max = 0
while x >= max:
x1 = x % 10
if x1 >= max:
max = x1
x //= 10
print(max) |
143574b59482dbb05d0834791ecc579f2073713f | glock3/Learning- | /Misha/Numbers/recursion_deuce_power.py | 482 | 4.28125 | 4 | def calculate_division_by_two(number):
if number == 1:
print('Entered number is a power of 2.')
elif number % 2 == 0:
number = number / 2
calculate_division_by_two(number)
else:
print('Entered number is NOT a power of 2.')
def main():
print('This program define, if entered number is a power of 2.')
number = int(input('Enter positive int value: '))
calculate_division_by_two(number)
if __name__ == "__main__":
main()
|
ca4b85c06aa1b1aa5aa9419b6f7a9511f73e6ac4 | AxelPuig/The_Rene_Project | /rene/talker/__init__.py | 4,119 | 3.515625 | 4 | import os
import platform
class Talker:
""" Makes the raspberry talk """
def __init__(self):
self.hello_said = []
self.hello_in_process = {}
self.nobody_rate = 0
self.time_since_last_action = 0
def inform_preparing(self):
rene_parle("Salut a vous les copains ! Je me prépare.")
def inform_ready(self):
rene_parle("Je suis prêt !")
def talk(self, people, action, person):
""" Says something adapted to the situation """
# Say hello if meeting someone for the first time since last run
for person in people:
if person['confidence_name'] >= 0.95:
if person['name'] not in self.hello_said: # Says hello to this person
if person['name'] not in self.hello_in_process:
self.hello_in_process[person['name']] = [1, 0]
# 1 pour le number of times he has been recognized,
# 0 to 2 for the number of loops iterations since recognition of data[name], maximum 2
elif self.hello_in_process[person['name']][0] == 1:
rene_parle('Bonjour ' + person['name'])
self.hello_said.append(person['name'])
else:
self.hello_in_process[person['name']] = [1, 0]
for i in self.hello_in_process:
if i not in self.hello_said and self.hello_in_process[i][0] != 0: # To avoid useless work
if self.hello_in_process[i][1] <= 2:
self.hello_in_process[i][1] += 1 # Remembers a loop has been run
else:
self.hello_in_process[i] = [0, 0] # Reset if still no recognition after 2 loops
# Checking if someone in the frame
if len(people) == 0:
self.nobody_rate += 1
else:
self.nobody_rate = 0
if self.nobody_rate >= 5:
self.nobody_rate = 0
# Says he can't find anyone !
read_file("rene/speaking/nobody")
if action == 1 and self.time_since_last_action > 1:
# Says how are you if hand raised and has waited since last action
if person['confidence_name'] > 0.95:
rene_parle("Comment ça va " + person['name'] + " ?")
else:
rene_parle("Comment ça va ?")
self.time_since_last_action = 0
elif action == 2 and self.time_since_last_action > 1:
# Says photo taken (that's wrong) if hand closed and has waited since last action
rene_parle("Ok, je vous ai pris en photo !")
self.time_since_last_action = 0
else:
self.time_since_last_action += 1
def rene_parle(text):
"""
On the raspberry, text read by vocal synthesis
On computer, text printed
:param text: text to say
"""
if platform.uname()[1] == "raspberrypi":
parole = open("parole.txt", "w") # Creating text file
parole.write("""#!/bin/bash\npico2wave -l fr-FR -w temp.wav '""" + text + """'
amixer sset 'PCM' 95%
omxplayer temp.wav
rm temp.wav""")
parole.close()
os.rename('parole.txt', 'parole.sh') # text file --> shell file
os.system('sh parole.sh') # run shell
os.remove('parole.sh') # remove shell
else:
print("[RASPI SAYS] " + text)
def read_file(file_name):
"""
File reading on raspberry pi.
On computer, printing file name
:param file_name
"""
if platform.uname()[1] == "raspberrypi":
lecture = open("lecture.txt", "w") # création d'un fichier texte
lecture.write("""#!/bin/bash
amixer sset 'PCM' 95%
omxplayer """ + file_name + """.wav""")
lecture.close()
os.rename('lecture.txt', 'lecture.sh') # fichier texte --> fichier shell
os.system('sh lecture.sh') # execution du fichier shell
os.remove('lecture.sh') # suppression du fichier shell
else:
print("[RASPI SAYS] " + file_name) |
a73f26e22bb28f99b336dc73d019d03cd3c9d14a | CodePracticeComputerScience/ProjectReportsOfResume | /pwMan-template_edited.py | 4,870 | 3.71875 | 4 | # KuntalPatel
#11/14/2019
# This program stores passwords in a file
# that is encrypted with a master password
#
# system packages: gcc libffi-devel python-devel openssl-devel
# python packages: pycryptodome
# references:
# 1. https://stackoverflow.com/questions/19232011/convert-dictionary-to-bytes-and-back-again-python
# 2. https://www.pycryptodome.org/en/latest/src/examples.html
#
# To run:
# python pwMan_edited.py Google.com
#
# To reset:
# rm passwords
#
# Example Output:
# $ python pwMan-template_edited.py google.com
# Do you have master password ? : enter y or n:
# y
# Enter Master Password:pass
# Your password is pass Please save it
# No password database, creating....
# Loading database...
# No entry for google.com, creating new...
# Do you want sys generated pwd : enter y or n:
# n
# New entry - enter password for google.com: google
# stored
#working with file so need to import csv module
#json module methods will be used to convert byte stream into object and vice versa.
#cipher module will provide different modes by which encypt and decrypt file.
#Random module methods will suggest random password according to parameters.
#PBKDF2 algorithm takes 3 parameters 1)salt 2)master password and 3)lendth of the desired key
import csv, os, sys, json,string
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol.KDF import PBKDF2
from random import *
passwordFile = "passwords"
##The salt value should be set here.
#salt value is hard coded here
salt = "1234"
##The header of the file.
head = " ____ __ __\n"+"| _ \ __ _ ___ ___| \/ | __ _ _ __ \n" +"| |_) / _` / __/ __| |\/| |/ _` | '_ \ \n" +"| __/ (_| \__ \__ \ | | | (_| | | | |\n" +"|_| \__,_|___/___/_| |_|\__,_|_| |_|\n"
#functions
#convert object into byte stream
def dictToBytes(dict):
return json.dumps(dict).encode('utf-8')
#give object from byte stream
def bytesToDict(dict):
return json.loads(dict)
#encryption mode is AES.
def encrypt(dict, k):
##Define the encryption scheme here.
cipher = AES.new(k, AES.MODE_EAX)
##Encrypt the dictionary value here.
ciphertext, tag = cipher.encrypt_and_digest(dict)
## writing encrypted value into file
with open(passwordFile, 'wb') as outfile:
[outfile.write(x) for x in (cipher.nonce, tag, ciphertext)]
def decrypt(k):
##reading encrypted value from the file
with open(passwordFile, 'rb') as infile:
nonce, tag, ciphertext = [ infile.read(x) for x in (16, 16, -1) ]
##Define the encryption scheme here.
cipher = AES.new(k, AES.MODE_EAX,nonce)
##Decrypt the ciphertext here.
data = cipher.decrypt_and_verify(ciphertext, tag)
return data
#randomly generate password from ascii letters,punctuation marks and digits
def generate_random_pwd():
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
return password
def Main():
print("\n\n")
if os.path.isfile(passwordFile):
mpw = input("Enter Master Password:\n")
else:
masterpwd = input("Do you have master password ? : enter y or n:\n")
if masterpwd == "y":
mpw = input("Enter Master Password:")
else:
mpw = generate_random_pwd()
print("Your password is "+ mpw +" Please save it")
# derive key from password
#generate key of length 16 key with the value of master password ans salt.
k = PBKDF2(mpw, salt, dkLen=16)
# check for password database file
if not os.path.isfile(passwordFile):
# create new passwords file
print("No password database, creating....")
newDict = dictToBytes({"TempSite":"TempPassword"})
encrypt(newDict, k)
# check usage
if len(sys.argv) != 2:
print("usage: python pwMan-template_edited.py <website>")
print("Please enter enough arguments")
return
else:
# decrypt passwords file to dictionary
try:
print("Loading database...")
pws1 =decrypt(k)
pws = bytesToDict(pws1)
except Exception as e:
print("Wrong password")
return
# print value for website or add new value
entry = sys.argv[1]
if entry in pws:
print("entry : " + str(entry))
print("password: " + str(pws[entry]))
else:
print("No entry for " + str(entry) + ", creating new...")
sys_gen_pwd = input("Do you want sys generated pwd : enter y or n:\n")
if(sys_gen_pwd == "y"):
newPass = generate_random_pwd()
print("your "+ str(entry) + "password is "+ newPass +" please save it")
else:
newPass = input("New entry - enter password for "+entry+": ")
pws[entry] = newPass
encrypt( dictToBytes(pws), k)
print("stored")
if __name__ == '__main__':
print(str(head))
Main()
|
de3a044a9cc5e7734b7fc6ed1cdf084b55c585f5 | liruileay/data_structure_in_python | /data_structure_python/question/chapter1_stack_queue_question/question1.py | 1,129 | 3.984375 | 4 | from development.chapter6.ArrayQueue import Empty
class Stack(object):
"""设计一个基于列表的栈这个栈具有getMin功能"""
def __init__(self):
self._data = []
self._help = []
def __len__(self):
"""获取栈中元素的个数"""
return len(self._data)
def is_empty(self):
"""判断栈中元素是否为空"""
return len(self._data) == 0
def push(self, v):
if self.is_empty():
self._data.append(v)
self._help.append(v)
else:
self._data.append(v)
max = self._help.pop()
if max >= v:
self._help.append(max)
self._help.append(v)
else:
self._help.append(max)
self._help.append(max)
def pop(self):
"""弹出最后一个进栈的元素"""
if self.is_empty():
raise Empty("Stack is empty")
self._help.pop()
return self._data.pop()
def get_min(self):
"""弹出栈中最小的元素"""
if self.is_empty():
raise Empty("Stack is empty")
self._data.pop()
return self._help.pop()
if __name__ == '__main__':
s = Stack()
for i in [3, 34, 5, 45, 45, 45, 6, 7, 7, 7, 7435, 345, 1, 3]:
s.push(i)
for i in range(8):
print(s.get_min())
|
6875bc546b723a30bcb2f5e98d400d414ddd1d50 | cswizard11/lambda | /unit_3/sprint_1_lambdata-cswizard11/sprint_challenge/acme_report.py | 1,454 | 3.71875 | 4 | from random import randint, sample, uniform
from acme import Product
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30):
products = [Product(name=ADJECTIVES[randint(0, len(ADJECTIVES) - 1)] + ' ' + NOUNS[randint(0, len(NOUNS) - 1)],
price=randint(5, 100),
weight=randint(5, 100),
flammability=uniform(0, 2.5))
for i in range(0, num_products)]
# generate and add random products.
return products
def inventory_report(products):
# Loop over the products to calculate the report.
names = []
avg_price = 0
avg_weight = 0
avg_flammability = 0
for i in products:
if not(i.name in names):
names.append(i.name)
avg_price += i.price
avg_weight += i.weight
avg_flammability += i.flammability
avg_price /= len(products)
avg_weight /= len(products)
avg_flammability /= len(products)
print('ACME CORPORATION OFFICIAL INVENTORY REPORT')
print('Unique product names:', len(names))
print('Average price:', avg_price)
print('Average weight:', avg_weight)
print('Average flammability:', avg_flammability)
if __name__ == '__main__':
inventory_report(generate_products()) |
79bf4dfe89d15e192f3b6af0c0fd5a19c0d0e33f | bedros-bzdigian/intro-to-python | /week3/pratical/lists/problem3.py | 308 | 3.875 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("number", help="display a cube of a given number", type=int)
args = parser.parse_args()
list2 = [0 , 'hi' , 2 , 100 ,300 , 2]
x = list2.count(args.number)
print ("list2: " , list2)
print ("the number of using this number is: " , x)
|
937e9794c08a886c46d17b0bf4ac2ef8398e51a7 | kanmani-kamalanathan/Kattis-Solutions | /No Duplicates/nodup.py | 77 | 3.5625 | 4 | print('yes' if (lambda z: len(z) == len(set(z)))(input().split()) else 'no')
|
7804844bab670497f42d06f061c479cc6d91ed13 | rockingrohit9639/pythonBasics | /classes.py | 299 | 3.578125 | 4 | class Students:
def print_details(self):
print(f"Name : {self.name}\nRoll No : {self.roll_no}\nSection : {self.sec}")
std1 = Students()
std1.name = input("Enter name of student : ")
std1.roll_no = input("Enter roll no : ")
std1.sec = input("Enter section : ")
std1.print_details()
|
6745f7d639da66708ce7b2ea4e1b0177af6e76ef | CJLucido/Intro-Python-I | /src/14_cal.py | 2,566 | 4.625 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
input None
if
print current datetime
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
input arg1 only
if
print month of current year datetime?
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
input arg1 arg2
if
print month of year
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
else
this should actually be paired with the first parameter/functionality above
print("program expects arguments to be given")
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
import sys
import calendar
from datetime import datetime
if len(sys.argv) > 2:
month = int(sys.argv[1])
year = int(sys.argv[2])
elif len(sys.argv) > 1:
month = int(sys.argv[1])
else:
month = 0
year = 0
# print(sys.argv)
# print(month)
current_year = datetime.today().year
current_month = datetime.today().month
# print(current_year)
# print(current_month)
# print(calendar.TextCalendar().prmonth(current_year,3, w=0, l=0))
#DONT FORGET TO INSTANTIATE TEXTCALENDAR!!!!!!!!!!!!!!
def print_calendar(year, month):
if year < 1 and month < 1:
print("program expects arguments to be given")
print(calendar.TextCalendar().prmonth(current_year, current_month))
elif month > 0 and year < 1:
print(calendar.TextCalendar().formatmonth(current_year, month))
else:
print(month)
print(calendar.TextCalendar().formatmonth(year, month) + " " + calendar.TextCalendar().formatyear(year))
print_calendar(year, month) |
64e51192f10b196a58ef5cbbdaacaf99cbf901f4 | geronimo0630/2021 | /clases/juego2.py | 1,317 | 4 | 4 | import random
#---entradas---#
mensaje_saludo = 'juguemos!'
pregunta_introduccion = '''
en este juego debes acertar un numero
que va desde el 1 al 10!!!
puedes intentarlo antes que se te acaben las vidas!!!
ingresa tu numero:
'''
pregunta_dificultad = '''
1-facil
2-moderado
3-dificil
'''
pregunta_fallaste = 'fallo pa, vuelva a intentarlo: '
MENSAJE_DESPEDIDAD = 'felicidades pri'
#--codigo--#
numeroOculto = random.randint (1,10)
vidas = ''
dificultad = int (input(pregunta_dificultad))
while (dificultad !=1 and dificultad != 2 and dificultad != 3):
print ('ingresa una opcion validad')
dificultad= int (input(pregunta_dificultad))
if(dificultad == 1):
print ('modo facil activado ')
vidas = 5
elif (dificultad ==2):
print ('modo moderado activado')
vidas = 3
else:
print ('modo dificil activado')
vidas = 1
numegroIngresado = int (input(pregunta_introduccion))
while (numegroIngresado != numeroOculto and vidas>1):
vidas -=1
print ( 'te quedan estas vidas : ',vidas)
numegroIngresado = int (input(pregunta_fallaste))
if (vidas>=0 and numegroIngresado == numeroOculto):
print (MENSAJE_DESPEDIDAD)
else:
print (pregunta_fallaste, 'el numero era el: ', numeroOculto)
|
184f9b4b2995fd8078c10440192e62f5279a391a | RoseGreene/Homework | /years100.py | 165 | 3.96875 | 4 | name = input("Enter your name: ")
age = int(input("Enter your age: "))
old = 100 - age
print(name + "," + " after " + str(old) + " years you will be 100 years old!") |
9094047497cfd16e27ae34fdf5b03fcc6823c335 | FabricioGalvani/data-engineering | /etl.py | 3,445 | 3.65625 | 4 | from openpyxl import load_workbook
import xlsxwriter
import csv
def load_csv_files(input_file):
'''
Function to load the csv files.
Parameters:
input_file (str): File input.
Returns:
file (obj): The csv file.
'''
with open(input_file, encoding='utf-8') as csvfile:
file = csv.reader(csvfile, delimiter=';')
if file:
return file
else:
return False
def load_xlsx_files(input_file):
'''
Function to load the xlsx files..
Parameters:
input_file (str): File input.
Returns:
sheet (obj): The sheet.
'''
wb = load_workbook(input_file)
sheet = wb['Processed']
if sheet:
return sheet
else:
return False
def format_date(transaction_date):
'''
Function to format the date.
Parameters:
transaction_date (date): The date which we will format.
Returns:
transaction_date (str): The formatted date(YYYYMMDD).
'''
if transaction_date:
transaction_date = transaction_date.date()
transaction_date = transaction_date.strftime('%Y%m%d')
return transaction_date
def format_cost(total_cost):
'''
Function to add the percentage to the value.
Parameters:
total_cost (int): The value which we will add the value.
Returns:
total_cost (float): The added value of the increase.
'''
percentage = 1.10
total_cost = round(float(total_cost) * percentage, 2)
return total_cost
def format_cost_center(cost_center_name):
'''
Function to format the name of the cost center.
Parameters:
cost_center_name (str): The cost center name.
Returns:
cost_center_name (str): The name of the cost center formatted if necessary.
'''
if cost_center_name == "Faturamento":
cost_center_name = "Contas a Pagar/Receber"
return cost_center_name
def transform_data(sheet):
'''
Function to format data.
Parameters:
sheet (obj): The file object.
Returns:
total_cost (list): The list of data.
'''
total_cost = []
rows = sheet.iter_rows(min_row=1, max_row=1)
first_row = next(rows)
header = [data.value for data in first_row]
total_cost.append(header)
for row in sheet.iter_rows(values_only = True, min_row=2):
row = list(row)
row[1] = format_date(row[1])
row[2] = format_cost_center(row[2])
row[3] = format_cost(row[3])
total_cost.append(row)
return total_cost
def save_sheet(file, file_name_output):
'''
Function to save the file.
Parameters:
file (str): The file to save.
file_name_output (str): File name output.
Returns:
True (bool): Return Boolean expression.
'''
with xlsxwriter.Workbook(file_name_output) as workbook:
worksheet = workbook.add_worksheet()
for row_num, data in enumerate(file):
worksheet.write_row(row_num, 0, data)
return True
if __name__ == "__main__":
csv_input_file = "files/CostCenter.csv"
load_csv_files(csv_input_file)
xlsx_input_file = "files/Values.xlsx"
sheet = load_xlsx_files(xlsx_input_file)
if sheet:
total_cost = transform_data(sheet)
file_name_output = "TotalCost.xlsx"
save_sheet(total_cost, file_name_output)
|
41b2e4e0d08dc15f31431d107c91bffb4745e3f2 | yeehaoo/mini-projects | /bank.py | 1,165 | 3.65625 | 4 | import tkinter as tk
class Root(tk.Tk):
def __init__(self):
super().__init__()
self.balance = 100
self.frame = tk.Frame(self)
self.frame.pack()
self.label_1 = tk.Label(self.frame,text="Bank Account")
self.label_1.pack()
self.lblAmount = tk.Label(self.frame,text=self.balance)
self.lblAmount.pack()
self.entry = tk.Entry(self.frame)
self.entry.pack()
self.btnDeposit = tk.Button(self.frame,text="Deposit",command=self.deposit)
self.btnDeposit.pack()
self.btnWithdraw = tk.Button(self.frame,text="Withdraw",command=self.withdraw)
self.btnWithdraw.pack()
def deposit(self):
if(self.entry.get() != ""):
amount = int(self.entry.get())
self.balance += amount
self.lblAmount.configure(text=self.balance)
def withdraw(self):
if(self.entry.get() != ""):
amount = int(self.entry.get())
self.balance -= amount
self.lblAmount.configure(text=self.balance)
if __name__ == "__main__":
root = Root()
root.mainloop()
|
76a0bf2b11c1fc18714630bbd720f56469eca66c | robingarbo/DOTfiles | /bin/group | 1,240 | 3.71875 | 4 | #!/usr/bin/python
import sys, os, getopt
def usage():
print("group inputs to NUM fileds per line, joined by \" \" ")
print("group NUM")
print("group NUM <arg1> <arg2> ... ")
if __name__ == '__main__':
if (len(sys.argv)<2):
usage()
sys.exit(1)
opt, args = getopt.getopt(sys.argv[1:], "r")
try:
cycle = int(args[0])
if (cycle <= 0):
print ( "%s is less or equal to zero" % sys.argv[1])
sys.exit(1)
except:
print("Cannot convert %s to integer"%sys.argv[1])
sys.exit(1)
if (len(sys.argv) == 2):
state = 0
t = []
# read from stdin
for i in sys.stdin:
state += 1
t.append(i.strip())
if (state == cycle):
print(" ".join(t))
t=[]
state = 0
if (state != 0):
print(" ".join(t))
else:
state = 0
t = []
# read from stdin
for i in sys.argv[2:]:
state += 1
t.append(i.strip())
if (state == cycle):
print(" ".join(t))
t=[]
state = 0
if (state != 0):
print(" ".join(t))
|
30d3502ddf188b01078071871cd8d3370928bdf4 | eclipse-ib/Software-University-Fundamentals_Module | /14-Retake_Exams/Mid_Exam_Retake-10_December_2019/01-Disneyland_Journey.py | 489 | 3.65625 | 4 | journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months+1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_money >= journey_cost:
print(f"Bravo! You can go to Disneyland and you will have {diff:.2f}lv. for souvenirs.")
else:
print(f"Sorry. You need {diff:.2f}lv. more.") |
17f7c7ab35a9bb71e7261cd6fa8a8233c22b4a9a | jinsookim/iitp18-hyu-bigdata | /section-A/source/proj06_control/p6_s13.py | 316 | 3.78125 | 4 | num_a = 100
num_b = 200
if num_a > num_b:
print('숫자A가 더 큰수입니다.')
max = num_a
elif num_a < num_b:
print('숫자B가 더큰수입니다.')
max = num_b
else:
print('숫자A와 숫자B는 같습니다.')
print('숫자A와 숫자B중 최대값은', max, '입니다.')
|
db8af07dbf5f6f4dca65caa427d61e8da1574ee9 | ilkerkesen/euler | /source/040.py | 329 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
LIMIT = 1000000
def main():
frac = ""
i = 1
while len(frac) <= LIMIT:
frac += str(i)
i += 1
result, i = 1, 1
while i <= LIMIT:
result *= int(frac[i-1])
i *= 10
print result
if __name__ == "__main__":
main()
|
d003d9a5417cc96025328c586393fa0bb7596da6 | Ahmed-Boughdiri/Python-Math | /compose.py | 1,300 | 3.53125 | 4 |
class Compose:
def __init__(self,equation):
self.equation = equation
def start(self):
result = []
operations = {
"+": "PLUS",
"-": "MIN",
"*": "MULT",
"/": "DIV"
}
start_char = 0
end_char = -1
while(end_char != None):
end_char += 1
if(self.equation[end_char] in "0123456789"):
end_char += 1
if(end_char == (len(self.equation) - 1)):
end_char = None
elif(self.equation[end_char] in "+-*/"):
variable = self.equation[start_char:end_char]
if("." in variable):
try:
variable = float(variable)
except:
# Return An Error
return "Error"
else:
try:
variable = int(variable)
except:
# Return An Error
return "Error"
result.append(variable)
result.append(operations[self.equation[end_char]])
else:
# Return An Error
return "Error"
return result
|
b898301c1100a38420864823c58546865b25b9f3 | ananiastnj/PythonLearnings | /LearningPrograms/Generator_Iterator.py | 875 | 3.828125 | 4 | '''for i in [1,2,3,4]: print(i)
for c in "Antony": print(c)
for d in {"x" : 1, "y" : 2}: print(d)
for line in open("Test.txt"): print(line)
'''
''' # Example 1
x = iter([1,2,3,4])
print(x)
print(x.__next__())
print(x.__next__())
'''
'''
#Example 2 : Iterator
class yrange:
def __init__(self,n):
self.i = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i<self.n:
i=self.i
self.i+=1
return i
else:
raise StopIteration()
y = yrange(3)
print(y.__next__())
print(list(yrange(5)))
print(sum(yrange(5)))
print(sum({2:1 , 7:2}))
'''
#Generator
def grange(n):
i=0
while i < n:
yield i
i += 1
g = grange(3)
print(g)
print(g.__next__())
print(g.__next__())
a = (x*x for x in range(10))
print(a)
print(a.__next__())
print(sum(a))
|
1c9aeea69b0068d3bbc9245ec004c0aebb631d7c | Omkar02/FAANG | /RemoveDupFromSortedArray.py | 1,264 | 3.890625 | 4 | import __main__ as main
from Helper.TimerLogger import CodeTimeLogging
fileName = main.__file__
fileName = fileName.split('\\')[-1]
CodeTimeLogging(Flag='F', filename=fileName, Tag='Array')
'''
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
'''
def getCountDup(nums):
if not nums:
return 0
prev_index = 0
prev = nums[0]
x = 1
while(prev != nums[-1]):
if nums[x] != prev:
prev = nums[x]
nums[prev_index + 1] = prev
prev_index += 1
x += 1
return prev_index + 1
nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
print(getCountDup(nums))
|
c021c716f2cb5d8e666c3ab5be7c0b84c9486641 | danielleappel/Python-Tutorial | /Code/fern_iterative.py | 1,044 | 3.78125 | 4 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import random
def fern_call(n):
"""Generates a fern fractal iteritavely.
Keyword arguments:
n -- the number of iterations
"""
v = ([0,0]) # Start at the origin.
plt.plot(v[0],v[1],'go', alpha = 0.3)
plt.title("Fern fractal iterative, n = %d" %n)
i = 0
while (i < n):
switch = random.randint(1,4)
if switch == 1:
v = np.dot(([0.85, 0.04],
[-0.04, 0.85]), v) + ([0,1.6])
elif switch == 2:
v = np.dot(([0.20, 0.26],
[0.23, 0.22]), v) + ([0,1.6])
elif switch == 3:
v = np.dot(([-0.15, 0.28],
[0.26, 0.24]), v) + ([0,0.44])
else :
v = np.dot(([0, 0],
[0, 0.16]), v)
plt.plot(v[0],v[1],'go', alpha = 0.3)
i += 1
plt.show()
def main():
n = 10000
fern_call(n)
if __name__ == "__main__":
main()
|
e306e71782d870b494d05fb4576e5341bac4b8d9 | TJBos/CS-Algorithms | /algo_foundations/other_algos/filtering_hashtables.py | 593 | 3.9375 | 4 | #reducing duplicates from a list by turning in a hashtable
items = ["apple", "pear", "banana", "orange", "banana", "grape", "pear"]
filter = dict()
for item in items:
filter[item] = 0
result = set(filter.keys())
#print(result)
#I think in JS you can just make a Tuple out of an array and convert back to array. Something like this: result = [... new Set(items)]
# -- Value Counting ---
counter = dict()
for item in items:
if (item in counter.keys()):
counter[item] += 1
else:
counter[item] = 1
print(counter)
# in JS we can use reduce to do this as well
|
5750f5a4d509fb2bf625cff9f6d07ab0fbd9480a | dyjae/LeetCodeLearn | /python/hot100/46.Permutations.py | 3,060 | 3.859375 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
__author__ = 'Jae'
from typing import List
class Permutations:
# 函数
def permute4(self, nums: List[int]) -> List[List[int]]:
from itertools import permutations
return permutations(nums)
# https://leetcode.com/problems/permutations/
# https://leetcode.wang/leetCode-46-Permutations.html
# Runtime: 36 ms, faster than 90.88% of Python3 online submissions for Permutations.
# Memory Usage: 13.9 MB, less than 67.20% of Python3 online submissions for Permutations.
def permute3(self, nums: List[int]) -> List[List[int]]:
rs = []
self.__upset(nums, 0, rs)
return rs
def __upset(self, nums: List[int], index: int, rs: List[List[int]]):
if index >= len(nums):
rs.append(nums.copy())
return
for i in range(index, len(nums)):
nums[i], nums[index] = nums[index], nums[i]
self.__upset(nums, index + 1, rs)
nums[i], nums[index] = nums[index], nums[i]
# 回溯 DFS
# Runtime: 32 ms, faster than 97.63% of Python3 online submissions for Permutations.
# Memory Usage: 14.1 MB, less than 30.71% of Python3 online submissions for Permutations.
def permute2(self, nums: List[int]) -> List[List[int]]:
rs = []
self.__back_track(nums, [], rs)
return rs
def __back_track(self, nums: List[int], temp: List[int], rs: List[List[int]]):
if len(temp) == len(nums):
rs.append(temp.copy())
return
for item in nums:
if temp.__contains__(item): continue
temp.append(item)
self.__back_track(nums, temp, rs)
temp.pop()
# 暴力求解,多重循环,通过在已有数字的间隙中插入新数字
# Runtime: 40 ms, faster than 77.80% of Python3 online submissions for Permutations.
# Memory Usage: 13.9 MB, less than 72.33% of Python3 online submissions for Permutations.
def permute(self, nums: List[int]) -> List[List[int]]:
rs = [[]]
for i in range(0, len(nums)):
currentSize = len(rs)
for j in range(0, currentSize):
for k in range(0, i + 1):
temp = rs[j].copy()
temp.insert(k, nums[i])
rs.append(temp)
# 移除上一步过程值
for j in range(0, currentSize):
rs.remove(rs[0])
return rs
def permute5(self, nums: List[int]) -> List[List[int]]:
perms = [[]]
for n in nums:
new_perms = []
for perm in perms:
for i in range(len(perm) + 1):
new_perms.append(perm[:i] + [n] + perm[i:]) ###insert n
perms = new_perms
return perms
if __name__ == "__main__":
list = [1, 2, 3]
check = Permutations()
print(check.permute(list))
print(check.permute5(list))
print(check.permute2(list))
print(check.permute3(list))
print(check.permute4(list))
|
33b733cdadf5f0bffcf42b89aa37f5d8566cb8da | FrankUSA2015/jianzhiOffice | /32-3.py | 1,028 | 3.640625 | 4 | # -*- coding: utf-8 -*-
#这个题的精妙所在有两点,第一点用双端队列的知识。第二点用了res来判断奇偶。
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> [[int]]:
if not root:
return []
res = []
dep = collections.deque([root])
while dep:
tmp = collections.deque()
for _ in range(len(dep)):
node = dep.popleft()
if len(res)%2:#用res中的数量来判断这一层的奇偶,如果res可以整除则这一行就是偶数,否则这一行是奇数
tmp.appendleft(node.val)
else:
tmp.append(node.val)
if node.left:
dep.append(node.left)
if node.right:
dep.append(node.right)
res.append(list(tmp))
return res |
36685782a0e2d6c2c21bf97385142e10c4eb95a1 | ejm2095/practice | /utils.py | 398 | 3.53125 | 4 | __author__ = 'undergroundskier'
def factors(n):
fact=[1,n]
check=2
rootn=n**.5
while check<rootn:
if n%check==0:
fact.append(check)
fact.append(n/check)
check+=1
if rootn==check:
fact.append(check)
fact.sort()
return fact
def largest(lst):
v = lst[0]
for x in lst:
if x>v:
v=x
return v |
b77a8e0314ed649bfb5ba40aa5469b6f82b27e41 | KYBee/DataStructure | /assignment2/assignment02_01_cal.py | 4,198 | 3.859375 | 4 | class Stack:
def __init__(self):
self.items = []
self.top = -1
def push(self, val):
self.items.append(val)
def pop(self):
try:
return self.items.pop()
except IndexError:
print("Stack is empty")
def top(self):
try:
return self.items[-1]
except IndexError:
print("Stack is empty")
def __len__(self):
return len(self.items)
def isEmpty(self):
return self.__len__() == 0
def peak(self):
try:
return self.items[-1]
except IndexError:
print("Stack is empty")
def get_postfix(equation):
postfix_equation = list()
Operator_stack = Stack()
operators = {"(": 0, ")": 0, "+": 1, "-": 1,
"*": 2, "/": 2, "%": 2, "^": 3}
temp = ""
for e in equation:
# 후위식으로 바꾸기
if e not in operators.keys(): # 숫자를 만난 경우
temp += e
else:
if temp:
postfix_equation.append(temp)
temp = ""
if Operator_stack.isEmpty() or e == "(":
Operator_stack.push(e)
else:
if operators[Operator_stack.peak()] < operators[e]:
Operator_stack.push(e)
elif e == ")":
while True:
if Operator_stack.peak() == "(":
Operator_stack.pop()
break
postfix_equation.append(Operator_stack.pop())
else:
postfix_equation.append(Operator_stack.pop())
while not(Operator_stack.isEmpty()) and operators[Operator_stack.peak()] >= operators[e]:
postfix_equation.append(Operator_stack.pop())
Operator_stack.push(e)
if temp:
postfix_equation.append(temp)
while not Operator_stack.isEmpty():
postfix_equation.append(Operator_stack.pop())
return postfix_equation
def get_value(equation):
postfix = get_postfix(equation)
operator = {"+": 1, "-": 1, "*": 2, "%": 2, "^": 3}
calculating_stack = Stack()
for token in postfix:
if token in operator.keys():
n2 = calculating_stack.pop()
n1 = calculating_stack.pop()
if token == "+":
result = int(n1) + int(n2)
elif token == "-":
result = int(n1) - int(n2)
elif token == "*":
result = int(n1) * int(n2)
elif token == "%":
result = int(n1) % int(n2)
elif token == "^":
result = int(n1) ** int(n2)
calculating_stack.push(result)
else:
calculating_stack.push(token)
return(calculating_stack.pop())
def print_error(space):
print(" " * space + "^ 이 위치에 오류가 있습니다.")
print(space)
return True
while True:
equation = input("")
operator = {"+": 1, "-": 1, "*": 2, "%": 2, "^": 3}
error = False
space = 0
if equation[-1] in operator.keys():
space = len(equation)-1
error = print_error(space)
else:
flag = [0, 0] # isnum, bracket_opened
for e in equation:
if e.isnumeric():
flag = [1, flag[1]]
elif e == "(":
if flag[0]: # 괄호 앞은 숫자가 올 수 없다.
error = print_error(space)
flag[1] += 1
elif e == ")":
if not flag[1]:
error = print_error(space)
flag[1] -= 1
elif e not in operator.keys():
error = print_error(space)
else:
if not flag[0]: # 연산자의 바로 이전은 숫자이어야 한다.
error = print_error(space)
flag = [0, flag[1]]
if error:
break
space += 1
else:
if flag[1]:
error = print_error(space)
if not error:
print(f"= {get_value(equation)}")
|
fba419edc5054d87aa2fc8ccdeb82e06375f3f86 | Greatbar/Python_Labs | /10_1.py | 92 | 3.546875 | 4 | s = str(input())
n = int(input())
print(s[n - 1] if 0 < n <= len(s) else 'ОШИБКА')
|
203ec0810426ac272f1483f50b50b4d437b086ba | larkaa/project_euler | /question17.py | 2,321 | 3.921875 | 4 | #!/usr/bin/env python3
#question 17
# count the number of letters in the numbers 1 to 1000
# format
# one hundred and thirty one
digits_str = ['','one','two','three','four','five','six','seven','eight','nine']
teens_str = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens_str = ['','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
digits = [len(x) for x in digits_str]
teens = [len(x) for x in teens_str]
tens = [len(x) for x in tens_str]
hundred = 7
hundred_and = 10
# X hundred *(1+(3+ninty nine others))
one_thou = len('onethousand')
total_sum = 0
# digits and teens
total_sum+= sum(digits) + sum(teens)
# tens are in the form twenty, thrity, then
# twenty twenty-one two...nine, thirty-one two... nine,
# = twenty appears 10 times more
# but the number one appears 8 times more for each twenty,
# so 8*9
#total_sum += sum(tens) + 9*(sum(tens) + 8*sum(digits))
#sumto99 = total_sum
#print(sumto99)
#3168
total_sum = 864
sumto99 = 864
# hundreds are of the form
# one hundred, two, three... nine
# one hundred AND one... ninety nine... nine hundred AND one... ninety nine
# -> hundred appears nine times more digits one time
# -> sumto99 appears 9 times more + hundred_and *90 (less 9 bc not including 100,200,300)
#total_sum += 9*(hundred + sum(digits)) #hundreds without and
#total_sum += 9*sumto99 + 90*hundred_and # hundreds with and
# otherwise, one hundred 99 times, , with 'and' 9 times
total_sum += 99*(sum(digits)+hundred) + 9*hundred_and + 9*sumto99
# one thousand once
total_sum += one_thou
print(total_sum)
#brute force backwards
total2 = one_thou
def to99(num):
#print(num)
temp = 0
for i in range(1,100):
if i<10:
temp+= (digits[i])
#print(digits_str[i])
elif i<20 and i>=10:
temp+= (teens[i%10])
#print(teens_str[i%10])
else:
#print(i,i//10,i%10)
temp+= (tens[i//10-1]) + (digits[i%10])
#print(tens_str[i//10-1],digits_str[i%10])
return(temp)
temp = 0
for hund in digits_str:
sumto99 = to99(10)
if len(hund)==0:
temp+= sumto99
elif len(hund)>0:
temp += len(hund)
temp += len('hundred') # case of 1 hundred, 2 hundred...
temp += 99*(len('and') + len(hund))
temp += sumto99
print(temp)
#864
to99(10)
|
6b6f948b442e09c04b243baa184541471cb829d3 | Faraday1221/project_euler | /problem_1.py | 477 | 4.1875 | 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 1000.
##solution using a for loop
y=0
for i in range(1,1000):
if i%3 ==0 or i%5==0:
# print 'i is equal to', i
y += i
# print 'y is equal to', y
#print y
##alternative using list comprehensions
ans = [x for x in range(1,1000) if x%3 ==0 or x%5 ==0 ]
print sum(ans) |
37f02c4606514931ad7a5ca7e6ddd9282ef659d0 | TGathman/Codewars | /5 kyu/Simple Pig Latin/Simple Pig Latin.py | 164 | 3.703125 | 4 | # Python 3.8, 20 march 2020
def pig_it(text):
punc = ["!", ".", "?"]
return " ".join(i[1:] + i[0] + "ay" if i not in punc else i for i in text.split())
|
3efd1aba802a2d12c5edb649d28e243c4b39772b | kingsamchen/Eureka | /crack-data-structures-and-algorithms/leetcode/plus_one_linked_list_q369.py | 932 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 核心思路
# 这题是 add_two_numbers_II_q445.py 的特例版本,做法更简单
# 另,这题没说不能修改原链表,所以可以先reverse,变成低位在前
# 处理之后再 reverse 回去
class Solution(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pnc = p = dummy
while p.next:
if p.val != 9:
pnc = p
p = p.next
val = p.val + 1
if val > 9:
p.val = 0
pnc.val += 1
while pnc.next != p:
pnc.next.val = 0
pnc = pnc.next
else:
p.val = val
return dummy.next if dummy.val == 0 else dummy
|
195eb2d55248246faafa8057a16f299eb32fe69a | bgoonz/UsefulResourceRepo2.0 | /_REPO/MICROSOFT/c9-python-getting-started/python-for-beginners/13_-_Functions/print_time_with_message_parameter.py | 593 | 4.1875 | 4 | from datetime import datetime
# Define a function to print the current time and task name
# Function the following parameters:
# task_name: Name of the task to display to output screen
def print_time(task_name):
print(task_name)
print(datetime.now())
print()
first_name = "Susan"
# Call print_time() function to display message and current time
# pass in name of task completed
print_time("first name assigned")
for x in range(0, 10):
print(x)
# Call print_time() function to display message and current time
# pass in name of task completed
print_time("loop completed")
|
4793d7af2f152a0f691a07033ff969e840b8fbb2 | hilalhusain/waterjugproblem | /waterjugprob.py | 717 | 3.78125 | 4 | jug1 = int(input("Small Jug Capacity: "))
jug2 = int(input("Large Jug Capacity: "))
amt1 = int(input("water present in small jug, J1: "))
amt2 = int(input("water present in large jug, J2: "))
t = int(input("Final in Large Jug: " ))
#jug1 = 3
#jug2 = 5
#t = 1
def jugSolver(amt1, amt2):
print(amt1, amt2)
if (amt2 == t and amt1 == 0):
return
elif amt2 == jug2:
jugSolver(amt1, 0)
elif amt1 != 0:
if amt1 <= jug2-amt2:
jugSolver(0, amt1+amt2)
elif amt1 > jug2-amt2:
jugSolver(amt1-(jug2-amt2),amt2+(jug2-amt2))
else:
jugSolver(jug1, amt2)
print("\nJ1 J2")
#jugSolver(2,4)
jugSolver(amt1,amt2) |
c003bbee5f5301bcb3dfc3c617d0ab13f8c2a22a | nageshwarbr/PersonalProjects | /healthyProgrammer/healthy_programmer.py | 1,901 | 3.515625 | 4 | # Healthy Programmer
# 9am - 5pm
# Water - water.mp3 (3.5 litres) - Drank - log - Every 40 min
# Eyes - eyes.mp3 - every 30 min - EyDone - log - Every 30 min
# Physical activity - physical.mp3 every - 45 min - ExDone - log
# Rules
# Pygame module to play audio
from pygame import mixer
from datetime import datetime
from time import time
def isNowInTimePeriod(start_time, end_time, now_time):
return start_time <= now_time <= end_time
def musiconloop(file, stopper):
mixer.init()
mixer.music.load(file)
mixer.music.play()
while True:
a = input()
if a == stopper:
mixer.music.stop()
break
def log_now(msg):
with open("mylogs.txt", "a") as f:
f.write(f"{msg} {datetime.now()} \n")
if __name__ == '__main__':
# musiconloop("water.mp3","stop")
init_water = time()
init_eyes = time()
init_exercise = time()
watersecs = 40 * 60
exsecs = 30 * 60
eyesecs = 45 * 60
timeStart = '9:00AM'
timeEnd = '5:00PM'
timeEnd = datetime.strptime(timeEnd, "%I:%M%p")
timeStart = datetime.strptime(timeStart, "%I:%M%p")
timeNow = datetime.now()
while isNowInTimePeriod(timeStart, timeEnd, datetime.now()):
if time() - init_water > watersecs:
print("Water drinking time. Enter 'drank' to stop alarm")
musiconloop("water.mp3", "drank")
init_water = time()
log_now("Drank water at ")
if time() - init_eyes > eyesecs:
print("Eye drop time. Enter 'doneeyes' to stop alarm")
musiconloop("eyes.mp3", "doneeyes")
init_eyes = time()
log_now("Eye drop at ")
if time() - init_exercise > exsecs:
print("Exercise time. Enter 'done' to stop alarm")
musiconloop("exercise.mp3", "done")
init_exercise = time()
log_now(" Exercise at ")
|
b18ac0d8aa4856d2f7dddc44e1d74dee6b3ab7c6 | YizhuZhan/python-study | /map&reduce&filter.py | 709 | 3.640625 | 4 | # -*- coding:utf-8 -*-
import math
import functools
def add(x, y, _f):
return _f(x) + _f(y)
print(add(25, 9, math.sqrt))
def format_name(s):
return s[0].upper() + s[1:].lower()
print(list(map(format_name, ['adam', 'LISA', 'barT'])))
def f(x, y):
return x + y
print(functools.reduce(f, [1, 3, 5, 7, 9])) # output: 25
print(functools.reduce(f, [1, 3, 5, 7, 9], 100)) # output: 125
def is_not_empty(s):
return s and len(s.strip()) > 0
print(list(filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']))) # output: ['test', 'str', 'END']
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print(list(filter(is_sqr, range(1, 101)))) # output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
|
f8c8012d19d57bddea61f43ee000c1003c0a8f15 | UX404/NeuralNetwork-Numpy | /Layer.py | 1,049 | 3.65625 | 4 | import numpy as np
class Linear():
def __init__(self, input_num, output_num):
self.weights = (np.random.rand(input_num, output_num) - 0.5) / 10 # [-0.05, 0.05]
self.bias = np.ones((1, output_num)) # 1
self.x = None
self.m = None
self.y = None
def forward(self, x):
self.x = x
self.m = np.dot(self.x, self.weights) + self.bias # 线性层
self.y = 1 / (1 + np.exp(-self.m)) # 激活函数 Sigmoid
return self.y
def backward(self, dy, learning_rate):
dm = dy * self.y * (1 - self.y) # 激活函数BP
dw = np.dot(self.x.T, dm) # 线性层BP
db = dm
dx = np.dot(dm, self.weights.T)
self.weights -= learning_rate * dw
self.bias -= learning_rate * db
return dx
class MSE():
def __init__(self):
self.x = None
def forward(self, x):
self.x = x
return self.x
def backward(self, truth):
return (self.x - truth) / self.x.size
|
3b89ba49d0ff4a720956a4cb69f69df147f5fff8 | davidally/IS211_Assignment1 | /assignment1_part2.py | 1,091 | 4.53125 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment 1 - Part 2"""
class Book(object):
"""This class creates a book.
Attributes:
attr1 (str): The title of the book.
attr2 (str): The author of the book.
"""
title = ''
author = ''
def __init__(self, title, author):
"""The book constructor.
Creates a new book with title and author properties.
Args:
title (str): The title of the book.
author (str): The author of the book.
"""
self.author = author
self.title = title
def display(self):
"""This will display the book's info.
Will format a string with the properties of
the book in order to display the information.
Returns:
str: Tells who wrote the book.
"""
return "{}, written by {}.".format(self.title, self.author)
book_1 = Book('Of Mice and Men', 'John Steinbeck')
book_2 = Book('To Kill a Mockingbird', 'Harper Lee')
print book_1.display()
print book_2.display() |
0bb1dd2919f33772aefa4cd06461a11affe57143 | AndongWen/leetcode | /数据结构/树/0066convertBST.py | 1,035 | 3.90625 | 4 | '''538把二叉搜索树转换为累加树
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。'''
'''思路:中序遍历,先遍历右子树'''
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
sum = 0
q = coll.deque()
cur = root
while cur or q:
while cur:
q.append(cur)
cur = cur.right
cur = q.pop()
cur.val += sum
sum = cur.val
cur = cur.left
return root
def convertBST2(self, root: TreeNode) -> TreeNode:
'''递归'''
self.sum = 0
self.travell(root)
return root
def travell(self, root: TreeNode):
if not root:
return
self.travell(root.right)
root.val += self.sum
self.sum = root.val
self.travell(root.left)
|
89756e4d05c4c6ec175e13bd64a8da15fa9ea20e | lcx94/python_daily | /data_structure/2020-04/20200416/path_sum.py | 1,086 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
---------------------------------
File Name: path_sum
Description: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Author: Liu Changxin
date: 2020/4/16
---------------------------------
Change Activity:
2020/4/16
"""
def has_path_sum(root, sum):
if not root:
return False
def iterator(node, target):
if not node:
return False
target -= node.val
if (target == 0) and (not node.left) and (not node.right):
return True
return iterator(node.left, target) or iterator(node.right, target)
return iterator(root, sum)
'''
res:
Runtime: 44 ms, faster than 53.40% of Python3 online submissions for Path Sum.
Memory Usage: 15.6 MB, less than 5.45% of Python3 online submissions for Path Sum.
''' |
67288610691403d7bec2e4eefe07da06a94461b4 | tobyt99/pythoncolt | /functions.py | 2,225 | 4.15625 | 4 | # exercise 44
# def return_day(day):
# days = {
# 1 : "Sunday",
# 2 : "Monday",
# 3 : "Tuesday",
# 4 : "Wednesday",
# 5 : "Thursday",
# 6 : "Friday",
# 7 : "Saturday"
# }
# if day in days:
# return days[day]
# return None
# return_day(5)
# exercise 45
# def last_element(aList):
# if len(aList) == 0:
# return None
# return(aList.pop())
# exercise 46
# def number_compare(x, y):
# if x == y:
# return "Numbers are equal"
# elif x > y:
# return "First is greater"
# return "Second is greater"
# number_compare(15,10)
# print (number_compare(1,1))
# print (number_compare(1,0))
# print (number_compare(0,1))
# exercise 47
# def single_letter_count(phrase, letter):
# return phrase.lower().count(letter.lower())
# single_letter_count("I love my dog", "o")
# print(single_letter_count("Hello World", "h"))
# print(single_letter_count("Hello World", "z"))
# print(single_letter_count("HelLo World", "l"))
# exercise 48
# from collections import Counter
# def multiple_letter_count(string):
# list(string)
# return dict(Counter(string))
# multiple_letter_count("awesome")
# print(multiple_letter_count("awesome"))
# def multiple_letter_count(string):
# return {letter: string.count(letter) for letter in string}
# multiple_letter_count("awesome")
# print(multiple_letter_count("awesome"))
# exercise 49
# def list_manipulation (aList, command, location, value=None):
# if (command == "remove" and location == "end"):
# return aList.pop()
# elif (command == "remove" and location == "beginning"):
# return aList.pop(0)
# elif (command == "add" and location == "beginning"):
# aList.insert(0, value)
# return aList
# elif (command== "add" and location == "end"):
# aList.append(value)
# return aList
# exercise 50
# def is_palindrome(check):
# check.lower().replace(" ", "")
# kcehc = "".join(reversed(check))
# if (check == kcehc):
# return True
# return False
# def is_palindrome(string):
# stripped = string.replace(" ", "")
# return stripped == stripped[::-1] |
0c919b071db1faaceaed4d0597b126cc876dc111 | Nakarp/Python | /Calculator/main.py | 614 | 3.890625 | 4 | import re
print(" ")
print("Calculator 2000")
print("Type 'exit' to exit\n")
previous = 0
run = True
def math_equation():
global run
global previous
equation = ""
if previous == 0:
equation = input("Enter equation:")
else:
equation = input(str(previous))
if equation == "exit":
print("Good Bye")
run = False
else:
equation = re.sub('[a-zA-Z,.:;" "ç()]', '', equation )
if previous == 0:
previous = eval(equation)
else:
previous = eval(str(previous) + equation)
while run:
math_equation() |
df479415001b9deac5fd94b60fad7e978317b576 | shermannatrix/python-dev | /Python AIO/Book 2 (CH3) Lists_Tuples/sets_basics.py | 422 | 3.640625 | 4 | sample_set = {1.98, 98.9, 74.95, 2.5, 1, 16.3}
sample_set.add(11.23)
# Adding items to the set
sample_set.update([88, 123.45, 2.98])
print(f"Updated set: {sample_set}")
# Make a copy and show the copy
ss2 = sample_set.copy()
print(ss2)
# Loop through the set and print each item right-aligned and formatted
print("\nLoop through set and print each item formatted.")
for price in sample_set:
print(f"{price:>6.2f}")
|
eee7f2412c349b86781ff357c96dd1c674fa9365 | EwertonBar/CursoemVideo_Python | /mundo01/desafios/desafio031.py | 258 | 3.546875 | 4 | dist=float(input('Qual a distância da sua viagem? '))
if dist <= 200:
print('O preço da sua passagem será {} reais. Tarifa: R$0.50.'.format(dist*0.5))
else:
print('O preço da sua passagem será {} reais. Tarifa: R$ 0.45.'.format(dist*0.45)) |
448559a0ad1c98ec36b563d1c6ba8bd6e1b64051 | bihtert/second | /Histogram of Frequencies.py | 219 | 4.03125 | 4 | #Histogram of Frequencies
n = int(input("Number of Frequency:"))
freq = []
for i in range(1,n+1):
f = int(input("Enter frequency %s" %i))
freq.append(f)
for i in range(n):
print(freq[i], ":" , freq[i]*"*") |
e295d0f90daa2c6622436bea363e39fdedc30231 | mevol/python_topaz3 | /topaz3/train_test_split.py | 8,293 | 3.5625 | 4 | """
Script to split a directory into training and testing samples.
Can take a directory filled with subdirectories (which should all be equal)
or a directory of similar files (same extension).
Copies the test samples to the test directory provided and then deletes them
from the original location.
"""
import argparse
import logging
import os
import random
import shutil
from pathlib import Path
from typing import Tuple
def test_split(file_list: Tuple, split_percent: float) -> Tuple:
"""
Takes in a tuple or list of file or directory locations,
returns a list of randomly selected files according to the split_percent
:param file_list: list to get a subset of
:param split_percent: percentage of files to split off and return, must be between 1 and 99
:returns: randomly selected subset of list
"""
try:
assert 0 <= split_percent <= 100
assert isinstance(split_percent, float) or isinstance(split_percent, int)
except AssertionError:
logging.error(f"Expected float between 0 and 100, got {split_percent}")
# How many files to split
split_num = int(len(file_list) * (split_percent / 100))
assert (
split_num > 0
), "Split percentage and/or number of files not big enough to create a test split."
# Seed random for predictable output
random.seed(9)
# Guarantees selection without replacement (no duplicates in output set given no duplicates in input set)
random_files = random.sample(file_list, split_num)
return random_files
def test_split_directory(
input_directory: str, split_percent: float, output_directory: str
) -> Tuple:
"""
Move files or directories from input dir to output dir to separate training and test
information.
Looks for all files in the input directory, checks they are all of the same type.
This means either all directories, or all files with the same file extension.
Randomly selects split_percent % of them to be moved to the output directory.
Random number generator is seeded so this is a deterministic translation.
Copies selected files to output directory then deletes.
This ensures that all copying is completed before any deletion takes place.
If there is an error during copying then function can be ran again with same
parameters (once error is fixed).
If the input directory contains subdirectories, they will be moved recursively.
Returns a tuple of the new file locations.
:param input_directory: directory to randomly select from
:param split_percent: percentage (0-100) of files to move
:param output_directory: new location for selected files
:return: tuple of new file locations
"""
logging.info(
f"Performing test split of {split_percent}% of files from {input_directory} to {output_directory}"
)
try:
input_dir_path = Path(input_directory)
assert input_dir_path.exists()
except (TypeError, AssertionError):
logging.error(f"Expected existing input directory, got {input_directory}")
raise
assert (
input_directory is not output_directory
), f"Expected different input and output directory, got {input_directory} and {output_directory}"
# Get list of files in directory
input_files = [file for file in input_dir_path.iterdir()]
assert len(input_files) > 0, f"Found no files in {input_dir_path}"
logging.info(f"Found {len(input_files)} files/dirs to be randomly selected from")
# Check files are all consistent with one another
# Gets the set of whether files are directories or not, as they should all be the same
# this is a straightforward comparison to the expected sets
all_directories = set([file.is_dir() for file in input_files])
assert all_directories == {True} or all_directories == {
False
}, f"Expected all directories or all files in {input_directory}, got mixture"
# Gets the set of all file extensions, there should only be one
# Directories return "" which will also suffice
file_extensions = set([file.suffix for file in input_files])
assert (
len(file_extensions) == 1
), f"Expected single file type in {input_directory}, got {file_extensions}"
# Perform the split
selected_files = test_split(input_files, split_percent)
logging.info(f"Randomly selected {len(selected_files)} files/dirs to be moved")
# Use different functions depending on whether using files or directories
# More options could be added in the future if there is need for special handling
# selected_files should have at least 1 value so safe to check
if Path(selected_files[0]).is_dir():
copied_file_locations = copy_directories(selected_files, output_directory)
# Remove the original directories
logging.info(f"Removing directories from {input_directory}")
for directory in selected_files:
shutil.rmtree(directory)
else:
copied_file_locations = copy_files(selected_files, output_directory)
# Remove the original files
logging.info(f"Removing files from {input_directory}")
for file in selected_files:
os.remove(file)
return copied_file_locations
def copy_files(file_list: Tuple, destination: str) -> Tuple:
"""Takes a list of files and copies them to the destination"""
logging.info(f"Copying files to {destination}")
try:
# shutil.copy returns the file destination
new_file_locations = [shutil.copy(file, destination) for file in file_list]
except shutil.SameFileError:
logging.error(
f"Source file and destination file are the same when copying to {destination}"
)
raise
except OSError:
logging.error(f"Error copying to {destination}")
raise
return new_file_locations
def copy_directories(dir_list: Tuple, destination: str) -> Tuple:
"""
Takes a list of directories and copies their trees to the destination with their name as the top
level directory.
Example: copy_directories(["/my/stuff"], "your") copies to "/your/stuff".
**Note:** The destination file should be empty as shutil.copytree will not work if there is already
a file or directory at the destination path.
Returns a list of the new top level file locations
"""
logging.info(f"Copying directory trees to {destination}")
try:
# shutil.copytree returns the file destination
new_file_locations = [
shutil.copytree(directory, (Path(destination) / Path(directory).name))
for directory in dir_list
]
except FileExistsError as e:
logging.error(
f"File or directory already exists at {e.filename}, so cannot overwrite"
)
raise
except OSError:
logging.error(f"Error copying to {destination}")
raise
return new_file_locations
def command_line():
"""Command line wrapper for test_split_directory"""
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(
description="Tool to randomly select a number of files/ or directories from an input directory and move them to the output directory. "
"Random number generator is seeded so this is a repeatable process given the same file inputs. "
"Input directory must contain either all directories or all files of the same type. "
"This helps to prevent unwanted files from affecting the test split produced."
)
parser.add_argument("input_dir", type=str, help="directory to move files/dirs from")
parser.add_argument(
"output_dir", type=str, help="selected files/dirs will be moved here"
)
parser.add_argument(
"--split_percent",
type=float,
default=5.0,
help="percentage of files/dirs to randomly select and move",
)
args = parser.parse_args()
# Execute function
new_file_locations = test_split_directory(
args.input_dir, args.split_percent, args.output_dir
)
print(
f"Successfully moved {len(new_file_locations)} files/dirs from {args.input_dir} to {args.output_dir}"
)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
command_line()
|
ac28cbc95a4faabc5b5d816c451d98bffe43cee4 | simrankaurkhaira1467/Training-with-Acadview | /assignment9.py | 3,482 | 4.3125 | 4 | #ASSIGNMENT ON CLASSES
#question 1: Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
class Circle():
def __init__(self, radius):
self.radius=radius
def getArea(self):
print("Area is : " + str(3.14 * self.radius * self.radius))
def getCircumference(self):
print("Circumference is: " + str(2 * 3.14 * self.radius))
obj=Circle(float(input("Enter the radius:")))
obj.getArea()
obj.getCircumference()
#question 2: Create a Student class and initialize it with name and roll number. Make methods to:
# 1.Display: It should display all information of the student.
class Student():
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def display(self):
print(self.name)
print(self.rollno)
obj=Student(input("Enter the name of student:"),input("Enter his/her roll number:"))
obj.display()
#question 3: Create a Temperature class. Make two methods:
#1. convertFahrenheit: It will take celsius and will print it into Fahrenheit.
#2. conertCelsius: It will take Fahrenheit and will convert it into celsius.
class Temperature():
def convertFahrenheit(self, celsius):
print("Temperature in Fahrenheit is :" + str((celsius * (9/5) +32)))
def convertCelsius(self, fahrenheit):
print("Temperature in Celsius is :" + str((fahrenheit-32) * (5/9)))
obj=Temperature()
obj.convertFahrenheit(float(input("Enter temperature in celsius:")))
obj.convertCelsius(float(input("Enter temperature in fahrenheit:")))
#question 4: Create a class MovieDetails and initialize it with Movie name, artist name, Year of release and ratings.
#1. Display: Display the details.
#2. Update: Update the movie details.
class MovieDetails():
def _init_(self,moviename,artistname,yearofrelease,ratings):
self.moviename=moviename
self.artistname=artistname
self.yearofrelease=yearofrelease
self.ratings=ratings
def display(self):
print("Movie name is :" +str(self.moviename))
print("Artist name is :" + str(self.artistname))
print("Year of release is :" + str(self.yearofrelease))
print("Rating is :" + str(self.ratings))
def update(self):
self.moviename=input("enter updated Movie name:")
self.artistname=input("enter updated Arist name:")
self.yearofrelease=input("enter updated year of release")
self.ratings=input("enter updated ratings:")
obj=MovieDetails('YJHD','DEEPIKA','2013','7')
obj.display()
obj.update()
obj.display()
#question 5: Create a class Expenditure and initialize it with expenditure, savings. Make the following methods:
#1. Display expenditure and savings.
#2. Calculate total salary.
#3. Display salary.
class Expenditure():
def __init__(self,expenditure,savings):
self.expenditure=expenditure
self.savings=savings
def display(self):
print("The Expenditure is: " + str(self.expenditure))
print("The Savings are" + str(self.savings))
def totalsalary(self):
Expenditure.totalsalary=self.expenditure+self.savings
def display_totalsalary(self):
print("Total salary is:" + str(self.totalsalary))
obj=Expenditure(input("\nEnter Expenditure:"), input("Enter savings:"))
obj.display()
obj.totalsalary()
obj.display_totalsalary()
|
8043f03708063ede50be2f30a08a1cecdae3816a | jojojames/Python | /mergeList.py | 1,320 | 3.609375 | 4 | def mergeList(aList, bList):
"""@todo: Docstring for mergeList.
:aList: @todo
:bList: @todo
:returns: @todo
"""
aIndex = 0
bIndex = 0
aLen = len(aList)
bLen = len(bList)
mergedList = []
while aIndex != aLen and bIndex != bLen:
if aList[aIndex] < bList[bIndex]:
tryToAppend(mergedList, aList[aIndex])
aIndex = aIndex + 1
elif aList[aIndex] > bList[bIndex]:
tryToAppend(mergedList, bList[bIndex])
bIndex = bIndex + 1
else:
tryToAppend(mergedList, aList[aIndex])
aIndex = aIndex + 1
bIndex = bIndex + 1
if not aList:
addRestToMergedList(mergedList, bList, bIndex)
if not bList:
addRestToMergedList(mergedList, aList, aIndex)
return mergedList
def addRestToMergedList(mergedList, restList, index):
sizeList = len(restList)
while index != sizeList:
mergedList.append(restList[index])
index = index + 1
def tryToAppend(mergedList, item):
if not mergedList or mergedList[-1] != item:
mergedList.append(item)
def main():
aList = [10, 20, 21, 21, 33, 44, 55, 600, 7000, 8000]
bList = [20, 30, 30, 400, 559, 652, 701, 80000]
mergedList = mergeList(aList, bList)
print mergedList
main()
|
e688daaf5690251e18be02ee121826bb81f35298 | han-shang/AID2018 | /thread02.py | 460 | 3.78125 | 4 | from threading import Thread
from threading import Lock
lock1 = Lock()
lock2 = Lock()
def print_numbers():
for i in range(1,53,2):
lock1.acquire()
print(i)
print(i+1)
lock2.release()
def print_abc():
for i in range(65,91):
lock2.acquire()
print(chr(i))
lock1.release()
t1 = Thread(target=print_numbers)
t2 = Thread(target=print_abc)
lock2.acquire()
t1.start()
t2.start()
t1.join()
t2.join() |
ae6ec8ad898a16dd4aaf6144590046097123c231 | vyaswanth965/Parent-reports | /Parent_reports_process/launch_instances.py | 750 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 14:02:41 2020
@author: EILAP6621
auto launch EC2 instance
"""
import boto3
aws_access_key_id= 'AKIA4TXJH6XFLQANY3FQ'
aws_secret_access_key= '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'
ec2 = boto3.resource('ec2',region_name='ap-south-1',aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)
# dynamic instances
# maxCount = int(input("Enter number of instances to be launched"))
maxCount = 1
# create a new EC2 instance
instances = ec2.create_instances(
ImageId='ami-0418b263587ac2161',
MinCount=1,
MaxCount=maxCount, # number of instance to be launched
InstanceType='t2.micro',
KeyName='autoLaunchKeypair'
)
# get instance ID
print(instances[0].instance_id)
|
11984873882273abd211f61c6d5bd4420f6672ea | Ovidiu2004/rezolvarea-problemelor-if-while-for | /if_while_for_8.py | 475 | 3.875 | 4 | a=eval(input("a = "))
b=eval(input("b = "))
c=eval(input("c = "))
if (a>0 and b>0 and c>0):
if ((a<b+c) and (b<a+c) and (c<a+b)):
if ((a==b==c)):
print ("triunghi echilateral")
if (((a==b) and (a!=c)) or ((b==c) and (b!=a)) or ((a==c) and (a!=b))):
print ("triunghi isoscel")
if (a!=b!=c):
print ("triunghi scalen")
else:
print("fals")
else:
print("lungimea nu poate fi negativa") |
7d93fa640bc47ca903e47c19038dd34a5cc616db | kyleetaan/git-pythonmasterclass | /src/basics/sets.py | 421 | 3.90625 | 4 | # farm_animals = {"sheep", "cows", "chickens"}
# for animal in farm_animals:
# print(animal)
# print("=" * 40)
# farm_animals.add("jobert")
# print(farm_animals)
even = set(range(0, 40, 2))
print(even)
print(len(even))
print()
squares = {1, 4, 9, 16, 25}
print(squares)
print(len(squares))
print()
print(even.union(squares))
print(len(even.union(squares)))
print(even & squares)
print(squares.intersection(even)) |
c9dd13cdf272967325f62d536eef68ff385be3bf | twaun95/Algorithm | /이진트리/BnSearch_1.py | 737 | 3.859375 | 4 | #리스트 내에서 원하는 원소의 위치 찾기
#이진탐색
#재귀함수
def binary_search(array, target, start, end):
#원소가 존재하지 않을 때 start와 end 가 교차한 순간
if end < start:
return None
#중간값을 구하고 소숫점 내림
mid = (end + start) // 2
if target == array[mid]:
return mid+1
elif target > array[mid]:
return binary_search(array, target, mid + 1, end)
else:
return binary_search(array, target, start, mid-1)
n, target = list(map(int, input().split()))
array = list(map(int, input().split()))
result = binary_search(array, target, 0, n-1)
if result == None:
print("원소가 존재하지 않습니다.")
else:
print("타겟의 위치: ", result)
|
c8225a2c3803ec07acec492c44775abd439c62bb | ConradKilroy/DataJoy_Python | /3DLinePlot.py | 2,037 | 3.796875 | 4 | # First the required libraries are imported:
# * `Axes3D` allows adding 3d objects to a 2d matplotlib plot.
# * The `rcPArams` method to customize the legend font size.
# * The `pyplot` submodule from the **matplotlib** library, a python 2D
# plotting library which produces publication quality figures.
# * The `numpy` library for efficient numeric-array manipulation
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import rcParams
import matplotlib.pyplot as plt
import numpy as np
# First, we set up the data to plot. This will create a spiral whirling around
# the z-axis. The `linspace()` function creates 300 points evenly spaced
# between -4pi and 4pi.
theta = np.linspace(-4 * np.pi, 4 * np.pi, 300)
x = np.cos(theta)
y = np.sin(theta)
# To create the plot a new set of 3D-axes is created, afterwards the `plot()`
# routine is used with a few extra parameters to tune up its appearance. For
# the colour of the curve it is possible to use either **html colour names**,
# **html hexadecimal** codes or 3-tuples representing **rgb values**.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, theta,
label = 'Parametric Curve', # label of the curve
color = 'DarkMagenta', # colour of the curve
linewidth = 3.2, # thickness of the line
linestyle = '--' # available styles - -- -. :
)
rcParams['legend.fontsize'] = 11 # legend font size
ax.legend() # adds the legend
# The code below sets the axes bounds and the axes labels.
ax.set_xlabel('X axis')
ax.set_xlim(-1.2, 1.2)
ax.set_ylabel('Y axis')
ax.set_ylim(-1.2, 1.2)
ax.set_zlabel('Z axis')
ax.set_zlim(-4*np.pi, 4*np.pi)
# Finally the plot title, the camera elevation, angle and distance are set.
ax.set_title('3D line plot,\n parametric curve', va='bottom')
ax.view_init(elev=18, azim=-27) # camera elevation and angle
ax.dist=9 # camera distance
plt.show() # display the plot
|
7c45fa33d85577d89244433b86887d3e18199329 | nima1367/Test---VolumeCalculator | /VolumeCalculator/Face.py | 953 | 3.765625 | 4 | import numpy as np
import math
class Face:
""" Constructor of the Face class"""
def __init__(self, vertices):
""" NormalFinder function finds the normal vector
of the given polygonal face (the result is not normalizd)
"""
def NormalFinder(vertices):
edge1 = np.subtract(vertices[0], vertices[2])
edge2 = np.subtract(vertices[1], vertices[0])
return np.cross(edge1, edge2)
self.Vertices = vertices
initialNormal = NormalFinder(vertices)
# this line calculates the magnitude of the cross product
crossMagn = math.sqrt(sum(initialNormal[i]*initialNormal[i] for i in range(3)))
# Normalize the obtained normal vector:
self.Normal = np.divide(initialNormal, crossMagn)
# the area of a triangle is the magnitude of the crosss product of two of its edges
self.Area = crossMagn/2.0 |
7a6c53c12700a536c3c02f3269d92c35459be5a0 | RickyL-2000/python-learning | /business/方方/作业3/problem3.py | 643 | 3.515625 | 4 | import random
print("作业5:统计分数出现次数")
scores = []
for i in range(1000):
scores.append(random.randint(0, 100))
counter = {}
for score in scores:
if score in counter:
counter[score] += 1
else:
counter[score] = 1
counter = sorted(counter.items(), key=lambda x: x[1], reverse=True)
for item in counter:
print(item[0], item[1])
number = -1
for item in counter:
if number != item[1]:
if number != -1:
print() # 去掉两段之间的空行
number = item[1]
print("次数", number, ":", item[0], end='')
else:
print(",", item[0], end='')
|
d4fa47260d7f656cff1aff15d34c6c71740df069 | Ania9/dip_example | /dip_29-135/e4_22.py | 91 | 3.578125 | 4 | def f(x):
return x*2
print f(4)
g= lambda x: x*2
print g(4)
print (lambda x: x*2)(4) |
cbaeda882d6c8137a2540923f7d8294ccb4fd13a | edprince/uni | /210/old-lab/substring.py | 307 | 3.765625 | 4 | def substring(s, b, l):
return s[0:b] + s[b+l:len(s)]
userString = raw_input('Please enter a string: ')
startSplice = int(input('Please enter the index of start of substring: '))
spliceLength = int(input('Enter the length of the splice sub: '))
print(substring(userString, startSplice, spliceLength))
|
63e1f1b2681e962c6604f5bd1560e8708a393e79 | vekergu/ops_doc | /learn_python/python练习100题/071-input-output.py | 1,145 | 3.734375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#=============================================================================
# FileName:
# Desc:
# Author: 白开水
# Email: [email protected]
# HomePage: https://github.com/vekergu
# Version: 0.0.1
# LastChange:
# History:
#=============================================================================
from __future__ import print_function
'''
题目:编写input()和output()函数输入,输出5个学生的数据记录。
程序分析:无。
'''
N = 3
#stu
#num : string
#name : string
#score[4] : list
student = []
for i in range(5):
student.append(['','',[]])
def input_stu(stu):
for i in range(N):
stu[i][0] = raw_input('input student num:\n')
stu[i][1] = raw_input('input stdent name:\n')
for j in range(3):
stu[i][2].append(int(raw_input('score:\n')))
def output_stu(stu):
for i in range(N):
print('%-6s%-10s' %(stu[i][0],stu[i][1]))
for j in range(3):
print('%-8'%stu[i][2][j])
if __name__ == '__main__':
input_stu(student)
print(student)
output_stu(student) |
b9f100619beb5f5db1ac24aa21e495c92699f406 | xw0220/pythoncourse | /experiment4/test6.py | 196 | 3.859375 | 4 | n=input("please input an integer:")
n=int(n)
factor=1
i=1
while i<=n:
print('{}*{}={}'.format(factor,i,factor*i))
factor=factor*i
i=i+1
print("the factor is:",factor)
print("baihu")
|
0a45ba854255bc83f24db180e117fd7305ee9132 | DroogieDroog/pirple_python_is_easy | /hw8/main.py | 4,298 | 4.34375 | 4 | """
pirple/python/hw8/main.py
Homework Assignment #8
Create a note-taking program that allows you to do the following
to files of notes:
1) Create a new one
2) Read one
3) Replace one completely
4) Append to one
5) Replace a single line in one
"""
import os.path as path
def create_new_file(new_file):
new_note = input('Enter the note you wish to save: ')
with open('data/' + new_file, "w") as note_file:
note_file.write(new_note + '\n')
def read_file(file_name, full_path):
print('Current contents of file {}.:'.format(file_name))
with open(full_path, 'r') as note_file:
print(note_file.read(), end='')
print('\b<END OF {}>\n'.format(file_name.upper()))
def replace_file(file_name):
print('Replacing file {} completely with newly entered notes.'.format(file_name))
create_new_file(file_name)
print('File {} has been replaced with new notes\n'.format(file_name))
def append_file(file_name, full_path):
print('Appending to file {}.'.format(file_name))
new_note = input('Enter the note you wish to append: ')
with open(full_path, 'a') as note_file:
note_file.write(new_note + '\n')
print('Note added to file {}\n'.format(file_name))
def replace_line(file_name, full_path):
with open(full_path, 'r') as note_file:
curr_notes = note_file.readlines()
line_choice = int(input('Enter the line number you want to replace in file {}: '.format(file_name)))
print('The current note on line {} of file {} is:'.format(str(line_choice), file_name))
print(curr_notes[line_choice - 1])
new_note = input('Enter the new note: ')
curr_notes[line_choice - 1] = new_note + '\n'
with open(full_path, 'w') as note_file:
for note in curr_notes:
note_file.write(note)
print('New note replaced line {} in file {}\n'.format(line_choice, file_name))
def process_existing_file(file_name, full_path):
print('File {} already exists'.format(file_name))
exit_menu = False
bad_choice = True
while bad_choice:
choice = input('Would you like to (1) Read the file\n'
' (2) Replace the file\n'
' (3) Add to the file\n'
' (4) Change a line in the file\n'
' (x) Exit\n?: ')
if choice.upper() == 'X':
exit_menu = True
bad_choice = False
elif choice not in ('1', '2', '3', '4'):
print('Your choice needs to be 1-4 or x\n')
bad_choice = True
elif choice == '1':
read_file(file_name, full_path)
bad_choice = False
elif choice == '2':
replace_file(file_name)
bad_choice = False
elif choice == '3':
append_file(file_name, full_path)
bad_choice = False
elif choice == '4':
replace_line(file_name, full_path)
bad_choice = False
if not exit_menu and not bad_choice:
correct_choice = False
while not correct_choice:
yn = input('Do you wish to process file {} further (y/n)? '.format(file_name))
if yn.upper() not in ('Y', 'N'):
print('Please respond with with a y or n.')
correct_choice = False
elif yn.upper() == 'Y':
correct_choice = True
bad_choice = True
else:
correct_choice = True
return exit_menu
def exit_program():
print('Goodbye!')
return 1
def main():
done = 0
while not done:
choice = input('Enter the file you wish to work on, or an x to Exit: ')
if choice.upper() == 'X':
done = exit_program()
elif path.isfile('data/' + choice):
exit_menu = process_existing_file(choice, 'data/' + choice)
if exit_menu:
done = exit_program()
else:
print('Creating a new file named', choice)
create_new_file(choice)
print('File {} has been updated and saved!'.format(choice))
print()
done = exit_program()
main() |
1e01c4af189960135a4eb8f9b31b3ba06882f373 | chungtseng/rosalind-1 | /code/GreedySort.py | 891 | 3.671875 | 4 | import sys
import os
def flip(array, num):
ind = [abs(el) for el in array].index(num)
reverse = [-el for el in array[num - 1:ind + 1][::-1]]
return array[:num - 1] + reverse + array[ind + 1:]
def perm_print(permutation):
print '(%s)' % ' '.join(str(el) if el < 0 else '+' + str(el) for el in permutation)
def greedy_sort(permutation):
for i in range(len(permutation)):
if abs(permutation[i]) != i + 1:
permutation = flip(permutation, i + 1)
perm_print(permutation)
if permutation[i] == -(i+1):
permutation = flip(permutation, i + 1)
perm_print(permutation)
return permutation
def main():
with open(sys.argv[1], "r") as f:
raw_str = f.readline().strip('()\n').split()
permutation = [int(el) for el in raw_str]
greedy_sort(permutation)
if __name__ == '__main__':
main() |
e64a87a732480b36eab9b59e11021f7122afec2d | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/nDruP/lesson03/mailroom.py | 4,267 | 4.25 | 4 | #!/usr/bin/env python3
"""
1. Create Data structure that holds Donor, Donation Amount.
2. Prompt user to Send a Thank You, Create a Report, or quit.
3. At any point, the user should be able to quit their current task and return
to the original prompt
4. From the original prompt, the user should be able to quit the scipt cleanly
"""
import sys
def send_thanks():
"""
Prompt for a full name.
Prompt->"list": show a list of the donor names
Prompt->name not in list: add name to list;
Then prompt for donation amount, add amount to donation history
Compose and print an email thanking the donor for their donation.
Return to main
"""
donor_name = "list"
donation_amt = None
print("Let's craft a very personal thank you note for our donor!")
print("Return to the main menu at any time by entering 'exit'")
print("Pull up a list of donor names by entering 'list'")
while donor_name == "list":
donor_name = input("Enter Donor Name >")
if donor_name.lower() == "list":
print(("{}\n"*len(name_list)).format(*name_list))
elif donor_name.lower() == "exit":
return
while not donation_amt:
donation_amt = input("Enter their Donation Amount >")
if donation_amt.lower() == "exit":
return
donation_amt = float(donation_amt)
if donor_name not in name_list:
donor_list.append([donor_name, [donation_amt]])
else:
donor_list[name_list.index(donor_name)][1].append(donation_amt)
print_divider()
message = f"Dearest {donor_name},\n"
message += f"Thank you so much for your donation of ${donation_amt:.2f}!\n"
message += "We will use this for something wonderful. Something...\n"
message += "Fantastic\n"
message += "Shrek was supposed to have 5 movies. We're going to make that"
message += " a reality."
message += f"\nSincerely,\n We're a Pyramid Scheme and so is {donor_name}"
print(message)
return
def create_report():
"""
Print a list of donors sorted by total historical donation amount.
Donor Name, Total Given, Num Gifts, Average Gift
"""
donation_list = list(enumerate([x[1] for x in donor_list]))
donation_list = sorted(donation_list, key=sum_2ple_2, reverse=True)
name_col_len = max([len(x) for x in name_list])
money_col_len = 12
headers = ["Donor Name", "Total Given", "# of Gifts", "Avg Donation"]
cols = "{:<" + f"{name_col_len}" + "}\t|{:^" + f"{money_col_len+5}"
cols += "}|{:^10}|{:^" + f"{money_col_len+5}" + "}"
cols = cols.format(*headers)
print(cols)
print("-"*len(cols))
for index, donation in donation_list:
name = name_list[index]
total = sum(donation)
num_gift = len(donation)
average = total/num_gift
row = f"{name:<{name_col_len}}\t| ${total:>{money_col_len+3}.2f}|"
row += f"{num_gift:^10d}| ${average:>{money_col_len+3}.2f}"
print(row)
return
def sum_2ple_2(tuples):
"""
Sum of a 2-ple's second element
"""
return sum(tuples[1])
def print_divider():
"""
Prints a divider so user has better idea of when they enter a new screen.
"""
print("\n"+"*"*50+"\n")
def main_menu():
user_prompt = None
valid_prompts = ["1", "2", "3"]
while user_prompt not in valid_prompts:
print("Please choose from the following options (1,2,3): ")
print("1. Send a Thank you")
print("2. Create Donor Report")
print("3. Quit")
user_prompt = input(">")
return int(user_prompt)
donor_list = [["Sleve McDichael", [86457.89, 2346.43, 9099.09]],
["Willie Dustice", [505.05, 43.21]],
["Rey McScriff", [666.00]],
["Mike Truk", [70935.30, 12546.70, 312.00]],
["Bobson Dugnutt", [1234.56, 789.00]],
["Todd Bonzalez", [715867.83, 10352.07]]]
name_list = [x[0] for x in donor_list]
option = 0
print_divider()
print("We're a Pyramid Scheme and So Are You! E-Mailroom")
while option != 3:
name_list = [x[0] for x in donor_list]
print_divider()
option = main_menu()
if option == 1:
print_divider()
send_thanks()
elif option == 2:
print_divider()
create_report()
print_divider()
sys.exit()
|
3b05728bbd3a045acf0f742803d867ce2f2de374 | green-fox-academy/marijanka | /week-4/Monday/double.py | 79 | 3.609375 | 4 | af = 123
def double(number):
return number * 2
af = double(af)
print(af)
|
01c18b4421a46a91e48eb94b585143253d93a9da | lollipopnougat/AlgorithmLearning | /力扣习题/208实现 Trie (前缀树)/problems.py | 1,154 | 3.890625 | 4 | class Node:
def __init__(self, v: str, end = False):
self.value = v
self.child = {}
self.end = end
class Trie:
def __init__(self):
self.root = Node(None)
def insert(self, word: str) -> None:
p = self.root
l = len(word)
i = -1
for i in range(l - 1):
if word[i] not in p.child:
p.child[word[i]] = Node(word[i])
p = p.child[word[i]]
i += 1
if word[i] not in p.child:
p.child[word[i]] = Node(word[i], True)
else:
p.child[word[i]].end = True
def search(self, word: str) -> bool:
p = self.root
l = len(word)
i = -1
for i in range(l - 1):
if word[i] not in p.child:
return False
p = p.child[word[i]]
i += 1
if word[i] not in p.child:
return False
return p.child[word[i]].end
def startsWith(self, prefix: str) -> bool:
p = self.root
for i in prefix:
if i not in p.child:
return False
p = p.child[i]
return True |
ee6dcd67c8e2749602919d82a72ffa774c1608d4 | sh2268411762/Python_Three | /SXB/venv/函数/函数的定义.py | 614 | 4.03125 | 4 | # 例 6-1
def sayHello(): # 函数定义
print("Hello World!") # 函数体
sayHello() # 函数调用
# 例 6-2
def sayHello1(s): # 函数定义
print(s) # 函数体
sayHello1("Hello!") # 函数调用
sayHello1("How are you?")
# 例 6-3
def fac(num):
if num == 1:
return 1
elif num < 1:
return 0
else:
ret = 1
while num > 1:
ret *= num
num -= 1
return ret
print(6, "!=", fac(6), sep="")
print(16, "!=", fac(16), sep="")
print(26, "!=", fac(26), sep="")
print(0, "!=", fac(0), sep="")
print(1, "!=", fac(1), sep="")
|
816bbba05e41fddc8c2cc7068ec0ad0b5652e8e8 | jollywing/jolly-code-snippets | /algorithm/insertion_sort.py | 688 | 4.09375 | 4 |
# Knowledges:
# insertion
# function define
# for loop
# range()
# if statement
# swap 2 objects
# print
def insertion_sort(a):
for i in range(1, len(a)):
for j in range(i, 0, -1):
if a[j] < a[j-1]:
t = a[j]
a[j] = a[j-1]
a[j-1] = t
else:
break
a = [1.1, -10, -300.33, 1E-2]
print('the given list is {}'.format(a))
insertion_sort(a)
print('After insertion sorting, it become into {}.'.format(a))
names = ["Wu", "Li", "Zhang", "Zhao", "Wan", "Cheng"]
print('the given list is {}'.format(names))
insertion_sort(names)
print('After insertion sorting, it become into {}.'.format(names))
|
3878351a762f5b47a3e40b93b290cfc95583f914 | Mahadevan007/myrepository | /noofnumeric.py | 103 | 3.8125 | 4 | string = input()
count = 0
for i in string:
if i.isdigit():
count = count + 1
print(count)
|
ea36a9c0396673b92f5e09b174db83b6c4a3af18 | nicosoncin/ThisIsCodingTest | /Binary Search/7-7.py | 220 | 3.546875 | 4 | n = int(input())
array = set(map(int, input().split()))
m = int(input())
targets = list(map(int, input().split()))
for target in targets:
if target in array:
print('yes', end=' ')
else:
print('no', end=' ') |
05c209d39842b010e5ba4a965d472f3fdf210317 | PragayanParamitaMohapatra/Basic_python | /MCQ/replace.py | 36 | 3.671875 | 4 | a="ABCD"
print(a.replace("AC","XY")) |
531f8d1ba3c0ca9dd434bf95e66eff5e26785746 | GriszaKaramazow/codewars-python | /6kyu - Write Number in Expanded Form.py | 925 | 4.1875 | 4 | # You will be given a number and you will need to return it as a string in Expanded Form. For example:
#
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
# NOTE: All numbers will be whole numbers greater than 0.
def expanded_form(num):
outcome = list()
for i in range(len(str(num))):
outcome.append(str((num % 10) * (10 ** i)))
num = int((num - (num % 10)) / 10)
return " + ".join(list(x for x in outcome[::-1] if x != "0"))
tests = ((12, "10 + 2"),
(42, "40 + 2"),
(70304, "70000 + 300 + 4"))
for test in tests:
test_outcome = expanded_form(test[0])
if test_outcome == test[1]:
print("\t{} is {}, test passed!".format(test_outcome, test[1]))
else:
print("!!! {} is not {}, wrong output!".format(test_outcome, test[1]))
|
02fc6d4408a665b388ed5354e261aa4adda635c3 | sammycosta/uri-python | /uri_2927.py | 518 | 3.5625 | 4 | # URI Online Judge | 2927
#A -> alunos \\ C -> computadores \\ X -> pc queimados por Caio \\ Y -> pc sem compilador
# nome: Samantha Costa
A, C, X, Y = [int(x) for x in input().split()]
pcs_disponiveis = C - (X+Y) - 1 #-1 é o pc que o prof vai usar.
resultado = 'default'
if 0 < A and Y and X <= C <= 1000:
if pcs_disponiveis >= A:
resultado = 'Igor feliz!'
elif A > pcs_disponiveis:
resultado = 'Igor bolado!'
if X > (Y/2):
resultado = 'Caio, a culpa eh sua!'
print(resultado) |
fa18256c47c366ae913db23c79da48a6d923d052 | chrido/i13monclient | /dto/temphdatatypes.py | 1,914 | 3.671875 | 4 | import uuid
class TempHumidityMeasurements:
"""
This class represents a measurement from
temperature humidity sensor
default Node: 19, 22, 23, 24
"""
def __init__(self, ts, temp, temp_external, humidity, battery):
"""
:param ts: timestamp in the format of datetime.now()
:param temp: float representing measurement of the temperature
:param temp_external: float representing measurement of the external temperature
:param humidity: float representing measurement of the humidity (relative)
:param battery: float representing measurement of the battery
:return:
"""
# the id of the record which will be stored in the database
self.id = uuid.uuid4()
# the UUID which represents the device itself
self.deviceid = None # todo macaddress or device id?
self.type = 'temp_hum_measurement'
self.ts = ts
self.temp = temp
self.temp_external = temp_external
self.humidity = humidity
self.battery = battery
def standardize(self, name, rate):
"""
standardize the atr name by rate
:param name:
:param rate:
:return:
"""
if name in self.__dict__:
if name == 'temp':
self.temp = self.temp * rate
elif name == 'temp_external':
self.temp_external = self.temp_external * rate
elif name == 'humidity':
self.humidity = self.humidity * rate
elif name == 'battery':
self.battery = self.battery * rate
elif name == 'all':
self.temp = self.temp * rate
self.temp_external = self.temp_external * rate
self.humidity = self.humidity * rate
self.battery = self.battery * rate
else:
raise AttributeError(name)
def __str__(self):
return """#type:temp_hum_measurement#ts:%s#deviceid:%s#temprature:%s
#external_temp:%s#humidity:%s#battery:%s""" % (self.ts, self.deviceid,
self.temp, self.temp_external,
self.humidity, self.battery)
|
d7359f7e8d8a422bfb827f481c1d12e538a69f09 | masci/playground | /cstutoring/003.py | 633 | 3.78125 | 4 | """
If there are 3 people in a room, the probability of two of those people having
THE SAME birthday is 0.008. For 4 people, it is 0.016 and for 5 people, it is
0.027.
Using the same rule of at least two people in a room of size 25, what is the
probability (rounded to the nearest 1000th) of two people having THE SAME
BIRTHDAY?
For the purpose of the calendar, there are 365 days in the year (Feb. 29th is
counted a Mar. 1st).
"""
def different_bd(n):
if n==1:
return 1
else:
return different_bd(n-1) * (365. - (n-1)) / 365
def main():
print 1 - different_bd(25)
if __name__ == "__main__":
main()
|
8511bb25ad9766ad356ae8c21c28e9d094eeafcc | sahilganguly/pynet_test | /exercise17.py | 310 | 3.65625 | 4 | #!/usr/bin/env python
def Function(x, y, z=20):
return (x + y + z);
print "Sum: {}".format(Function(1, 5, 10))
print "Sum: {}".format(Function(x=1, y=5))
print "Sum: {}".format(Function(1, y=5, z=20))
print "Sum: {}".format(Function('I', 'am', 'Groot'))
print "Sum: {}".format(Function([1], [5], [100]))
|
35850b5230d9e5274648b749f5902fe894980a67 | amymhaddad/cs_and_programming_using_python | /week3_exercises/how_many_ex.py | 290 | 3.75 | 4 |
animals = {
'a': ['aardvark'],
'b': ['baboon'],
'c': ['coati'],
'd': ['donkey', 'dog', 'dingo'],
}
def how_many(aDict):
count = 0
for anim in animals:
len_values = len(animals[anim])
count += len_values
return count
print(how_many(animals))
|
3c392d9426baefac70db93a3c090dbcdd7e37f34 | kehsan/python-games-2014 | /pong.py | 7,030 | 4.125 | 4 | # Implementation of classic arcade game Pong
###### The program should be loaded on to ####
###### http://www.codeskulptor.org/ to be able to run ####
## The classic Ping-pong video game from the 70s
## Up and Down Arrow for the right player to move the pad
## 'w', 's' key for the left player to move the pad
## Hit 'New Game' button to start the game
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
#
paddle1_pos= HEIGHT/2
paddle2_pos= HEIGHT/2
paddle1_vel = 0
paddle2_vel = 0
#
ball_pos = [WIDTH/2, HEIGHT/2]
ball_vel=[0,0]
#
left_score = 0
right_score = 0
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH/2, HEIGHT/2]
if direction == "RIGHT":
ball_vel[1] = ball_vel[1] * -1
if direction == "LEFT":
ball_vel[0] = ball_vel[0] * -1
ball_vel[1] = ball_vel[1] * -1
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
global left_score, right_score
global ball_vel, ball_pos
paddle1_pos= HEIGHT/2
paddle2_pos= HEIGHT/2
paddle1_vel = 0
paddle2_vel = 0
ball_pos = [WIDTH/2, HEIGHT/2]
ball_vel=[0,0]
left_score = 0
right_score = 0
button.set_text('New Game')
# ball_vel[0] = random.randrange(1, 4)
# ball_vel[1] = random.randrange(4,8)
#it seems that if vel[0] > 4 there is problem
#print 'vel[0] ', ball_vel[0], 'vel[1] ', ball_vel[1]
ball_vel[0] = 4
ball_vel[1] = 11
# need to draw a ball for new game
spawn_ball('RIGHT')
def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
global paddle1_vel, paddle2_vel
global WIDTH, HEIGHT
global PAD_WIDTH, PAD_HEIGHT, HALF_PAD_HEIGHT, HALD_PAD_WIDTH
global left_score, right_score
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
# calculate ball position
ball_pos[0] = ball_pos[0] + ball_vel[0]
ball_pos[1] = ball_pos[1] + ball_vel[1]
#************* this is for hitting the side wall returns that has
if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH :
ball_vel[0] = ball_vel[0] * -1
if ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH:
ball_vel[0] = ball_vel[0] * -1
#
#*******Bouncing off the vertical and the floor ***************
if ball_pos[1] <= BALL_RADIUS :
ball_vel[1] = ball_vel[1] * -1
if ball_pos[1] >= HEIGHT - BALL_RADIUS :
ball_vel[1] = ball_vel[1] * -1
# padd and ball collision
global RIGHT,LEFT
#***** left side
if ball_pos[0] == BALL_RADIUS + PAD_WIDTH:
if (ball_pos[1]>= paddle2_pos - PAD_HEIGHT/2) and (ball_pos[1] <= paddle2_pos + PAD_HEIGHT/2):
ball_vel[1] = (ball_vel[1] +ball_vel[1]*0.1) * -1
ball_pos[1] += ball_vel[1]
#LEFT = True
else:
right_score += 1
LEFT = False
spawn_ball("LEFT")
# ****** right side
if ball_pos[0] == WIDTH - BALL_RADIUS - PAD_WIDTH:
if (ball_pos[1] >= paddle1_pos - PAD_HEIGHT/2) and (ball_pos[1] <= paddle1_pos + PAD_HEIGHT/2):
ball_vel[1] = (ball_vel[1] +ball_vel[1]*0.1) * -1
ball_pos[1] += ball_vel[1]
#RIGHT = True
else:
left_score += 1
RIGHT = False
spawn_ball("RIGHT")
# Start a new game if score is 5
if left_score == 5 or right_score == 5:
#how to stop the game
#button.set_text('Press for new game')
new_game()
pass
# draw ball
#if button.get_text() == 'New Game':
canvas.draw_circle([ball_pos[0], ball_pos[1]], BALL_RADIUS, 10, 'White','white')
# update paddle's vertical position, keep paddle on the screen
# NEED CODE TO STOP THE PADDLE GO OFF THE SCREEN
paddle1_pos += paddle1_vel
paddle2_pos += paddle2_vel
if paddle1_pos <= PAD_HEIGHT/2 :
paddle1_pos = PAD_HEIGHT/2
elif paddle1_pos >= HEIGHT - PAD_HEIGHT/2 :
paddle1_pos = HEIGHT - PAD_HEIGHT/2
if paddle2_pos <= PAD_HEIGHT/2 :
paddle2_pos = PAD_HEIGHT/2
elif paddle2_pos >= HEIGHT - PAD_HEIGHT/2 :
paddle2_pos = HEIGHT - PAD_HEIGHT/2
# draw paddles
canvas.draw_line([WIDTH , paddle1_pos - HALF_PAD_HEIGHT],
[WIDTH , paddle1_pos + HALF_PAD_HEIGHT],
PAD_WIDTH,'White')
canvas.draw_line([0 , paddle2_pos - HALF_PAD_HEIGHT],
[0 , paddle2_pos + HALF_PAD_HEIGHT],
PAD_WIDTH,'White')
# draw scores
#if button.get_text() == 'New Game':
canvas.draw_text(str(left_score), [250, 50], 20, 'Blue')
canvas.draw_text(str(right_score), [350, 50], 20, 'Blue')
def keydown(key):
global paddle1_vel, paddle2_vel
global paddle1_pos, paddle2_pos
up_tick=6
if key == simplegui.KEY_MAP['down']:
paddle1_vel += up_tick
if key == simplegui.KEY_MAP['up']:
paddle1_vel += up_tick * -1
if key == simplegui.KEY_MAP['s']:
paddle2_vel += up_tick
if key == simplegui.KEY_MAP['w']:
paddle2_vel += up_tick * -1
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['up']:
paddle1_vel = 0
if key == simplegui.KEY_MAP['down']:
paddle1_vel = 0
if key == simplegui.KEY_MAP['w']:
paddle2_vel = 0
if key == simplegui.KEY_MAP['s']:
paddle2_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
event=frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
button=frame.add_button('New Game', new_game,100)
# start frame
#new_game()
frame.start()
|
0b6772f72e55f1eaf0671a9a21c75cd1b398cd55 | infexorg/jetstream | /jetstream/calc.py | 1,184 | 3.984375 | 4 | def pathcalc_om(om1, om2, om3, omd):
"""Calculate the path required to reach a target by anchoring waypoints on
orbital markers.
Args:
om1 (float): Distance in km of closest OM to target.
om2 (float): Distance in km of 2nd closest OM to target.
om3 (float): Distance in km of 3rd closest OM to target.
omd (float): Distance in km between adjacent OMs on planetary body.
Returns:
leg1 (float): Distance in km of 1st leg (OM1 -> OM2)
leg2 (float): Distance in km of 2nd leg (OM2 -> OM3)
leg1r (float): Distance in km to OM2 after travelling 1st leg
leg2r (float): Distance in km to OM3 after travelling 2nd leg
"""
# Calculate leg length using OM pathing formulae
leg1 = (om1**2 + omd**2 - om2**2) / (2*omd)
mid = (omd**2 + leg1**2 - omd*leg1)**0.5
leg2 = (omd**2 - omd*leg1 + om1**2 - om3**2) / (2*mid)
# Calculate remaining distance to OMs after travelling leg
leg1r = omd - leg1
leg2r = mid - leg2
# Round all values
leg1 = round(leg1, 1)
leg2 = round(leg2, 1)
leg1r = round(leg1r, 1)
leg2r = round(leg2r, 1)
return leg1, leg2, leg1r, leg2r
|
4ced180a7d4839d8604b0ea2546d1dff6e59942c | josecbm/2PracticaJunio2017_201504231 | /cola.py | 951 | 3.515625 | 4 | import pila
class nodoLista(object):
"""docstring for listaCola"""
def __init__(self,dato):
self.dato =dato
self.siguiente = None
self.aux = None
class listaCola():
global listapila
listapila = pila.pila()
def __init__(self):
self.cabeza = None
def add(self , dato):
nuevoNodo = nodoLista(dato)
if self.cabeza == None:
nuevoNodo.siguiente = None
self.cabeza = nuevoNodo
else:
self.aux = self.cabeza
while self.aux.siguiente!=None:
self.aux = self.aux.siguiente
self.aux.siguiente=nuevoNodo
def recorrer(self):
self.aux = self.cabeza
while self.aux!=None:
print self.aux.dato
listapila.recorrerOperar(self.aux.dato)
self.aux = self.aux.siguiente
def desencolar(self):
if self.cabeza!=None:
aux = self.cabeza
self.cabeza = self.cabeza.siguiente
return aux.dato
#listita = listaCola()
#listita.add("1")
#listita.add("2")
#listita.add("3")
#listita.add("4")
#listita.recorrer() |
a4855e912a3de2795e5395de645a21b765e5837c | erdaibi/niubi | /add_commodity.py | 1,303 | 3.546875 | 4 | class CommodityModel:
def __init__(self, cid, name, price):
self.cid = cid
self.name = name
self.price = price
class CommodityView:
def __init__(self):
self.controlle = CommodityController()
def display_menu(self):
print("1) 获取商品信息")
print("2) 显示商品信息")
print("3) 删除商品信息")
print("4) 修改商品信息")
print("5) 显示最贵商品信息")
def select_menu(self):
while True:
try:
item = int(input("请输入选项:"))
if item == 1:
self.input_commoditys()
except:
print("输入有误")
def input_commoditys(self):
name = input("请输入商品名:")
cid = int(input("请输入商品编号:"))
price = float(input("请输入商品价格:"))
comd = CommodityModel(cid, name, price)
self.controlle.add_commoditys(comd)
class CommodityController:
def __init__(self):
self.list_comd = []
self.comd_target = 1001
def add_commoditys(self, comd_target):
self.comd_target += 1
self.list_comd.append(comd_target)
# 测试添加商品功能
c = CommodityView()
c.display_menu()
c.select_menu()
|
53b78c98709d6eac8ac2211beb79353657779cfd | 15194779206/practice_tests | /education/A:pythonBase_danei/4:阶段项目/A-Days/2.1:.py | 998 | 4.03125 | 4 | """
练习2:为两个已有功能(存款取款),添加新功能
"""
def func_dition(func):
def wapper(*args):
print("验证账户")
return func(*args)
return wapper
@func_dition
def deposit(money):
print("存款",money)
def withdraw():
print("取钱")
return 10000
deposit(5000)
"""
练习3:为学生的学习方法,添加新功能(统计执行时间)
"""
import time
def sumTime(func):
def timeall(*args):
start_time = time.time()
print("start",start_time)
result =func(*args)
end_time = time.time()
print("end", end_time)
print("差值:", end_time - start_time)
return result
return timeall
class Student:
def __init__(self,name):
self.name =name
@sumTime
def study(self):
print("开始学习啦")
time.sleep(2)
stu = Student("张三")
stu.study()
|
9f1818f931bccd2c4b6846c244431babb75f9a42 | lizcarey13/cs61a | /practice/summation.py | 276 | 4.03125 | 4 | def summation(term, n):
i, total = 1, 0
while i <= n:
total += term(i)
i += 1
return total
def square(x):
return x * x
def sum_squares(n):
i, total = 1, 0
while i <= n:
total += square(i)
i += 1
return total
"""Sum the first n powers of two
>>>summation()
|
a4942b24f13460eba24253377950c54b07dbb949 | thomas-li-sjtu/Sword_Point_Offer | /JZ17_Has sub tree/solution.py | 1,410 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if not pRoot1 or not pRoot2:
return False
tree1 = [pRoot1]
flag = 0
while tree1:
tmp = tree1.pop(0)
if tmp.val == pRoot2.val:
flag = self.subtree(tmp, pRoot2)
if tmp.left:
tree1.append(tmp.left)
if tmp.right:
tree1.append(tmp.right)
if flag:
return True
else:
return False
def subtree(self, tmp, pRoot2):
tree2 = [pRoot2]
tree_tmp = [tmp]
while tree2 and tree_tmp:
tmp = tree2[0]
tmp_tree1 = tree_tmp[0]
if tmp.val != tmp_tree1.val:
break
tree2.pop(0) # 先判别是否相等,再 pop
tree_tmp.pop(0) #
if tmp.left:
tree2.append(tmp.left)
if tmp_tree1.left:
tree_tmp.append(tmp_tree1.left)
if tmp.right:
tree2.append(tmp.right)
if tmp_tree1.right:
tree_tmp.append(tmp_tree1.right)
if not tree2:
return 1
else:
return 0
|
625e9e48496d3da1d8f042ddd794c30fe07c81dd | devLorran/Python | /ex0091.py | 670 | 3.71875 | 4 | '''Crie um programa onde 4 jogadores joguem um dado
e tenham resultados aletórios. Guarde esses resultados
em um dicionário. No final coloque esse dicionário
em ordem, sabendo que o vencedor tirou o maior número
no dado'''
from random import randint
from time import sleep
from operator import itemgetter
dado = {'jogador 1': randint(0, 6),
'jogador 2': randint(0, 6),
'jogador 3': randint(0, 6),
'jogador 4': randint(0, 6)}
for k, v in dado.items():
print(f'O jogador {k} sorteou {v}')
print('RANKING DOS JOGADORES')
ranking = list()
ranking = sorted(dado.items(), key=itemgetter(1), reverse=True)
print(ranking)
|
a52a12b6de0070c0c52c100ed6eff59e1e52bccd | dilipRathoreRepo/data_structures | /recursion/word_split.py | 430 | 3.59375 | 4 |
# word_split('themanran',['the','ran','man'])
def word_split(phrase, list_of_words, output=None):
if output is None:
output = []
for word in list_of_words:
if phrase.startswith(word):
output.append(word)
word_split(phrase[len(word):], list_of_words, output)
return output
phrase = 'themanran'
list_of_words = ['the', 'ran', 'man']
print(word_split(phrase, list_of_words))
|
dd96001a6221c2692c84521dc6dfe1572e5a3698 | dudrbs703/codeup-python-100 | /print_6070.py | 269 | 4 | 4 | # print_6070.py
a = int(input())
if (a is 12) or (a is 1) or (a is 2):
print("winter")
elif (a is 3) or (a is 4) or (a is 5):
print("spring")
elif (a is 6) or (a is 7) or (a is 8):
print("summer")
elif (a is 9) or (a is 10) or (a is 1):
print("fall")
|
d9988fbbde144f45fdbeb8a20c09b61afcb77db9 | jddelia/algos_and_ds | /Section5/seclectionSort.py | 566 | 3.984375 | 4 | #! /usr/bin/python3
# This program implements a selection sort.
import math
def selection_sort(lst):
new_lst = []
lowest = math.inf
for passnum in range(len(lst)):
for i in lst:
if i in new_lst:
if new_lst.count(i) == lst.count(i):
continue
if i < lowest:
lowest = i
new_lst.append(lowest)
lowest = math.inf
return new_lst
def main():
lst = [26,54,93,17,77,31,44,55,20]
print(selection_sort(lst))
if __name__ == "__main__":
main()
|
6b8d17fdddcdc6d868d402ae5516245092aba6c6 | Harrywekesa/Animal-game | /turtlegraphics.py | 1,829 | 4.21875 | 4 | import turtle as t
def rectangle(horizontal, vertical, color):
t.pendown()
t.pensize(1)
t.color(color)
t.begin_fill()
#This for looop draws a rectangle
for _ in range(1, 3): #this range function maks the loop run twice
t.forward(horizontal)
t.right(90)
t.forward(vertical)
t.right(90)
t.end_fill()
t.penup()
t.shape('turtle')
t.setheading(0)
t.forward(80)
t.penup()
t.speed('slow')
t.bgcolor('Dodger blue')
#drawing robots feet
t.goto(-100, -150 )
rectangle(50, 20, 'Blue')
t.goto(-30, -150)
rectangle(50, 20, 'Blue')
#Drawing the legs
t.goto(-25, -50) #The turtle moves to position x = –25, y = –50.
rectangle(15, 100, 'Grey') #Drawing the left leg
t.goto(-55,-50)
rectangle(-15, 100 ,'Grey')
#Drawing the body
t.goto(-90, 100)
rectangle(100, 150, 'Red') #Draw a red rectangle 100 across and 150 down.
#Drawing the arms
#Upper right arm
t.goto(-150, 70)
rectangle(60, 15, 'Grey')
#Lower right arm
t.goto(-150, 110)
rectangle(15, 40, 'Grey')
t.goto(-155, 130)
rectangle(25, 25, 'green')
t.goto(-147, 130)
rectangle(10, 15, t.bgcolor())
#Upper left arm
t.goto(10, 70)
rectangle(60, 15, 'Grey')
#Lower left arm
t.goto(55, 110)
rectangle(15, 40, 'Gold')
t.goto(50, 130)
rectangle(25, 25, 'Green')
t.goto(58, 130)
rectangle(10, 15, t.bgcolor())
#Drawing the neck
t.goto(-50, 120)
rectangle(15, 20, 'Yellow')
#Drawing the head
t.goto(-85, 170)
rectangle(80, 50, 'Red')
#Drawing the eyes
t.goto(-60, 160)
rectangle(30, 10, 'White') #Drawing the white part of the eyes
#Drawing the right pupil
t.goto(-55, 155)
rectangle(5, 5, 'Black')
#Drawing the left pupil
t.goto(-40, 155)
rectangle(5, 5, 'Black')
#Mouth
t.goto(-65, 135)
rectangle(40, 5, 'Black')
# t.hideturtle() makes the turtle invisible |
931c6dfe8e1d170598ed91646ad970aca8182607 | rohan-thomas/Coding-Problems | /ValidAnagram.py | 468 | 3.5 | 4 | class Rohan(object):
def isAnagram(self,s, t):
maps = {}
mapt = {}
for c in s:
maps[c] = maps.get(c,0)+1
for c in t:
mapt[c] = mapt.get(c,0)+1
if maps == mapt:
print("true")
else:
print("false")
return maps == mapt
rohan1 = "rohanthomas"
rohan2 = "thomnahoras"
test = Rohan()
test.isAnagram(rohan1,rohan2) |
a5a34ca8b1c1547daee21ab9092f118668fee04a | anster01/Routing_App | /dijkstra.py | 1,136 | 3.6875 | 4 | def dijkstra(graph, start, end, weight):
duration = {}
pred = {}
for node in graph.keys():
duration[node] = float('Inf')
pred[node] = ''
duration[start] = 0
all_nodes = list(graph)
while len(all_nodes) > 0:
shortest = duration[all_nodes[0]]
shortest_node = all_nodes[0]
for node in all_nodes:
if (duration[node] < shortest):
shortest = duration[node]
shortest_node = node
all_nodes.remove(shortest_node)
for adjacent_node, adjacent_value in graph[shortest_node].items():
if duration[adjacent_node] > duration[shortest_node] + adjacent_value[weight]:
duration[adjacent_node] = duration[shortest_node] + adjacent_value[weight]
pred[adjacent_node] = shortest_node
path = []
node = end
while not (node == start):
if path.count(node) == 0:
path.insert(0, node)
node = pred[node]
else:
break
path.insert(0, start)
return {'path': path, 'length': duration[end]}
|
c45cd7cd5193d711e9c99977848080058efd17ad | laloparkour/pildoras_informaticas_python | /Practicas/#mail.py | 208 | 4.0625 | 4 | email = input("Introduce un correo: ")
arroba = email.count("@")
if (arroba != 1 or email.find("@") == 0 or email.rfind("@") == len(email)-1):
print("Email Incorrecto")
else:
print("Email Correcto")
|
85ad3666cc319b11c434cf7d0bcc2471e65e1d48 | jjack94/boolean_functions | /equal.py | 615 | 4.15625 | 4 | # james jack
# 3/5/21
# function that takes two inputs from a user and prints whether they are equal or not
def equal(): # creates function
x = int(input("What is the first number you would like to use?: ")) # first var
y = int(input("What is the second number you would like to use?: ")) # second var
if x > y or y > x: # if x is less than y or if y is greater than x allows a statement to be made to compare them
print("These are not equal")
else:
print("These are equal") # if the conditions above are not triggered the numbers must be equal value
equal()
|
570bf3803ba8d3a67def77f1f775b7c9336cb487 | sammcd4/calculator | /calc.py | 472 | 4 | 4 | import numbers
def add_values(val1, val2):
# Add any values, handling any conversion from string
val1_, val2_ = val1, val2
if not is_valid_number(val1_):
val1_ = float(val1)
if not is_valid_number(val2_):
val2_ = float(val2)
return val1_ + val2_
def is_valid_number(val):
valid = True
if not isinstance(val, numbers.Number):
#print('Val1 of {} is not a number!'.format(val))
valid = False
return valid |
51a2092f4209825d5d9e465e9bd2502def18cf24 | LarisaFonareva/Dictionaries | /2.18_Genealogy_ancestors_and_descendants.py | 1,195 | 3.890625 | 4 | def func(child, parent):
if child==parent: # если дошла до первого предка
return True
while child in d:
child=d[child] # ребенком делаю родителя, ищу его родителя
if child==parent: # если дошла до первого предка
return True
return False
d={}
for _ in range(int(input())-1):
child, parent=input().split()
d[child]=parent
print(d)
for _ in range(int(input())):
person1, person2 = input().split()
if func(person1,person2):
print(2, end=' ')
elif func(person2,person1):
print(1,end=' ')
else:
print(0,end=' ')
# def func(c, p):
# while c in d:
# c = d[c]
# if c==p:
# return True
# return False
# d = {}
# for _ in range(int(input()) - 1):
# child, parent = input().split()
# d[child] = d.get(child, '') + parent
# # for c in d:
# # print(c,' ', d[c])
# for _ in range(int(input())):
# x1, x2 = input().split()
# if func(x1, x2):
# print(2, end=' ')
# elif func(x2, x1):
# print(1, end=' ')
# else:
# print(0, end=' ') |
8f2fdfe386f20fe86d5bad71fedb94e63b4c1ee9 | Aasthaengg/IBMdataset | /Python_codes/p02819/s945954757.py | 219 | 3.703125 | 4 | import math
def prime(n):
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
n = int(input())
while True:
if prime(n):
break
else:
n += 1
print(n) |
1906d71621de84e3e88bee1983e937d8436eaa13 | sergeykoryagin/tproger | /tasks/task13.py | 135 | 3.765625 | 4 | num1 = input()
num2 = num1 + num1
num3 = int(num2 + num1)
num1 = int(num1)
num2 = int(num2)
result = num1 + num2 + num3
print(result)
|
f501345a2e092b8b9030031e4c90ccdb0b17c34e | jmetzz/ml-fundamentals | /src/neural_networks/base/activations.py | 2,300 | 4.3125 | 4 | from typing import Sequence
import numpy as np
def step(z: float) -> float:
return 1.0 if z >= 0.0 else 0.0
def sigmoid(z: np.ndarray) -> np.ndarray:
"""Calculate the sigmoid activation function
The sigmoid function take any range real number
and returns the output value which falls in the range of 0 to 1.
When the input z is a vector or Numpy array,
Numpy automatically applies the function
element wise, that is, in vectorized form.
Examples:
>>> input = np.arange(-10, 10, 1)
>>> [sigmoid(input)
>>> [sigmoid(x) for x in input]
"""
return 1.0 / (1.0 + np.exp(-z))
def tanh(z: np.ndarray) -> np.ndarray:
"""Calculate the tangent activation function
Takes any range real number and returns the output value
which falls in the range of 0 to 1.
When the input z is a vector or Numpy array,
Numpy automatically applies the function
element wise, that is, in vectorized form.
Examples:
>>> input = np.arange(-10, 10, 1)
>>> [tanh(input)
>>> [tanh(x) for x in input]
"""
# tanh(z) = 2σ(2z) − 1
return 2 * np.array(sigmoid(z)) - 1
def hypertang(z: np.ndarray) -> np.ndarray:
"""Calculate the hyper tangent activation function
Takes any range real number and returns the output value
which falls in the range of 0 to 1.
When the input z is a vector or Numpy array,
Numpy automatically applies the function
element wise, that is, in vectorized form.
Examples:
>>> input = np.arange(-10, 10, 1)
>>> [hypertang(input)
>>> [hypertang(x) for x in input]
"""
exp = np.exp(2 * z)
return (exp - 1) / (exp + 1)
def softmax(z: np.ndarray) -> np.ndarray:
""""Calculate the softmax activation function
Takes any range real number and returns
the probabilities range with values between 0 and 1,
and the sum of all the probabilities will be equal to one.
When the input z is a vector or Numpy array,
Numpy automatically applies the function
element wise, that is, in vectorized form.
Examples:
>>> input = np.arange(-10, 10, 1)
>>> [softmax(input)
>>> [softmax(x) for x in input]
"""
return np.exp(z) / np.sum(np.exp(z), axis=0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.