blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
88b7c2b539778c54e9ba2072c44b163fda95e785 | fis-jogos/2016-2 | /python-101/06 funções.py | 739 | 4.3125 | 4 | # Definimos uma função que calcula a soma de todos os números pares até um
# certo valor
def soma_pares(x):
y = 0
S = 0
while y <= x:
S += y
y += 2
return y
# Agora podemos chamar nossa função e recuperar o valor passado para o "return"
valor = soma_pares(100)
print('A soma de todos os pares de 1 a 100 é: %s' % valor)
# Exercícios
# ----------
#
# 1) Defina uma função que calcule o fatorial de um número.
#
# 2) Faça um programa que pergunte para o usuário o fatorial do número e depois
# imprima o resultado. O programa deve utilizar a função definida
# anteriormente e deve continuar perguntando por mais números até que o
# usuário entre com o valor 0.
|
52489878319e534194790e9c44477222cfb87d84 | fis-jogos/2016-2 | /exemplos/flappy/flappybird.py | 1,414 | 3.546875 | 4 | import random
TITLE = 'Flappy'
WIDTH = 400
HEIGHT = 708
GRAVITY = 500
JUMPSPEED = 200
SPEED = 3
GAP = 130
OBS_HEIGHT = 500
HEIGHT_RANGE = (-50, 200)
bird = Actor('bird0', pos=(100, HEIGHT / 2))
bird.vy = 0
bird.dead = False
bottom = Actor('bottom', pos=(-100, 400))
top = Actor('top', pos=(-100, 400))
def set_random_height():
top.y = random.randint(*HEIGHT_RANGE)
bottom.y = top.y + GAP + OBS_HEIGHT
if bird.dead:
bird.y = HEIGHT / 2
bird.image = 'bird0'
bird.vy = 0
bird.dead = False
def dead():
bird.dead = True
bird.image = 'birddead'
def update(dt):
# Atualiza passaro
bird.y += bird.vy * dt
bird.vy += GRAVITY * dt
if keyboard.space and not bird.dead:
bird.vy = -JUMPSPEED
if not bird.dead:
if bird.vy < -20:
bird.image = 'bird2'
elif bird.vy > 20:
bird.image = 'bird1'
else:
bird.image = 'bird0'
# Atualiza obstaculos
bottom.x -= SPEED
top.x -= SPEED
if bottom.x < -100:
set_random_height()
bottom.x = top.x = WIDTH + 50
# Checa colisao
if not bird.dead and bird.right > top.left and bird.left < top.right:
if bird.bottom > bottom.top or bird.top < top.bottom:
dead()
def draw():
screen.blit('background', pos=(0, 0))
bottom.draw()
top.draw()
bird.draw()
|
00a40a7a31116aa3940051f4f2de3093313ba0dc | sajjad0057/Practice-Python | /DS and Algorithm/Recursion.py | 100 | 3.5 | 4 | def f(n):
if n<=1:
return n
print(n-1,n-2)
return f(n-1)+f(n-2)
print(f(7)) |
5f3b579a7b89545a018ad5ed1dae0fb2c6784ead | sajjad0057/Practice-Python | /OOP_class_and_static_method.py | 1,536 | 3.65625 | 4 | class StoryBook:
no_of_books=0
discount =0.5 # its called class variable
def __init__(self,name,price,author,date):
self.name=name
self.price=price
self.author=author
self.p_date=date
StoryBook.no_of_books += 1
def applying_discount(self):
self.price = int(self.price * StoryBook.discount)
return self.price
def __str__(self):
return str(self.name) #,self.y,self.z,self.w
#CLASS METHOD
@classmethod # its works like alternative constractor
def set_discount(cls,new_discount):
cls.discount=new_discount
@classmethod
def construct_from_string(cls,book_str):
name, price, author, date = book_str.split(',')
return cls(name, price, author, date)
# STATIC_METHOD
@staticmethod
def check_price(price):
if int(price)>100:
print("Price is greather than 100")
else:
print("price is less than 100")
book_1=StoryBook('sajjad',30,'zahan','2-3-4')
book_2=StoryBook('sajjad',100,'zahan','2-3-4')
# print(book_2)
# book_2.discount=0.6
# print(book_2.applying_discount())
# print(book_2)
# print(StoryBook.no_of_books)
# print(book_1.price)
# print(book_1.discount)
# StoryBook.set_discount(0.7)
# print(book_2.applying_discount())
book_str = 'Harry Poter, 200, JK Rowling, 1970'
harry_poter=StoryBook.construct_from_string(book_str)
print(harry_poter)
StoryBook.check_price(harry_poter.price)
|
7a40ab3b75bd4d7a8d23ee6dea231773019b72e7 | sajjad0057/Practice-Python | /py_list.py | 583 | 3.859375 | 4 | subject=["c++","java","c","c#","python","basic"]
sub=(len(subject))
print("1->",sub)
subject.append("assemble")
print("2->",subject)
subject.insert(2,"sajjad")
print("3->",subject)
subject.remove("sajjad")
print("4->",subject)
subject2=subject.copy()
print("5->",subject2)
pos=subject.index("c#") #To find index No. use this formet
print("6->Index",pos)
pos_2=subject2[3] #To find index value use this formet
print("7->The 3 No. index value is:",pos_2)
subject.sort()
print("8->",subject)
'''
python have lerge number
of builtin function
plz search it
''' |
7ad2419d13fd0ddae7e8bc2320b0aad9ceed1e79 | sajjad0057/Practice-Python | /OOP8_multilevelInheritance.py | 728 | 3.875 | 4 | '''
Exaple for multi-level Inheritance!
'''
class A:
def display1(self):
print("I am inside A class");
class B(A):
def display2(self):
super().display1();
print("I am inside B class");
class C(B):
def display3(self):
super().display2()
print("I am inside C class");
c=C();
c.display3();
'''
Example for Multiple Inheritance!
'''
class X:
def display11(self):
print("I am inside X class");
class Y():
def display22(self):
print("I am inside Y class");
class Z(X,Y):
def display33(self):
super().display11()
super().display22()
print("I am inside Z class");
z=Z();
z.display33();
|
e9f846f5464649428ec8b7a6cdadc76cde91bd2f | sajjad0057/Practice-Python | /DS and Algorithm/Algorithmic_Tools/Devide-n-Conquer/marge_sort.py | 1,092 | 4.15625 | 4 | def marge_sort(a,b):
marged_list = []
len_a , len_b = len(a),len(b)
index_a, index_b = 0,0
#print(f'index_a , index_b = {index_a} , {index_b}')
while index_a<len_a and index_b<len(b):
if a[index_a]<b[index_b]:
marged_list.append(a[index_a])
index_a +=1
else:
marged_list.append(b[index_b])
index_b +=1
#print(f'index_a , index_b = {index_a} , {index_b}')
if index_a<len(a):
marged_list.extend(a[index_a:])
#print("****",marged_list)
if index_b<len(b):
marged_list.extend(b[index_b:])
#print("+++++", marged_list)
return marged_list
def marge(L):
if len(L)<=1:
return L
mid = len(L)//2
left = marge(L[:mid])
right = marge(L[mid:])
return marge_sort(left,right)
if __name__ == "__main__":
L = [5, 6, 34, 32, 6, 8, 3, 2, 5, 7, 5, 55, 43, 3, 33, 4, 6, 78]
sorted_list = marge(L)
print("Original List : ", L)
print("Sorted List : ", sorted_list)
|
26414e80300ccbfb508993b00fedb999b20487e0 | sajjad0057/Practice-Python | /DS and Algorithm/Algorithmic_Tools/Devide-n-Conquer/quick_sort.py | 527 | 3.671875 | 4 | def partition(L,low,high):
pivot = L[high]
i = low - 1
for j in range(low,high):
if L[j]<pivot:
i +=1
L[i],L[j] = L[j],L[i]
print(L)
L[i+1],L[high] = L[high],L[i+1]
return i+1
def quick_sort(L,low,high):
if low>=high:
return
p = partition(L,low,high)
quick_sort(L,low,p-1)
quick_sort(L,p+1,high)
L = [1,5,6,3,8,6,4,7,2,6]
print("Old list -----> : ",L)
quick_sort(L,0,len(L)-1)
print("Sorted list -----> : ",L) |
76b834b478b32dc88a2f6f6330da01f349cff490 | sajjad0057/Practice-Python | /py_2.py | 153 | 4.0625 | 4 | while 1:
a=int(input("Enter the number a: "))
if a>=5 and a<20:
print("yes! I am right")
else:
print("My concept wrong") |
d3fdd903219898c91c2fd6bfeb95ae7735d8eba0 | aprz512/learn-python | /ex17.py | 498 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from os.path import exists
print "This script can copy a file to another!"
source_file = raw_input("choose a file to copy : ")
target_file = raw_input("choose a file to save : ")
file_data = open(source_file).read()
print "%s length = %d" % (source_file, len(file_data))
print "%s exist? %r" % (target_file, exists(target_file))
open(target_file, "w").write(file_data)
# 没有使用变量保存文件,程序结束后,python会自动关闭文件,不用调用 close
|
d0e213dd1e560dd0a7a569c47e1363d83a31387b | memetics19/selenium_scraping | /Browser.py | 1,019 | 3.53125 | 4 | import csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
"""place your path here in the executable path"""
driver = webdriver.Chrome(executable_path = r"C:\Users\Lenovo\Documents\astaqc\selenium\Drivers\chromedriver.exe")
BASE_URL = "https://google.com"
""" Base_URL is been passed to driver"""
driver.get(BASE_URL)
search = "spanish flu filetype:pdf"
search_box = driver.find_element_by_xpath("//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input").send_keys(search,Keys.RETURN)
""" All the href will be stored in results """
def GetLinks():
for a in driver.find_elements_by_xpath("//a"):
""" Finding the element by using xpath """
href = a.get_attribute("href") ### Getting all the href and storing the list
print(href)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
driver.find_element_by_xpath('/html/body/div[5]/div[2]/div[9]/div[1]/div[2]/div/div[5]/div[2]/span[1]/div')
GetLinks()
driver.close() |
205ac964350d0547f90e710e63bf13376f284074 | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week3/class2/combination_one_zero.py | 252 | 3.9375 | 4 | times = 0
for a in range(2):
p1 = a
for b in range(2):
p2 = b
for c in range(2):
p3 = c
string = str(p1) + str(p2) + str(p3)
times = times + 1
print(str(times) + ": " + string)
|
27cbc84ffd348ab3a9aa0c21d50149e98cc6e940 | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week3/class1/break_continue.py | 187 | 4.0625 | 4 | # Break
for a in range(10):
if a == 3:
break
print(a)
# Cnotinue
for a in range(10):
if a == 3:
continue
print(a)
# for a in range(2,10):
# print(a)
|
21e628b27a954ccfcd7c54fa946a719cab15b522 | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week3/class1/break_continue_2.py | 165 | 3.875 | 4 | # Cnotinue
for a in range(10):
if a % 2 == 0:
continue
print(a)
print("---")
for a in range(10):
if a % 2 != 0:
continue
print(a)
|
1bf786a8bebc2f14d45deef9aceb1891c152f21b | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /week16/plot_test.py | 364 | 3.515625 | 4 | import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
#plt.plot(squares)
#plt.show()
squares = [10,20,30,40,50]
input_value = [10,20,30,40,40]
#plt.plot(squares,linewidth = 5)
plt.scatter(input_value,squares,linewidth = 5)
plt.title("Square Number 虹", fontsize = 24)
plt.xlabel("Value", fontsize = 14)
plt.ylabel("Square of Value", fontsize = 14)
plt.show() |
5cf93df98db5fb6fe7444fffbbd1fa79559607cd | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week4/Class1/Homework.py | 1,080 | 4.25 | 4 | #Create a list of numbers, randomly assigned.
#Scan the list and display several values:The minimum, the maximum, count and average
#Don`t use the “min”, “max”, “len ” and “sum” functions
#1. Len : gives the number of elements in array.
#2. Min, max: Gives the highest highestor lowest number in the array.
#3. Sum: Adds all the numbers in array.
import random
mylist = []
for a in range(10):
mylist.append(random.randint(1,101))
print(mylist)
# Length of the list
len = 0
for x in mylist:
len += 1
print('len = ',len)
# Sum of the list
sum=0
for x in mylist:
sum += x
print('sum = ',sum)
# Average of the list
print('ave = ',sum/len)
# Max Value
maxValue = mylist[0]
for y in mylist:
if y > maxValue:
maxValue = y
print ('max = ',maxValue)
# Min Value
minValue = mylist[0]
for y in mylist:
if y < minValue:
minValue = y
print ('min = ',minValue)
#print('len = ',len(mylist))
#print('max = ',max(mylist))
#print('min = ',min(mylist))
#print('sum = ',sum(mylist))
#print('ave = ',sum(mylist)/len(mylist)) |
04ad4e7ddc982df2baae2832efa409182c348037 | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week7/Test/Question_2.py | 551 | 3.9375 | 4 | # Lists
my_list = []
while True:
element = input("Please enter an element to add to the list[fin = finished] > ")
if element != "fin" and element != "":
my_list.append(element)
elif element == "":
print("Wrong! The input should not be empty")
else:
print()
length = len(my_list)
print("The list contains {} elements, here they are: ".format(length))
print()
number = 0
for e in my_list:
number += 1
print(str(number) + " : "+ e)
break
|
d676b0f0c8fe48d25a1afe03d6f2b2f2572654fe | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week7/Exercise/student_collection.py | 752 | 3.796875 | 4 | class Student:
#id=0
#name = ""
#gpa = 0
#def __init__(self,id,name,gpa):
def __init__(self, id:int, name:str, gpa:float):
self.id = id
self.name = name
self.gpa = gpa
class StudentClass:
def __init__(self):
self.students = []
def add_student(self, student:Student):
self.students += [student]
def get_average_gpa(self):
sum_gpa =0
for s in self.students:
sum_gpa += s.gpa
return sum_gpa/len(self.students)
math_101 = StudentClass()
s1 = Student(100, "Mary", 2.8)
s2 = Student(200, "Bob", 3.2)
s3 = Student(300, "Brendan", 3.5)
math_101.add_student(s1)
math_101.add_student(s2)
math_101.add_student(s3)
print(math_101.get_average_gpa()) |
cc576900d66498650727d7be7c7d429c0f6c9dc9 | DerekSomerville/FakePythonGuessNumber | /src/main/test/RandomInputTest.py | 254 | 3.71875 | 4 | import unittest
from src.main.python.RandomInput import RandomInput
class RandomInputTest(unittest.TestCase):
def testGet(self):
randomInput = RandomInput()
self.assertTrue(randomInput.getInputInt("") <= randomInput.getMaxNumber()) |
385c852ea3fcbafe34205fd8e048c1f8235cb77a | Hiroki9759/learning-tensorflow | /session.py | 925 | 3.609375 | 4 | """sessionは演算グラフの実行単位のようなもの
構成した演算グラフはSession内で実行することとなり、同一のグラフでもSessionが異なれば別の環境としてみなされる
このため、Sessionを別にするグラフ間のVariableの値の共有などは行われない
"""
import tensorflow as tf
#変数の定義
counter = tf.Variable(0,name = "counter")
step_size = tf.constant(1,name = "step_size")
#現在のCOUNTERにstep_sizeを足す
increment_op = tf.add(counter,step_size)
#increment_op の演算結果でcounterの値を更新
count_up_op = tf.assign(counter,increment_op)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(3):
print(sess.run(count_up_op))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(3):
print(sess.run(count_up_op))
|
f36cb9863dd96dbf1dfebcc837c8aec18de33967 | LXXJONGEUN/Graduation_Project | /web/crypto/RSA2.py | 1,398 | 4.125 | 4 | def gcd(a, b):
while b!=0:
a, b = b, a%b
return a
def encrypt(pk, plaintext):
key, n = pk
cipher = [(ord(char) ** key) % n for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
key, n = pk
plain = [chr((char ** key) % n) for char in ciphertext]
return ''.join(plain)
def get_private_key(e, tot):
k=1
while (e*k)%tot != 1 or k == e:
k+=1
return k
def get_public_key(tot):
e=2
while e<tot and gcd(e, tot) != 1:
e += 1
return e
# m = input("Enter the text to be encrypted:")
# # Step 1. Choose two prime numbers
# p = 13
# q = 23
# print("Two prime numbers(p and q) are:", str(p), "and", str(q))
# # Step 2. Compute n = pq which is the modulus of both the keys
# n = p*q
# print("n(p*q)=", str(p), "*", str(q), "=", str(n))
# # Step 3. Calculate totient
# totient = (p-1)*(q-1)
# print("(p-1)*(q-1)=", str(totient))
# # Step 4. Find public key e
# e = get_public_key(totient)
# print("Public key(n, e):("+str(n)+","+str(e)+")")
# # Step 5. Find private key d
# d = get_private_key(e, totient)
# print("Private key(n, d):("+str(n)+","+str(d)+")")
# # Step 6.Encrypt message
# encrypted_msg = encrypt((e,n), m)
# print(encrypted_msg)
# print('Encrypted Message:', ''.join(map(lambda x: str(x), encrypted_msg)))
# # Step 7.Decrypt message
# print('Decrypted Message:', decrypt((d,n),encrypted_msg)) |
2a37ea50a90ccd9bea92ec07095715f269de7734 | Fareshamad/AI | /formatief opdracht/FizzBuzz.py | 647 | 4.03125 | 4 | """Schrijf een programma dat de getallen 1 tot 100 print, maar print voor veelvouden van drie “fizz” in plaats van het getal en voor veelvouden van vijf print “buzz” in plaats van
het getal. Getallen die zowel veelvoud zijn van drie als van vijf worden afgedrukt als “fizzbuzz”"""
def FizzBuzz():
for fizzbuzz in range(0,101):
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
print("fizzbuzz")
continue
elif fizzbuzz % 3 == 0:
print("fizz")
continue
elif fizzbuzz % 5 == 0:
print("buzz")
continue
print(fizzbuzz)
print(FizzBuzz()) |
bfc716c11ce00d081cb9866d4f38dafabe37cca3 | SvjatN/Codewars5 | /CodeWarsT19.py | 527 | 4.0625 | 4 | """
Given a string, you have to return a string
in which each character (case-sensitive) is repeated once.
double_char("String") ==> "SSttrriinngg"
double_char("Hello World") ==> "HHeelllloo WWoorrlldd"
double_char("1234!_ ") ==> "11223344!!__ "
"""
def double_char(s):
s = list(s)
res_list = []
res_str = ""
for i in s:
for j in i:
res_list.append(j)
res_list.append(j)
for i in range(len(res_list)):
res_str = res_str + res_list[i]
return res_str
|
c71bf3f81c3d747b871dfdd4028780085c0356af | AgustGreen/mi_primer_programa | /PokemonCombat.py | 1,203 | 3.953125 | 4 | sel_pokemon = input("contra que pokemon quieres combatir?: (Squirtle / Bulbasaur / Charmander): ")
pikachu_hp = 100
enemy_hp = 0
enemy_atk = 0
if sel_pokemon == "Squirtle":
enemy_hp = 90
pokemon_name = "Squirtle"
enemy_atk = 8
elif sel_pokemon == "Bulbasaur":
enemy_hp = 100
pokemon_name = "Bulbasaur"
enemy_atk = 10
elif sel_pokemon == "Charmander":
enemy_hp = 80
pokemon_name = "Charmander"
enemy_atk = 7
while pikachu_hp > 0 and enemy_hp > 0:
sel_attack = input("Que ataque quieres usar? (Chispazo -10 / Bola voltio -12): ")
if sel_attack == "Chispazo":
print("Has utilizado Chispazo")
enemy_hp -= 10
elif sel_attack == "Bola voltio":
print("Has utilizado Bola voltio")
enemy_hp -= 12
else:
print("El ataque no es valido")
enemy_hp -= 0
print("La vida del {} es de {}".format(pokemon_name, enemy_hp))
print(("{} te ha hecho {} de daño").format(pokemon_name, enemy_atk))
pikachu_hp -= enemy_atk
print("La vida de tu Pikachu es de {}".format(pikachu_hp))
if enemy_hp <= 0:
print("Has ganado")
elif pikachu_hp <= 0:
print("Has perdido")
print("El combate ha terminado")
|
351bfe9883d4b7a1f5b55d191fdbfb6845b6f5e4 | AgustGreen/mi_primer_programa | /guess.py | 649 | 3.765625 | 4 | number_guess = 2
user_number = int(input("adivina un numero del 1 al 10 (tienes 3 intentos): "))
if number_guess == user_number:
print("has ganado!")
elif number_guess != user_number:
print("has perdido, reintenta")
user_number = int(input("adivina un numero del 1 al 10 (tienes 2 intentos): "))
if number_guess == user_number:
print("has ganado!")
elif number_guess != user_number:
print("has perdido, reintenta")
user_number = int(input("adivina un numero del 1 al 10 (tienes 1 intento): "))
if number_guess == user_number:
print("has ganado!")
elif number_guess != user_number:
print("has perdido, reintenta")
|
dfe42d63885c79a64f88d2e15288c107b0926346 | mateuspinto/presto | /src/Memories/AbstractMemory.py | 1,158 | 3.640625 | 4 | import abc
class AbstractMemory(metaclass=abc.ABCMeta):
@abc.abstractmethod
def appendProcess(self, pid: int, numberOfVariables: int, processTable, diagnostics) -> int:
"""
Append a new process and return the memory offset.
"""
pass
@abc.abstractmethod
def name(self) -> str:
pass
@abc.abstractmethod
def __str__(self) -> str:
pass
@abc.abstractmethod
def popProcess(self, pid: int) -> None:
pass
@abc.abstractmethod
def getValue(self, pid: int, variableNumber: int, processTable) -> int:
pass
@abc.abstractmethod
def declare(self, pid: int, variableNumber: int, processTable) -> None:
pass
@abc.abstractmethod
def setValue(self, pid: int, variableNumber: int, value: int, processTable) -> None:
pass
@abc.abstractmethod
def moveToInfiniteMemory(self, pid: int, processTable, infiniteMemory) -> None:
"""
Move all variables to virtual memory for final print
"""
pass
@abc.abstractmethod
def haveMemoryAvailable(self, numberOfVariables: int) -> bool:
pass
|
5df9bc71268dd9b6c126886c70dce8b0c265a9a7 | MissouriMRR/IARC-2019 | /flight/tasks/yaw_task.py | 1,890 | 3.8125 | 4 | """A TaskBase subclass for yawing a amount in degrees."""
from constants import YAW_SPEED
from task_base import TaskBase
DEGREE_BUFFER = .5 #acceptable error of angle in degrees
class Yaw(TaskBase):
"""
A task to make the drone yaw to a given heading either relative or absolute.
Attributes
----------
_has_started : bool
Indicates whether the drone has started to yaw.
_new_heading : int
Stores the given heading after modding it by 360 to keep it in range.
_yaw_speed : int
The speed in degrees/sec that the drone performs the yaw.
_yaw_direction : int
The direction which you force the drone rotoate: -1 for counterclockwise, and 1 for clockwise.
__relative : bool
Stores whether the given heading is relative or absolute: True means relative and False means absolute.
"""
def __init__(self, drone, heading):
"""
Initialize a task for yawing.
Parameters
----------
drone : dronekit.Vehicle
The drone being controlled.
heading : int
The heading for the drone to go to.
"""
super(Yaw, self).__init__(drone)
self._has_started = False
self._new_heading = heading%360
self._yaw_speed = YAW_SPEED
self._yaw_direction = 1 #defaulted to 1 (clockwise)
self._relative = True #defaulted to always be relative
def perform(self):
"""Do one iteration of logic for yawing the drone."""
if not self._has_started:
self.start_heading = self._drone.heading
self._drone.send_yaw(self._new_heading, self._yaw_speed, self._yaw_direction, self._relative)
self._has_started = True
if abs(self._drone.heading - self.start_heading) < self._new_heading - DEGREE_BUFFER:
return False
else:
return True |
2c0dc75b0b88a02ecec2cc27fafdbcd752ddfcdf | MissouriMRR/IARC-2019 | /flight/utils/timer.py | 2,401 | 3.9375 | 4 | """"A class that allows for the execution of arbitrary code at set intervals."""
from time import sleep
from timeit import default_timer as timer
import threading
class Timer():
""" Runs code as specified intervals. """
def __init__(self):
self._event_threads = []
self._stop_event_map = {}
self._thread_map = {}
self._lock = threading.Lock()
self._num_threads_lock = threading.Lock()
self.reset()
def _create_event_thread(self, closure, name):
stop_event = threading.Event()
self._stop_event_map[name] = stop_event
thread = threading.Thread(target=closure, args=(stop_event,))
thread.daemon = True
self._thread_map[name] = thread
self._event_threads.append(thread)
thread.start()
@property
def num_threads(self):
with self._num_threads_lock:
return len(self._event_threads)
def add_callback(self, name, when_to_call, callback, recurring=False):
""" Add a block of code that is called every when_to_call seconds. """
if name in self._stop_event_map:
raise ValueError('The `name` parameter cannot be assigned the \
duplicate name: "{}"!'.format(name))
if when_to_call <= self.elapsed:
callback()
return
def handle_event(stop_event):
while recurring and not stop_event.is_set():
sleep(max(when_to_call-self.elapsed, 0))
event_handled = False
while (((not event_handled) or recurring) and
not stop_event.is_set()):
if when_to_call <= self.elapsed:
callback()
event_handled = True
break
sleep(1e-3)
if self.num_threads == 1 and recurring:
self.reset()
self._create_event_thread(handle_event, name)
def stop_callback(self, name):
self._stop_event_map[name].set()
def shutdown(self):
for name, stop_event in self._stop_event_map.items():
stop_event.set()
self._thread_map[name].join()
@property
def elapsed(self):
with self._lock as lock:
return timer() - self._start
def reset(self):
with self._lock:
self._start = timer()
|
58766b4143459df54f7610db86ca0fa11574af2d | annikaslund/python_practice | /python-fundamentals/48-last_argument/test.py | 670 | 3.671875 | 4 | import unittest
# Click to add an import
from last_argument import last_argument
class UnitTests(unittest.TestCase):
def test_input_1(self):
# Failure message:
# expected last_arguments(1, 2, 3) to be 3
self.assertEqual(last_argument(1, 2, 3), 3)
def test_input_2(self):
# Failure message:
# expected last_arguments("what", "a", "strange", "function") to be "function"
self.assertEqual(last_argument(
"what", "a", "strange", "function"), "function")
def test_input_3(self):
# Failure message:
# expected last_arguments() to be None
self.assertIsNone(last_argument())
|
b0daf15869f65fe5058919cfc3095a854059defc | annikaslund/python_practice | /python-fundamentals/18-sum_even_values/test.py | 651 | 3.5625 | 4 | import unittest
# Click to add an import
from sum_even_values import sum_even_values
class UnitTests(unittest.TestCase):
def test_input_1(self):
# Failure message:
# expected sum_even_values([1, 2, 3, 4, 5, 6]) to equal 12
self.assertEqual(sum_even_values([1, 2, 3, 4, 5, 6]), 12)
def test_input_2(self):
# Failure message:
# expected sum_even_values([4, 2, 1, 10]) to equal 16
self.assertEqual(sum_even_values([4, 2, 1, 10]), 16)
def test_input_3(self):
# Failure message:
# expected sum_even_values([1]) to equal 0
self.assertEqual(sum_even_values([1]), 0)
|
bae6be57308a63bc6063b9e76bd9117bf9f00a7e | annikaslund/python_practice | /python-fundamentals/01-product/product.py | 97 | 3.5 | 4 | def product(a, b):
""" takes in two integers and returns the product """
return a * b
|
5903073956c3a4f5b7e47cf23da710a354ea43ec | annikaslund/python_practice | /python-fundamentals/07-list_manipulation/test.py | 2,193 | 3.953125 | 4 | import unittest
# Click to add an import
from list_manipulation import list_manipulation
class UnitTests(unittest.TestCase):
def test_remove_from_end(self):
# Failure message:
# expected list_manipulation([1, 2, 3], "remove", "end") to equal 3
self.assertEqual(list_manipulation([1, 2, 3], "remove", "end"), 3)
def test_remove_from_end_mutates_list(self):
# Failure message:
# expected list to be [1, 2] after calling list_manipulation([1, 2, 3], "remove", "end")
l = [1, 2, 3]
list_manipulation(l, "remove", "end")
self.assertEqual(l, [1, 2])
def test_remove_from_beginning(self):
# Failure message:
# expected list_manipulation([1, 2], "remove", "beginning") to equal 1
self.assertEqual(list_manipulation([1, 2], "remove", "beginning"), 1)
def test_remove_from_beginning_mutates_list(self):
# Failure message:
# expected list to be [2] after calling list_manipulation([1, 2], "remove", "beginning")
l = [1, 2]
list_manipulation(l, "remove", "beginning")
self.assertEqual(l, [2])
def test_add_to_beginning(self):
# Failure message:
# expected list_manipulation([2], "add", "beginning", 20) to equal [20, 2]
self.assertEqual(list_manipulation(
[2], "add", "beginning", 20), [20, 2])
def test_add_to_beginning_mutates_list(self):
# Failure message:
# expected list to be [20, 2] after calling list_manipulation([2], "add", "beginning", 20)
l = [2]
list_manipulation(l, "add", "beginning", 20)
self.assertEqual(l, [20, 2])
def test_add_to_end(self):
# Failure message:
# expected list_manipulation([20, 2], "add", "beginning", 30) to equal [20, 2, 30]
self.assertEqual(list_manipulation(
[20, 2], "add", "end", 30), [20, 2, 30])
def test_add_to_end_mutates_list(self):
# Failure message:
# expected list to be [20, 2, 30] after calling list_manipulation([20, 2], "add", "end", 30)
l = [20, 2]
list_manipulation(l, "add", "end", 30)
self.assertEqual(l, [20, 2, 30])
|
28395516a71b1f5c50480ef3274bd2cfb9bd83ff | annikaslund/python_practice | /python-fundamentals/46-three_odd_numbers/solution.py | 203 | 4.0625 | 4 | def three_odd_numbers(nums):
"""Are any 3 seq numbers odd?"""
for i in range(len(nums) - 2):
if (nums[i] + nums[i + 1] + nums[i + 2]) % 2 != 0:
return True
return False
|
e8cf2f63f38c417981c670689bbb649ccb1f296d | annikaslund/python_practice | /python-fundamentals/04-number_compare/number_compare.py | 301 | 4.15625 | 4 | def number_compare(num1, num2):
""" takes in two numbers and returns a string
indicating how the numbers compare to each other. """
if num1 > num2:
return "First is greater"
elif num2 > num1:
return "Second is greater"
else:
return "Numbers are equal" |
42c723406fb4e8e3fd00dd2a0f2f2aeb2a283f2a | annikaslund/python_practice | /python-fundamentals/10-flip_case/test.py | 500 | 3.515625 | 4 | import unittest
# Click to add an import
from flip_case import flip_case
class UnitTests(unittest.TestCase):
def test_input_1(self):
# Failure message:
# expected flip_case("Hardy har har", "h") to equal "hardy Har Har"
self.assertEqual(flip_case("Hardy har har", "h"), "hardy Har Har")
def test_input_2(self):
# Failure message:
# expected flip_case("Aaaaahhh!", "A") to equal "aAAAAhhh!"
self.assertEqual(flip_case("Aaaaahhh!", "A"), "aAAAAhhh!")
|
91e08c304bdf2dcade4f00ad513711d7cadde116 | annikaslund/python_practice | /python-fundamentals/18-sum_even_values/sum_even_values.py | 235 | 4.15625 | 4 | def sum_even_values(li):
""" sums even values in list and returns sum """
total = 0
for num in li:
if num % 2 == 0:
total += num
return total
# return sum([num for num in li if num % 2 == 0]) |
a210057a9ea3677c6b80d6dd5bef785f59d30c28 | annikaslund/python_practice | /python-fundamentals/17-calculate/calculate.py | 450 | 3.828125 | 4 | def calculate(op, first, second, make_int=False, msg="Success!"):
if op == "add":
addition = first + second
string_sum = f" {addition}"
return msg + string_sum
if op == "subtract":
subtraction = first - second
string_diff = f" {subtraction}"
return msg + string_diff
if op == "multiply":
product = first * second
string_prod = f" {product}"
return msg + string_prod
|
53b0e25540a35c7f25d239582ec7b91437efcea9 | annikaslund/python_practice | /python-fundamentals/44-is_odd_string/test.py | 963 | 3.71875 | 4 | import unittest
# Click to add an import
from is_odd_string import is_odd_string
class UnitTests(unittest.TestCase):
def test_input_1(self):
# Failure message:
# expected is_odd_string('a') to equal True
self.assertEqual(is_odd_string('a'), True)
def test_input_2(self):
# Failure message:
# expected is_odd_string('aaaa') to equal False
self.assertEqual(is_odd_string('aaaa'), False)
def test_input_3(self):
# Failure message:
# expected is_odd_string('amazing') to equal True
self.assertEqual(is_odd_string('amazing'), True)
def test_input_4(self):
# Failure message:
# expected is_odd_string('veryfun') to equal True
self.assertEqual(is_odd_string('veryfun'), True)
def test_input_5(self):
# Failure message:
# expected is_odd_string('veryfunny') to equal False
self.assertEqual(is_odd_string('veryfunny'), False)
|
55064e1933108b59cef7f8ef68c1377c37cd1f0d | samhorsfield96/graph_benchmarking | /gfa_to_fasta.py | 529 | 3.578125 | 4 | def gfa_to_fasta(in_file):
"""Converts .gfa file to .fasta, using same file name.
Args:
in_file (str)
path for .gfa file to convert.
"""
base = os.path.splitext(in_file)[0]
out_file = base + ".fasta"
with open(in_file, "r") as f, open(out_file, "w") as o:
for line in f:
parsed_line = re.split(r'\t+', line.rstrip('\t'))
if parsed_line[0] == "S":
o.write(">" + str(parsed_line[1]) + "\n" + str(parsed_line[2]) + "\n")
|
09e9772ec25fde7fefacc52d531c195e5fe0b2ff | Davies-Career-and-Technical-High-School/2-1-activity-basic-calculations-JermsterOrtega | /question1.py | 77 | 3.953125 | 4 | num = int(input("Enter a integer: "))
print(num+1)
print(num+2)
print(num+3) |
4a7ae8be053783e401d5bc5cfe999efb4fe5a066 | ElinaBarabas/Graph-Algorithms | /Laboratory 4/main.py | 4,497 | 3.828125 | 4 | import random
# Write a program that, given an undirected connected graph, constructs
# a minumal spanning tree using the Kruskal's algorithm.
class UndirectedGraph:
def __init__(self, n, m):
self._n = n
self._m = m
self._vertices_list = []
self._cost_dictionary = {}
self.initial_vertices()
def get_number_of_vertices(self):
return self._n
def get_number_of_edges(self):
return self._m
def get_value_cost_dictionary(self, origin, target):
key = (origin, target)
return self._cost_dictionary[key]
def get_edges(self):
for key, value in self._cost_dictionary.items():
yield key
def get_set_of_vertices(self):
return self._vertices_list
def get_cost_dictionary(self):
return self._cost_dictionary
def get_cost(self, key):
return self._cost_dictionary[key]
def set_keys(self, key, values):
self._cost_dictionary[key] = values
def initial_vertices(self):
for index in range(self._n + 1):
self._vertices_list.append(index)
def is_edge(self, origin, target):
edge = (origin, target)
return edge in self._cost_dictionary.keys()
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
x_root = self.find(parent, x)
y_root = self.find(parent, y)
if rank[x_root] < rank[y_root]:
parent[x_root] = y_root
elif rank[x_root] > rank[y_root]:
parent[y_root] = x_root
else:
parent[y_root] = x_root
rank[x_root] += 1
def KruskalMST(self):
result = []
i = 0
number_of_required_edges = 0
sorted_copy_keys = sorted(self._cost_dictionary,
key=self._cost_dictionary.get)
print("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")
#print(str(sorted_copy_keys))
print("Initial: ", self.get_cost_dictionary())
print("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")
sorted_copy_values = sorted(self._cost_dictionary.values())
#print(str(sorted_copy_values))
#print("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")
sorted_dictionary = dict(zip(sorted_copy_keys, sorted_copy_values))
self._cost_dictionary = sorted_dictionary
print("Sorted: ",self.get_cost_dictionary())
print("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")
parent = []
rank = []
for node in range(self._n):
parent.append(node)
rank.append(0)
while number_of_required_edges < self._n - 1:
u, v = sorted_copy_keys[i]
w = sorted_copy_values[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
number_of_required_edges = number_of_required_edges + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)
def read_file(file_path):
file = open(file_path, "r")
n, m = map(int, file.readline().split())
one_graph = UndirectedGraph(int(n), int(m))
for edge in range(m):
origin, target, cost = map(int, file.readline().split())
if cost is not None:
key_pair = (int(origin), int(target))
one_graph.set_keys(key_pair, int(cost))
file.close()
return one_graph
g = read_file("graph.txt")
g.KruskalMST()
|
2f31f5055102830f31addc93e260ab4987aa08b9 | sumukh31/Algos_DS | /arrays/missing_element.py | 339 | 4.03125 | 4 | import collections
def missing_element(arr1,arr2):
count = collections.defaultdict(int)
for num in arr2:
count[num] += 1
for num in arr1:
if count[num] == 0:
return num
else:
count[num] -= 1
arr1 = [1,2,3,3]
arr2 = [1,2,3]
missing = missing_element(arr1,arr2)
print (missing)
|
9787de1d538f6bd0ebd744120567261116825ee7 | minkookBae/algorithm_prac | /BOJ_4344.py | 500 | 3.703125 | 4 | import sys
def avg(N,target_list):
temp = sum(target_list)
avg_list = temp / N
return avg_list
q = lambda : list(map(int,sys.stdin.readline().split()))
C = int(sys.stdin.readline())
for i in range(C):
count = 0
target_list = q()
N = target_list[0]
target_list = target_list[1:]
temp_avg = avg(N,target_list)
for j in target_list:
if j > temp_avg:
count += 1
answer = count / N * 100
print("%.3f"%answer,end="%")
print() |
32136afe9ae4dcc40002f5af0760f209c7af7beb | minkookBae/algorithm_prac | /BOJ_2110.py | 667 | 3.6875 | 4 | import sys
def routerInstall(distance):
count = 1
cur_home = target_list[0]
for i in range(1,N):
if (distance <= target_list[i] - cur_home):
count += 1
cur_home = target_list[i]
return count
N, C = list(map(int,sys.stdin.readline().split()))
target_list = []
for _ in range(N):
target_list.append(int(sys.stdin.readline()))
target_list.sort()
low = 1
high = target_list[-1] - target_list[0]
while(low <= high):
mid = (low + high + 1) // 2
router_count = routerInstall(mid)
if(router_count < C):
high = mid -1
else:
answer = mid
low = mid + 1
print(answer) |
a77f55dd11890ba5c479d4c2a9c2daeab0da9b1c | minkookBae/algorithm_prac | /BOJ_9020.py | 595 | 3.515625 | 4 | import sys
def prime_list(n):
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True: # i가 소수인 경우
for j in range(i+i, n, i): # i이후 i의 배수들을 False 판정
sieve[j] = False
# 소수 목록 산출
return [i for i in range(2, n) if sieve[i] == True]
T = int(sys.stdin.readline())
for _ in range(T):
n = int(sys.stdin.readline())
temp = prime_list(n)
for i in range(n//2,1,-1):
if(i in temp and n-i in temp):
print(i,n-i)
break |
4eed14ed9ab6d37d0cd52297cf316ab42386072c | minkookBae/algorithm_prac | /탑.py | 420 | 3.65625 | 4 | def solution(heights):
answer = [0 for _ in range(len(heights))]
for i in range(len(heights)-1,-1,-1):
flag = False
for j in range(i-1,-1,-1):
if(heights[i] < heights[j]):
flag = True
answer[i] = j+1
break
return answer
if __name__ == "__main__":
heights = [3,9,9,3,5,7,2]
print(solution(heights)) |
1bed83194912d27581e2a8485d12f8835fcf7f5d | zewa1999/PythonExamples | /1/Cursul 1/26. CheileDictionarului.py | 897 | 4 | 4 | # Un dictionar poate fi format din mai multe chei si valori
# O valoare nu poate exista fara o cheie
dictionar = {
"cheie" : "valoare"
}
# Practic cheia este elementul cu care accesam valoarea
# Dar o cheie poate fi doar de tipul string?
# Hai sa vedem
dictionar2 = {
1 : "valoare",
True : "alta valoare"#,
#[1,2,3] : "lista" # Nu merge
}
# De ce nu merge oare lista ca si o cheie?
# Deoarece o cheie poate fi doar o variabila ce are proprietatea ca nu se poate schimba!!!
# De aceea putem folosi, numere intregi, stringuri sau valori booleene
# Ce se intampla daca avem doua chei identice?
# Exemplu:
dictionar3 = {
1 : True,
1: False
}
print(dictionar3[1])
# Se afiseaza False! Pentru ca o data ce scriem aceeasi cheie intr-un dictionar, valoarea de inainte, care in cazul nostru era True
# Se va modifica si va deveni ultima gasita in dictionar, care e False
|
2a8cac67a41ef3373963129190c540fb2fd1b70e | zewa1999/PythonExamples | /1/Cursul 1/30. FunctiSet.py | 1,156 | 3.515625 | 4 | # De decomentat daca doresti sa vezi ce fac functiile
setul_meu = {1, 2, 3, 4, 5}
setul_tau = {4, 5, 6, 7, 8, 8, 9}
# Diferenta dintre setul_meu si setul_tau. Ce se afla in setul meu si nu se afla in setul tau. Returneaza un nou set
# set_nou = setul_meu.difference(setul_tau)
# print(set_nou)
# Stergerea unui element daca exista in set
# setul_meu.discard(5)
# print(setul_meu)
# Sterge toate elementele din set CARE nu se regasesc in ambele seturi si afiseaza setul ramas. Modificarile le face pe setul actual
# setul_meu.difference_update(setul_tau)
# print(setul_meu)
# Intersectia
# print(setul_meu.intersection(setul_tau))
# Putem scrie si asa
# print(setul_meu & setul_tau)
# Nu exista elemente comune in set. Daca exista se returneaza False, daca nu exista se returneaza True
# print(setul_meu.isdisjoint(setul_tau)) #-> False
# Reuniunea seturilor
# print(setul_meu.union(setul_tau))
# Putem scrie si astfel
# print(setul_meu | setul_tau
# Includere setul_meu este inclus in setul_tau
# print(setul_meu.issubset(setul_tau)) #->False
# Includere, setul_tau are elementele din setul_meu
# print(setul_meu.issuperset(setul_tau)) #->False
|
a248e88ef3202892eb8e8109174aa6f04768cde2 | zewa1999/PythonExamples | /1/Cursul 2/23. FunctiivsMetode.py | 438 | 3.984375 | 4 | # metodele sunt cele ce sunt determinate de un tip de date
# EX:
string = "andreea"
print(string.capitalize()) # Face prima litera a propozitiei una mare
# .capitalize este determinata de un string, practic metodele sunt cele care vin cu un punct dupa tipul de date
# Forma: tip_date.metoda()
# Functiile sunt cele ce le am invatat inainte, functii definite de noi
def functie(nume):
print(f"{nume} e numele meu!")
functie(string) |
86bd5e64245d9f3fb7d87810b84a076ecc0ff6e5 | zewa1999/PythonExamples | /1/Cursul 2/5. OperatoriLogici.py | 724 | 4.03125 | 4 | # Urmatorii sunt operatori logici:
# and, or, not, >, <, ==, >=, <=, !=
# Exemple:
print(4>5)
print(4<5)
print(4 == 5)
print("salut" == "salut")
print('a' > 'b') # False
print('a' > 'A') # True
print(5>=5)
print(5<=6)
print(0 != 0) # != inseamna nu e egal
print(not True) # negatie
# Ultimele 2 valori afiseaza rezultatul asta pentru ca literele in Python sunt transformate in cod ASCII
# Codul ASCII, este o tabela de numere si valori, fiecare valoare, in cazul nostru caracter are un numar
# La a > A se afiseaza False pt ca numarul unde e stocat a este mai mic decat b
# La a > A se afiseaza True pt ca numarul unde e stocat a este mai mare decat A
# http://www.asciitable.com/ -> Uitate aici, litera A are 65 si a e 97 |
922ee381b05ee6b59b2c933a86ba65a1be7894ea | zewa1999/PythonExamples | /1/Cursul 2/2. TruthyVSFalsey.py | 1,145 | 3.859375 | 4 | # Atunci cand folosim un if, avem nevoie de valori booleene pentru a putea rula if-ul
# De aceea Python, face conversie la bool in ciuda faptului ca poate variabila noastra este una de tip string
# Exemplu:
am_mancat = "Da, am mancat"
# Daca afisam aceasta variabila, dupa ce am facut conversia la bool, am_mancat v-a fi True -> Asta inseamna Truthy
print(f"Variabila am_mancat string este: {am_mancat}")
print(f"Variabila am_mancat bool este: {bool(am_mancat)}")
# Falsey -> Daca variabila noastra este goala sau este 0, atunci vom avea fals
lucruri_facute_azi = "" # N-am facut nimic, deci las string-ul gol
print(f"Variabila lucruri_facute_azi string este: {lucruri_facute_azi}") # E un string gol
print(f"Variabila lucruri_facute_azi bool este: {bool(lucruri_facute_azi)}")
# De ce trebuie sa stim asta? Pt a scrie cod mai bun si mai aratos, ca si tine
# Exemplu
# Avem un formular de creare a unui utilizator. Acesta trebuie sa aiba un nume de cont si o parola
nume_cont = "andreea99"
parola = "feb1999"
if nume_cont and parola: # Daca nume_cont si parola exista atunci afisam ca s-a creat contul
print("Cont creat cu succes!") |
e049fe76f4ada3de64bd80d79c162137bf4bc9ed | TigranShukuryan/gittest.1 | /github_test.py | 471 | 3.578125 | 4 | class Money:
def __init__(self, amount, currency, amount_2):
self.amount_1 = amount
self.currency_1 = currency
self.amount_second = amount_2
def __repr__(self):
return str(self.amount_1) + " " + self.currency_1
def represetation(self):
return str(self.amount_1 - self.amount_second) + self.currency_1
final = Money(35, "usd", 15)
final_second = Money(67, "usd", 55)
print(final)
print(final.represetation())
print() |
623ffe41f56ba094c9e3fd741aff49cd384b49ba | fyngyrz/wtfm | /aa_formboiler.py | 12,217 | 3.640625 | 4 | #
# Contains routines to make building and reading forms much simpler
# -----------------------------------------------------------------
import time
import re
months = ['Jan','Feb','Mar','Aprl','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
fmonths = ['January','February','March','April','May','June','July','August','September','October','November','December']
# d is date in form: "YYYYMMDD"
def hrdate(d):
global fmonths
year = d[:4]
month = int(d[4:6])
day = int(d[6:8])
sfx = 'th'
if day == 1: sfx = 'st'
if day == 2: sfx = 'nd'
if day == 3: sfx = 'rd'
if day == 21: sfx = 'st'
if day == 22: sfx = 'nd'
if day == 23: sfx = 'rd'
if day == 31: sfx = 'st'
return fmonths[month-1]+' '+str(day)+sfx+', '+year
# date is in form: "YYYYMMDD"
def getweekday(date):
if type(date) != str:
return 1
if len(date) != 8:
return 1
wd = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
try:
yr = int(date[0:4])
mo = int(date[4:6])
da = int(date[6:8])
tp = (yr,mo,da,12,0,0,0,0,0)
foo = time.mktime(tp)
swatch = time.localtime(foo)
bar = wd[swatch[6]]
return bar,(swatch[6]+2)%7
except:
print 'date is a '+str(type(date))+'. date="'+str(date)+'" of length '+str(len(date))
# sy,ey in form 'YYYY'
# sm,em in form 'MM'
# sd,ed in form 'DD'
# --------------------
def makedatesorderly(sy,sm,sd,ey,em,ed):
if ey < sy: # oh, backwards years, eh? Not happening...
t = sy
sy = ey
ey = t
if sy == ey:
if em < sm: # backwards months in same year? Oy vey, you got de bad genes
t = sm
sm = em
em = t
if sm == em:
if ed < sd: # backwards days in same year, same month? Nope...
t = sd
sd = ed
ed = t
return sy,sm,sd,ey,em,ed
# ll = [[sValue,textDesc],[sValue,textDesc]]
def buildDds(name,ll,selected=None):
t = '<SELECT NAME="'+name+'">\n'
for el in ll:
kick = ''
if selected != None and selected != '':
if str(el[0]) == str(selected):
kick = ' SELECTED'
t += '<OPTION VALUE="'+str(el[0])+'"'+kick+'>'+str(el[1])+'\n'
t += '</SELECT>\n'
return t
# use builddropdown(), not this:
# ------------------------------
def lowbuilddropdown(name,ps,ad,sy):
ad = ad[0:4]
if ps == None or ps == '':
ps = str(ad)
t = '<SELECT NAME="'+name+'">'
for i in range(int(sy),int(ad)+1):
kick = ''
if str(i) == ps:
kick = ' SELECTED'
t += '<Option VALUE="'+str(i)+'"'+kick+'>'+str(i)
t += '</select>\n'
return t
# Builds a drop-down list of years from sy to this 'ad'
# and if ps == one of those years, will PreSelect that year
# input element is named 'name'
# ------------------------------------------------------------
def builddropdown(name,ps,ad=None,sy=None):
if ad == None:
ad = str(time.localtime()[0])
ad = ad[:4]
if sy == None:
sy = '1900'
if sy > ad:
ad = sy
# label, preselect, last selectable year, start year
return lowbuilddropdown(name,ps,ad,sy)
def builddaydropdown(name,ps):
if ps == None:
ps = str(time.localtime()[2])
t = '<SELECT NAME="'+name+'">'
for i in range(1,32):
kick = ''
if int(i) == int(ps):
kick = ' SELECTED'
rv = str(i)
if i < 10:
rv = '0'+rv
t += '<Option VALUE="'+rv+'"'+kick+'>'+str(i)
t += '</select>\n'
return t
def buildmondropdown(name,ps):
if ps == None:
ps = str(time.localtime()[1])
tt = ['January','February','March','April','May','June','July','August','September','October','November','December']
t = '<SELECT NAME="'+name+'">'
for i in range(1,13):
kick = ''
if int(i) == int(ps):
kick = ' SELECTED'
rv = str(i)
if i < 10:
rv = '0'+rv
t += '<Option VALUE="'+rv+'"'+kick+'>'+tt[i-1]
t += '</select>\n'
return t
# The four 'make' methods following default to producing table rows
# with two cells: A right-justified cell with the lable content,
# and a right justified cell with the unput element(s), and if
# you use this default, you'll only have to provide a table wrapper.
#
# However, you can supply format strings that allow you to embed
# the label and element any way you like. Since the lable and elements
# are returned as one string, if you would prefer to parse them
# yourself, just call this way...
#
# (...,lfmt='%s'+sepString,efmt='%s')
#
# ...then in your code, you can break them apart for later mucking about
# this way:
#
# label,element = result.split(sepString)
#
# Of course sepString has to NOT appear in the results anywhere.
# I suggest something like: sepString = '@#$K-J;U+H=5@#$'
# it's not pretty, but it sure isn't likely to break, lol.
# Make up your own, of course.
# --------------------------------------------------------------------------
# Year, month, date selector
#
# retrieve with getadatefield()
# -----------------------------
# label describes the widget's purpose
#
# yl is ( year) NAME="yl"
# ml is (month) NAME="ml"
# dl is ( day) NAME="dl"
#
# yv is the year preset
# mv is the month preset
# dv is the day preset
#
# ad is
#
# lfmt and efmt control how the widget is presented.
# --------------------------------------------------
def makedrow(label,yl,ml,dl,yv,mv,dv,ad,lfmt='',efmt=''):
# ad = ad[0:4]
if lfmt == '':
lfmt = '<tr><td align="right">%s</td>'
o = lfmt % (label)
# label
# preselect
# last selectable year (this year if unset)
# start year (1900 if unset)
s = ''
s += buildmondropdown(ml,mv)
s += builddaydropdown(dl,dv)
s += builddropdown(yl,yv,ad)
if efmt == '':
efmt = '<td>%s</td></tr>'
o += efmt % (s)
return o
# year, month selector (good for credit card expiry)
#
# retrieve with getadate6field()
# --------------------------------------------------
def make6drow(label,yl,ml,yv,mv,ad,lfmt='',efmt=''):
ad = ad[0:4]
if lfmt == '':
lfmt = '<tr><td align="right">%s</td>'
o = lfmt % (label)
s = builddropdown(yl,yv,ad)
s += buildmondropdown(ml,mv)
if efmt == '':
efmt = '<td>%s</td></tr>'
o += efmt % (s)
return o
# Bulleted selector:
# ------------------
# makeselector(label,list-of-2-tuples,cgi-name,default-selected,left-format,right-format)
def makeselector(label,ll,cginame,defs=None,lfmt=None,rfmt=None):
if lfmt == None: lfmt = '<tr><td align="right">%s</td>'
if rfmt == None: rfmt = '<td>%s</td></tr>'
boil = '<INPUT TYPE="radio" NAME="[CGINAME]" VALUE="[DATA]"[SELECTOR]>[LABEL]<br>'
thing = ''
for el in ll:
item = boil
item = item.replace('[CGINAME]',cginame)
item = item.replace('[DATA]', el[0])
item = item.replace('[LABEL]', el[1])
selector = ''
if defs != None:
if el[0] == defs:
selector = ' CHECKED'
item = item.replace('[SELECTOR]',selector)
thing += item
line = lfmt % (label,)
line += rfmt % (thing,)
return line
# value selector as row
#
# retrieve with any of
# getannfield(),getnfield(),getsafefield(),getfield()
# ---------------------------------------------------
def makevrow(label,tag,variable,length,lfmt='',efmt='',olimit=64,tt=1):
l = str(length)
tts = ''
tte = ''
if tt == 1:
tts = '<font face="courier">'
tte = '</font>'
fl = int(l)
if fl > olimit:
fl = olimit
l = str(olimit)
fl = str(fl)
key = '['+tag.upper()+']'
if lfmt == '':
lfmt = '<tr><td align="right">'+tts+'%s'+tte+'</td>'
o = lfmt % (label)
if 0:
sty = 'style="font-size: 16px; font-family:Courier;" '
else:
sty = ''
s = '<INPUT '+sty+'TYPE="TEXT" SIZE='+fl+' MAXLENGTH='+l+' NAME="'+tag+'" VALUE="'+key+'">'
s = s.replace(key,str(variable))
if efmt == '':
efmt = '<td>'+tts+'%s'+tte+'</td></tr>'
o += efmt % (s)
return o
# value selector as cell
#
# retrieve with any of
# getannfield(),getnfield(),getsafefield(),getfield()
# ---------------------------------------------------
def makevcell(label,tag,variable,length,lfmt='',efmt='',olimit=64,tt=1):
l = str(length)
tts = ''
tte = ''
if tt == 1:
tts = '<font face="courier">'
tte = '</font>'
fl = int(l)
if fl > olimit:
fl = olimit
l = str(olimit)
fl = str(fl)
key = '['+tag.upper()+']'
if lfmt == '':
lfmt = '<td align="right">'+tts+'%s'+tte+'</td>'
o = lfmt % (label)
if 0:
sty = 'style="font-size: 16px; font-family:Courier;" '
else:
sty = ''
s = '<INPUT '+sty+'TYPE="TEXT" SIZE='+fl+' MAXLENGTH='+l+' NAME="'+tag+'" VALUE="'+key+'">'
s = s.replace(key,str(variable))
if efmt == '':
efmt = '<td>'+tts+'%s'+tte+'</td>'
o += efmt % (s)
return o
def maketextarea(label,tag,variable,lfmt='',efmt='',rows=8,cols=40,tt=1,pid='',mno=0):
tts = ''
tte = ''
if tt == 1:
tts = '<font face="courier">'
tte = '</font>'
if mno != 0:
sty = 'style="font-size: 16px; font-family:Courier new,Monospace;" '
else:
sty = ''
key = '['+tag.upper()+']'
if lfmt == '':
lfmt = '<tr><td align="right">'+tts+'%s'+tte+'</td>'
o = lfmt % (label)
s = '<TEXTAREA '+pid+sty+'NAME="'+tag+'" ROWS='+str(rows)+' COLS='+str(cols)+'>'
s+= key
s+= '</TEXTAREA>'
s = s.replace(key,str(variable))
if efmt == '':
efmt = '<td>'+tts+'%s'+tte+'</td></tr>'
o += efmt % (s)
return o
# Checked option selector
#
# retrieve with getacheckfield()
# ------------------------------
def makecheckrow(label,tag,variable,lfmt='',efmt=''):
key = '['+tag.upper()+']'
if lfmt == '':
lfmt = '<tr><td align="right">%s</td>'
o = lfmt % (label)
s = '<input type="checkbox" name="'+tag+'" value="ON"'+key+'>'
if variable == 'ON':
s = s.replace(key,' CHECKED')
else:
s = s.replace(key,'')
if efmt == '':
efmt = '<td>%s</td></tr>'
o += efmt % (s)
return o
# Checked option selector in cell
#
# retrieve with getacheckfield()
# ------------------------------
def makecheckcells(label,tag,variable,lfmt='',efmt=''):
key = '['+tag.upper()+']'
if lfmt == '':
lfmt = '<td align="right">%s</td>'
o = lfmt % (label)
s = '<input type="checkbox" name="'+tag+'" value="ON"'+key+'>'
if variable == 'ON':
s = s.replace(key,' CHECKED')
else:
s = s.replace(key,'')
if efmt == '':
efmt = '<td>%s</td>'
o += efmt % (s)
return o
def makecrow(label,tag,variable,lfmt='',efmt=''):
return makecheckrow(label,tag,variable,lfmt,efmt)
# These are retrieval functions from the above type input widgets
# ---------------------------------------------------------------
def getfield(form,fieldname,default):
try:
result = str(form[fieldname].value)
except:
result = default
return result
def safer(result):
if type(result) == str:
result = result.replace("'","'")
result = result.replace("\\","\")
result = result.replace('"',""")
if result.lower().find('<script') != -1:
p = re.compile(r'<script.*?>') # kill <script> tags outright
result = p.sub('', result)
p = re.compile(r'</script.*?>') # kill </script> tags outright
result = p.sub('', result)
return result
def getsafefield(form,fieldname,default):
result = safer(getfield(form,fieldname,default))
if type(result) == None:
result = ''
return result
def getnfield(form,fieldname,default):
x = getsafefield(form,fieldname,default)
if x == '': return default
try:
x = int(x)
except:
return default
return x
def getannfield(form,label,default,minimum,maximum):
v = getnfield(form,label,default)
if minimum != None:
if v < minimum: v = minimum
if maximum != None:
if v > maximum: v = maximum
return v
def getacheckfield(form,label,default):
v = getsafefield(form,label,default)
if v != 'ON':
v = default
return v
def getachecknfield(form,label,default): # default is 0 or 1
default = str(default)
if default == '0': default = ''
else: default = 'ON'
v = getsafefield(form,label,default)
if v == 'ON':
v = '1'
else:
v = '0'
return v
def getadatefield(form,xly,xlm,xld,dy,dm,dd):
try:
xsy = str(getsafefield(form,xly,'')).strip()
xsm = str(getsafefield(form,xlm,'')).strip()
xsd = str(getsafefield(form,xld,'')).strip()
except:
xsy = dy
xsm = dm
xsd = dd
if len(xsy) == 0: xsy = dy
if len(xsm) == 0: xsm = dm
if len(xsd) == 0: xsd = dd
return xsy,xsm,xsd
def getnormdate(form,xly,xlm,xld):
dy = str(time.localtime()[0])
dm = str(time.localtime()[1])
dd = str(time.localtime()[2])
ray = getadatefield(form,xly,xlm,xld,dy,dm,dd)
return ray[0]+ray[1]+ray[2]
def getadate6field(form,xly,xlm,dy,dm):
try:
xsy = str(getsafefield(form,xly,'')).strip()
xsm = str(getsafefield(form,xlm,'')).strip()
except:
xsy = dy
xsm = dm
if len(xsy) == 0: xsy = dy
if len(xsm) == 0: xsm = dm
return xsy,xsm
|
3788f9f7ebbc70b497996b8c77512844a3181bb2 | allanfarrell/deakin | /SIT210-Task5.3D-Morse_GUI/morse_gui.py | 1,118 | 3.828125 | 4 | from tkinter import *
import tkinter.font
import RPi.GPIO as GPIO
import morse_code as MC
## Configure pins
redPin = 11
# Set configuration to use board pin numbers
GPIO.setmode(GPIO.BOARD)
GPIO.setup(redPin, GPIO.OUT)
# Turn off all lights to start - Not sure why light turns on at start up
GPIO.output(redPin, GPIO.LOW)
## Base GUI window
win = Tk()
win.title("Morse code implementation")
win.geometry("275x175")
## Events
def redOn():
GPIO.output(redPin, GPIO.HIGH)
def redOff():
GPIO.output(redPin, GPIO.LOW)
def close():
GPIO.cleanup()
win.destroy()
def morseCodeiffy():
morse_str2 = morse_str.get()
MC.reader(morse_str2, redOn, redOff)
## Widgets
# Textbox
morse_str = StringVar()
textBox = Entry(win, width=30, textvariable=morse_str)
textBox.grid(row=0, column=1)
# Buttons
submitbutton = Button(win, text="Submit", command=morseCodeiffy, height = 1, width = 30)
submitbutton.grid(row=1, column=1)
exitbutton = Button(win, text="Close", command=close, height = 1, width = 30)
exitbutton.grid(row=2, column=1)
# Close application
win.protocol("WM_DELETE_WINDOW", close) |
46b72c59b9ac526ec066b5be7527d51a212a7647 | graemediack/uni-project-networks | /PlotDegreeDist.py | 3,955 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 22:39:26 2018
@author: graeme
"""
#function to create some informative plots
def plot_graph(G):
degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*sorted(degreeCount.items()))
sumcnt = sum(cnt)
cnt = list(cnt)
for x in range(len(cnt)):
cnt[x] = float(cnt[x])/sumcnt
cnt = tuple(cnt)
fig, ax = plt.subplots()
plt.loglog(deg, cnt)
plt.ylabel("P(k)")
plt.xlabel("degree k")
# draw graph in inset
plt.axes([0.4, 0.4, 0.5, 0.5])
Gcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0]
pos = nx.spring_layout(G)
plt.axis('off')
nx.draw_networkx_nodes(G, pos, node_size=20)
nx.draw_networkx_edges(G, pos, alpha=0.4)
plt.show()
fig, ax = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='b')
#plt.title("Degree Histogram")
plt.ylabel("P(k)")
plt.xlabel("degree k")
#ax.set_xticks([d + 0.4 for d in deg])
#ax.set_xticklabels(deg)
# draw graph in inset
plt.axes([0.4, 0.4, 0.5, 0.5])
Gcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0]
pos = nx.spring_layout(G)
plt.axis('off')
nx.draw_networkx_nodes(G, pos, node_size=20)
nx.draw_networkx_edges(G, pos, alpha=0.4)
plt.show()
#Identify largest k-core with nodes
#x = 1
#k = 0
#while x != 0:
# k += 1
# x = len(nx.k_core(G,k))
k = max(nx.core_number(G).values())
print('Largest k is',k)
#Plotting k-cores
options = {
'node_color': 'red',
'node_size': 20,
'edge_color': 'grey',
'width': 1,
}
if k == 6:
plt.subplot(321,title='1-core')
nx.draw(nx.k_core(G,1),**options)
plt.subplot(322,title='2-core')
nx.draw(nx.k_core(G,2),**options)
plt.subplot(323,title='3-core')
nx.draw(nx.k_core(G,3),**options)
plt.subplot(324,title='4-core')
nx.draw(nx.k_core(G,4),**options)
plt.subplot(325,title='5-core')
nx.draw(nx.k_core(G,5),**options)
plt.subplot(326,title='6-core')
nx.draw(nx.k_core(G,6),**options)
plt.show()
elif k == 5:
plt.subplot(321,title='1-core')
nx.draw(nx.k_core(G,1),**options)
plt.subplot(322,title='2-core')
nx.draw(nx.k_core(G,2),**options)
plt.subplot(323,title='3-core')
nx.draw(nx.k_core(G,3),**options)
plt.subplot(324,title='4-core')
nx.draw(nx.k_core(G,4),**options)
plt.subplot(325,title='5-core')
nx.draw(nx.k_core(G,5),**options)
plt.show()
elif k == 4:
plt.subplot(221,title='1-core')
nx.draw(nx.k_core(G,1),**options)
plt.subplot(222,title='2-core')
nx.draw(nx.k_core(G,2),**options)
plt.subplot(223,title='3-core')
nx.draw(nx.k_core(G,3),**options)
plt.subplot(224,title='4-core')
nx.draw(nx.k_core(G,4),**options)
plt.show()
elif k == 3:
plt.subplot(221,title='1-core')
nx.draw(nx.k_core(G,1),**options)
plt.subplot(222,title='2-core')
nx.draw(nx.k_core(G,2),**options)
plt.subplot(223,title='3-core')
nx.draw(nx.k_core(G,3),**options)
plt.show()
elif k == 2:
plt.subplot(121,title='1-core')
nx.draw(nx.k_core(G,1),**options)
plt.subplot(122,title='2-core')
nx.draw(nx.k_core(G,2),**options)
plt.show()
pos=nx.spring_layout(nx.k_core(G,k))
nx.draw(nx.k_core(G,k),pos,**options)
nx.draw_networkx_labels(nx.k_core(G,k),pos,font_color='k')
plt.show() |
53f32a2d944edc230c91dcee9f2fa3f7f7a195e8 | denis-nuzhdin/dntest3 | /test/lesson7.2.py | 2,369 | 3.796875 | 4 | import sys
def open_file(file_name,mode):
"""открываем файл"""
try:
the_file = open(file_name,mode,encoding='utf-8')
except IOError as e:
print("Не возможно открыть файл: ", file_name)
sys.exit()
else:
return the_file
def next_line(the_file):
"""возвращает в форматироанном виде строку"""
line = the_file.readline()
line.replace("/","\n")
return line
def next_block(the_file):
"""возвращает блок данных"""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
weight = next_line(the_file)
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
return category, question, answers, weight, correct, explanation
def welcome(title):
print("Добро пожаловать")
print("\t\t", title, "\n")
def player_name():
name_player = input("введите имя: ")
return name_player
def main():
record = []
name = player_name()
trivia_file = open("trivia.txt","r")
title = next_line(trivia_file)
welcome(title)
score = 0
category, question, answers,weight, correct, explanation = next_block(trivia_file)
while category:
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
answer = input("ваш ответ:")
if answer == correct:
print("\n Да", end=" ")
score += int(weight)
else:
print("\n Нет", end=" ")
print(explanation)
print("Счет: ", score, "\n")
#переход к следующему вопросу
category, question, answers, weight, correct, explanation = next_block(trivia_file)
trivia_file.close()
print("конец")
print(name, "ваш счет: ", score)
record.append(name,)
record.append(str(score))
print(record)
save_record = open("record.txt", "a", encoding="utf-8")
#save_record.writelines(record)
save_record.write(name)
save_record.write("\t")
save_record.write(str(score))
save_record.writelines("\n")
save_record.close()
main() |
ead524f4ffa1480cbc084a49a8541ece1aab8221 | denis-nuzhdin/dntest3 | /test/lesson3.1.py | 1,100 | 3.8125 | 4 | #глава №3, страница 103, игра Отгадай число, задание номер 4
import random
NUMBER_MIN = 1
NUMBER_MAX = 100
NUMBER = 1
#guess = int(input("num: "))
def ask_number(question):
"""просит ввести число из диапазона"""
responce = None
while responce not in range(NUMBER_MIN,NUMBER_MAX):
responce = int(input(question))
return responce
def main():
tires = 1
guess = ask_number("Выбери число: ")
NUMBER_MIN = 1
NUMBER_MAX = 100
NUMBER = 1
while NUMBER!= guess:
if NUMBER > guess:
print("less")
NUMBER_MAX=NUMBER
else:
print("more")
NUMBER_MIN=NUMBER
NUMBER = int(random.randint(NUMBER_MIN, NUMBER_MAX))
#guess = int(input("try again: "))
tires += 1
print(NUMBER)
if NUMBER!=guess and tires >=5:
print("looser")
break
elif NUMBER!=guess and tires<5:
print("next numb")
else:
print("winner")
main() |
a6cb989bcfb96258bbd2e6213971b1336118e89a | denis-nuzhdin/dntest3 | /test/lesson5.6.py | 1,711 | 4.0625 | 4 | #Задание из главы №5 "Кто твой папа"
family = {"Олег": {"отец":"Александр", "дед":"Петр"},
"Дмитрий":{"отец": "Михаил", "дед":"Степан"}
}
choice=None
sun=""
father=""
grandfather=""
#sun = input("Имя: ")
#print(sun)
#print("Дед: ",family[sun]["дед"])
#print("Отец: ",family[sun]["отец"])
while choice !=0:
print("""
Меню:
0 - Выйти
1 - Найти отца и деда
2 - Добавить новое поколение
3 - Удалить поколение
""")
choice = input("выбор № в меню: ")
if choice == "0":
print("goodbay")
elif choice == "1":
sun = input("Введите имя сына для добавления: ")
if sun in family:
print("Имя отца:", family[sun]["отец"])
print("Имя деда:", family[sun]["дед"])
else:
print("Нет такого имени")
elif choice=="2":
sun = input("Введите имя сына для удаления покаления: ")
if sun not in family:
father = input("Введите имя отца: ")
grandfather = input("Введите имя деда: ")
family[sun] = dict(отец=father, дед=grandfather )
print(family)
else:
print("уже есть")
elif choice=="3":
sun = input("Введите имя сына: ")
if sun in family:
del family[sun]
print(family)
else:
print("такого имени нет в списке") |
cd0ebfb58d975a582aca3a4eb620eb3b84933e93 | roostercrab/CIT104-Python-Answers | /H1P2.py | 99 | 4 | 4 | miles = int(input("Miles? "))
kilometers = miles * 1.609
print(str(kilometers) + " kilometers")
|
bcd734f683d2951423faf6b1e4324560588dcf30 | randomInteger/pytail | /pytail.py | 1,566 | 3.671875 | 4 | #!/usr/bin/env python3
#pytail.py
#Very simple tail implementation in python3
#Author: Christopher Gleeson, April 2018
#Note: Need a big enough test file? try: seq 1 100000 > ./file.txt
import os
import sys
#buffer as much as two blocks
block_size = 4096
buffer_size = 2 * block_size
#This is not great input argument handling and we should use a nice package like
#getopt
if len(sys.argv) < 3:
print("Please call this tool with <filename> <numlines> as arguments")
print("Exiting")
sys.exit(1)
file_name = sys.argv[1] # file path, absolute
num_lines = int(sys.argv[2]) # num_lines requested
file_size = os.stat(file_name).st_size # size of file in bytes, no more seek relative to end :-(
lines = []
#special case if the file is super small, do it the easy way
if file_size < buffer_size:
with open(file_name) as f:
lines = f.readlines()
for line in lines[-num_lines:]:
print(line, end='') #Else you get double newlines...
sys.exit(0)
#Continuing means we can seek to buffer_size...
i = 0 #counter variable, we may have to go back a few times to get enough lines
with open(file_name) as f:
while True:
i += 1
f.seek(file_size - buffer_size*i) #Seek to the end of the file - the buffer * count
lines.extend(f.readlines()) #We don't want a list of lists, just extend the list
if len(lines) >= num_lines or f.tell() == 0: #stop when we have enough lines or we are at the last line
for line in lines[-num_lines:]:
print(line, end='')
break
|
82d9c3e50df8a8d0c41a666a0d49ec3e8d025caa | HasibulKabir/MindBot | /mindbot/command/nasa/asteroid.py | 2,119 | 3.609375 | 4 | """
This module provides methods to send user information about closest o Earth asteroids.
Powered by https://api.nasa.gov/
User will receive information about 5 closest to Earth asteroids for the current day
as well as links for this objects for further reading.
API KEY is required. It is free after registration.
"""
from requests import get, status_codes, RequestException
from time import gmtime, strftime
from urllib.parse import urlencode
from mindbot.config import NASA_API_KEY
from ..commandbase import CommandBase
class AsteroidCommand(CommandBase):
name = '/asteroids'
help_text = " - Retrieve a list of 5 Asteroids based on today closest approach to Earth."
today = strftime("%Y-%m-%d", gmtime())
ASTEROID_TEXT = (
'Name: [{object[name]}]({object[nasa_jpl_url]})\n'
'Absolute Magnitude: {object[absolute_magnitude_h]}\n'
'Minimum Diameter: {object[estimated_diameter][kilometers][estimated_diameter_min]}\n'
'Maximum Diameter: {object[estimated_diameter][kilometers][estimated_diameter_max]}\n'
'Hazardous? {object[is_potentially_hazardous_asteroid]}\n'
)
def __call__(self, *args, **kwargs):
super().__call__(*args, **kwargs)
json = self.get_json()
if json:
objects = json['near_earth_objects'][self.today][:5]
[self.send_telegram_message(self.ASTEROID_TEXT.format(object=o)) for o in objects]
else:
self.send_telegram_message('Error while processing the request.')
def get_json(self):
try:
response = get(self.form_url)
except RequestException as e:
self._logger.debug('RequestException {}'.format(e))
return
if response.status_code == status_codes.codes.ok:
return response.json()
@property
def form_url(self):
return 'https://api.nasa.gov/neo/rest/v1/feed?{query}'.format(
query=urlencode({'api_key': NASA_API_KEY,
'start_date': self.today,
'end_date': self.today})
)
|
7c96e216dfa09a1efc87ceb204f183e6fb26ac5f | yh97yhyh/ProblemSolving | /backjoon/string/5622.py | 296 | 3.515625 | 4 | '''
다이얼
'''
import sys
dials = ['', '', '', 'ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']
string = list(sys.stdin.readline())
sum = 0
for s in string:
for d in dials[3:]:
if d.find(s) != -1:
# print(d, s)
sum += dials.index(d)
print(sum) |
723ea14adc540758ec56aa7432fb55f78f475c96 | yh97yhyh/ProblemSolving | /programmers/concept/topology_sort.py | 681 | 3.875 | 4 |
from collections import defaultdict
adjacency_list = defaultdict()
adjacency_list['a'] = ['d']
adjacency_list['b'] = ['d']
adjacency_list['c'] = ['e']
adjacency_list['d'] = ['e']
adjacency_list['e'] = []
visited_list = defaultdict()
visited_list['a'] = False
visited_list['b'] = False
visited_list['c'] = False
visited_list['d'] = False
visited_list['e'] = False
output_stack = []
def topology_sort(vertex):
if not visited_list[vertex]:
visited_list[vertex] = True
for neighbor in adjacency_list[vertex]:
topology_sort(neighbor)
output_stack.insert(0, vertex)
for vertex in visited_list:
topology_sort(vertex)
print(output_stack) |
4b54aab527e56e694b57aadedfe4211a15a2522e | yh97yhyh/ProblemSolving | /backjoon/brute-force/1436.py | 375 | 3.53125 | 4 | '''
영화감독 숌
'''
import sys
n = int(sys.stdin.readline())
number = 666
while(n):
if '666' in str(number):
n -= 1
number += 1
print(number-1)
'''
n = 2일 때, number의 값은 while문에서 666부터 증가
number = 666이니 n은 -1로 인해 1이 됨.
number은 667부터 1씩 증가하고 1666일 때, n은 0이 되어 while문이 종료.
''' |
951fb7af4c39b6698773d327937459e996c8c060 | yh97yhyh/ProblemSolving | /backjoon/sort/2750.py | 177 | 3.5625 | 4 | '''
수 정렬하기
'''
import sys
n = int(sys.stdin.readline())
arr = []
for i in range(n):
arr.append(int(sys.stdin.readline()))
arr.sort()
for a in arr:
print(a) |
26b3afe644c821827a9a9e43e651f54a397d4e4a | yh97yhyh/ProblemSolving | /programmers/kit/stack_queue01.py | 1,088 | 3.53125 | 4 | '''
< 주식가격 >
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때,
가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
'''
p1 = [1, 2, 3, 2, 3]
p2 = [1, 2, 3, 2, 3, 1]
p3 = [3, 1]
# 효율성 테스트 실패
def solution(prices):
answer = []
for i in range(len(prices)):
time = prices[i:len(prices)-1]
for j in range(i+1, len(prices)):
if prices[i] > prices[j]:
time = prices[i:j]
break
answer.append(len(time))
return answer
# 정답
def solution2(prices):
answer = []
for i in range(len(prices)):
count = 0
for j in range(i+1, len(prices)):
count = count + 1
if prices[i] > prices[j]:
break
answer.append(count)
return answer
print(solution2(p1))
print(solution2(p2))
print(solution2(p3))
|
8568ecd1d95b32939869851a50f6bc0b4423f9cf | yh97yhyh/ProblemSolving | /programmers/level1/level1_01.py | 934 | 3.5 | 4 | '''
< 체육복 >
'''
n1, n2, n3 = 5, 5, 3
lost1, lost2, lost3 = [2, 4], [2, 4], [3]
reserve1, reserve2, reserve3 = [1, 3, 5], [3], [1]
# 오답
# def solution2(n, lost, reserve):
# lend = []
# reserve = list(set(reserve) - set(lost))
# lost = list(set(lost) - set(reserve))
# for i in range(len(reserve)):
# for j in range(len(lost)):
# if abs(reserve[i] - lost[j]) == 1:
# lend.append(lost[j])
# break
#
# return n - len(list(set(lost) - set(lend)))
def solution(n, lost, reserve):
set_reserve = set(reserve) - set(lost)
set_lost = set(lost) - set(reserve)
for i in set_reserve:
if i-1 in set_lost:
set_lost.remove(i-1)
elif i+1 in set_lost:
set_lost.remove(i+1)
return n - len(set_lost)
print(solution(n1, lost1, reserve1))
print(solution(n2, lost2, reserve2))
print(solution(n3, lost3, reserve3)) |
a074ed0760295869373910a70a65e12876b9af6b | qq20004604/publish-article-with-tags | /server_python/libs/printcolor_lingling/__init__.py | 1,321 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 红色背景
def print_red(str):
print("\033[0;37;41m" + str + "\033[0m")
# 绿色背景
def print_green(str):
print("\033[0;37;42m" + str + "\033[0m")
# 白色背景
def print_normal(str):
print(str)
# 根据测试结果输出
# list形式是可变参数,至少2个参数,否则为错误
# 最后一个参数是一个字符串
# 之前的参数应当都是 True。如果至少有一个False,则为错误,其他情况为正确。
# 显示结果有两种:【1】正确,显示(字符串 + ok)【2】错误(红色背景,字符串 + Error)
def print_testresult(*list):
length = len(list)
if length <= 1:
print_red(str + " ERROR !")
return;
str = list[length - 1]
isCorrect = True
# 遍历拿到索引
for i in range(length):
# 如果不是最后一个
if i != length - 1:
# 则判断他的返回值是不是 False。理论上应该都是True,如果是False则说明不符(出错了)
if list[i] == False:
isCorrect = False
# 根据结果显示最后是正确还是错误,如果是错误,会有红底 和 Error 提示
if isCorrect == True:
print_normal(str + " OK !")
else:
print_red(str + " ERROR !")
|
6cd5e54c3fd9774d1cc2c7c3661c4c4b891c4e2a | uditiarora/CG-Lab | /lab1/line.py | 545 | 3.5 | 4 | import transform
from graphics import *
import time
def putPixle(win, x, y):
pt = Point(x,y)
pt.draw(win)
def drawLine(coords,x1,y1,x2,y2):
x3,y3 = transform.transformPoint(coords,x1,y1)
x4,y4 = transform.transformPoint(coords,x2,y2)
win = GraphWin("Line")
dx = x4-x3
dy = y4-y3
m = 2*dy
err = m - dx
y = y1
for x in range(int(x3),int(x4+1)):
time.sleep(0.01)
putPixle(win,x,y)
err = err + m
if(err>=0):
y = y + 1
err = err - 2 * dx
coords = [0,0,500,600,0,0,700,900]
drawLine(coords,90,90,100,100)
|
36e5c1c8fe5533f16dccd4b3600b871264aa72f8 | keniel123/netcentric | /server3 real.py | 7,452 | 4.125 | 4 | # Server to implement simplified RSA algorithm.
# The server waits for the client to say Hello. Once the client says hello,
# the server sends the client a public key. The client uses the public key to
# send a session key with confidentiality to the server. The server then sends
# a nonce (number used once) to the client, encrypted with the server's private
# key. The client decrypts that nonce and sends it back to server encrypted
# with the session key.
# Author: fokumdt 2015-11-02
#!/usr/bin/python3
import socket
import random
import math
import hashlib
import time
import sys
import simplified_AES
def expMod(b,n,m):
"""Computes the modular exponent of a number"""
"""returns (b^n mod m)"""
if n==0:
return 1
elif n%2==0:
return expMod((b*b)%m, n/2, m)
else:
return(b*expMod(b,n-1,m))%m
def RSAencrypt(m, e, n):
"""Encryption side of RSA"""
# Fill in the code to do RSA encryption
c=modular_Exponentiation(m,e,n)
return c
def RSAdecrypt(c, d, n):
"""Decryption side of RSA"""
# Fill in the code to do RSA decryption
m=modular_Exponentiation(c,d,n)
return m
def gcd_iter(u, v):
"""Iterative Euclidean algorithm"""
while v != 0:
u, v = v, u % v
return u
def prime(n):
for i in range(2,n):
if n%i==0:
return False
return True
def isprime(n):
"""
return true if n is a prime number and false otherwise"""
if prime(n):
return True
else:
return False
def modular_Exponentiation(a,b,n):
x=1
while(b>0):
if (b&1==1):x=(x*a)%n
a=(a*a)%n
b >>= 1# represents binary conversion for example a >> = 15 (means 0000 1111)
return x%n
def ext_Euclid(m,n):
"""Extended Euclidean algorithm"""
# Provide the rest of the code to use the extended Euclidean algorithm
# Refer to the project specification.
A1,A2,A3=1,0,m
B1,B2,B3=0,1,n
while True:
if B3==0:
return A3
if B3==1:
return B2
Q=math.floor(A3/B3)
T1,T2,T3=A1-Q*B1,A2-Q*B2,A3-Q*B3
A1,A2,A3=B1,B2,B3
B1,B2,B3=T1,T2,T3
def generateNonce():
"""This method returns a 16-bit random integer derived from hashing the
current time. This is used to test for liveness"""
hash = hashlib.sha1()
hash.update(str(time.time()).encode('utf-8'))
return int.from_bytes(hash.digest()[:2], byteorder=sys.byteorder)
def genKeys(p, q):
"""Generate n, phi(n), e, and d."""
# Fill in code to generate the server's public and private keys.
# Make sure to use the Extended Euclidean algorithm.
n=p*q#generates n by using the formula n=p*q
phi=(p-1)*(q-1)#generates phi by using the formula phi=(p-1)*(q-1)
e= random.randrange(1,phi)
t=gcd_iter(e,phi)
while t!=1:
e=random.randrange(1,phi)#generates e such that the greatest common divisor of that number and phi is 1
t=gcd_iter(e,phi)
d=ext_Euclid(phi,e)#generates d by making the formula that d*e Mod phi =1
while d<0:
d+=phi
return n,e,d,phi
def clientHelloResp(n, e):
"""Responds to client's hello message with modulus and exponent"""
status = "105 Hello "+ str(n) + " " + str(e)
return status
def SessionKeyResp(nonce):
"""Responds to session key with nonce"""
status = "113 Nonce "+ str(nonce)
return status
def nonceVerification(nonce, decryptedNonce):
"""Verifies that the transmitted nonce matches that received
from the client."""
if nonce==decryptedNonce:
return "200 OK"
else:
return "400 Error Detected"
#Enter code to compare the nonce and the decryptedNonce. This method
# should return a string of "200 OK" if the parameters match otherwise
# it should return "400 Error Detected"
HOST = '' # Symbolic name meaning all available interfaces
PORT = 9000 # Arbitrary non-privileged port
strHello = "100 Hello"
strHelloResp = "105 Hello"
strSessionKey = "112 SessionKey"
strSessionKeyResp = "113 Nonce"
strNonceResp = "130"
strServerStatus = ""
print("###############################Welcome To My Server######################################")
print ("Enter prime numbers. One should be between 907 and 1013, and the other\
between 53 and 67")
p = int(input('Enter P : '))
q = int(input('Enter Q: '))
while (not isprime(p) or not isprime(q)):#prompt user if value not prime
if not isprime(p):print ("first number was not prime!!!")
if not isprime(q):print ("Second number was not prime!!!")
print("")
p = int(input("Please enter a prime number between 907 and 1013: "))
q = int(input("Please enter a prime number between 53 and 67: "))
while (p<907 or p>1013) or (q<53 or q>67): # prompt user to re-enter prime
if p<907 or p>1013:print ("first number Must Be greater Than 907 and less than 1013!!!")
if q<53 or q>67:print ("Second number Must Be greater Than 53 and less than 67!!!")
print("")
p = int(input("Please enter a prime number between 907 and 1013: "))
q = int(input("Please enter a prime number between 53 and 67: "))
# You should delete the next three lines. They are included so your program can
# run to completion
n,e,d,phi= genKeys(p, q)#function call to generate keys and assign values to n,e,d,phi
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# The next line is included to allow for quicker reuse of a socket.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024).decode('utf-8')
print (data)
if data and data.find(strHello) >= 0:
msg = clientHelloResp(n, e)
conn.sendall(bytes(msg,'utf-8'))
data = conn.recv(1024).decode('utf-8')
print (data)
if data and data.find(strSessionKey) >= 0:
# Add code to parse the received string and extract the symmetric key
a=data[15:]
symmkey=int(a)#converts the parsed symmetric key to a integer
print ("D:" + str(d))#print the value for d
print ("N:" + str(n))#print the value for n
print ("E:"+ str(e))#print the value for e
print ("PhiN:"+ str(phi))#print the value for phi(N)
SymmKey = RSAdecrypt(symmkey,d,n)# Make appropriate function call to decrypt the symmetric key
print ("Decrypted Symmetric Key:" +str(SymmKey))
# The next line generates the round keys for simplified AES
simplified_AES.keyExp(int(SymmKey))
challenge = generateNonce()#the value returned from calling generateNonce() is assigned to the challenge variable
print ("Challenge:" + str(challenge))#print generated nonce
msg = SessionKeyResp(RSAdecrypt(challenge,d, n))
print ("Encrypted Nonce:"+str(msg))#printing of encrypted nonce
conn.sendall(bytes(msg,'utf-8'))
data = conn.recv(1024).decode('utf-8')
if data and data.find(strNonceResp) >= 0:
# Add code to parse the received string and extract the nonce
encryptedChallenge=int(data[4:])
# The next line runs AES decryption to retrieve the key.
decryptedNonce = simplified_AES.decrypt(encryptedChallenge)
msg = nonceVerification(challenge, decryptedNonce)# Make function call to compare the nonce sent with that received
conn.sendall(bytes(msg,'utf-8'))
data = conn.recv(1024).decode('utf-8')#the server recieves the client's public key
print (data)#the server prints the client's public key
conn.close()
|
3dde83c6e5f6a9f36dfe90f34f39f654304a45b9 | jstockbot/jstock | /com/javamix/samples/fibonacci2.py | 261 | 4.09375 | 4 | dictionary = {
1:1,
2:1
}
def fibonacci(n):
if n in dictionary:
return dictionary[n]
else:
output = fibonacci(n-1) + fibonacci(n-2)
dictionary[n] = output
return output
print("value = {}".format(fibonacci(100))) |
1ed2bf08a8167cb744fe9e298e0c130f515ee7d7 | jstockbot/jstock | /com/javamix/samples/fibonacci.py | 332 | 3.890625 | 4 | counter = 0
def fibonacci(n) :
print("fibonacci({})를 구합니다.".format(n))
global counter
counter += 1
if n == 1 :
return 1
if n == 2 :
return 1
else :
return fibonacci(n-1) + fibonacci(n-2)
print("value = {}".format(fibonacci(10)))
print("덧셈 횟수는 {}".format(counter)) |
575bb55c33213cb0a1f87ace4fc25753deacba1f | rajgaur98/facedetection | /Facedetect.py | 1,462 | 3.625 | 4 | import cv2
from tkinter import *
def fd():
face_cascade = cv2.CascadeClassifier(
"C:\\Users\\Gaur\\PycharmProjects\\miniproject\\venv\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml")
video = cv2.VideoCapture(0)
a = 1
while True:
check, frame = video.read()
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.05, minNeighbors=5)
for x,y,w,h in faces:
frame = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3)
if a is 1:
print('human face detected')
cv2.imwrite("f1.jpg", frame)
a = a+1
cv2.imshow("win", frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('m'):
cv2.imwrite("extra.jpg", frame)
video.release()
cv2.destroyAllWindows()
root = Tk()
root.geometry("600x300")
label_1 = Label(root, text="\n\nAutomatic Face Detection\n\n")
label_1.pack()
label_3 = Label(root, text="Click 'Start' to start automatic face detection\n\nNote: As soon as human face appears in front of camera image would be clicked and saved\n\nPress 'm' for saving extra image\n\nPress 'q' to end detection\n\n" )
label_3.pack()
button_1 = Button(root, text = "Start", command = fd)
button_1.pack()
root.mainloop() |
75d031db7791b051136953a715b4d01876541f4c | n00blet/Project_Euler | /6_SqarDiffernce.py | 559 | 3.859375 | 4 | """ The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """
def squares():
a=xrange(1,101)
b=sum(a)
return b*b-sum(i*i for i in a)
print squares()
|
9b8690aa821b1a1c78d519446248b7257acadec0 | pola5pola5/edu90_python | /atcoder002.py | 1,537 | 3.5 | 4 | """
長さ N の正しいカッコ列をすべて、辞書順に出力してください。
ただし、正しいカッコ列は次のように定義されています :
() は正しいカッコ列である
S が正しいカッコ列であるとき、文字列 ( +S+ ) は正しいカッコ列である
S,T が正しいカッコ列であるとき、文字列 S+Tは正しいカッコ列である
それ以外の文字列はすべて、正しいカッコ列でない
4
()()
(())
"""
# 小さい制約は全探索
# 二進数に置き換える(bit全探索)
# ・(と)の数が同じ
# ・全てのiについて左からi文字目までの時点で(の数が)の数以上
# 上記2点を満たすのが必要十分
def hantei(S: str) -> bool:
dep = 0
for i in range(len(S)):
# (と)の出現をプラマイで表現
if S[i] == "(":
dep += 1
if S[i] == ")":
dep -= 1
# )の方が先に多く出るのはおかしい
if dep < 0:
return False
if dep == 0:
return True
return False
if __name__ == '__main__':
N = int(input())
# 全通り試すための2^nループ
for i in range(2**N):
Candidate = ""
for j in range(N):
j = N - 1 - j
# &はビットAND
if (i & 1<<j) == 0:
Candidate += "("
else:
Candidate += ")"
# print(Candidate)
I = hantei(Candidate)
if I:
print(Candidate)
|
5782821de302c085dbfd6b3c50c3ec64e581d75f | danrongLi/Advent_of_Code_2020 | /Day1/code.py | 652 | 3.515625 | 4 | def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
# return f.readlines()
return [int(line[:-1]) for line in f.readlines()]
def part1(vals: list) -> int:
for val in vals:
if (2020 - val) in vals:
return (2020 - val) * val
def part2(vals: list) -> int:
for i in range(len(vals)):
for j in range(i, len(vals)):
if (2020 - vals[i] - vals[j]) in vals:
return vals[i] * vals[j] * (2020 - vals[i] - vals[j])
if __name__ == "__main__":
vals = readFile()
print(f"Part 1: {part1(vals)}")
print(f"Part 2: {part2(vals)}")
# jk |
b39ff4287ef2b0ea8b5ae0ef2a37de198c1a8c91 | neonua/Python-Is-Easy-Homeworks | /homework_4_lists.py | 1,096 | 4.0625 | 4 | """
This file describes work with lists
"""
# Defining lists
myUniqueList = []
myLeftovers = []
def append(item):
"""
Appends item to myUniqueList.
If can't - appends item to myLeftovers.
"""
print(f'Appending {item} ...')
# Check if item already in myUniqueList
if item in myUniqueList:
# If yes, append value to myLeftovers and return False
append_to_list(item, myLeftovers, 'Can\'t append to myUniqueList so appending to myLeftovers')
return False
# If no, append to myUniqueList and return True
append_to_list(item, myUniqueList, 'Append to myUniqueList')
return True
def append_to_list(item, list, text):
"""
Appends item to list and prints needed info
"""
print(text)
list.append(item)
print_lists()
def print_lists():
"""
Prints two lists in specific format
"""
print(f'myUniqueList = {myUniqueList}\nmyLeftovers = {myLeftovers}\n')
# Testing
append(1)
append(1)
append(1)
append('2')
append(2)
append('2')
append([])
append([])
append([1, 2])
append([1, 3])
append([1, 3])
|
3873bfded71a3f3ab53374deaab5e7c455d23b7e | CyanYoung/english_chinese_translate | /util.py | 356 | 3.5 | 4 | def load_word(path):
words = list()
with open(path, 'r') as f:
for line in f:
words.append(line.strip())
return words
def load_word_re(path):
words = load_word(path)
return '(' + ')|('.join(words) + ')'
def map_item(name, items):
if name in items:
return items[name]
else:
raise KeyError
|
a8da1d0e0461f15604e9f61b2d7e6b73455bca4e | tobias290/Converter | /helpers.py | 1,902 | 3.921875 | 4 | from typing import Union
def set_to_middle(screen_width: Union[int, float], widget_width: Union[int, float]) -> Union[int, float]:
"""
Gets the value for a widget to be centred
:param screen_width: Width of the screen currently
:param widget_width: Width of the widget
:return: Returns the X position that would put the widget in the middle of the screen
"""
return (screen_width / 2) - int(widget_width / 2)
class ListHelper:
"""
Take a list and records the current, previous and next element in the list
"""
def __init__(self, arr: list):
self.__arr: list = arr
self.__i: int = 0
@property
def previous(self):
"""
Returns the element before the current element.
If the current element is the first in the list then the previous element will be the last item in the list
"""
return self.__arr[-1] if self.__i == 0 else self.__arr[self.__i - 1]
@property
def current(self):
"""
Returns the current element
"""
return self.__arr[self.__i]
@property
def next(self):
"""
Returns the next element after the current.
If the current element is the last in the list then the next element will be the first item in the list
"""
return self.__arr[0] if self.__i == len(self.__arr) - 1 else self.__arr[self.__i + 1]
def change_previous_to_current(self):
"""
Changes the index/ current element to be the previous element in the list
"""
self.__i = len(self.__arr) - 1 if self.__i == 0 else self.__i - 1
def change_next_to_current(self):
"""
Changes the index/ current element to be the next element in the list
"""
self.__i = 0 if self.__i == len(self.__arr) - 1 else self.__i + 1
|
8f1286d5ffa06aa47f11df2902ccee51e55247f6 | 19doughertyjoseph/josephdougherty-python | /UnitLab321/Unit321Lab.py | 1,384 | 4.0625 | 4 | def main():
numlist1 = (93.4, 92.5, 93.5, 85.6, 98.9)
gradeIn = input('What grade are you in -?')
grade1 = getYearInSchool(gradeIn)
print('you are a ' + str(grade1))
percent = calcAverageGrade()
print('your average grade is ' + str(percent))
grade = getLetterGrade(int(percent))
print('Your letter grade is ' + str(grade))
if percent >= 65:
print('Yay you are passing!')
else:
print('You failed. Study more')
def getYearInSchool(grade1):
if grade1 == '9':
return 'Freshman'
elif grade1 == '10':
return 'Sophomore'
elif grade1 == '11':
return 'Junior'
elif grade1 == '12':
return 'Senior'
else:
return 'not in highschool'
def calcAverageGrade():
print('calcAverageGrade')
sum = 0.0
num = input('how many grades')
grades = []
print(num)
for x in range(0, int(num)):
grades.append(input('grade'))
for i in grades:
sum = (sum + float(i))
print(sum)
average = (sum/len(grades))
print(average)
return(average)
def getLetterGrade(avgLetterGrade):
print('getLetterGrade')
if avgLetterGrade >= 90:
return 'A'
elif avgLetterGrade >= 80:
return 'B'
elif avgLetterGrade >= 70:
return 'C'
elif avgLetterGrade >= 65:
return 'D'
else:
return 'F'
main()
|
884bed1132eb119bee2605c4c79982fbb4c38a93 | 19doughertyjoseph/josephdougherty-python | /UnitLab4B/Unit Lab 4B.py | 313 | 3.59375 | 4 | for i in range(0,5):
print(i)
answer=(i+10)
skrt= (i*10)
print("pause")
print( str(i) + "+ 10 =" + str(answer))
print( str(i) + "*10 =" + str(skrt))
print("pause")
myList= [10,20,30,40,50]
print(myList)
for a in range(0, len(myList)):
myList[a]=myList[a] *10
print(myList)
|
4a5ffb428059845f0761201c602942bb964f0e55 | 19doughertyjoseph/josephdougherty-python | /TurtleProject/Turtle Project.py | 939 | 4.125 | 4 | import turtle
turtle.setup(width=750, height=750)
pen = turtle.Pen()
pen.speed(200)
black_color = (0.0, 0.0, 0.0)
white_color = (1.0, 1.0, 1.0)
red_color = (1.0, 0.0, 0.0)
green_color = (0.0, 1.0, 0.0)
blue_color = (0.0, 0.0, 1.0)
def basicLine():
moveTo(-50, 0)
pen.forward(100)
#The origin on the screen is (0,0)
def basicSquare():
pen.pencolor(blue_color)
moveTo(-100, -100)
for x in range(4):
pen.forward(200)
pen.left(90)
def basicCircle():
pen.pencolor(red_color)
moveTo(0, -300)
pen.circle(300)
def basicTriangle():
pen.pencolor('#33cc8c')
moveTo(-200, -150)
for x in range(3):
pen.forward(400)
pen.left(120)
def moveTo(x, y):
pen.penup()
pen.setpos(x, y)
pen.pendown()
#Between drawings we have to pick up the pen and move it to the desired location
basicLine()
basicSquare()
basicCircle()
basicTriangle()
turtle.exitonclick()
|
0ed3044556e7faa1464a480dbe0550b2a22e20c5 | leobyeon/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 360 | 4.28125 | 4 | #!/usr/bin/python3
def append_write(filename="", text=""):
"""
appends a string at the end of a text file
and returns the number of chars added
"""
charCount = 0
with open(filename, "a+", encoding="utf-8") as myFile:
for i in text:
charCount += 1
myFile.write(i)
myFile.close()
return charCount
|
782aaed5b483e43ad662f142a885ea19158f2daa | leobyeon/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 563 | 4.0625 | 4 | #!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
"""reads n lines of a text file and prints"""
with open(filename, encoding="utf-8") as myFile:
linecount = 0
for line in myFile:
linecount += 1
myFile.close()
with open(filename, encoding="utf-8") as myFile:
if nb_lines <= 0 or nb_lines >= linecount:
print(myFile.read(), end="")
else:
while nb_lines != 0:
line = myFile.readline()
print(line, end="")
nb_lines -= 1
|
3350a3f4eb39496974b03fb5df9f49e9dcfbf3e2 | leobyeon/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 749 | 3.953125 | 4 | #!/usr/bin/python3
def matrix_divided(matrix, div):
"""function divides a matrix"""
if ((type(matrix) is not list) or
(not all(type(row) is list for row in matrix)) or
(not all(
type(i) in (float, int) for row in matrix for i in row))):
raise TypeError("matrix must be a matrix (list of lists) \
of integers/floats")
for i, ls in enumerate(matrix):
if len(ls) != len(matrix[i - 1]):
raise TypeError("Each row of the matrix must have the same size")
if type(div) not in (float, int):
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
return [[round(x / div, 2) for x in y] for y in matrix]
|
1eb07317c0bc8e108a32ab5feb0cdf2c47c33940 | leobyeon/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,575 | 3.6875 | 4 | #!/usr/bin/python3
"""rectangle module"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""define Square class"""
def __init__(self, size, x=0, y=0, id=None):
"""initialize"""
super().__init__(size, size, x, y, id)
def __str__(self):
"""override the default str"""
return "[Square] ({}) {}/{} - {}".format(
self.id, self.x, self.y, self.width)
@property
def size(self):
"""return the size"""
return self.width
@size.setter
def size(self, value):
"""set the size"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""assign an arg to each attribute"""
i = 0
if isinstance(args, tuple) and len(args) > 0:
for arg in args:
if i == 0:
self.id = arg
if i == 1:
self.size = arg
if i == 2:
self.x = arg
if i == 3:
self.y = arg
i += 1
for k, v in kwargs.items():
if k == "id":
self.id = v
if k == "size":
self.size = v
if k == "x":
self.x = v
if k == "y":
self.y = v
def to_dictionary(self):
"""return the dict representation of a square"""
sq = {}
sq["id"] = self.id
sq["size"] = self.size
sq["x"] = self.x
sq["y"] = self.y
return sq
|
67c976bd994bb5772e1bbdf3b525c39e9834fefe | OliverSieweke/titanic | /notebooks/model_simon/feature_engineering.py | 2,389 | 3.5625 | 4 | import pandas as pd
import numpy as np
def name_titles(df, title_list):
'''
input: df, cutoff=12
Creates a binary column indicating whether passenger's name contains
a certain string (one column per string provided).
Based on Name column, removes said column.
output: df
'''
for title in title_list:
df[title]=(df['Name'].str.contains(title)).astype('int')
del df['Name']
return df
def children(df, cutoff=12):
'''
input: df, cutoff=12
Creates a binary column indicating whether the passenger was a child.
Based on the age column, removes said column.
output: df
'''
df['child'] = (df['Age'] <= cutoff).astype('int')
del df['Age']
return df
def many_parch(df, cutoff=2):
'''
input: df, cutoff=2
Creates a binary column indicating whether a passenger had many
parents or children.
Based on Parch column, removes said column.
output: df
'''
df['many_parch'] = (df['Parch'] > cutoff).astype('int')
del df['Parch']
return df
def many_sibsp(df, cutoff=1):
'''
input: df, cutoff=1
Creates a binary column indicating whether a passenger had many
siblings or spouses.
Based on SibSp column, removes said column.
output: df
'''
df['many_sibsp'] = (df['SibSp'] > cutoff).astype('int')
del df['SibSp']
return df
def fill_fare_na(df):
'''
input: df
Fills missing values for Fare with median fare
output: df
'''
median_fare = df['Fare'].median()
df = df.fillna({'Fare': median_fare})
return df
def log_fare(df):
'''
input: df
Converts fare values into log.
output: df
'''
df['log_fare'] = 0
df.loc[(df['Fare']>0), 'log_fare'] = np.log(df['Fare'])
del df['Fare']
return df
def female_class3(df):
'''
input: df
Creates column with interaction term for women in 3rd class.
(1 for women in 3rd class, otherwise 0).
output: df
'''
df['female_class3'] = 0
df.loc[(df['Sex']=='female')&(df['Pclass']==3),'female_class3'] = 1
return df
def male_class1(df):
'''
input: df
Creates column with interaction term for men in 1st class.
(1 for men in 1st class, otherwise 0).
output: df
'''
df['male_class1'] = 0
df.loc[(df['Sex']=='male')&(df['Pclass']==1),'male_class1'] = 1
return df
|
2e140bf2f365bcd2c734cb689f44555b9c5de870 | Nipuncp/lyceaum | /lpthw/ex9.py | 372 | 3.515625 | 4 | #Here is some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJuly\nAug"
print("Here are the days:", days)
print("Here are the months:", months)
print("""
There is something going on here
With the three double quotes
We'll be able to type as much as we like
Even 4 lines we want or 5 or 6
""")
|
828a52fcf979bb4c8dc3793babbfcf41a71efa2b | Nipuncp/lyceaum | /lpthw/ex3.py | 479 | 4.25 | 4 | print ("I'll now count my chickens")
print ("Hens:", 25 +30 / 6)
print ("Roosters", 100-25 *3%4)
print ("I'll now count the eggs:")
print (3 +2 + 1 - 5 + 4 % 2-1 % 4 + 6)
print ("Is it true that 3 + 2 < 5 - 7")
print (3 + 2 < 5 -7)
print ("What is 3 + 2", 3 + 2)
print ("What is 5 - 7", 5 - 7)
print ("THat is why, it is false")
print ("HOw about some more?")
print ("Is it greater?", 5 >= -2)
print ("Is it greater or equal?", 5 >= -2)
print ("Is it lesser or equal",5 <= -2)
|
7ce43b9da0bc4c37b8f50d464c3ab1bf8f3e1550 | FullStackPark/Python | /demo/004.py | 502 | 3.75 | 4 | #!/bin/python3
import re
def get_word_frequencies(file_name):
dic = {}
txt = open(file_name, 'r').read().splitlines()
no_flag=0
for line in txt:
line = re.sub(r'[.?!,""/\W]', ' ', line)
for word in line.split():
if word.isdigit():
pass
else:
dic.setdefault(word.lower(), 0)
dic[word.lower()] += 1
print (dic)
if __name__ == '__main__':
get_word_frequencies("WhatisPython.txt") |
fefe99ae80decc1c40885d81430a651ddbcd3541 | anupam-newgen/my-python-doodling | /calculator.py | 281 | 4.15625 | 4 | print('Add 2 with 2 = ', (2 + 2))
print('Subtract 2 from 2 = ', (2 - 2))
print('Multiply 2 with 2 = ', (2 * 2))
print('2 raise to the power 2 = ', (2 ** 2))
print('2 divide by 2 = ', (2 / 2))
# This is a comment.
# You can use above concept to solve complex equations as well.
|
1fec6ac5c98bcac8bff0fc97d37cf7846021a0b8 | MathBosco/exPython | /Ex014.py | 293 | 4.375 | 4 | #Enunciado:
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
celsius = float(input('Insira a temperatura em grau Celsius: '))
fahrenheit = (celsius * 9/5) + 32
print('A temperatura em Fahrenheit é: {} °F'.format(fahrenheit))
|
c8ae0a53f5a5c60bbe9422c3b8d2f2c71732dd8f | MathBosco/exPython | /Ex010.py | 434 | 4.03125 | 4 | #Enunciado
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
dinheiro = float(input('Qual o valor que você possui na sua carteira? R$ '))
dolares = dinheiro / 5.41
euro = dinheiro / 6.60
print('Com o valor de R${:.2f} você poderá comprar U${:.2f}'.format(dinheiro , dolares)
print('Com o valor de R${:;2f} você poderá comprar €{:.2f}'.format(dinheiro, euro))
|
7e69eebfecf375005e7f365a3fb8e2ae1941e792 | MarcosDihl/corretaza-buscador | /seucorretor/crm/utils.py | 791 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
INVALID_PHONE_CHARS = "()-+."
def formata_fone(fone):
""" retorna o numero de telefone visualmente melhor para leitura """
if len(fone) == 11:
return "(%s) %s %s-%s" % (fone[:2], fone[2:3], fone[3:7], fone[7:])
elif len(fone) == 10:
return "(%s) %s-%s" % (fone[:2], fone[2:6], fone[6:])
else:
return fone
def formata_fone_limpa(fone):
""" remove caracteres nao numericos do fone """
if fone == '(00)0000-0000':
return ''
if not fone:
return ''
fone = "".join(fone.split())
for digit in INVALID_PHONE_CHARS:
fone = fone.replace(digit, "")
if not fone.isdigit():
fone = ''
return fone
|
4fe4a7775fb251e2f7ad3bc0fa8ea490df5066b3 | gurudattshenoy/python_guru | /datastructures/searchtechniques/binary_search.py | 670 | 3.9375 | 4 | def binary_search(input:'List',key:'int')->'int':
print("The input is : {} and key to search is : {}".format(input,key))
left = 0
right = len(input) - 1
result = -1
while(left <= right):
mid = (left + right) //2
if input[mid] == key:
result = mid
break
elif key > input[mid]:
left = mid + 1
else:
right = mid - 1
return result
input = [100,2,5,24,10,11,1]
# Pre-requisite of binary search - Elements needs to be in sorted order
input.sort()
key = 1
print(binary_search(input,key))
key = 100
print(binary_search(input,key))
key =30
print(binary_search(input,key))
|
fd4002dc1278567eca851cf908ccbbe31432fa3f | ramankala/a3_kong9580_kala9110 | /startA3/Node.py | 1,894 | 3.75 | 4 | #CP372 Assignment 3
#Raman Kala: 120869110
#Ricky Kong: 180659580
from common import *
class Node:
def __init__(self, ID, networksimulator, costs):
self.myID = ID
self.ns = networksimulator
num = self.ns.NUM_NODES
self.distanceTable = [[0 for i in range(num)] for j in range(num)]
self.routes = [0 for i in range(num)]
# you implement the rest of constructor
for i in range(num):
if(i != ID):
if(costs[i] != self.ns.INFINITY):
print("\nTOLAYER2: " + "source: {} ".format(self.myID) + "dest: {} ".format(i) + "costs: ", end="")
for j in range(num):
if(costs[i] != self.ns.INFINITY):
print("{} ".format(costs[j]), end="")
if(i != j):
self.distanceTable[i][j] = self.ns.INFINITY
if(costs[i] != self.ns.INFINITY):
print("\n")
self.distanceTable[ID][i] = costs[i]
else:
for j in range(num):
if(j != ID):
self.distanceTable[j][i] = self.ns.INFINITY
def recvUpdate(self, pkt):
self.distanceTable[pkt.sourceid] = pkt.mincosts
# you implement the rest of it
return
def printdt(self):
print(" D"+str(self.myID)+" | ", end="")
for i in range(self.ns.NUM_NODES):
print("{:3d} ".format(i), end="")
print()
print(" ----|-", end="")
for i in range(self.ns.NUM_NODES):
print("------", end="")
print()
for i in range(self.ns.NUM_NODES):
print(" {}| ".format(i), end="" )
for j in range(self.ns.NUM_NODES):
print("{:3d} ".format(self.distanceTable[i][j]), end="" )
print()
print()
|
a779e15cf7b615cc8b6d3e1adc6a421ba5b2d50a | kalexanderk/GenomeAnalysis | /MinimumSkewProblem.py | 670 | 3.734375 | 4 | def SkewDiagram(text):
skew = []
skew.append(0)
count = 0
for i in text:
if i == "G":
skew.append(skew[count] + 1)
elif i == "C":
skew.append(skew[count] - 1)
else:
skew.append(skew[count])
count += 1
print skew
return skew
def MinimumSkewProblem(text):
skew_array = SkewDiagram(text)
min_value = max(skew_array)
result = []
count = 0
for i in skew_array:
if i == min_value:
result.append(count)
count += 1
return result
text = "GCATACACTTCCCAGTAGGTACTG"
data = MinimumSkewProblem(text)
print(" ".join(str(x) for x in data)) |
107615912f6e0ce5b41d70057e3016a912c84973 | anoopm031/Box_ball_git | /test2.py | 3,811 | 3.515625 | 4 | from Box_Ball import *
from psuedo_box import *
def populate_psuedo_box_list(box_agent_list):
"creating psuedo box objects-should return a list with psuedo box agents"
temp_psuedo=[]
for box in box_agent_list:
psuedo=Psuedo_box(box.name,box.position,(box.x_vel,box.y_vel,box.z_vel),(box.x_acc,box.y_acc,box.z_acc))
temp_psuedo.append(psuedo)
return temp_psuedo
def game():
#obstruction 1
obstruction_1=Obstruction((200,800),100,-400,"rect",BLUE)
obstruction_list.append(obstruction_1)
#obstruction 2
obstruction_2=Obstruction((500,800),100,-400,"rect",BLUE)
obstruction_list.append(obstruction_2)
#obstruction 3
obstruction_3=Obstruction((350,0),100,400,"rect",BLUE)
obstruction_list.append(obstruction_3)
#define gate w.r.t obstructions
'''corresponding gates and and box should be named same. That's box.name should be same as gate.name for box-gate combo'''
#gate A
gate_A_pos=[325,400]
gate_A=Gate("A",gate_A_pos)
gate_list.append(gate_A)
#gate B
gate_B_pos = [475,400]
gate_B=Gate("B",gate_B_pos)
gate_list.append(gate_B)
#box agent 1
x_lim_1=[20,330]
y_lim_1=[20,100]
x_spawn_lim_1=[20,330]
y_spawn_lim_1=[20,100]
gate_position_1=gate_A.position
color_1=RED
box_agent_A=Box_agents("A",x_lim_1,y_lim_1,x_spawn_lim_1,y_spawn_lim_1,gate_position_1,color_1)
box_agent_list.append(box_agent_A)
#box agent 2
x_lim_2=[470,780]
y_lim_2=[20,100]
x_spawn_lim_2=[470,780]
y_spawn_lim_2=[20,100]
gate_position_2=gate_B.position
color_2=RED
box_agent_B=Box_agents("B",x_lim_2,y_lim_2,x_spawn_lim_2,y_spawn_lim_2,gate_position_2,color_2)
box_agent_list.append(box_agent_B)
'''as of now only single ball is there, so no need to be careful on naming and gate-ball relationships. 1 ball, 2 gate'''
#ball_agent
agent_guard_gates=gate_list
ball_agent_pos=[400,750]
ball_agent_1=Ball_agent("1",ball_agent_pos,agent_guard_gates,MAROON)
ball_agent_list.append(ball_agent_1)
block_ratio_dict = gate_ball_len_ratio(gate_list, ball_agent_list, box_agent_list)
running=True
iter_no=0
SENSOR_FREQUENCY=5
psuedo_box_list=populate_psuedo_box_list(box_agent_list)
while running:
ground.fill(BLACK)
for event in pygame.event.get():
if event.type==pygame.QUIT:
end_game()
if event.type==pygame.KEYDOWN and event.key==pygame.K_ESCAPE:
end_game()
for obstruction in obstruction_list:
obstruction.draw_obstruction()
for box_agent in box_agent_list:
box_agent.move_box_new()
for gate in gate_list:
gate.draw_gate()
if iter_no/SENSOR_FREQUENCY==1:
for box,psuedo_box in zip(box_agent_list,psuedo_box_list):
psuedo_box.update_info(box.position,(box.x_vel,box.y_vel,box.z_vel),(box.x_acc,box.y_acc,box.z_acc))
else:
for psuedo_box in psuedo_box_list:
psuedo_box.predict_new_pos()
for ball_agent in ball_agent_list:
ball_agent.move_ball(psuedo_box_list,block_ratio_dict)
#ball_agent.move_ball(box_agent_list,block_ratio_dict)
movable_boxes= sum(box.movable for box in box_agent_list)
if movable_boxes==0:
finished=True
while finished:
for event in pygame.event.get():
if event.type == pygame.QUIT:
end_game()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
end_game()
clock.tick(60)
pygame.display.flip()
'''no ending condition is defined. ruuning is always TRUE'''
game()
|
3755f30fe7d962aa723c06c8e24df3a46ca91410 | selva86/python | /exercises/concept/little-sisters-essay/.meta/exemplar.py | 1,085 | 4.09375 | 4 | def capitalize_title(title):
"""
:param title: str title string that needs title casing
:return: str title string in title case (first letters capitalized)
"""
return title.title()
def check_sentence_ending(sentence):
"""
:param sentence: str a sentence to check.
:return: bool True if punctuated correctly with period, False otherwise.
"""
return sentence.endswith(".")
def clean_up_spacing(sentence):
"""
:param sentence: str a sentence to clean of leading and trailing space characters.
:return: str a sentence that has been cleaned of leading and trailing space characters.
"""
clean_sentence = sentence.strip()
return clean_sentence
def replace_word_choice(sentence, old_word, new_word):
"""
:param sentence: str a sentence to replace words in.
:param old_word: str word to replace
:param new_word: str replacement word
:return: str input sentence with new words in place of old words
"""
better_sentence = sentence.replace(old_word, new_word)
return better_sentence
|
4df2e2270df04452ca0403b08547f2bebad70504 | selva86/python | /exercises/concept/guidos-gorgeous-lasagna/.meta/exemplar.py | 1,640 | 4.28125 | 4 | # time the lasagna should be in the oven according to the cookbook.
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(elapsed_bake_time):
"""Calculate the bake time remaining.
:param elapsed_bake_time: int baking time already elapsed
:return: int remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME'
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""
return EXPECTED_BAKE_TIME - elapsed_bake_time
def preparation_time_in_minutes(number_of_layers):
"""Calculate the preparation time.
:param number_of_layers: int the number of lasagna layers made
:return: int amount of prep time (in minutes), based on 2 minutes per layer added
This function takes an integer representing the number of layers added to the dish,
calculating preparation time using a time of 2 minutes per layer added.
"""
return number_of_layers * PREPARATION_TIME
def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time):
"""Calculate the elapsed time.
:param number_of_layers: int the number of layers in the lasagna
:param elapsed_bake_time: int elapsed cooking time
:return: int total time elapsed (in in minutes) preparing and cooking
This function takes two integers representing the number of lasagna layers and the time already spent baking
and calculates the total elapsed minutes spent cooking the lasagna.
"""
return preparation_time_in_minutes(number_of_layers) + elapsed_bake_time
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.