blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0d17b4072ba18f40dd38734748c59b9770737d68 | debu999/Python_Notes | /closure_decorators/local_functions.py | 3,021 | 3.734375 | 4 | store = []
def sort_by_last_letter(strings):
def last_letter(s):
return s[-1]
store.append(last_letter)
print(last_letter)
return sorted(strings, key = last_letter, reverse=True)
print(sort_by_last_letter(["Debabrata", "Priyabrata", "Ramesh", "Devendra", "Augustine", "Boominathan"]))
#Closure testing
def enclosing():
x,y = 'ABC', 'PQR'
def inner():
print(x,y)
return inner
lf = enclosing()
lf()
print(lf.__closure__)
def raise_to(exp):
def raise_to_exp(x):
return pow(x, exp)
return raise_to_exp
sqrt = raise_to(.5)
sqr = raise_to(2)
print(sqrt)
print(sqrt(4), sqr(4))
#bindings
message = 'Global'
def enclosing():
message = 'Enclosing'
def local():
message = 'local'
print("local msg:", message)
print("enclosing msg:", message)
local()
print("enclosing msg:", message)
print("Global msg: ", message)
enclosing()
#global and nonlocal usage
import time
def make_timer():
last_called = None
def elapsed():
nonlocal last_called
now = time.time()
if last_called is None:
last_called = now
return None
result = now - last_called
last_called = now
return result
return elapsed
timing = make_timer()
print(timing())
time.sleep(2)
print(timing())
def escape_unicode(f):
def wraps(*args, **kwargs):
x = f(*args, **kwargs)
return ascii(x)
return wraps
@escape_unicode
def n_city():
return "Tromsø"
print(n_city())
class CallCount:
def __init__(self, f):
self.f = f
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.f(*args, **kwargs)
@CallCount
def hello(name):
print("Hello {}".format(name))
hello("Debabrata")
hello("Priyu")
hello("Abhijeet")
# print(hello.__closure__)
print(hello.f)
print(hello.count)
#As class instance variable
class Trace:
def __init__(self):
self.enabled = True
def __call__(self, f):
def wrap(*args, **kwargs):
if self.enabled:
print("Calling {}".format(f))
return f(*args, **kwargs)
return wrap
tracer = Trace()
@tracer
def rotate_list(l):
return l[1:]+[l[0]]
l = [ 1, 2, 3]
l = rotate_list(l)
print(l)
l = rotate_list(l)
print(l)
l = rotate_list(l)
print(l)
l = rotate_list(l)
print(l)
tracer.enabled = False
l = rotate_list(l)
print(l)
l = rotate_list(l)
print(l)
tracer.enabled = True
@tracer
@escape_unicode
def new_city_make(name):
return name+" - Tromsø"
print(new_city_make("Deb"))
@escape_unicode
@tracer
def new_city_make(name):
return name+" - Tromsø"
print(new_city_make("Deb"))
tracer.enabled = True
class NewCity:
def __init__(self, suffix):
self.suffix = suffix
@tracer
def new_city_make(self, name):
return name + " looking for a change. - Suffix: "+self.suffix
cty = NewCity("title is Patnaik.")
print(cty.new_city_make("Deb"))
|
d1a177814b999f4e4b17055daeb5446dd9115f51 | someOne404/Python | /pre-exam3/11.27_high_scores_append.py | 440 | 3.59375 | 4 | scores = []
with open('scores.csv', 'r') as f:
for line in f:
n, s = line.strip().split(',')
if int(s) > 0:
scores.append([int(s), n])
scores.sort()
scores.reverse()
for pair in scores:
s, n = pair
print(n, 'got', s)
name = input('Who are you? ')
score = input('What was your score? ')
with open('scores.csv', 'a') as f:
print(name+','+score, file=f)
# reading can't create file, writing can
|
551d1d6e4e312cbea6630fc2530f5e5ddf502a8b | SaumLucky/python | /1.19.py | 248 | 4.09375 | 4 | time_gone = int(input("enter the time gone "))
hour = (time_gone % (60 * 60 * 24) // 3600 )
minutes = time_gone % (60 * 60) // 60
seconds = time_gone % 10
print(hour // 10,hour % 10, ":", minutes // 10,minutes % 10, ":", seconds // 10,seconds % 10) |
ae4b57bb952ce0e54708cebc2a8333a005224e51 | mukulsingh94868/ML-project | /mukki.py | 474 | 4.3125 | 4 | #!/usr/bin/python3
import matplotlib.pyplot as plt
# only loading python ori lib
x=[2,3]
x1=[4,3,8]
y=[9,5]
y1=[2,9,7]
plt.xlabel("time")
plt.ylabel("speed")
plt.plot(x,y,label="water") # thus will draw a straight line
plt.plot(x1,y1,label="sand") # thuis will draw a straight line
plt.grid(color='green') # to form grid in graph
plt.legend() # # to show labels with plot
plt.xlim(0,12) # to show min and max number in x axis
plt.ylim(0,15) # y axis
plt.show
|
3435584d0374723a3f365232e3bb461eff505a70 | Avador-77/python-programs | /ThinkPythonBookSolutions/5-10checking usernames.py | 421 | 3.671875 | 4 | current_users = ['RAJat','ANMOL','bajaj','tekchand','mohit', 'shubam','pankaj']
new_users = ['Rajat','Anmol','bajaj','sathiya','nilofar']
Cu_lower = [user.lower() for user in current_users]
for username in new_users:
if username.lower() in Cu_lower:
print("Sorry, the name " + username + ' has been taken. Try using a different username.')
else:
print('Username ' + username +' is available.')
|
b2b52bb5b71c8d5ffa77ef1c0c2e40c7e6aa7269 | Simthem/algos_data_structures | /algorithms/implement_strstr.py | 264 | 3.65625 | 4 | def implement_str(haystack, needle):
if (not haystack and not needle) or not needle:
return 0;
for i in range(len(haystack)):
cur = haystack[i:i + len(needle)];
if cur == needle[0:len(needle)]:
return i;
return -1;
|
0a3880862e092ea689ed321bfe9b7e39b011f241 | joaoluizn/exercism | /python/core/hamming/hamming.py | 224 | 3.515625 | 4 | def distance(strand_a :str, strand_b :str) -> int:
if len(strand_a) != len(strand_b):
raise ValueError("Strand Lenths doesn't match.")
return len([(s1, s2) for s1, s2 in zip(strand_a, strand_b) if s1 != s2])
|
8163d724b812afd2702e2337f27d989c7a03190d | Lokitosi/Python-UD | /Programa graficador de poligonos.py | 624 | 3.828125 | 4 | import turtle
pipo = turtle.Turtle()
cerrar = 0
def figura():
lados = turtle.numinput("Lados", "Ingrese cuantos lados tendra la figura:")
tamaño = turtle.numinput("Tamaño", "Ingrese el tamaño de la figura:")
relleno = turtle.textinput("relleno", "Desea rellenar la figura")
pipo.clear()
pipo.color("#1AB231", "#19EC38")
pipo.begin_fill()
pipo.pensize(5)
for i in range(int(lados)):
pipo.forward(tamaño)
pipo.right(-360/lados)
turtle.color("black", "red")
if relleno == "si":
pipo.end_fill()
while cerrar == 0:
figura()
|
10e81551185865e7f1e773a17a5cb75874a615ba | darioss/estudos | /Python/divisao_inteira.py | 258 | 3.90625 | 4 | def main():
# escreva o seu programa
num1 = int(input("Digite o valor de n (n > 0): "))
num2 = int(input("Digite o valor de d (0<=d<=9): "))
resultado = num1//num2
print("O Digito %d ocorre %d vezes em %d" %(num2, resultado, num1))
main() |
b400fa8072e376108d86c8f4782ceb14e4348978 | AlexKaracaoglu/Cryptography | /PS1/AKaracaogluHW1.py | 8,386 | 3.609375 | 4 | import conversions
import string
from timeit import default_timer as timer
# NAME: ALEX KARACAOGLU
# Code for number 2 (Some pieces may be used later on as well)
# The cipher text was given in hex, I will convert them to ascii and use them
ciphertext1_in_b64 = "EjctKjswcH5+GjF+JzErfik/MCp+KjF+NTAxKX4/fi07PSw7KmF+fhoxficxK34uLDEzNy07fjAxKn4qMX4qOzIyYX5+HTIxLTsscH5+EjsqfjM7fik2Ny0uOyx+NzB+JzErLH47Pyxw"
ciphertext1_in_as = conversions.b64_to_as(ciphertext1_in_b64)
ciphertext2_in_b64 = "mvS+86C886e6oba387y186e7uqDzp7ykvfOku7ahtvO2pbahqvOnvL20prbzuqDzpLK0tLq9tPOku7a987altqGq87GysLjzuqDzp6ahvba3/fPzh7u2qvShtvOntr+/ur2086C2sKG2p6Dzp7uyp/Ogu7ymv7fzvbaltqHzsbbzobaltrK/trf9"
ciphertext2_in_as = conversions.b64_to_as(ciphertext2_in_b64)
# individual_xor: function that takes in a cipher character and the key and returns the xor result
def individual_xor(ct,k):
plain = conversions.xor(ct,k*len(ct))
return plain
# brute: Takes in a string and returns a list of all 256 possible decryptions
def brute(text):
for key in range(256):
print str(chr(key)) + ":" +individual_xor(text,chr(key))
# count_printable: takes in a string and returns the number of printable characters
def count_printable(text):
count=0
for i in range(len(text)):
if text[i] in string.printable:
count = count + 1
else:
count = count
return count
# count_letters: takes in a string and returns the number of letters
def count_letters(text):
count = 0
for i in range(len(text)):
if text[i] in string.ascii_letters:
count = count + 1
else:
count = count
return count
# add: Takes in an array and returns a float that is the value after adding all the entries together
def add(a):
b = 0.0
for i in range(len(a)):
b = b + a[i]
return b
#Final_counts: takes in an array and returns a smaller array, used as a helper function in counts
def finalCounts(dist):
final = [0] * 26
for i in range(len(final)):
final[i] = dist[i]+dist[i+26]
return final
#counts: Takes in a string and returns an array of the distribution of the letters
def counts(text):
a = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
dist = [0] * 52
for i in range(len(text)):
b = text[i]
for j in range(len(dist)):
if b == a[j]:
dist[j] = dist[j]+1
else:
dist[j] = dist[j]
return dist
#englishy: takes in a text and returns a negative value corresponding to how "englishy" the input text is. (Closer to 0.0 is more "englishy")
def englishy(text):
a = finalCounts(counts(text))
length = float(len(text))
b = [(x / length) for x in a]
freq =[0.0817, 0.0153, 0.0224, 0.0470, 0.121, 0.0217, 0.0210, 0.0606, 0.0724, 0.0010, 0.0090, 0.0379, 0.0315, 0.0684, 0.0773, 0.0170, 0.0009, 0.0575, 0.0605, 0.0885, 0.0283, 0.0092, 0.0260, 0.0013, 0.0226, 0.0002]
score = [0] *26
for i in range(26):
score[i] = -(abs(b[i]-freq[i]))
c = add(score)
return c * 5
# all_scores: Takes in a string and prints out a series of keys and their resulting scores
def all_scores(text):
for i in range(256):
rating = (1 * count_printable(individual_xor(text,chr(i)))) +(.75 * count_letters(individual_xor(text,chr(i))))+ (englishy(individual_xor(text,chr(i))))
print str(i) + ":" + str(rating)
def best_score(text):
max_score = 0
max_score_character = ''
rating = 0
for i in range(256):
rating = (1 * count_printable(individual_xor(text,chr(i)))) +(.75 * count_letters(individual_xor(text,chr(i))))+ (englishy(individual_xor(text,chr(i))))
if rating >= max_score:
max_score = rating
max_score_character = chr(i)
return str(max_score)
# best_key: Takes in a string and prints out the best key and the best score when ran through the scoring alcgorithm I created. (Larger score is better)
def best_key(text):
max_score = 0
max_score_character = ''
rating = 0
for i in range(256):
rating = (1 * count_printable(individual_xor(text,chr(i)))) +(.75 * count_letters(individual_xor(text,chr(i))))+ (englishy(individual_xor(text,chr(i))))
if rating >= max_score:
max_score = rating
max_score_character = chr(i)
return str(max_score_character)
# one_byte_xor: Takes in a ciphertext, in form of an ascii string, and returns the decrypted message
def one_byte_xor(ciphertext):
key = best_key(ciphertext)
plaintext = individual_xor(ciphertext,key)
return plaintext
# Code for number 3 (Some pieces may be used later on as well)
# mod: takes in two integers and retrns the first mod the second
def mod(a,b):
return a % b
# new_xor: Takes in string and a key and returns the xor of the text using the given key
def new_xor(text,key):
plain = conversions.xor(text,key)
return plain
# remove: Takes in a string and removes all non printable items and replaces them with ''
def remove(text):
s = ''
for i in range(len(text)):
if text[i] not in string.printable:
s = s + ""
else:
s = s + text[i]
return s
# recover: Takes in a word file and returns the cipher text that is taken from the body of the document
def recover(filename):
f = open(filename,'rb')
s = f.read()
a = s[540]
b = s[541]
c = ord(a)
d = ord(b)
final = (d*256)+c+512
cipher = s[2560:final]
return cipher
# repeating_byte_xor: Takes in a string and a key and modifies the key to be repeating and of the same length as the text, then performs an xor
def repeating_byte_xor(text,key):
a = len(text)
b = len(key)
c = (a/b)
d = mod(a,b)
new_key = (key*c) + key[:d]
f = conversions.xor(text,new_key)
return f
# decrypt_msword: Takes in a word file, opens the file, reads the file and extracts the body (ciphertext) then decrypts it using the repating key xor
# The key was given to us, so I will convert it to ascii and use it: hex("b624bd2ab42a39a235a0b4a9b6a734cd")
key_for_number_3_in_hex = "b624bd2ab42a39a235a0b4a9b6a734cd"
key_for_number_3_in_as = conversions.hex_to_as(key_for_number_3_in_hex)
def decrypt_msword(filename, key):
ciphertext = recover(filename)
plaintext = repeating_byte_xor(ciphertext, key)
finaltext = remove(plaintext)
final = finaltext.replace('\r',"")
return final
# Code for Number 4
# timeSingleDecrypt: Returns how long it takes the computer to perform one decryption of key length 16 on 'MSWord1.doc'
def timeSingleDecrypt():
start = timer()
decrypt_msword('MSWordXOR1.doc',key_for_number_3_in_as)
end = timer()
return(end - start)
def timemanydecrypts():
total = 0.0
for i in range(10000):
total = total + timeSingleDecrypt()
final = float(total / (10000))
return final
# getTotalTime: Returns the number of YEARS it would take to do all (256**16) decrptions (Brute force method)
def getTotalTime():
a = timemanydecrypts()
numberKeys = 256 ** 16
totalSeconds = float(a * numberKeys)
secondsInYear = 31536000
transfer = long (totalSeconds / secondsInYear)
return str(transfer)
# Code for number 6
# extract_subtexts: Takes in a string and a key length, and builds a list of subtexts as discussed in class
def extract_subtexts(ciphertext,keylength):
subtexts=['']*keylength
for j in range(len(ciphertext)):
subtexts[j%keylength]+=ciphertext[j]
return subtexts
# make_key: Takes in the subtexts and contructs the best possible key using my scoring system
def make_key(extracted_subtexts):
s = ''
for i in range(16):
s = s + best_key(extracted_subtexts[i])
return s
# ct_only_msword: Takes in a file and then returns the plain text decryption to the best of its ability
def ct_only_msword(filename):
ciphertext = recover(filename)
subtexts = extract_subtexts(ciphertext, 16)
key = make_key(subtexts)
plaintext = repeating_byte_xor(ciphertext, key)
final = remove(plaintext)
plain = final.strip('\n')
plain2 = plain.strip('\r')
plain3 = plain2.replace('\r','')
plain4 = plain3.replace('\x0b','')
plain5 = plain4.replace('\n','')
return plain5
|
823dc05bfc37e20f35c801f26ab0457ab99929e6 | eedriss67/User-Log-in-Project | /user_log-in project.py | 851 | 4 | 4 | # This is a simple project that takes user's log-in information and validates it.
import time
name = input("Create a log-in name: ")
password = input("Create a password: ")
user_name = input("Please enter your name to log-in: ")
user_password = input("Please enter your password to log-in: ")
if user_name == name and user_password == password:
print("Access granted!")
print("Wait...")
print("Loading.....")
time.sleep(8)
print(".....")
time.sleep(5)
print(".....")
time.sleep(3)
print("All clear")
elif user_name == name and user_password != password:
print("You have entered a wrong user password. Please try again.")
elif user_name != name and user_password == password:
print("You have entered a wrong user name.")
else:
print("Access denied! Try again later.")
|
67cedaff99a04f30ab73b174cc41e6135765105c | idalyli/pildoraspython | /funcioneslambda/practica_map.py | 684 | 3.546875 | 4 | class Empleado:
def __init__(self,nombre,cargo,salario):
self.nombre=nombre
self.cargo=cargo
self.salario=salario
def __str__(self):
return "{}que trabaja como {} tiene un salario de $ {}".format(self.nombre,self.cargo,self.salario)
lista_empleados=[
Empleado("Juan","Director",750000),
Empleado("Elsa","Administrativa",550000),
Empleado("Oscar","Operativo",350000)
]
def calculo_comision(empleado):
if (empleado.salario<=400000):
empleado.salario = empleado.salario * 1.03
return empleado
lista_empleados_comision=map(calculo_comision,lista_empleados)
for empleado in lista_empleados_comision:
print(empleado) |
9d54965d4ed2fb1a6b2f2d43414897d8893179a3 | uilic/socialflask | /people.py | 2,016 | 3.546875 | 4 |
class Human:
"""Class human with the atributes given in the data.json file, and also with
one extra atribute, string ID for easier work with picture urls"""
def __init__(self, ident, firstName, surName, age, gender, friendsId):
self.ident = ident
self.firstName = firstName
self.surName = surName
self.age = age
self.gender = gender
self.friendsId = friendsId
self.strId = str(ident)
def getFriends(self, group): # returns list of human objects of friends
friendsList = []
for g in group:
for i in self.friendsId:
if i == g.ident:
h = Human(g.ident, g.firstName, g.surName, g.age, g.gender, g.friendsId)
friendsList.append(h)
return friendsList
def getFriendsOfFriends(self, group): # returns list of friends of friends
friendsOfFriendsList = []
fofId = []
for f in self.getFriends(group):
for fre in f.getFriends(group):
if fre.ident not in self.friendsId + fofId and fre.ident != self.ident:
h = Human(fre.ident, fre.firstName, fre.surName,
fre.age, fre.gender, fre.friendsId)
friendsOfFriendsList.append(h)
fofId.append(h.ident)
return friendsOfFriendsList
def getSuggestedFriends(self, group):
"""returns a list of the suggested friends by first calculating mutual
friends and separating those friends who have two or more mutuals"""
suggestedFriends = []
mutualFriendsId = []
for fof in self.getFriendsOfFriends(group):
for f in fof.getFriends(group):
if f.ident in self.friendsId:
mutualFriendsId.append(f.ident)
if len(mutualFriendsId) > 1:
suggestedFriends.append((fof, len(mutualFriendsId)))
mutualFriendsId = []
return suggestedFriends
|
5afc30f13063bd0bf4c86e105ba1d09896d14cca | asierblaz/PythonProjects | /Listak/Listak11.py | 216 | 3.71875 | 4 | '''
17/12/2020 Asier Blazquez
Write a Python program to find the index of an item in a specified list
'''
import random
list =["a","e","i","o","u"]
aleatorioa =int( random.randrange(0, len(list)-1))
print(list[aleatorioa]) |
9e35c703baaaa26a852852f611ee5a14afd4af8a | mikkokotila/game-theory-sim | /gt.py | 4,911 | 4.09375 | 4 | #!/usr/bin/python
import time
import random
# starting turn and per turn cost for players
turn = 0
tax_rate = 0.2
cost_of_living = 0.3
players = 2
service_cost = 0.01101
minimum = 0.1
gdp = 1
demand = 1
inflation = 0.01
# productivity and resource settings
productivity = 1
current_account = 100
motivation_adjustment = 0.01
# player one starting settings
p1_productivity = 1
p1_bank = 10
p1_motivation = 1
# player two starting settings
p2_productivity = 1
p2_bank = 10
p2_motivation = 1
# extra configuration values initialised
p1_thisround = 0
p1_lastround = 0
p2_thisround = 0
p2_lastround = 0
gdplastround = 1
cost_of_living_temp = 0
reason = "abc"
# game starts
# user input for contribution levels is collected
p1_give = input("What ratio will player 1 give back at : ")
p2_give = input("What ratio will player 2 give back at : ")
sleeptime = input("Delay in seconds between rounds : ")
while current_account > minimum and p1_bank > minimum and p2_bank > minimum:
turn = turn + 1
# set randomness factor for both players
p1_random = round(random.uniform(0.9, 1.1), 3)
p2_random = round(random.uniform(0.9, 1.1), 3)
# adjusting the cost of living for the round
cost_of_living_temp = cost_of_living * inflation
cost_of_living = cost_of_living + cost_of_living_temp
# player 1 cost of living reduction
if p1_bank >= cost_of_living * p1_random:
p1_bank = p1_bank - cost_of_living * p1_random
elif p1_bank < cost_of_living * p1_random:
current_account = current_account - cost_of_living * p1_random / 10
# player 2 cost of living reduction
if p2_bank >= cost_of_living * p2_random:
p2_bank = p2_bank - cost_of_living * p2_random
elif p2_bank < cost_of_living * p2_random:
current_account = current_account - cost_of_living * p2_random / 10
# player 1 production and earnings turn
productivity_temp1 = (p1_productivity * p1_motivation) * p1_random
p1_bank = productivity_temp1 + p1_bank
# player 2 production and earnings turn
productivity_temp2 = (p2_productivity * p2_motivation) * p2_random
p2_bank = productivity_temp2 + p2_bank
# deducting the turn cost for both players
p1_bank = p1_bank - (tax_rate * p1_random) * productivity_temp1
p2_bank = p2_bank - (tax_rate * p2_random) * productivity_temp2
# the money goes to the bank (current_account)
current_account = current_account + (tax_rate * productivity_temp1)
current_account = current_account + (tax_rate * productivity_temp2)
# player 1 contribution to the current_account
bank_temp1 = productivity_temp1 * p1_give
p1_bank = p1_bank - bank_temp1
current_account = current_account + bank_temp1
# player 2 contribution to the current_account
bank_temp2 = productivity_temp2 * p2_give
p2_bank = p2_bank - bank_temp2
current_account = current_account + bank_temp2
# player 1 motivation adjustment (neg)
if bank_temp2 <= bank_temp1:
p1_motivation = p1_motivation - (p1_motivation * motivation_adjustment * p1_random)
else:
p1_motivation = p1_motivation + (p1_bank / p2_bank) * (p1_give / p2_give) * demand * p1_random
# player 2 motivation adjustment (neg)
if bank_temp1 <= bank_temp2:
p2_motivation = p2_motivation + (p2_motivation * motivation_adjustment * p2_random)
else:
p2_motivation = p2_motivation + (p2_bank / p1_bank) * (p2_give / p1_give) * demand * p2_random
# admin fee is deducted from the current_account
current_account = current_account - gdp * service_cost
# GDP adjustment
gdplastround = gdp
gdp = gdp + (productivity_temp1 + productivity_temp2)
# Demand adjustment for both players
p1_lastround = p1_thisround
p2_lastround = p2_thisround
p1_thisround = productivity_temp2 - (tax_rate * p1_random) * productivity_temp1
p2_thisround = productivity_temp2 - (tax_rate * p2_random) * productivity_temp2
if p1_lastround >= p1_thisround:
demand = demand * 0.99 * p1_random
elif p1_lastround <= p1_thisround:
demand = demand * 1.01 * p1_random
if p2_lastround >= p2_thisround:
demand = demand * 0.99 * p2_random
elif p1_lastround <= p1_thisround:
demand = demand * 1.01 * p2_random
# creating the printed values
p1 = round(productivity_temp1, 2)
p2 = round(productivity_temp2, 2)
b1 = round(p1_bank, 2)
b2 = round(p2_bank, 2)
m1 = round(p1_motivation, 2)
m2 = round(p2_motivation, 2)
de = round(demand, 2)
gd = round(gdp, 2)
cu = round(current_account, 2)
ex = round(gdp * service_cost)
cl = round(cost_of_living, 2)
gl = round(gdplastround / gdp, 4)
# results for the turn are printed on the screen
print(turn," : ",p1,p2,b1,b2,m1,m2,de,gd,cu,ex,cl,gl)
# the delay before next round is set
time.sleep(sleeptime)
if current_account <= minimum:
reason = "CURRENT ACCOUNT ON NEGATIVE"
elif p1_bank <= minimum:
reason = "PLAYER 1 BUSTED"
elif p2_bank <= minimum:
reason = "PLAYER 2 BUSTED"
print("GAME OVER", p1_give,"vs.",p2_give,"on",turn,"due to",reason)
|
f0489bf500a492b8499e77fdaedcc4b5dc55bf6a | eli-front/excessive-tic-tac-toe | /python/ttt.py | 2,680 | 3.890625 | 4 | # Copyright (c) 2020 Eli B. Front. All rights reserved.
from os import system, name
board = [[' ', ' ', ' '],[' ', ' ', ' '],[' ', ' ', ' ']]
currentPlayer = 'x'
# Prints the current board and clears the previous board
def printBoard():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
for i in range(3):
print(' {} | {} | {}'.format(board[i][0],board[i][1],board[i][2]))
if i != 2:
print('___ ___ ___ ')
# Checks if all elements in an array are equal
def equalArray(a):
return a[1:] == a[:-1]
# If there is a winner it will return that player
def gameOver():
for i in range(3):
# horizontal
if equalArray(board[i]) and board[i][0] != ' ':
return board[i][0]
# vertical
vertBoard = [j[i] for j in board]
if equalArray(vertBoard) and vertBoard[0] != ' ':
return vertBoard[0]
center = board[1][1]
if center != ' ':
# diagonal
if board[0][0] == center == board[2][2] or board[0][2] == center == board[2][0]:
return center
# Checks if the board is full
def boardFull():
for i in board:
for j in i:
if j == ' ':
return False
return True
printBoard()
while gameOver() == None:
if boardFull():
print("cat's Game")
break
x = input('type x of your move: ')
y = input('type y of your move: ')
printBoard()
# Checks the size of the inputs (should be 1)
if len(x) == 1 and len(y) == 1:
# Checks if the inputs are numbers
if x.isnumeric() and y.isnumeric():
# Converts the inputs to numbers
x = int(x)
y = int(y)
# Checks if the inputs fall in the correct range
if (x >= 0 and x < 3) and (y >= 0 and y < 3):
# Checks if the input spot is empty
if board[y][x] == ' ':
# Sets the board spot to the currentPlayer
board[y][x] = currentPlayer
currentPlayer = 'x' if currentPlayer == 'o' else 'o'
printBoard()
else:
print('this spot is already taken')
else:
print('the inputs must follow these constraints: 0 <= input < 3')
else:
print('your inputs were not integers')
else:
print('your input was either too long or short, make sure it has correct formatting\n ex ->1')
winner = gameOver()
# Outputs an output if it exists
if (winner != None):
print(winner + ' wins!')
|
e1db4276b50a0eb813d728182e6a79e68b87bcb4 | wanghan79/2020_Master_Python | /2019102960李婧怡/第三次作业:randomFloatStr.py | 1,263 | 3.75 | 4 | import random
def randomFloat(start, end): #1.随机生成1000个[0,100]范围内的浮点随机数,取出[20,50]之间的数字,存放在set集合中
set_random_float = set()
for i in range(1000):
randomFloat = random.uniform(start, end) #生成随机浮点数
if randomFloat>= 20 and randomFloat<= 50:
print('小于20并大于50的浮点数: ', randomFloat)
set_random_float.add(randomFloat) #加入集合
print('随机浮点数集合:', set_random_float)
def randomStr(num): # 2. 1000个随机字符串,输出包含子串“at”的字符串
random_float_str = set()
for i in range(num):#生成1000个字符串
len = 10#每个字符串长度为10
str = ''
for j in range(len):
str += random.choice('abcdefghijklmnopqrstuvwxyz') # 随机生成字符串
random_float_str.add(str)
set_ramdom_str = set(random_float_str)
print('随机字符串:',set_ramdom_str)
for i in random_float_str: # 取出包含at的字符串
if 'at' in i:
print(i)
if __name__ == '__main__': #3.封装后使用主函数
randomFloat(0, 100)
randomStr(1000)
|
835a31c68bb82734fb407a18dc3b5df79e9c6f3d | Aasthaengg/IBMdataset | /Python_codes/p02260/s841811880.py | 748 | 3.84375 | 4 | def selection_sort(alist):
"""Sort alist by selection sort.
Returns the sorted list and number of swap operation.
>>> selection_sort([5, 6, 4, 2, 1, 3])
([1, 2, 3, 4, 5, 6], 4)
"""
size = len(alist)
c = 0
for i in range(size):
mini = i
for j in range(i, size):
if alist[mini] > alist[j]:
mini = j
if i != mini:
alist[i], alist[mini] = alist[mini], alist[i]
c += 1
return (alist, c)
def run():
_ = int(input()) # flake8: noqa
nums = [int(i) for i in input().split()]
(sortednums, count) = selection_sort(nums)
print(" ".join([str(i) for i in sortednums]))
print(count)
if __name__ == '__main__':
run()
|
e98cbe4360f5d601ae362b3491cd236ec0ef7a0c | LinaMeddeb/GuessTheNumber | /GuessTheNumber.py | 916 | 3.9375 | 4 | # Guess my nbr
from random import randint
nbr_essays_max = 5
nbr_essays = 1
max_random = 20
my_nbr = randint(1,max_random) # number chosen by the PC
your_nbr = 0 # Number proposed by the player
print("I chose a number between 1 and",max_random)
print("It's up to you to guess it in ",nbr_essays_max,"attempts at most!")
while your_nbr != my_nbr and nbr_essays <= nbr_essays_max:
print("Essay nbr ",nbr_essays)
while True:
try:
your_nbr = int(input("Your proposition : "))
break
except ValueError:
print("Invalid response. Try again !")
if your_nbr < my_nbr:
print("Too small")
elif your_nbr > my_nbr:
print("Too big")
else:
print("Good Job ! You found ", my_nbr, "in", nbr_essays, "essay(s)")
nbr_essays += 1
if nbr_essays > nbr_essays_max and your_nbr != my_nbr:
print("Sorry, you used your", nbr_essays_max, "essays to no avail")
print("I had chosen the number", my_nbr, ".")
|
46f766b2d8fed1a909a6086b69e4200bdbcf58aa | Hilldrupca/LeetCode | /python/Monthly/Oct2020/sortlist.py | 5,766 | 4.25 | 4 | from typing import Tuple
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def _path(self):
'''Helper method to ensure correct next values'''
res = []
node = self
while node:
res.append(node.val)
node = node.next
return res
class Solution:
'''
LeetCode Monthly Challenge for October 13th, 2020.
'''
def sortList(self, head: ListNode) -> ListNode:
'''
Returns the head node of a linked list after sorting. Uses merge sort,
and attempts to us O(1) memory. Recursive merge sort is commented out
at the end.
Params:
head - The head node of a linked list.
Returns:
ListNode - The (new) head node of the sorted linked list.
Example:
Given the following linked list:
4 -> 2 -> 1 -> 3
sortList(4) -> 1 whose path = 1 -> 2 -> 3 -> 4
'''
if not head or not head.next:
return head
length = self._get_length(head)
gap = 1
while gap < length:
start1 = head
first_iter = True
while start1:
end1 = self._end_point(start1, gap)
# Break in case the first segment is the end of the linked list
start2 = end1.next
if not start2:
break
end2 = self._end_point(start2, gap)
# Store starting point of next iteration
temp = end2.next
start1, end2 = self._merge(start1, end1, start2, end2)
# Piece sorted segments together
if first_iter:
head = start1
first_iter = False
else:
prev.next = start1
prev = end2
start1 = temp
# Ensures tail ListNode's next = None
prev.next = start1
gap *= 2
return head
def _merge(self, start1: ListNode, end1: ListNode,
start2: ListNode, end2: ListNode) -> Tuple[ListNode, ListNode]:
'''
Merges and sorts two linked list segments
Params:
start1 - The starting ListNode of first linked list segment.
end1 - The ending ListNode of first linked list segment.
start2 - The starting ListNode of second linked list segment.
end2 - The ending ListNode of second linked list segment.
Returns:
Tuple[ListNode, ListNode] - Returns both the (new) head ListNode,
and the (new) tail ListNode of the
current segment.
'''
if start1.val > start2.val:
start1, start2 = start2, start1
end1, end2 = end2, end1
head = start1
stop2 = end2.next
while start1 != end1 and start2 != stop2:
if start1.next.val > start2.val:
start1.next, start2.next, start2 = start2, start1.next, \
start2.next
start1 = start1.next
if start1 == end1:
start1.next = start2
else:
end2 = end1
return head, end2
def _end_point(self, node, gap) -> ListNode:
'''
Returns the ListNode at the end of the current gap distance.
Params:
node - The ListNode to start from.
gap - The number of nodes to include in the segment.
Returns:
ListNode - The ListNode at the end of the gap.
'''
while gap > 1 and node.next:
gap -= 1
node = node.next
return node
def _get_length(self, node) -> int:
'''Returns the length of the linked list'''
length = 0
while node:
length += 1
node = node.next
return length
'''
### NOTE: Below is a recursive version of merge sort.
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def middle(node: ListNode) -> ListNode:
slow = fast = node
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
return slow
def sorted_merge(left: ListNode, right: ListNode) -> ListNode:
if left == None:
return right
elif right == None:
return left
elif left.val <= right.val:
left.next = sorted_merge(left.next, right)
return left
else:
right.next = sorted_merge(left, right.next)
return right
def merge_sort(node: ListNode) -> ListNode:
if not node or not node.next:
return node
slow = fast = node
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
next_to_mid = slow.next
slow.next = None
return sorted_merge(merge_sort(node), merge_sort(next_to_mid))
if not head or not head.next:
return head
return merge_sort(head)
'''
|
155f68308b2aee9f02de512c794cd134b1db9b9a | Allen-Maharjan/Sudoku_Queens | /backupqueen.py | 1,391 | 3.578125 | 4 | initial_grid = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
counter = 0
def main():
#let us consider four queens which should not attack each other
counter1 = 0
q = [1,1,1,1]
print(initial_grid)
#putting the queen in the initial grid
for i in range (0,len(q)):
initial_grid[i][0]= q[i]
print(initial_grid)
for i in range (0,len(q)):
if(calculation(initial_grid,len(q),i)==1):
if (i>0):
i = i - 1
if (counter1 == -3):
counter1 = 0
counter1 = counter1 + 1
if (counter == 0):
if (i == 3):
counter1 = -3
print('maharjan')
initial_grid[i][0] = 0
initial_grid[i][counter1+i] = 1
print(initial_grid)
def calculation(initial_grid,num,i):
for j in range (0,num):
if (initial_grid[i][j] == 0 or initial_grid[j][i] == 0 ):
counter = 0
print('name')
#if((i+j)<4 or (j+1)<4):
#if (initial_grid[i+j][j+1] == 0):
# counter = 0
else:
print('allen is my name')
counter = 1
break
return counter
main()
|
eb9617eb4c9a77ef08b7176f8da7cd906c29000c | nladino215/day6-nladino215 | /problemSetDay6.py | 307 | 4.09375 | 4 | # File name: problemSetDay6.py
num = 1
n = int(input("write a number"))
while num <= n:
if num % 2 == 0:
print("# is even")
num += 1
if num % 2 != 0:
print("# is odd")
num += 1
t = "*"
print(t)
while t != "****":
if t != "****":
t += "*"
print(t)
|
b8ef08df95ed33b673247a79f88845a57eb65c26 | HiddenEvent/PYthon_Start | /workspace/.vscode/Day03/Test01.py | 446 | 3.734375 | 4 | 198*256
print("{}*{}={}".format(198,256,198*256))
#문자열과 정수 출력
print("%s : %d"%("나이",20))
print("{} : {}".format("나이", 20))
#실수 출력 -- 파이썬에서는 서식문자를 사용할 떄만 출력시 소수점 6번쨰 자리까지 기본출력이 된다.
print(123.567)
print("%f"%(123.567))
print("%f , %.2f"%(123.567, 123.567))
print("{:f}".format(123.567))
print("{:f} , {:.2f}".format(123.567, 123.567)) |
58027840c7367d8695fb96a13d1f3b3fb6c6e8e1 | pashkewi41/SpecialistPython2_v2 | /Module3/practice/03_task_Fraction_part1.py | 1,813 | 3.9375 | 4 | # Задание "Простые дроби"
class Fraction:
def __init__(self, fraction_str): # Дробь в конструктор передается в виде строки
# А мы храним дробь в виде
self.numerator = ... # числителя
self.denominator = ... # знаменатель
# целую часть перебрасываем в числитель
# минус, если он есть, тоже храним в числителе
def __str__(self):
"""
Возвращает строковое представление в формате: <Целая часть> <числитель>/<знаменатель>
Пример: -3 5/7
"""
pass
# Примеры создания дробей:
f1 = Fraction("3 12/15")
f2 = Fraction("-1 2/6")
f3 = Fraction("2/4")
f4 = Fraction("-2/4")
f5 = Fraction("3/4")
# TODO: Задание: реализуйте операции с дробями
# Примечание: в начальной реализации получившиеся дроби упрощать не требуется.
# При операциях с дробями их можно приводить к максимальному общему знаменателю.
# Сложение
f_sum = f1 + f2
print(f"{f1} + {f2} = {f_sum}")
# Вычитание
f_sub = f3 - f4
print(f"{f3} + {f4} = {f_sub}")
# Умножение
f_mult = f3 * f4
print(f"{f3} * {f4} = {f_mult}")
# Сравнение (> < == != <= >=)
if f5 > f4:
print(f"{f5} > {f4}")
elif f5 < f4:
print(f"{f5} < {f4}")
else:
print(f"{f5} = {f4}")
# Сложение с целым(int) числом
f_sum2 = f1 + 2
print(f"{f1} + {2} = {f_sum2}")
f_sum3 = 2 + f1
print(f"{2} + {f1} = {f_sum2}") |
889c1490773dc07bd1abd1f33462ca696334f809 | sebnorth/flask-python-coursera | /app/static/Memory.py | 2,913 | 3.890625 | 4 | # Mini-project 5 for An Introduction to Interactive Programming in Python class
# based on the template from: http://www.codeskulptor.org/#examples-memory_template.py
import simplegui
import random
memory_deck = range(8) + range(8)
print memory_deck
exposed = [False]*8 + [False]*8
print exposed
board_height = 100
board_width = 800
half_card_width = board_width / 32
half_card_height = 44
first = -1
second = -1
state = 0
turns = 0
# helper function to initialize globals
def new_game():
global state, exposed, first, second, state, turns
first = -1
second = -1
state = 0
turns = 0
exposed = [False]*8 + [False]*8
random.shuffle(memory_deck)
label.set_text("Turns = " + str(turns))
# define event handlers
def mouseclick(pos):
global first, second, state, turns
# add game state logic here
# print pos[0]/(2*half_card_width)
card_number = pos[0]/(2*half_card_width)
if state == 0:
if not exposed[card_number]:
exposed[card_number] = not exposed[card_number]
turns+=1
label.set_text("Turns = " + str(turns))
first = card_number
state = 1
else:
pass
elif state == 1:
if not exposed[card_number]:
exposed[card_number] = not exposed[card_number]
second = card_number
state = 2
else:
if not exposed[card_number]:
if memory_deck[first] == memory_deck[second]:
pass
else:
exposed[first] = not exposed[first]
exposed[second] = not exposed[second]
exposed[card_number] = not exposed[card_number]
turns+=1
label.set_text("Turns = " + str(turns))
first = card_number
state = 1
# cards are logically 50x100 pixels in size
def draw(canvas):
for idx in range(16):
if exposed[idx]:
canvas.draw_text(str(memory_deck[idx]), (half_card_width + idx*board_width/16, board_height/2), 30, 'Red')
else:
LU = [idx*board_width/16, board_height/2 - half_card_height]
RU = [idx*board_width/16 + 2*half_card_width , board_height/2 - half_card_height]
RB = [idx*board_width/16 + 2*half_card_width , board_height/2 + half_card_height]
LB = [idx*board_width/16, board_height/2 + half_card_height]
canvas.draw_polygon([LU,RU,RB,LB], 2, 'Yellow', 'Green')
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(turns))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric
|
93ca60fa6c722bbc59f89c4e37da46239e3ed962 | wellington-ishimaru/IFSP-Funcoes | /questao3.py | 281 | 4.15625 | 4 | #-*- coding: UTF-8 -*-
def soma (num1, num2, num3):
return num1 + num2 + num3
numeros = []
for i in range(0, 3):
numeros.append(float(input(f"Digite o numero {i + 1} de 3: ")))
print(f'A soma dos 3 numeros e igual: {soma(numeros[0], numeros[1], numeros[2])}')
|
49f42081ffb84f868943291bb51f0642cc23556f | muttakin-ahmed/testPythonRepo | /fibonacciSeqGen.py | 379 | 3.828125 | 4 | def fib(n):
a=1
b=1
fib_seq = []
fib_seq.append(a)
fib_seq.append(b)
for i in range(n):
a,b = b,a+b
fib_seq.append(b)
return fib_seq[:n]
while True:
try:
num = int(input("Please enter a number: "))
except:
print("Invalid Input. Please try again.")
continue
else:
print(fib(num))
break
|
fa1c5c648fd562f636721c0649ddbe2217597363 | dongyeon94/basic-exercise-Python | /tkinter_game/maintable.py | 2,176 | 3.53125 | 4 | ## 수정 해야 될듯
from imagebtn import *
from tkinter import *
from random import *
import time
class Maintable(Frame):
n = 0
selected_image = 0
def __init__(self, master, picture, alphabet, width):
super(Maintable, self).__init__()
self.image_number_list = [] # 셔플된 이미지의 번호를 저장하기 위한 리스트. 16개
self.master = master # maintable frame의 parent 설정
self.width = width # maintable의 넓이. = 4
self.n = width * width # maintable에 추가될 이미지 수. = 16
self.picture = picture # app에서 생성한 이미지 받아와서 저장
# 숨겨진 이미지 셔플링
self.random_shuffle()
for i in range(0,self.width):
for j in range(0,self.width):
num =i*self.width+j
w = ImageButton(self, image = alphabet[num])
w.grid(row=i,column=j)
w.add_hidden(alphabet=alphabet[num],hidden=picture[self.image_number_list[num]])
w.bind("<Button-1>", self.show_hidden)
w.bind("<ButtonRelease>", self.hide_picture)
def random_shuffle(self):
for i in range(16):
randnum = randint(0, 15)
while randnum in self.image_number_list:
randnum = randint(0, 15)
self.image_number_list.append(randnum)
return self.image_number_list
# hidden 이미지 셔플링
# 선택된 알파벳 ImageButton의 숨겨진 이미지 출력
def show_hidden(self, event):
event.widget.config(image=event.widget.get_hidden())
def hide_picture(self, event):
time.sleep(1)
selected_image = self.picture.index(event.widget.hidden)
event.widget.config(image=event.widget.alphabet)
# 카드를 알파벳이 보이게 되돌려 놓음
if selected_image== self.master.conveyor.image_number_list[self.master.conveyor.cur_idx]:
self.master.conveyor.correct_match()
else:
self.master.conveyor.wrong_match()
# 뒤집은 카드가 찾는 카드일 경우 또는 그렇지 않을 경우의 처리
|
444d6aa41895fcc6797d84596fa39a4f7d16c288 | avnit/https---github.com-avnit-ContractWork | /Class1/FirstPython.py | 298 | 4 | 4 | print('Hello World Python!')
#first code
n=5
while(n>0):
print(n)
n = n -1
print('done')
# second code
n=10.0
r=10.0
n = int(n)
print(type(r))
r = int(r)
print(type(r))
while(n>0):
while(r>0):
z = n**r
print(n,"*",r,"=",z)
r=r-1
n=n-1
# third code sample
|
3e4f82d16820d3904415ce7ce0a122d4796764a2 | Auphie/univHomework | /semister1/hw_041a.py | 359 | 3.796875 | 4 | def numDecod(string):
res = 0
if string == '' or string[0] == '0':
return res
if len(string) <= 2 and int(string)<=26:
res += 1
if 1 <= int(string[0]) <=26:
res += numDecod(string[1:])
if 1 <= int(string[0:2]) <=26:
res += numDecod(string[2:])
return res
a ='121'
result = numDecod(a)
print(result) |
ad60da822b91373a570d468f016d83d171386ea7 | bettyYHchen/Model-the-Bicycle-Industry | /main.py | 1,705 | 3.59375 | 4 | from Bike_business import *
import random
import copy
bike_list=[]
for j in xrange(6):
j=j+1
name='bike%s'%j
cost=150.00+float(random.choice(range(400)))
weight=50.00+float(random.choice(range(10)))
b=Bicycle(name,weight,cost)
bike_list.append(b)
bike_list[0].cost=101.0
inventory={}
for b in bike_list:
inventory[b.name]=random.choice(range(30))
margin={}
for b in bike_list:
margin[b.name]=0.2*b.cost
my_bshop=BikeShops("red_and_blue",inventory,margin)
c1=Customers('bob',200,'True')
c2=Customers('dave',500,'True')
c3=Customers('jesse',1000,'True')
b1={}
b2={}
b3={}
for b in bike_list:
if b.cost <= 1000:
b3[b.name]=b.cost
if b.cost <= 500:
b2[b.name]=b.cost
if b.cost <= 200:
b1[b.name]=b.cost
print c1.name+" can afford"+str(b1)
print c2.name+" can afford"+str(b2)
print c3.name+" can afford"+str(b3)
print "The initial inventory is"+str(my_bshop.inventory)
profit=0
p1=random.choice(list(b1.keys()))
c1.fund=c1.fund-b1[p1]
my_bshop.inventory[p1]=my_bshop.inventory[p1]-1
profit=profit+my_bshop.margin[p1]
print c1.name+" purchases "+p1+".\n"+c1.name+" now have "+str(c1.fund)+" dollars left."
p2=random.choice(list(b2.keys()))
c2.fund=c2.fund-b2[p2]
my_bshop.inventory[p2]=my_bshop.inventory[p2]-1
profit=profit+my_bshop.margin[p2]
print c2.name+" purchases "+p2+".\n"+c2.name+" now have "+str(c2.fund)+" dollars left."
p3=random.choice(list(b3.keys()))
c3.fund=c3.fund-b3[p3]
my_bshop.inventory[p3]=my_bshop.inventory[p3]-1
profit=profit+my_bshop.margin[p3]
print c3.name+" purchases "+p3+".\n"+c3.name+" now have "+str(c3.fund)+" dollars left."
print "Remaining inventory is"+str(my_bshop.inventory)
print "We made "+str(profit)+" dollars profit"
|
bbfa2d1931c4e03bac83ffdff7c613fe0e63efd0 | marcosviniciussd/CalcProjects | /tempo.py | 425 | 3.75 | 4 |
segundos_str = input("Entre com o numero de segundos que deseja converter: ")
total_segs = int(segundos_str)
horas = 0;
minutos = 0
segundos_restantes = 0
segundos_restantes_final = 0
horas = total_segs // 3600
segundos_restantes = total_segs % 3600
minutos = segundos_restantes // 60
segundos_restantes_final = segundos_restantes % 60
print(horas, "horas, ", minutos, "minutos e", segundos_restantes_final, "segundos.")
|
a3ba38f479a3fe4eb0aaefdce987e2237e191755 | sourcery-ai-bot/Python-Curso-em-Video | /python_exercicios/desafio083.py | 856 | 4.21875 | 4 | # Crie um programa onde o usuário digite uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
while True:
exp = str(input('Digite uma expressão matemática: '))
if exp.count('(') != exp.count(')'):
print('A expressão está incorreta!')
else:
print('A expressão está correta!')
break
# Solução Guanabara
# expr = str(input('Digite a expressão: '))
# pilha = []
# for símb in expr:
# if símb == '(':
# pilha.append('(')
# elif símb == ')':
# if len(pilha) > 0:
# pilha.pop()
# else:
# pilha.append(')')
# break
# if len(pilha) == 0:
# print('Sua expressão está válida!')
# else:
# print('Sua expressão está errada!') |
55fd0d5e3bb62c73193112e6336379950f82edbb | belsouza/backupexercises | /python/partida.py | 2,643 | 3.90625 | 4 | global v_user = 0
global v_comp = 0
partida_vencedor = ""
n = int( input("Quantas peças? ") )
m = int( input("Limite de peças por jogada? ") )
jogada = n % (m+1)
end = False
vezpc = ""
vezuser = ""
if jogada == 0:
print("Você começa!")
vezuser = True
else:
print("O computador começa!")
vezpc = True
while n > 0 or end != False:
if vezuser == True:
npecas = int(input("nQuantas peças você vai tirar?"))
#teste para ver se o numero digitado esta de acordo
if n > npecas:
n = n - npecas
print("Você tirou", npecas ,"peças.\nAgora restam ", n ,"peças no tabuleiro.\n")
vezpc = True
vezuser = False
else:
while n <= npecas:
if npecas > n:
print("Jogada não válida.O mázimo de peças que podem ser retiradas eh", m,"\nTente de novo!")
npecas = int(input("Entre com o valor: "))
if npecas < m:
print("Numero nao valido")
else:
break
else:
n = n - npecas
break
print("Você tirou", npecas ,"peças")
if npecas == 0:
print("Fim de Jogo!")
v_user = v_user + 1
partida_vencedor = "Usuário"
vezpc = True
vezuser = False
end = True
break
else:
vezpc = True
vezuser = False
if vezpc == True:
npecas = m
if n > npecas:
n = n - npecas
print("O computador tirou", npecas ,"peças.\nAgora restam ", n ,"peças no tabuleiro.\n")
vezpc = False
vezuser = True
else:
if n <= npecas:
n = npecas
print("O computador tirou", n ,"peças.\nAcabou!.\n")
v_comp = v_comp + 1
partida_vencedor = "Computador"
end = True
break |
45c37538f3bf62d1141fa15a78bbd663598b620f | pyparsing/pyparsing | /examples/indentedGrammarExample.py | 1,016 | 3.515625 | 4 | # indentedGrammarExample.py
#
# Copyright (c) 2006,2016 Paul McGuire
#
# A sample of a pyparsing grammar using indentation for
# grouping (like Python does).
#
# Updated to use indentedBlock helper method.
#
from pyparsing import *
data = """\
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
"""
stmt = Forward()
suite = IndentedBlock(stmt)
identifier = Word(alphas, alphanums)
funcDecl = (
"def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":"
)
funcDef = Group(funcDecl + suite)
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << (funcDef | assignment | identifier)
module_body = OneOrMore(stmt)
print(data)
parseTree = module_body.parseString(data)
parseTree.pprint()
|
1cc32cc462131ca1a8bfe1fd336ceea804985fb9 | jhylands/sle | /sle/graph.py | 1,818 | 3.609375 | 4 | #!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
import sys
#get the input string and split it into X-axis labels, values, error bars
input =[sys.argv[1].split('Z')]
#split the X-axis labels element into an array of those labels
XLabels = input[0][0].split('Y')
#get a list of the siries colours
COL = input[0][1].split('Y')
#split the means up into siries
SeriesV = input[0][2].split('Y')
#split the error bars up into siries
SeriesE = input[0][3].split('Y')
#Error bar color
ErrCol = input[0][4]
#Ylabel
YLabel =input[0][5]
Means = [x for x in range(0,len(SeriesV))]
for index in range(len(Means)):
Means[index] = SeriesV[index].split('X')
Means[index] = [float(x) for x in Means[index]]
Std = [x for x in range(0,len(SeriesE))]
for index in range(len(Std)):
Std[index] = SeriesE[index].split('X')
Std[index] = [float(x) for x in Std[index]]
#number of bars for each series
N = len(Std)
#array of the error bars
ind = np.arange(N) # the x locations for the groups
width = 0.3 # the width of the bars
fig, ax = plt.subplots()
rects = [0 for x in xrange(len(Means))]
for index in range(len(Means)):
print (index)
wid = width*(index)
print(wid)
# rects[index] = ax.bar(ind + wid , Means[index], width, yerr=Std[index])
rects[index] = ax.bar(ind + wid , Means[index], width, color=COL[index], yerr=Std[index],error_kw=dict(ecolor=ErrCol,lw=2,capsize=5,capthick=2))
# add some lables
ax.set_ylabel(YLabel)
#ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
#array of X axis lables
ax.set_xticklabels( XLabels )
ax.set_xlabel('Question')
#legend lables
#ax.legend( (rects[0][0], rects[1][0], rects[2][0]), ('woMen', 'men', 'Unspecified') )
#save to tempery file
plt.savefig('temp.png')
|
902d90d4c9224a06260a5a8c516dfdfcfa2cab2f | nirvana9/py | /test/ex_02.py | 95 | 3.546875 | 4 | #!/usr/bin/env python
s = 0
for x in range(101):
s = s + x
print s
print sum(range(101))
|
00abf2e887bd0f1d4f36834045ccef65e86906ea | ari-hacks/kata-practice | /tests/python_test/phone_number.py | 650 | 3.859375 | 4 | import unittest
from katas.python.kyu6.phone_number import create_phone_number
class TestCreatePhoneNumber(unittest.TestCase):
def test_create_phone_number(self):
self.assertEqual(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890")
self.assertEqual(create_phone_number([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), "(111) 111-1111")
self.assertEqual(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890")
self.assertEqual(create_phone_number([0, 2, 3, 0, 5, 6, 0, 8, 9, 0]), "(023) 056-0890")
self.assertEqual(create_phone_number([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), "(000) 000-0000")
|
f401968a0bca6f9021f6c1fd927ce9f4b3e3151e | Arin-py07/Python-Recursion | /SumofNaturalNo.py | 103 | 3.65625 | 4 | #Summary
n = 10
n=int(input("Enter n:"))
sum=n*(n+1)//2
print("sum is",sum)
#Output
Enter n:sum is 55
|
9723792da73ae1b60454938393e409f962334b41 | KazutoYunoki/programing-contest | /atcoder/abc143/c.py | 246 | 3.640625 | 4 | def main():
N = int(input())
S = list(input())
merge = []
sura = S[0]
merge.append(sura)
for i in S:
if i != merge[-1]:
merge.append(i)
print(len(merge))
if __name__ == "__main__":
main()
|
34748d3856c7a66ce05e3f8835b3b02e741ddd79 | KloseRinz233/gobang | /tools.py | 2,286 | 3.734375 | 4 | def check_position(array,x,y):
if(x<0 or x>14 or y<0 or y>14):
return False
else:
return array[x][y]
def check_surrounding(array,x,y,deep):
for i in range(-deep,deep+1):
for j in range(-deep,deep+1):
if((i!=0 or j!=0) and (check_position(array,x+i,y+j)==1 or check_position(array,x+i,y+j)==2)):
return 1
return 0
def get_possible_position(array):
possible_position1=[]
possible_position2=[]
for i in range(0,15):
for j in range(0,15):
if(check_surrounding(array,i,j,1) and check_position(array,i,j)==0):
possible_position1.append([i,j])
elif(check_surrounding(array,i,j,2) and check_position(array,i,j)==0):
possible_position2.append([i,j])
possible_position1.extend(possible_position2)
return possible_position1
def check_win(array):
chess_type=0
flag=1
draw=1
for i in range(0,15):
for j in range(0,15):
if(check_position(array,i,j)==1 or check_position(array,i,j)==2):
chess_type=check_position(array,i,j)
flag=1
for k in range(1,5):
if(check_position(array,i-k,j)!=chess_type):
flag=0
break
if(flag==1):
return [chess_type,'win']
flag=1
for k in range(1,5):
if(check_position(array,i-k,j-k)!=chess_type):
flag=0
break
if(flag==1):
return [chess_type,'win']
flag=1
for k in range(1,5):
if(check_position(array,i,j-k)!=chess_type):
flag=0
break
if(flag==1):
return [chess_type,'win']
flag=1
for k in range(1,5):
if(check_position(array,i-k,j+k)!=chess_type):
flag=0
break
if(flag==1):
return [chess_type,'win']
else:
draw=0
if(draw==1):
return [0,'draw']
return False |
4b5e18f174f912f9710e729248af3245d49944af | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/ptrjas005/question3.py | 176 | 4.125 | 4 | print("Approximation of pi: 3.142")
x = eval(input("Enter the radius:\n"))
area = round(x**2*3.142,3)
if (area==19.637):
print("Area: 19.635")
else:
print("Area:",area) |
ca5385f438ebf6c3a585795a0cc528f81b2ef1cf | TheAlphaQuacker/second-try-at-my-quiz | /main.py | 386 | 3.671875 | 4 | from tkinter import *
class MainScreen:
def __init__ (self, master):
background_color = "black"
self.main_frame = Frame(master, bg = background_color, padx=100, pady=100)
self.main_frame.grid()
self.Heading_label = Label(self.main_frame, )
if __name__ == "__main__":
root = Tk()
root.title("Quiz on Global Pollution")
root.mainloop() |
08759d17585271d4d521202a7bf08bb2b92ba443 | scheidguy/ProjectE | /1-50/prob5.py | 337 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 15:53:51 2020
@author: schei
"""
max_val = 20
num = 20
not_done = True
while not_done:
for mod in range(max_val, 1, -1):
if num % mod != 0:
num += 1
break
elif mod == 2:
not_done = False
print(num)
break
|
a91fd2c4444d81f9677dbd38ca1bd93af1b7b06b | adh2004/Python | /Lab10/Lab10P2.py | 482 | 4.28125 | 4 | import length
def main():
inches = 0
feet = 0
m = 0
cm = 0
miles = 0
km = 0
inches = int(input('How many inches?: '))
cm = length.inches_to_cm(inches)
print('It is equivalent to ', cm , ' cm')
feet = int(input('How many feet?: '))
m = length.feet_to_m(feet)
print('It is equivalent to ', m , ' m')
miles = int(input('How many miles?:'))
km = length.miles_to_km(miles)
print('It is equivalent to ', km , ' km')
main()
|
a2faf5e7f112893f4ed86ff42dfffd7008cef0a6 | jinzhe-mu/muwj | /class_python/异常.py | 909 | 3.921875 | 4 | ##出现了异常进行异常捕获,当不知道异常时候,可以直接用except: 不加具体异常进行捕获
while True:
try:
num1 = int(input("输入一个除数"))
num2 = int(input("输入一个被除数"))
print(num1/num2)
break
except ZeroDivisionError:
print("被除数不能为零")
except ValueError:
print("请输入数值型整数")
except:
print("输入数字异常")
# else:
# print("没有发生异常")
# finally:
# print("发没有发生异常都执行")
#抛出异常:
print("抛出异常:")
x = 10
if x > 5:
raise Exception("这是一个抛出的异常")
#自定义异常:
print("自定义异常:")
class MyException(Exception):
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
raise MyException ("value1", "value2") |
d3ca48f3a24cbd97bf60ac340112fd850f4038e2 | oskomorokhov/python | /study/checkio/Home/caesar_cipher_encryptor.py | 1,575 | 3.828125 | 4 | #!/usr/bin/env checkio --domain=py run caesar-cipher-encryptor
# https://py.checkio.org/mission/caesar-cipher-encryptor/
# This mission is the part of the set. Another one -Caesar cipher decriptor.
#
# Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar cipher where each letter of input text is replaced by another that stands at a fixed distance. For example ("a b c", 3) == "d e f"
#
#
#
# Input:A secret message as a string (lowercase letters only and white spaces)
#
# Output:The same string, but encrypted
#
# Precondition:
# 0<len(text)<50
# -26<delta<26
#
#
# END_DESC
def to_encrypt(text, delta):
import string
alphabet = string.ascii_lowercase
cipher = []
for i in text.lower():
if i == " ":
cipher.append(" ")
continue
if alphabet.index(i)+delta > 26:
cipher.append(alphabet[alphabet.index(i)-(26-delta)])
else:
cipher.append(alphabet[alphabet.index(i)+delta])
return "".join(cipher)
if __name__ == '__main__':
# print("Example:")
#print(to_encrypt('abc', 10))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert to_encrypt("a b c", 3) == "d e f"
assert to_encrypt("a b c", -3) == "x y z"
assert to_encrypt("simple text", 16) == "iycfbu junj"
assert to_encrypt("important text", 10) == "swzybdkxd dohd"
assert to_encrypt("state secret", -13) == "fgngr frperg"
print("Coding complete? Click 'Check' to earn cool rewards!")
|
6e2f8de1fec7a67963b5b7847f90e3425ce9cbfd | saikirandulla/HW05 | /HW05_ex09_01.py | 680 | 3.84375 | 4 | #!/usr/bin/env python
# HW05_ex09_01.py
# Write a program that reads words.txt and prints only the
# words with more than 20 characters (not counting whitespace).
##############################################################################
# Imports
# Body
def long_words():
try:
fin = open('words.txt')
line = fin.readline()
for line in fin:
s = line.split()
for i in range (len(s)):
if len(s[i]) > 20:
print s[i]
except:
print 'Something went wrong with the file'
##############################################################################
def main():
# Call your functions here.
long_words()
if __name__ == '__main__':
main()
|
05a867311f8a3c72881ac5978b57847b3e1efe09 | Monster-Moon/hackerrank | /baekjoon/02/9498.py | 197 | 3.578125 | 4 |
score = int(input())
score_dic = {'A' : [90, 100], 'B': [80, 89], 'C': [70, 79], 'D': [60, 69], 'F': [0, 59]}
print([i[0] for i in score_dic.items() if score >= i[1][0] and score <= i[1][1]][0])
|
cb06d55273dbe85bbfce046c4301478fbb9e9bb1 | hcodydibble/data-structures | /src/quick_sort.py | 570 | 4.03125 | 4 | """Function for implementing a quick sort algorithm."""
def quick_sort(a_list):
"""Quick sort algorithm."""
if isinstance(a_list, list):
if len(a_list) < 2:
return a_list
ref_num = [a_list.pop(0)]
bigger_nums = []
smaller_nums = []
for num in a_list:
if num > ref_num[0]:
bigger_nums.append(num)
else:
smaller_nums.append(num)
return quick_sort(smaller_nums) + ref_num + quick_sort(bigger_nums)
else:
raise ValueError("Lists only")
|
56e8a3f3b6f91cd94a02152b42cf6f4a96a73638 | nick-delgado/python | /googleapi.py | 752 | 3.734375 | 4 | import googlemaps
from datetime import datetime
#API-KEY= AIzaSyDV93OxljDchBbiBHjfjfbhpMMIyn3aYs8
gmaps = googlemaps.Client(key='AIzaSyDV93OxljDchBbiBHjfjfbhpMMIyn3aYs8')
reverse_geocode_result = gmaps.reverse_geocode((35.10873, -86.11313))
#what is returned?
#what can be parsed?
#is it always consistent?
#does it change based on location?
# in higher concentration areas of POI is there a filtering system to decrease results or to filter results to what we need?
geocode_result = gmaps.geocode('37363')
#can i return an geolocation from this?
#then use that geopoint to find airports within that radius?
#what about very large zip code areas?
#what about doing a functions that if no top 10 airports are found then increase the mileage radius search?
print(reverse_geocode_result)
print(geocode_result)
|
4f83e3c6cf695e27e17a07cfd778262aad65a718 | T-Douwes-UU/NumeriekeMethoden | /Project 1/1.10.2.3_template.py | 6,243 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################## PART 3 ##########################
"""
We can now make the pendulum a bit more realistic, by adding a viscous friction with air.
The equation of motion of the pendulum with the addition of viscous friction become
theta''(t) = -(g/L) * sin(theta(t)) - beta * theta'(t)
with beta being a viscous friction coefficient.
The equations can be decomposed in
omega'(t) = -(g/L) * sin(theta(t)) - beta * omega(t)
theta'(t) = omega(t)
and can again be integrated using the runge-kutta algorithm.
The resulting trajectories are shown together with the ones of the pendulum without friction.
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
plt.close('all')
t = np.linspace(0,100,10001)
dt = t[1] - t[0] #timestep
g = 9.8 #m/s**2
L = 1.
theta_0 = np.deg2rad(60)
omega_0 = 0
#Define the viscous coefficient
beta = 0.5
def derivatives_simple_pendulum(state, t):
"""
state: numpy array giving the state of the pendulum at time t (theta and omega)
Function that returns the derivatives
theta'(t) = omega(t)
omega'(t) = ...
Returns a np.array containing the derivatives (theta', omega')
"""
#YOUR CODE GOES HERE
#Define the derivatives of theta and omega (the function to integrate)
def derivatives_pendulum_with_friction(state, t):
"""
state: numpy array giving the state of the pendulum at time t
Returns an np.array (theta',omega') with the derivatives of theta and omega
"""
#YOUR CODE GOES HERE
def runge_kutta(old_state, t, dt, derivatives):
"""
state: numpy array giving the state of the pendulum at time t
t: starting time
dt: integration step
derivatives: function that calculate the derivatives of the coordinates
Function that performs an integration step using to runge-kutta algorithm
Returns an np.array containing the new state (theta, omega)
"""
#Calculate the ks
k1 = dt * derivatives(old_state, t)
k2 = dt * derivatives(old_state + (0.5 * k1), t + 0.5 * dt)
k3 = dt * derivatives(old_state + (0.5 * k2), t + 0.5 * dt)
k4 = dt * derivatives(old_state + k3, t + dt)
#And consequently the new state of the system
new_state = old_state + (k1 + 2*k2 + 2*k3 + k4) / 6.
return new_state
def pendulum_location(theta,L):
"""
Returns the location of the pendulum end as a function of the angle and length
"""
x = L * np.sin(theta)
y = - L * np.cos(theta)
return np.array([x,y])
state_fric = np.array([[theta_0,omega_0]]) #create arrays containing the initial angle/velocity/location of the pendulum
x_y_fric = pendulum_location(theta_0,L)
state_simple = np.array([[theta_0,omega_0]])
x_y_simple = pendulum_location(theta_0,L)
for index,time in enumerate(t[1:]): #update the pendulum angle/velocity/location using the runge kutta integration
state_new_fric = runge_kutta(state_fric[index,:],time,dt,derivatives_pendulum_with_friction)
x_y_new_fric = pendulum_location(state_new_fric[0],L)
state_new_simple = runge_kutta(state_simple[index,:],time,dt,derivatives_simple_pendulum)
x_y_new_simple = pendulum_location(state_new_simple[0],L)
state_fric = np.vstack((state_fric,state_new_fric))
x_y_fric = np.vstack((x_y_fric,x_y_new_fric))
state_simple = np.vstack((state_simple,state_new_simple))
x_y_simple = np.vstack((x_y_simple,x_y_new_simple))
def execute_part3():
t_window = 0.1*t[-1]
fig,ax = plt.subplots(2,2)
anim_theta_fric, = ax[0,0].plot([],[],'b-')
anim_theta_simple, = ax[0,0].plot([],[],'b--')
ax[0,0].set_xlim(0, t_window)
ax[0,0].set_ylim(-1.1*np.max(np.abs(state_simple[:,0])),1.1*np.max(np.abs(state_simple[:,0])))
ax[0,0].set_xlabel('t')
ax[0,0].set_ylabel(r'$\theta$(t)')
anim_omega_fric, = ax[0,1].plot([],[],'r-')
anim_omega_simple, = ax[0,1].plot([],[],'r--')
ax[0,1].set_xlim(0, t_window)
ax[0,1].set_ylim(-1.1*np.max(np.abs(state_simple[:,1])),1.1*np.max(np.abs(state_simple[:,1])))
ax[0,1].set_xlabel('t')
ax[0,1].set_ylabel(r'$\omega$(t)')
anim_pendulum, = ax[1,0].plot([],[],'bo-')
anim_trajectory, = ax[1,0].plot([],[],'r-')
ax[1,0].set_xlim(-1.1*np.max(np.abs(x_y_simple[:,0])),1.1*np.max(np.abs(x_y_simple[:,0])))
ax[1,0].set_ylim(-1.1*np.max(np.abs(x_y_simple[:,1])),1.1*np.max(np.abs(x_y_simple[:,1])))
ax[1,0].set_xlabel('x(t)')
ax[1,0].set_ylabel('y(t)')
anim_phase, = ax[1,1].plot([],[],'b-')
ax[1,1].set_xlim(-1.1*np.max(np.abs(state_simple[:,0])),1.1*np.max(np.abs(state_simple[:,0])))
ax[1,1].set_ylim(-1.1*np.max(np.abs(state_simple[:,1])),1.1*np.max(np.abs(state_simple[:,1])))
ax[1,1].set_xlabel(r'$\theta$(t)')
ax[1,1].set_ylabel(r'$\omega$(t)')
def init():
anim_theta_fric.set_data([], [])
anim_theta_simple.set_data([], [])
anim_omega_fric.set_data([], [])
anim_omega_simple.set_data([], [])
anim_pendulum.set_data([], [])
anim_trajectory.set_data([], [])
anim_phase.set_data([], [])
#The animation function which is called every frame
def animate(i, state,state_sa,x_y,x_y_sa):
anim_theta_fric.set_data(t[0:i],state_fric[0:i,0])
anim_theta_simple.set_data(t[0:i],state_simple[0:i,0])
anim_omega_fric.set_data(t[0:i],state_fric[0:i,1])
anim_omega_simple.set_data(t[0:i],state_simple[0:i,1])
anim_pendulum.set_data([0,x_y_fric[i,0]],[0,x_y_fric[i,1]])
anim_trajectory.set_data(x_y_fric[0:i,0],x_y_fric[0:i,1])
anim_phase.set_data(state_fric[0:i,0],state_fric[0:i,1])
if t[i] > t_window:
ax[0,0].set_xlim(t[i]-t_window, t[i])
ax[0,1].set_xlim(t[i]-t_window, t[i])
#Call the animator
anim = animation.FuncAnimation(fig, animate, init_func=init, fargs=(state_fric,state_simple,x_y_fric,x_y_simple), interval=10) #change interval for the plotting speed
return anim
|
542624d0e5e0373763a9b0b886d40fc269c2925a | paulrodriguez/daily-coding-problem | /problem_137.py | 1,090 | 4.125 | 4 | '''
Implement a bit array.
A bit array is a space efficient array that holds a value of 1 or 0 at each index
init(size): initialize the array with size
set(i, val): updates index at i with val where val is either 1 or 0.
get(i): gets the value at index i.
'''
'''
time complexity: O(1)
space complexity: O(1) ? (only using one 32-bit number)
might want to create an array of integers where each one can hold 32 bits
'''
class BitArray:
def __init__(self,size):
self.size = size
self.arr = 0#1 << (self.size+1)
def set(self,i,val):
if i >=self.size:
return
if ((1<<i)&self.arr) !=0:
if val == 0:
self.arr = self.arr ^ (1 << i)
else:
if val == 1:
self.arr = self.arr ^ (1 << i)
def get(self,i):
if ((1 << i)&self.arr) !=0:
return 1
else:
return 0
ba = BitArray(10)
ba.set(2,1)
assert ba.get(2) == 1
ba.set(0,0)
assert ba.get(0) == 0
ba.set(0,1)
assert ba.get(0) == 1
ba.set(5,1)
assert ba.get(5) == 1
assert ba.get(4) == 0
|
abab52e44e2653a6e81fe719c592b289ce17fae2 | williamsyb/mycookbook | /algorithms/BAT-algorithms/Tree/二叉查找树-两数之和.py | 1,616 | 4.09375 | 4 | """
一、题目
给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
二、案例
输入:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
输出: True(因为存在 2 + 7 = 9)
三、思路
使用中序遍历得到有序数组之后,再利用双指针对数组进行查找。
应该注意到,这一题不能用分别在左右子树两部分来处理这种思想,因为两个待求的节点可能分别在左右子树中。
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 中序遍历 非递归实现
def inorder_traversal(root, nums):
stack = []
cur = root
if root is None:
return nums
while len(stack) != 0 or cur is not None:
while cur is not None:
stack.append(cur)
cur = cur.left
node = stack.pop()
nums.append(node.val)
cur = node.right
def findTarget(root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
nums = []
inorder_traversal(root, nums)
start = 0
end = len(nums) - 1
while start < end:
if nums[start] + nums[end] == k:
return True
elif nums[start] + nums[end] < k:
start += 1
else:
end -= 1
return False
if __name__ == '__main__':
from .tree import construct_tree
root = construct_tree()
print(findTarget(root, 9))
|
441a7d743a3e9aae1dab54eec1750bc4517f7119 | Wolemercy/monty-hall | /monty-hall.py | 1,864 | 3.796875 | 4 | # The Monty Hall Problem
import random
# Instantiating a random treasure map
def single_run():
maps = ['wasteland', 'wasteland', 'wasteland']
treasure_index = random.randint(0, 2)
maps[treasure_index] = 'one piece'
return maps
# Luffy's first choice
def luffy():
luffy_first_choice = random.randint(0, 2)
return luffy_first_choice
# Monty's choice of a location that is neither Luffy's choice nor the treasure location
def monty(maps, luffy_first_choice):
monty_choice = 0
while monty_choice == luffy_first_choice or maps[monty_choice] == 'one piece':
monty_choice += 1
return monty_choice
# switch Luffy's choice
def luffy_switch(luffy_first_choice, monty_choice):
luffy_switch_choice = 0
while luffy_switch_choice == luffy_first_choice or luffy_switch_choice == monty_choice:
luffy_switch_choice += 1
return luffy_switch_choice
# output to be displayed
def output(stick, switch, trials):
stick_percent = round((stick/trials) * 100)
switch_percent = round((switch/trials) * 100)
print(f'Luffy found One Piece {stick_percent} % of the time when he decided to stick to his initial choice ')
print(f'Luffy found One Piece {switch_percent} % of the time when he decided to switch his initial choice')
print('The Monty Hall Problem')
trials = int(input('Enter the number of trials: '))
# Luffy sticks
stick_count = 0
# Luffy switches
switch_count = 0
for i in range(trials):
maps = single_run()
luffy_first_choice = luffy()
monty_choice = monty(maps, luffy_first_choice)
luffy_switch_choice = luffy_switch(luffy_first_choice, monty_choice)
if maps[luffy_first_choice] == 'one piece':
stick_count += 1
elif maps[luffy_switch_choice] == 'one piece':
switch_count += 1
output(stick_count, switch_count, trials)
|
9aa88f0b5dc3921b398cc59305289ffabd54d14b | DavidSchmidtSBU/DavidSchmidtSBU.github.io | /Bible2.py | 814 | 4.09375 | 4 | # First find a bible in text form
inFile = open('KJV12.TXT', 'r')
MyWord = 'God' #Initialize MyWord
count = 0 #Initialize count
inLine = inFile.readline() #Read in a line of text
while (inLine != ''): #While more lines to read
lineList = inLine.split(' ') #Split words into a list
# Look through the list. If the word God is found,
# add 1 to count
for i in range (0, len(lineList)):
if (lineList[i] == MyWord):
count = count + 1
# Go get another doughnu…line of text
inLine = inFile.readline()
# Done—just read the entire Bible. Superpower? Not quite..
print("The word God was used: ", count)# …but still…
print("End of processing!")
inFile.close() # Done!
|
e6aebf71ce7887dbc48b05a3b49a6bf365c5677e | BreakZhu/py_recommend_demo | /sort/insertSort.py | 1,214 | 4.03125 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
插入排序:
对于一个n个数的数列:
拿出第二个数,跟第一个比较,如果第二个大,第二个就放在第一个后面,否则放在第一个前面,这样前两个数就是正确顺序了
拿出第三个数,跟第二个数比较,如果比第二个数小,就放在第二个数前面,再跟第一个数比,比第一个小就放在第一个前面,这样前三个数就是正确顺序
....
拿出最后一个数,跟之前的正确顺序进行比较,插入到合适的位置当中。
可以理解成: 每次拿到一个数,他前面都是一个有序的数列,然后,找到我何时的位置,我插入进去
最坏时间复杂度: O(n^2)
最优时间复杂度: O(n)
稳定性:稳定的排序
"""
def insertSort(arr):
length = len(arr)
for i in range(1, length):
x = arr[i]
for j in range(i, -1, -1):
# j为当前位置,试探j-1位置
if x < arr[j-1]:
arr[j] = arr[j-1]
else:
# 位置确定为j
break
arr[j] = x
arr = [4, 7, 8, 2, 3, 5]
insertSort(arr)
print(arr) |
cd22553a918a290415e26406e8f8e0ccb306d066 | sai-kumar-peddireddy/PythonLearnigTrack | /Tuples/Tuples.py | 1,581 | 4.21875 | 4 | """
Tue Jul 24 04:49:08 IST 2018
source : https://www.geeksforgeeks.org/tuples-in-python/
Tuples
Tuples are similar to lists. repetition, nesting, indexing is similar to list
Tuples are immutable lists are mutable
Tuples are represented in ()
"""
t1 = () # empty tupple
print(t1, "\tlen(t1)", len(t1))
t = (1, 5, 7, "Sai kumar", "Peddireddy") # creation of tupple
print("t[0]", t[0]) # accessing tupple
print("t[-1]", t[-1])
# Slicing tupple
print("t[:-2]", t[:-2])
print("t[::-2]:", t[::-2])
print("t[1:3]", t[1:3])
# printing tupple
for i in t:
print(i, "\t", end="")
print("\n", t)
# Concatenation of tupples
t2 = ("abc", 2.5, 55, 77)
print("t:", t, "\nt2:", t2, "\nt1+t2:", t+t2)
# nesting tupples
t3 = (t, t2)
print("t3:", t3)
print("t3[1][0][1:]", t3[1][0][1:])
# repetition
print("t2 * 2 :", t2 * 2)
t4 = t2 * 2
print("t4", t4)
# tuples are immutable when we try to change gives an error
# t4[1] = 2 gives an error
print("len(t3):", len(t3), "\tlen(t3[0])", len(t3[0])) # finding the length
# conveting list to tupple
li = [1, "!!", 3.33, 1]
t5 = tuple(li)
print("list:", li, "\tlist converted into tupple", t5)
# tuple functions
print("t5.count(1):", t5.count(1)) # counts number of occurrences in tuple
print("t5.index(1):", t5.index(1)) # index of element first occurrences in tuple
t6 = (1, 5, 9, 0, 89)
print("maximum element max(t6):", max(t6))
print("minimum element min(t6):", min(t6))
t7 = ("abc", "sai", "kumar", "peddireddy")
print("maximum element max(t6):", max(t7))
print("minimum element min(t6):", min(t7))
|
f73e8fbd52485cdbfb4e189293cc795f47c99c84 | rudolphlogin/Python_training | /class and modules/write_file_txt.py | 1,786 | 3.78125 | 4 | '''Demonstrate writing text to a file'''
from io import UnsupportedOperation
print('Default Windows 10 encoding "cp1252".')
with open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\written.txt',mode='w') as out_file:
out_file.write('This is the first line of text.\n')
with open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\written.txt',mode='a') as append_file:
append_file.write('This line is appended at the end.\n')
with open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\written.txt',mode='r') as in_file:
print(in_file.read())
lines = (
'Line 1\n','Line 2\n',
'Line 3\n','Line 4\n'
)
''' Using a file without the "with" context'''
try:
out_file = open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\without.txt',mode='w',buffering=1,encoding='us')
out_file.writelines(lines)
out_file.flush()
finally:
out_file.close()
try:
in_file = open('without.txt',encoding='us')
print(in_file.tell(),end=' <- File position before first read\n')
print(in_file.read(7))
print(in_file.tell(),end='<- File position after first read\n')
print(in_file.read(7))
print(in_file.tell(),end='<- File position after second read\n')
in_file.seek(0,0) # seek(offset, from_what) from_what=0 is BOF
print(in_file.tell(),end ='<- BOF after seek(0,0)\n')
in_file.seek(0,2) # from_what=2 is EOF
print(in_file.tell(),end=' <- BOF after seek(0,0)\n')
print(in_file.read()) # print from position to end
print(in_file.tell(), end=' <- EOF after read() \n')
in_file.seek(7,1) # from_what =1 is relative to position -- it is not supported in python 3
print(in_file.tell(), end=' <- File position after relative seek \n')
except UnsupportedOperation:
print('Text files do not support relative seeks')
finally:
in_file.close()
|
7ed5687461706e83a8a8bd4fbf4a977e3af7705a | finalshake/machine-learning | /python/thread.py | 982 | 3.625 | 4 | import threading, time
str = ''
counter = 0
lock = threading.Lock()
def do_count():
global counter
print('%s counting to %d' %(threading.current_thread().name, counter))
counter += 1
time.sleep(1)
def count():
global counter
global str
switcher = False
while True:
if str == 'stop':
switcher = False
elif str == 'start':
switcher = True
if switcher:
do_count()
else:
counter = 0
continue
def ask_loop():
global str
while True:
print('input something:')
lock.acquire()
str = input()
lock.release()
print('recived %s' %str)
if __name__ == '__main__':
count_thread1 = threading.Thread(target=count, name='count_thread1', args=())
count_thread2 = threading.Thread(target=count, name='count_thread2', args=())
count_thread1.start()
time.sleep(0.3)
count_thread2.start()
ask_loop()
|
e257c939df135cf613423568d384504b3a30bb79 | paulacaicedo/TallerAlgoritmos | /ejercicio20.py | 317 | 3.84375 | 4 |
#EJERCICIO 20
numero=int(input("Introduzca un diigto: "))
numero_nn=numero*11
numero_nnn=numero*111
resultado=numero+numero_nn+numero_nnn
print("El valor digitado es: ",numero)
print("El valor digitado nn: ",numero_nn)
print("El valor digitado nnn: ",numero_nnn)
print("El resultado de la suma es: ",resultado)
|
2a8c23a5f3c59a1e61e3582212f51b9f5761605a | jpmacveigh/Particule_atmos | /ew.py | 559 | 3.5625 | 4 | def ew (temperature):
""" Calcul de la pression de vapeur saturante (hPa)
en fonction de la température (°C) par la formule de Tetens
formule de Tetens: ew=6.107*10**(7.5*temperature/(temperature+237.3))
Permet de calculer, par définition de sa température du point de
rosée Td, la pression de vapeur d'une particule = e=ew(Td). """
ew=6.107*10**(7.5*temperature/(temperature+237.3))
return ew
#print ew(10) # pression de vapeur saturante avec T = 10°c
#print ew(8) # pression de vapeur avec Td= 8 °C |
101baddd04f942e5937f4d3df88ca44abc32b4bd | shaked-nesher/mat1 | /equations.py | 1,547 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 14:59:31 2021
@author: shaked nesher
"""
def pow1(z, num):
sumpow = 1
for i in range(num):
sumpow *= z
return float(sumpow)
def factorial(num):
sumfactorial = 1
for i in range(1, num + 1):
sumfactorial *= i
return float(sumfactorial)
def exponent(x: float) -> float:
try:
sumexponent = 1
for i in range(1, 101):
sumexponent += pow1(x, i) / factorial(i)
return float(sumexponent)
except:
return float(0)
def abs (x):
if x<0:
return float(-x)
else:
return float(x)
def Ln(x: float) -> float:
try:
if x == 1 or x<=0:
return float(0)
yn = x-1.0
yn1=0
tmp=yn
while (abs(yn-yn1)>0.001):
yn=tmp
yn1= yn + 2 * ((x - exponent(yn)) / (x + exponent(yn)))
tmp=yn1
return float(yn1)
except:
return float(0)
def XtimesY(x: float, y: float) -> float:
try:
if x > 0:
sumxtimey=exponent(y * Ln(x))
sumxtimey=('%0.6f' % sumxtimey)
return float(sumxtimey)
else:
return float(0)
except:
return float(0)
def sqrt(x:float,y:float) -> float:
try:
if y>0 and x!=0:
sumsqrt=XtimesY(y,1/x)
sumsqrt=('%0.6f' % sumsqrt)
return float(sumsqrt)
else:
return float(0)
except:
return float(0)
def calculate(x:float) -> float:
try:
final=exponent(x)*XtimesY(7,x)*XtimesY(x,-1)*sqrt(x,x)
final=('%0.6f' % final)
return float(final)
except:
return float(0)
|
3c63f5f208d7e5a8075ed4bc4ca1bdc3c8ddb3af | 152midnite/Vision | /verification/metrics.py | 1,526 | 3.609375 | 4 | answers = {}
with open('./results','r') as file1:
lines = file1.readlines()
for line in lines:
print(line)
key, value = line.split(' ')
key, value = key[:],value[:-1]
if key in answers:
if value in answers[key]:
continue
else:
answers[key].append(value)
else:
answers[key] = [value]
[print(element,answers[element]) for element in answers]
result = 0
for element in answers:
for value in answers[element]:
print(value,element)
if element == value:
result += 1
print(result)
print(len(answers))
def hamming_distance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
if len(s1) != len(s2):
#print("Undefined for sequences of unequal length")
return None
return sum(el1 != el2 for el1, el2 in zip(s1, s2))
distances = []
for element in answers:
if len(answers[element]) == None:
pass
elif len(answers[element]) > 1:
sub_distances = []
for i in answers[element]:
sub_distances.append(hamming_distance(element,i))
if sub_distances:
sub_distances = [x for x in sub_distances if x is not None]
distances.append(min(sub_distances))
else:
distance = hamming_distance(element,answers[element][0])
distances.append(distance)
distances = [x for x in distances if x is not None]
print(distances)
print(sum(distances)/len(distances))
|
48d709b8d433781039928bc7e31677aaabeca49c | girishgupta211/algorithms | /string/rearrange_sentence.py | 721 | 3.765625 | 4 | def rearrangeTheSentence(sentence):
dot_exists = False
if sentence[-1] == ".":
sentence = sentence[:-1]
dot_exists = True
arr = sentence.split(' ')
n = len(arr)
arr[0] = arr[0].lower()
for i in range(1, n):
word = arr[i]
j = i - 1
while j >= 0 and len(word) < len(arr[j]):
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = word
arr[0] = arr[0].title()
result = " ".join(arr)
if dot_exists:
result = result + "."
return result
if __name__ == "__main__":
# sentence = "Houston we have a problem"
sentence = "It is in the sun the beach hottest."
res = rearrangeTheSentence(sentence)
print(res)
|
874a39ff6f49b7cba3d279f1d311a2b22479b555 | wenjunli-0/Simulation-Methods-for-Stochastic-Systems | /codes/project2_Q1.py | 2,072 | 3.515625 | 4 | # Question 1
import numpy as np
import matplotlib.pyplot as plt
# part (a)
N = 1000 # switch N among: 100, 500, 1000
samples = np.random.uniform(-3, 2, N)
counts, bins, ignored = plt.hist(samples, edgecolor='black', alpha=0.75)
plt.figure(1)
plt.title("Histogram of {} Uniformly Distributed Samples".format(N))
plt.xlabel("Sample Values")
plt.ylabel("Frequency")
plt.show()
# part (b)
sample_mean = np.mean(samples)
sample_variance = np.var(samples)
print("sample mean = {} and sample variance = {}".format(sample_mean, sample_variance))
# part (c)
from sklearn.utils import resample
N_resample = 1000 # number of resample
std = []
mean = []
# re-sample, compute corresponding mean & std, and store them
for i in range(N_resample):
re_samples = resample(samples, n_samples=len(samples), replace=True)
mean.append(np.mean(re_samples))
std.append(np.std(re_samples))
# sort mean and std
mean = np.sort(mean)
std = np.sort(std)
# compute 95% confidence interval
a = 95
per_1_mean = np.percentile(mean, (100-a)/2, interpolation='nearest')
per_2_mean = np.percentile(mean, (100+a)/2, interpolation='nearest')
print('The ', str((100-a)/2), '% percentile mean is: ', str(per_1_mean))
print('The ', str((100+a)/2), '% percentile mean is: ', str(per_2_mean))
per_1_std = np.percentile(std, (100-a)/2, interpolation='nearest')
per_2_std = np.percentile(std, (100+a)/2, interpolation='nearest')
print('The ', str((100-a)/2), '% percentile std is: ', str(per_1_std))
print('The ', str((100+a)/2), '% percentile std is: ', str(per_2_std))
# plot
plt.figure(2)
bins = np.arange(min(mean) - 0.1, max(mean)+0.1, 0.02)
plt.hist(mean, bins, edgecolor='black', alpha=0.75)
plt.title("Bootstrap Confidence Interval for Sample Mean")
plt.ylabel("Frequency")
plt.xlabel("Sample Means")
plt.show()
plt.figure(3)
bins = np.arange(min(std) - 0.1, max(std)+0.1, 0.01)-0.5
plt.hist(std, bins, edgecolor='black', alpha=0.75)
plt.title("Bootstrap Confidence Interval for Sample Deviation")
plt.ylabel("Frequency")
plt.xlabel("Sample Deviations")
plt.show()
|
be6c47fc775d7b01e5ea4670f1d69ae9f963eb50 | Ciuel/Python-Grupo12 | /Materia/Practicas/Practica2/Practica2E10.py | 1,309 | 3.890625 | 4 | '''
10. Escriba un programa que solicite por teclado una palabra y calcule el valor de la misma dada
la siguiente tabla de valores del juego Scrabble:
Letra valor
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10
*Tenga en cuenta qué estructura elige para guardar estos valores en Python
Ejemplo 1
• Palabra: “solo”
• valor: 4
Ejemplo 2
• Palabra: “tomate”
• valor: 8
'''
palabra = input("Escriba una palabra: ").upper() #Se ingresa por teclado la palabra
dicci_Scrabble = {
("A", "E", "I", "O", "U", "L", "N", "R", "S", "T"): 1, #Creo un diccionario con los puntajes determinados en la consigna, para luego procesar la palabra con este diccionario
("D", "G"): 2,
("B", "C", "M", "P"): 3,
("F", "H", "V", "W", "Y"): 4,
("K"): 5,
("J","X"): 8,
("Q","Z"): 10
}
valor_palabra=0 #Contador Total
for char in palabra:
for tup in dicci_Scrabble: #Itero la palabra consiguiendo cada letra y luego, busco la letra dentro del diccionario, para conocer su valor
if char in tup:
valor_palabra+=dicci_Scrabble[tup] #Una vez encontrado el valor de esa letra, aumento el contrador total con el valo propuesto para esa letra
print(f"La palabra: {palabra.lower()} vale {valor_palabra} puntos")
|
b738662ddfd1947917431ef6eec224e4e4292cef | davidbosss/py_notes | /mdp_example.py | 1,178 | 3.625 | 4 | # Markov Decision Process Example
# Author: Christina Dimitriadou (christina.delta.k@gmail.com)
# Date: 20/06/2021
# Import Libraries
import sys
sys.setrecursionlimit(1000)
# create the model:
class TestMDP(object):
def __init__(self, N):
self.N = N # N is the number of blocks
def initialState(self):
return 1
def stateEnd(self, state):
return state == self.N
def actions(self, state):
# returns a list of valid actions
outcome = []
if state+1 <= self.N:
outcome.append('action_1')
if state*2 <= self.N:
outcome.append('action_2')
return outcome
def succProbReward(self, state, action):
# returns list with: new state, probability, reward
# state = s, action = a, new state = s', prob = T(s,a,s'), reward = Reward(s,a, s')
outcome = []
if action == 'action_1':
outcome.append((state+1, 1., -1.))
elif action == 'action_2':
outcome.append((state*2, 0.5, -2.))
otcome.append((state, 0.5, -2.))
return outcome
def discount(self):
return 1.
def states(self):
return range(1, self.N+1)
|
e1c98ed2fa37f6a4cdeee2034fd74652974175fa | gebijiaxiaowang/leetcode | /offer/30.py | 1,233 | 3.8125 | 4 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020/9/4 20:09
# @Author : dly
# @File : 30.py
# @Desc:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.help_list = []
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
if len(self.help_list) == 0:
self.help_list.append(x)
self.stack.append(x)
else:
tmp = self.help_list[-1]
if x > tmp:
self.help_list.append(tmp)
self.stack.append(x)
else:
self.help_list.append(x)
self.stack.append(x)
def pop(self):
"""
:rtype: None
"""
top = self.stack.pop(-1)
self.help_list.pop(-1)
return top
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def min(self):
"""
:rtype: int
"""
return self.help_list[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
|
cb33874f5385162e97a5a5a4990020d9b54bbda5 | learnerofmuses/slotMachine | /csci152Spring2014/feb6p1.py | 593 | 4.03125 | 4 | #Design a program that asks the user to enter a series
#of 20 numbers. The program should store the numbers in a list
#and then display the following data:
#the lowest number in the list
#the highest number in the list
#the total of the number in the list
#the average of the numbers in the list
import random
def deadpool(my_list):
sum = 0
average = 0
count = 0
while(count<0):
def main():
size = random.randint(20)
my_list = []
for i in range(size):
my_list.append(random.randint(1, 100))
print("generated list is: ")
print(my_list)
if(len(my_list)>0):
print
|
1409080ecb2c3189785c75ef5eed8743edd08b6b | rfc8367/R1 | /L2/Bonus 1.py | 301 | 3.84375 | 4 | x = float(input("Введите число: "))
tpl = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
if x in tpl or abs(x) in tpl:
print("Число" , x, "присутствует среди элементов")
else:
print("Число" , x, "отсутствует среди элементов") |
2577f1e2a52fec47a4f603f2fd496fa33ff07dfa | csshlok/Prac-file | /Q2.py | 106 | 3.96875 | 4 | celsius = float(input("Enter Celcius: "))
fahrenheit = (9/5)*celsius + 32
print("Fahrenheit ",fahrenheit)
|
e28787446c9911c2c5e3c9ac8b2d1a400d047a23 | frankieliu/problems | /leetcode/python/680/original/680.valid-palindrome-ii.0.py | 787 | 3.609375 | 4 | #
# @lc app=leetcode id=680 lang=python3
#
# [680] Valid Palindrome II
#
# https://leetcode.com/problems/valid-palindrome-ii/description/
#
# algorithms
# Easy (33.56%)
# Total Accepted: 59.3K
# Total Submissions: 176.7K
# Testcase Example: '"aba"'
#
#
# Given a non-empty string s, you may delete at most one character. Judge
# whether you can make it a palindrome.
#
#
# Example 1:
#
# Input: "aba"
# Output: True
#
#
#
# Example 2:
#
# Input: "abca"
# Output: True
# Explanation: You could delete the character 'c'.
#
#
#
# Note:
#
# The string will only contain lowercase characters a-z.
# The maximum length of the string is 50000.
#
#
#
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
|
2da48199ed0005985339debfe46578494b0487c7 | sidmaskey13/assignment_3 | /Ac.py | 573 | 3.796875 | 4 | #Quick sort
def partition(x, low, high):
i = (low - 1)
pivot = x[high]
for j in range(low, high):
if x[j] <= pivot:
i = i + 1
x[i], x[j] = x[j], x[i]
x[i + 1], x[high] = x[high], x[i + 1]
return (i + 1)
def quickSort(x, low, high):
if low < high:
pi = partition(x, low, high)
quickSort(x, low, pi - 1)
quickSort(x, pi + 1, high)
x = [1, 10, 5, 3, 12, 44, 14, 6]
n = len(x)
quickSort(x, 0, n - 1)
print("Sorted:")
for i in range(n):
print("%d" % x[i]),
|
0bfd1019d812ff07605422be6d326f9d9baa0dbc | tommyli3318/Zot-Calendar | /flask-backend/course.py | 2,251 | 3.5 | 4 | from courseTask import CourseTask
class Course:
"""contains all the information for a specific course"""
def __init__(self, course_name: str, category_weights: dict) -> None:
self.course_name = course_name
self.category_weights = category_weights
# self.cat_scores = {n:(0,0) for n in self.category_weights} # {category: (n,d)}
self.assignments = {} #{(assignment_name, category) : (n,d)}
self.to_do = [] # list of task objects
def get_name(self) -> str:
return self.course_name
def add_task(self, name: str, m: int, d: int, y: int, task_cat: str = None, points_p = 0) -> None:
# add a CourseTask objct
self.to_do.append(CourseTask(self.course_name, name,m,d,y, task_cat, points_p))
def add_grade(self, name: str, category: str, score: tuple) -> None:
self.assignments[(name,category)] = score
def remove_grade(self, category: str, score: tuple) -> None:
del self.assignments[(name,category)]
def get_grade(self):
pass
def set_grade(self, name: str, category: str, n_score: tuple) -> None:
self.assignments[(name,category)] = n_score
def get_overall_score(self) -> float:
cat_scores = {n:[0,0] for n in self.category_weights} # {category: (n,d)}
for nc, nd in self.assignments.items():
cat_scores[nc[1]][0] += nd[0]
cat_scores[nc[1]][1] += nd[1]
for cat in cat_scores:
if cat_scores[cat][1] == 0:
cat_scores[cat] = 1.0
else:
cat_scores[cat] = cat_scores[cat][0]/cat_scores[cat][1]
final_score = sum(cat_scores[cat] * self.category_weights[cat] for cat in cat_scores)
return round(final_score, 3)
def get_simulated_score(self, category: str, pp: int) -> float:
save = self
self.add_grade("temp", category, (0, pp))
tempscore = self.get_overall_score()
del self.assignments[("temp",category)]
self = save
return round(tempscore, 3)
def get_to_do(self):
return [str(x) for x in self.to_do]
def get_to_do_obj(self):
return self.to_do
#def __str__(self):
#return self.course_name
"""
testing = Course("math", {'homework': .3, 'tests': .7})
testing.add_grade("assignment 1", "homework", (10,10))
testing.add_grade("assignment 2", "homework", (5,10))
testing.add_grade("test 1", "tests", (8,10))
print(testing.get_overall_score())
#final grade : 78.5
""" |
1dd1477b9c7b9b48962fb948399bdb5ff82dd587 | joshuasearle/ds-and-algs | /adts/heaps/heap.py | 1,519 | 3.90625 | 4 | class AbstractHeap(object):
"""
Stores the min item at root
"""
def __init__(self):
self.array = []
self.length = 0
def __len__(self): return len(self.array)
def parent_index(self, i): return (i - 1) // 2
def left_index(self, i): return 2 * i + 1
def right_index(self, i): return 2 * i + 2
def parent(self, i): return self.array[self.parent_index(i)]
def left(self, i): return self.array[self.left_index(i)]
def right(self, i): return self.array[self.right_index(i)]
def has_parent(self, i): return self.parent_index(i) >= 0
def has_left(self, i): return self.left_index(i) < len(self)
def has_right(self, i): return self.right_index(i) < len(self)
def swap(self, i1, i2):
tmp = self.array[i1]
self.array[i1] = self.array[i2]
self.array[i2] = tmp
def peek(self):
if len(self) == 0: raise IndexError()
return self.array[0]
def poll(self):
if len(self) == 0: raise IndexError()
item = self.array[0]
# Swap last in first, then remove last
self.array[0] = self.array[len(self) - 1]
self.array.pop()
self.heapify_down()
return item
def add(self, value):
self.array.append(value)
self.heapify_up()
def heapify_up(self):
raise NotImplementedError()
def heapify_down(self):
raise NotImplementedError() |
a68b60d20055522231a77787454a3176af012b2c | incessantmeraki/probabilities | /probability_one.py | 557 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
result = []
def throw_coin (number_of_samples, sample_sizes):
for i in range(number_of_samples):
trial = np.random.choice(['H','T'], size = sample_sizes)
result.append(np.mean(trial == 'H'))
return result
sample_sizes = np.arange(1,1001,1)
probabilities = throw_coin(20,10)
print(probabilities)
# plt.plot(trials, probabilities, 'o-')
# plt.xlabel("Number of trials")
# plt.ylabel("Probability")
# plt.title("Probability of Heads")
# plt.show()
|
717d424ced232d6ad69c446926b6b4599154d57c | ClockWorks001/pyworks | /hello12.py | 315 | 3.71875 | 4 | # coding: UTF-8
# 辞書 key value
sales = {"taniguchi":200, "fukoji":300, "dotinstall":500}
print(sales)
print(sales["taniguchi"])
sales["fukoji"] = 800
print(sales)
# in
print("taniguchi" in sales) #True
# keys, values, items
print(sales.keys())
print(sales.values())
print(sales.items())
print(len(sales))
|
a53876680961d15e7fc19a323e2b5319cbb5b173 | simon090/cs50 | /credit.py | 1,195 | 3.90625 | 4 | import sys
if len(sys.argv) == 2:
card_num = sys.argv[1]
else:
card_num = int(input("Enter card number: "))
print(card_num)
def valid_card_checker(number):
doubles_list = []
doubles_list_singles = []
singles_list = []
for i,j in enumerate(reversed((str(number)))):
if i%2!=0:
doubles_list.append(int(j))
else:
singles_list.append(int(j))
for i in range(len(doubles_list)):
doubles_list[i]*=2
for i in doubles_list:
if i >= 10:
tmp = [int(d) for d in str(i)]
for i in tmp:
doubles_list_singles.append(i)
else:
doubles_list_singles.append(i)
card_sum = sum(doubles_list_singles) + sum(singles_list)
if card_sum % 10 == 0:
print("Valid card")
if len(str(number)) == 15:
print("Card is AMEX")
elif len(str(number)) == 13:
print("Card is Visa")
elif len(str(number)) == 16:
if str(number)[0] == "4":
print("Card is Visa")
else:
print("Card is Mastercard")
else:
print("Invalid card")
valid_card_checker(int(card_num)) |
f85319f68d3998192f6ddad164018827ac727689 | kr-aashish/Customer-segmentation-using-Hierarchical-Clustering | /Project.py | 1,512 | 3.53125 | 4 | #importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#importing datasets
Dataset = pd.read_csv('Customers.csv')
X = Dataset.iloc[:, [3,4]].values #.values will give array rather df
#Using dendogram to find optimal number of clusters
import scipy.cluster.hierarchy as sch
dendogram = sch.dendrogram(sch.linkage(X, method='ward'))
plt.xlabel('Customers')
plt.ylabel('Euclidian distance')
plt.title('Dendogram')
plt.show()
#numbe of clusters should be the number of longest vertical lines
#fitting the model to our dataset
from sklearn.cluster import AgglomerativeClustering
hc = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward')
#ward - centroid dist
y_hc = hc.fit_predict(X)
# Visualising the clusters and interpretation using pyplot
# s - for size, c for colour, label is legend
plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'cyan', label = '1st Cluster')
plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'green', label = '2nd Cluster')
plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'red', label = '3rd Cluster')
#plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'blue', label = '4th Cluster') --
#-- first condt - for row no and 2nd is column number
plt.title('Clusters of customers')
plt.xlabel('Annual Salary (k$)')
plt.ylabel('Spendings (1 to 100)')
#these 2 are the x and y axes of the plot
plt.legend()
plt.show()
|
d4345c54dbe811072bfd1366ed011c012dede49b | NamburiSrinath/Artificial-Intelligence | /gradientdescent/gradientdescent.py | 1,064 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
function = lambda x: (x ** 3)-(3 *(x ** 2))+7
#Get 1000 evenly spaced numbers between -1 and 3 (arbitratil chosen to ensure steep curve)
x = np.linspace(-1,3,500)
#Plot the curve
plt.plot(x, function(x))
plt.show()
def deriv(x):
x_deriv = 3* (x**2) - (6 * (x))
return x_deriv
def step(x_new, x_prev, precision, l_r):
x_list, y_list = [x_new], [function(x_new)]
while abs(x_new - x_prev) > precision:
x_prev = x_new
d_x = - deriv(x_prev)
x_new = x_prev + (l_r * d_x)
x_list.append(x_new)
y_list.append(function(x_new))
print ("Local minimum occurs at: "+ str(x_new))
print ("Number of steps: " + str(len(x_list)))
plt.subplot(1,2,2)
plt.scatter(x_list,y_list,c="g")
plt.plot(x_list,y_list,c="g")
plt.plot(x,function(x), c="r")
plt.title("Gradient descent")
plt.subplot(1,2,1)
plt.scatter(x_list,y_list,c="g")
plt.plot(x_list,y_list,c="g")
plt.plot(x,function(x), c="r")
plt.xlim([1.0,2.1])
plt.title("Zoomed in Gradient descent to Key Area")
plt.show()
step(0.5, 0, 0.001, 0.05) |
d2c05b2602baad40d2fb3058d73ee6acc9c235b3 | ChinYikMing/pyscript | /file.py | 186 | 3.734375 | 4 | #!/usr/bin/python
filename = "text.txt"
fd = open(filename, "w")
fd.write("Hello")
fd.write("World")
fd.close()
fd = open(filename, "r")
for line in fd:
print(line)
fd.close() |
73f95dd0630e0ce609ab3540197b1e97103b99f4 | Nico-Duduf/Formation_Python | /Exercices/digit.py | 208 | 3.734375 | 4 | test = 7
numCar = 3
def numero(num,nbreCaracteres):
chaineNum = str(num)
while len(chaineNum) < nbreCaracteres:
chaineNum = "0" + chaineNum
return chaineNum
print(numero(test,numCar))
|
2996dc55bb01f036f0df13c8449ee823020c2c58 | Krishna9331/python | /chapter11/ex11.py | 282 | 4.03125 | 4 | # end='' tell that go to next line without putting new line
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height=input()
print("How much do you weight?", end=' ')
weight=input()
print(f"So you're {age} old, {height} tall and {weight} heavy.")
|
c71752902154de4d67f501dd5a2fd5bb660ecf01 | suziW/myLeetCode | /77.py | 537 | 3.78125 | 4 | from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
r = []
def backtrack(combination, n, k):
if k == 0:
r.append(combination[:])
return
for i in range(k, n+1):
combination.append(i)
backtrack(combination, i-1, k-1)
combination.pop()
backtrack([], n, k)
return r
if __name__ == "__main__":
n = 4
k = 2
r = Solution().combine(n, k)
print(r) |
398be0416eb43110e7927fe952971f4b5d6711b4 | Icode4passion/practicepythonprogams | /word_count.py | 861 | 4.125 | 4 | # # word_list = ["red","yellow","green","red","blue","green","orange"]
# # unique_word = []
# # for word in word_list:
# # if word not in unique_word:
# # unique_word+=[word]
# # word_frequency = []
# # for word in unique_word:
# # word_frequency += [float(word_list.count(word))/len(word_list)]
# # for i in range(len(unique_word)):
# # print unique_word[i]
# # print word_frequency[i]
# #
# word_list = ['words', 'other', 'words']
# # Get a set of unique words from the list
# word_set = set(word_list)
# # create your frequency dictionary
# freq = {}
# # iterate through them, once per unique word.
# for word in word_set:
# freq[word] = word_list.count(word) / float(len(word_list))
# print freq
test_string = raw_input("Enter a String")
l = []
l = test_string.split(' ')
word_feq = [l.count(p) for p in l]
print dict(zip(l,word_feq)) |
a78b142329849409a342d196ca855ee2b11fb521 | tartofour/python-IESN-1BQ1-TIR | /exercices/serie1/ex10.py | 525 | 3.875 | 4 | #!/usr/bin/env python3
total_secondes = int(input("Entrez un nombre de secondes : "))
nb_semaines = total_secondes // 604800
nb_jours = (total_secondes % 604800) // 86400
nb_heures = ((total_secondes % 604800) % 86400) // 3600
nb_minutes = (((total_secondes % 604800) % 86400) % 3600) // 60
nb_secondes = ((((total_secondes % 604800) % 86400) % 3600) % 60 ) % 60
print("{} secondes = {} semaines {} jours {} heure {} minutes {} secondes".format(total_secondes, nb_semaines, nb_jours, nb_heures, nb_minutes, nb_secondes))
|
6e25daed7c0441da127781f8be1d1ef31f95bf97 | unknown090105/algorithm | /grokking/Ch09/longest_common_substring.py | 790 | 3.921875 | 4 | def longest_common_substring(word_a, word_b):
# 2d array construction
cols = len(word_a)
rows = len(word_b)
table = []
for i in range(cols):
col = []
for j in range(rows):
col.append(0) # initialization with 0
table.append(col)
# maximum distance calculation
max_dist = 0
for i in range(cols):
for j in range(rows):
if word_a[i] == word_b[j]:
if i > 0 and j > 0:
table[i][j] = table[i-1][j-1] + 1
else:
table[i][j] = 1
else:
table[i][j] = 0
if table[i][i] > max_dist:
max_dist = table[i][i]
print(table)
return max_dist
print(longest_common_substring("hish", "vista")) |
a3100f10719f3ea6118720b005558dc0dae79fb6 | BOSONCODE/Python-Tutorial | /PythonBasic/面向对象/class.py | 2,239 | 4.40625 | 4 | '''
OOP: object-oriented programming
面向对象是一种方法, 这个说起来是软件工程里面的长篇大论
这里粗略简单地来说的话就是 物以类聚
比如说 芒果、苹果、香蕉 这些都是一个一个的对象 这些可以归为一类就是水果
然后水果之间又有一些关系, 比如说长在树上的可以分为一类, 长在地上的分为一类, 那么
这些又是继承于水果这一个类
水果类专业术语叫做基类 生长环境类又叫做 派生类
多态就是基类的不同行为
'''
#私有变量不可以直接访问只能由当前类访问
#protected 派生类可以访问 但是不可以直接由对象访问, 对象不可以直接访问
#public 基类、派生类和对象都可以直接访问
class BaseClass:
__privateVar = "I'm the private Variable"
_protectedVar = "I'm the protected Variable"
publicVar = "I'm the public Variable"
def getPrivateVar(self):
return self.__privateVar
def __str__(self):
'''return self.__privateVar \
+ self._protectedVar \
+ self.publicVar'''
return "I'm the Base Class"
class DerivedClass(BaseClass): #继承
def __init__(self):
print(BaseClass.publicVar)
print(BaseClass._protectedVar)
#print(BaseClass.__privateVar) 如果这么写就会报错
def printPrivateVar(self):
#print(BaseClass())
print(self.getPrivateVar()) #这么访问私有变量就没问题
#output: I'm the private Variable
def __str__(self):
return "I'm the Derived Class"
def polymorphic(obj):
print(obj)
if __name__ == '__main__':
test = DerivedClass()
test2 = BaseClass()
polymorphic(test)
#output:I'm the Derived Class
polymorphic(test2)
#output: I'm the Base Class
test.printPrivateVar()
'''
I'm the public Variable
I'm the protected Variable
Traceback (most recent call last):
File "F:\python\PythonBasic\面向对象\class.py", line 23, in <module>
test = DerivedClass()
File "F:\python\PythonBasic\面向对象\class.py", line 20, in __init__
print(BaseClass.__privateVar)
AttributeError: type object 'BaseClass' has no attribute '_DerivedClass__privateVar'
'''
|
30f96300274d383c4934fa60baf22dd2afbd1dd9 | santhosh-kumar/AlgorithmsAndDataStructures | /python/problems/array/find_min_in_sorted_rotated_array.py | 1,425 | 4 | 4 | """
Find Min In Sorted Rotated Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
"""
from common.problem import Problem
class FindMinInSortedRotatedArray(Problem):
"""
Find Min In Sorted Rotated Array
"""
PROBLEM_NAME = "FindMinInSortedRotatedArray"
def __init__(self, input_list):
"""Find Min In Sorted Rotated Array
Args:
input_list: Contains a list of integers (sorted)
Returns:
None
Raises:
None
"""
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
def solve(self):
"""Solve the problem
Note: O(log n) (runtime) solution works by comparing the middle element with the right most element.
Then adjusting the left and right indices.
Args:
Returns:
integer
Raises:
None
"""
left = 0
right = len(self.input_list) - 1
while left < right and self.input_list[left] > self.input_list[right]:
middle = int((left + right) / 2)
if self.input_list[middle] > self.input_list[right]:
left = middle + 1
else:
right = middle
return self.input_list[left]
|
db1fd179ca6079c70b43ef1f1e7981a254f0cf35 | JerinPaulS/Python-Programs | /PartitionList.py | 1,489 | 4.03125 | 4 | '''
86. Partition List
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]
Constraints:
The number of nodes in the list is in the range [0, 200].
-100 <= Node.val <= 100
-200 <= x <= 200
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
if head is None:
return head
dummy1 = ListNode(0)
dummy2 = ListNode(0)
curr = head
left = dummy1
right = dummy2
while curr is not None:
if curr.val < x:
if left == dummy1:
dummy1.next = curr
else:
left.next = curr
left = left.next
else:
if right == dummy2:
dummy2.next = curr
else:
right.next = curr
right = right.next
temp = curr.next
curr.next = None
curr = temp
left.next = dummy2.next
return dummy1.next |
8cfab1be8340b252162100aadc31ec83d82db6b1 | Chunkygoo/Algorithms | /Graphs/rectangleMania.py | 2,685 | 3.765625 | 4 | UP = "up"
RIGHT = "right"
DOWN = "down"
LEFT = "left"
# O(N^2) T O(N^2) S
def rectangleMania(coords):
coordsTable = getCoordsTable(coords, {})
return countRectangles(coordsTable, coords)
# O(N^2) T O(N^2) S
def getCoordsTable(coords, coordsTable):
for coord1 in coords:
coord1Table = {UP: [], RIGHT: [], DOWN: [], LEFT: []}
for coord2 in coords:
direction = getCoordsDirection(coord1, coord2)
if direction in coord1Table:
coord1Table[direction].append(coord2)
coord1String = coordToString(coord1)
coordsTable[coord1String] = coord1Table
return coordsTable
def getCoordsDirection(coord1, coord2):
x1, y1 = coord1
x2, y2 = coord2
if y1 == y2:
if x2 > x1:
return RIGHT
elif x2 < x1:
return LEFT
elif x1 == x2:
if y2 > y1:
return UP
elif y2 < y1:
return DOWN
return ""
def coordToString(coord):
x, y = coord
return str(x) + "-" + str(y)
# O(N^2) T O(4) S, O(4) because that's the max possible on the recursive stack
def countRectangles(coordsTable, coords):
rectangles = 0
for coord in coords:
rectangles += getRectangles(coordsTable, coord, UP, coord)
return rectangles
def getRectangles(coordsTable, coord, direction, bottomLeft):
coordString = coordToString(coord)
if direction == LEFT:
foundRectangle = bottomLeft in coordsTable[coordString][direction]
return 1 if foundRectangle else 0
else:
rectangles = 0
nextDirection = getNextDirection(direction)
for coord in coordsTable[coordString][direction]:
rectangles += getRectangles(coordsTable, coord, nextDirection, bottomLeft)
return rectangles
def getNextDirection(direction):
if direction == UP:
return RIGHT
elif direction == RIGHT:
return DOWN
elif direction == DOWN:
return LEFT
else:
return ""
#======================================Solution 2==============================================
# O(N^2) T O(N) S
def rectangleMania(coords):
coordsTable = getCoordsTable(coords, {})
return countRectangles(coordsTable, coords)
# O(N) T O(N) S
def getCoordsTable(coords, coordsTable):
for coord in coords:
coordString = coordToString(coord)
coordsTable[coordString] = True
return coordsTable
def coordToString(coord):
x, y = coord
return str(x) + "-" + str(y)
# O(N^2) T O(1) S
def countRectangles(coordsTable, coords):
rectangles = 0
for x1, y1 in coords:
for x2, y2 in coords:
if inUpperRight([x1, y1], [x2, y2]):
upperCoord = coordToString([x1, y2])
rightCoord = coordToString([x2, y1])
if upperCoord in coordsTable and rightCoord in coordsTable:
rectangles += 1
return rectangles
def inUpperRight(coord1, coord2):
x1, y1 = coord1
x2, y2 = coord2
return x2 > x1 and y2 > y1
|
8a2d38c3f0ca1c4c875f7a52f13b721d1b96cf25 | zzz136454872/leetcode | /wiggleSort.py | 982 | 3.640625 | 4 | from typing import List
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort()
base = len(nums) // 2
if len(nums) % 2 != 0:
base += 1
res1 = []
res2 = []
for i in range(len(nums) // 2):
res1.append(nums[i])
res1.append(nums[i + base])
res2.append(nums[i + base])
res2.append(nums[i])
res2 = res2[::-1]
if len(nums) % 2 != 0:
res1.append(nums[len(nums) // 2])
res = res1
for i in range(len(res) - 1):
if res[i] == res[i + 1]:
res = res2
break
for i in range(len(res)):
nums[i] = res[i]
nums = [1, 5, 1, 1, 6, 4]
nums = [1, 3, 2, 2, 3, 1]
nums = [1, 1, 2]
nums = [1, 1, 2, 1, 2, 2, 1]
nums = [4, 5, 5, 6]
Solution().wiggleSort(nums)
print(nums)
|
318443155950bd94e6aad6e7494b186852778456 | kn2322/topdown-funk | /utilfuncs.py | 1,661 | 3.671875 | 4 | from kivy.vector import Vector
from math import hypot
"""Module used to contain utility functions used for processing in the game.
"""
# deltay/deltax distance calculations
def difference(pos1, pos2):
return (pos2[0] - pos1[0], pos2[1] - pos1[1])
# For graphics components, returns the sprite facing direction.
def get_direction(angle):
if -22.5 < angle <= 22.5:
return 'right'
elif 22.5 < angle <= 67.5:
return 'downright'
elif 67.5 < angle <= 112.5:
return 'down'
elif 112.5 < angle <= 157.5:
return 'downleft'
elif 157.5 < angle <= 180 or -180 <= angle < -157.5:
return 'left'
elif -157.5 <= angle < -112.5:
return 'upleft'
elif -112.5 <= angle < -67.5:
return 'up'
elif -67.5 <= angle < -22.5:
return 'upright'
else:
# idk why this exists.
raise ValueError('The angle {} is out of bounds.'.format(angle))
# For circular collision detection
def circle_collide(a, b):
# Confused about whether the condition should be with < or <=, negligible.
d = (a.width + b.width) / 2 - hypot(*difference(a.center, b.center))
if d > 0:
return d
else:
return 0
# Gets x, y direction towards target.
def get_dir_to(entity, other):
delta = difference(entity.center, other.center)
angle = atan2(delta[1], delta[0])
x = cos(angle)
y = sin(angle)
return [x, y]
# Applying label markups.
def label_markup(text, tag):
info = tag.split('=')[0].strip('[]')
end_tag = '[/{}]'.format(info)
return tag + text + end_tag
if __name__ == '__main__':
print('To shreds, you say?') |
9615fa6392605acf304e001cdd24e662f5171173 | willcodefortea/dailyprogrammer | /193.py | 1,096 | 4.03125 | 4 | """
(Easy): Acronym Expander
http://www.reddit.com/r/dailyprogrammer/comments/2ptrmp/20141219_challenge_193_easy_acronym_expander/
"""
import re
ACRONYMS = (
("lol", "laugh out loud"),
("dw", "don't worry"),
("hf", "have fun"),
("gg", "good game"),
("brb", "be right back"),
("g2g", "got to go"),
("wtf", "what the fuck"),
("wp", "well played"),
("gl", "good luck"),
("imo", "in my opinion"),
)
def expand_words(line):
"""Take a line and expand it."""
for acronym, text in ACRONYMS:
# String matching, let's use some regex.
# replace any match that is surrounded by 0 or 1 non text character
line = re.sub(r'(\W{,1})%s(\W{,1})' % acronym, r'\1%s\2' % text, line)
return line
if __name__ == '__main__':
tests = [
('wtf that was unfair', 'what the fuck that was unfair'),
('gl all hf', 'good luck all have fun'),
]
for test, expected in tests:
assert expand_words(test) == expected
# Now print the final example
print expand_words("imo that was wp. Anyway I've g2g")
|
815115dfd814453d05c5af91a516f8eca5629a93 | APARNAS1998/luminardjango1 | /python test/calculator.py | 1,437 | 4.1875 | 4 | def addition():
num1=float(input('enter the first number'))
num2=float(input('enter the second number'))
res=num1+num2
print('result=',res)
def substraction():
num1 = float(input('enter the first number'))
num2 = float(input('enter the second number'))
res = num1 - num2
print('result=',res)
def multiplication():
num1 = float(input('enter the first number'))
num2 = float(input('enter the second number'))
res = num1 * num2
print('result=',res)
def division():
num1 = float(input('enter the first number'))
num2 = float(input('enter the second number'))
res = num1/num2
print('result=',res)
def floordivision():
num1 = float(input('enter the first number'))
num2 = float(input('enter the second number'))
res = num1 // num2
print('result=',res)
def exponent():
base = float(input('enter the base number'))
exponent = float(input('enter the exponent number'))
res = base**exponent
print('result=',res)
print('enter the operation')
print('1.addition')
print('2.substraction')
print('3.multiplication')
print('4.division')
print('5.floor division')
print('6.exponential')
choice=int(input('choice='))
if choice==1:
addition()
elif choice==2:
substraction()
elif choice==3:
multiplication()
elif choice == 4:
division()
elif choice == 5:
floordivision()
elif choice == 6:
exponent()
else:
print('invalid')
|
b772bcbf87b00426a98c4f6578d34fe952d4c94f | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/olgmof001/util.py | 1,814 | 3.515625 | 4 | """Tofunmi Olagoke
29 April 2014
2048 game functions(1)"""
def create_grid(grid):
for i in range (4):
grid.append ([0,0,0,0])
return grid
def print_grid (grid):
print("+--------------------+")
#putting the grid into columns
for i in grid:
print("|", end="")
for x in i:
if x==0:
x=" "
print(x," "*(4-len(str(x))),end="")
print("|")
print("+--------------------+")
def check_lost (grid):
duplicate=0
for x in grid:
for inlist in x:
#checks for equal adjacent numbers
if inlist==0 or x[0]==x[1]or x[1]==x[2] or x[2]==x[3] or x[0]==x[3]:
return False
for x in grid:
for inlist in x:
if not inlist==0 or not x[0]==x[1]or not x[1]==x[2] or not x[2]==x[3] or not x[0]==x[3]:
return True
def check_won (grid):
for x in grid:
for inlist in x:
#checks if there are numbers over 32
if inlist>=32:
return True
for x in grid:
for inlist in x:
if not inlist>=32:
return False
def copy_grid (grid):
#reproduces the grid given
nl=[]
for i in grid:
for x in i:
nl=nl+[x]
nl1=nl[0:4]
nl2=nl[4:8]
nl3=nl[8:12]
nl4=nl[12:16]
finallist=[nl1,nl2,nl3,nl4]
return finallist
def grid_equal (grid1, grid2):
if grid1==grid2:
return True
if not grid1==grid2:
return False
|
17b6e252f98a3c628a9254f087712f1b497b8afd | vanyaio/learning_python | /mut_immut.py | 1,051 | 3.796875 | 4 | def underline():
print('_________')
#id - identificator for object
x = [1, 2, 3]
print(id(x))
print(id([1,2,3]))
underline()
#is - does two vars refer to the same obj?
x = [1, 2, 3]
y = x
print(y is x) #true
print(y is [1, 2, 3]) #false
underline()
x = [1, 2, 3]
y = x
x.append(4)
print(x)
print(y)
underline()
#mutable: list, dict, set,
#immutable: numbers, bool, tuple, string, frozenset
#when creates immutable obj, always create new part in memory
#not always true for immutable, for example false, true has only 2 id
x = [1, 2, 3]
y = x
y.append(4)
s = "123"
t = s
t = t + "4"
print(str(x) + " " + s)
underline()
x = 10
y = 10
print(id(x) == id(y))
x = []
y = []
print(id(x) == id(y))
underline()
#program that counts different objs in a list
objects = []
ids = set()
for obj in objects:
ids.add(id(obj))
print(ids)
print(len(ids))
underline()
#funcs
def foo_mut(a):
a.append(10)
a = [1]
foo_mut(a)
print a
def foo_immut(a):
a = a + a
a = 10
foo_immut(a)
print(a)
a = 'abc'
foo_immut(a)
print a
a = a + a
print a
|
7ca456a91a833b0db662d027abee9991d1ce9417 | ReemAlattas/LeetCode-Solutions | /Merge_Two_Lists.py | 1,395 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Check if either of the lists is null
if l1 is None:
return l2
if l2 is None:
return l1
# Choose head which is smaller of the two lists
if l1.val < l2.val:
temp = head = ListNode(l1.val)
l1 = l1.next
else:
temp = head = ListNode(l2.val)
l2 = l2.next
# Loop until any of the list becomes null
while l1 is not None and l2 is not None:
if l1.val < l2.val:
temp.next = ListNode(l1.val)
l1 = l1.next
else:
temp.next = ListNode(l2.val)
l2 = l2.next
temp = temp.next
# Add all the nodes in l1, if remaining
while l1 is not None:
temp.next = ListNode(l1.val)
l1 = l1.next
temp = temp.next
# Add all the nodes in l2, if remaining
while l2 is not None:
temp.next = ListNode(l2.val)
l2 = l2.next
temp = temp.next
return head
|
0c2f3e6d0ae8ece5066a38c5ad9b96155f6ad000 | rjackowens/Code-Snippets | /Testing Dictionary Item Method.py | 298 | 4.03125 | 4 | d = {'H': 1.008, 'He': 4.003, 'Li': 6.94}
for elements, weights in d.items():
print(elements, weights)
listOfElements = list(elements for elements, weight in d.items())
listOfWeights = list(weight for elements, weight in d.items())
print(listOfElements, listOfWeights)
#print(listOfWeights)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.