blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
04dbf5bed84307be97d3d79497059d11d313adcc | kev0960/ProjectEuler | /14/14.py | 682 | 3.640625 | 4 | collatz = {}
longest = 1
longest_cnt = 1
for i in range(1, 1000000):
cur = i
current_chain = [cur]
last_step = -1
while cur != 1:
if cur in collatz:
last_step = collatz[cur]
break
if cur % 2 == 0:
cur = cur // 2
else:
cur = 3 * cur + 1
current_chain.append(cur)
# Add the elements in the chain to the dict.
if last_step == -1:
last_step = 0
for k in range(len(current_chain)):
collatz[current_chain[k]] = len(current_chain) - k - 1 + last_step
if longest_cnt < collatz[i]:
longest_cnt = collatz[i]
longest = i
print(longest, longest_cnt) |
d3b9a8641104d1f2c6a8e9f3981894b696bbbd51 | elenildo1/pythonProject | /Aula2 - Vaiaveis.py | 555 | 4.0625 | 4 | #Variaveis
a = float(input("Entre com o primeiro numero :"))
b = float(input("Entre com o segundo numero :"))
soma = a + b #soma
subtracao = a - b
multiplicacao = a * b
divisao = a / b
resto = a % b #resto
print("A soma de ", a, " + ", b," = " , soma)
print("A subtracao de ", a, "-", b, "=" , subtracao)
print("A Divisão de", a, "/ por ", b , " = ", divisao)
print("O resto de ", a, " / ", b , resto)
#print(type(soma))
print("Outra forma de imprimir :")
e = 10 / 2
d = 10 % 2
print(e)
print('soma:{sm}'.format(sm = soma).format(subtracao))
|
7f281afb8635e411fd3f5feba9973b2e321733f1 | guillermd/Python | /Learning Projects Python/Ejercicios/Funciones/ejercicios2.py | 1,239 | 3.84375 | 4 | '''
Escriba una funcion es_bisiesto()
que determine si un año determinado
es un año bisiesto.Un año bisiesto
es divisible por 4, pero no por 100.
===================================================
def es_bisiesto(anyo):
if(anyo%4==0 and anyo%4!=100):
return("El año es bisiesto")
return("El año no es bisiesto")
print(es_bisiesto(int(input("Introduzca un año:"))))
===================================================
'''
'''
Escribir un pequeño programa donde:
- Se ingresa el año en curso.
- Se ingresa el nombre y el año de nacimiento de tres personas.
- Se calcula cuántos años cumplirán durante el año en curso.
- Se imprime en pantalla.
===================================================
class Persona():
def __init__(self, nombre, anyo):
self.nombre=nombre
self.anyo=anyo
anyoActual=int(input('Introduce el año actual:'))
lista=[]
count=0
for item in range(5):
count+=1
n=input('Introduce el nombre:')
e=input('Introduce su año de nacimiento:')
p=Persona(n, int(e))
lista.append(p)
for i in lista:
print ("La edad de" , i.nombre, "es " ,anyoActual-i.anyo)
print("items", len(lista))
==========================================================
''' |
6d5d7ac1da17a69f901812babfdd3d3f3a0f221a | ArthurBrito1/MY-SCRIPTS-PYTHON | /Desafios/desafio27.py | 356 | 3.90625 | 4 | import random
print('A maquina esta pensando em um numero de 0 a 5... adivinhe se for capaz hehehehe')
numero = random.randint(0,5)
digite = int(input('Digite um numero de 0 a 5 seuu lixo:'))
if numero:
print('DROGAA!! mizeravel gurreiro voçê passou pelo desafio!')
else:
print('Voçê é um fracassoe e será englido pelo meu CRACKRM!')
|
dc8afd52235100312fffaa0e68e0e2be8565d40b | chlloyd/maya-model-asset-checker | /assetchecks/image/filesize.py | 693 | 3.609375 | 4 | import os
def image_file_size(sourceimages_path, min_image_size=100000): # File size, small being useless file
"""
Args:
sourceimages_path:Path for sourceimages folder
min_image_size:Defaulting to 10000 bytes (100KB), this sets the minimum image size.
Returns:A list of all images with paths smaller than the set minimum image size.
"""
small_image_list = []
for subdir, dirs, files in os.walk(sourceimages_path):
for file in files:
filename = os.path.join(subdir, file)
if os.path.getsize(filename) <= min_image_size:
small_image_list.append(os.path.basename(filename))
return small_image_list
|
583ccaead0a51dac74d9d4b0a6037fcee94c6ec0 | juliakyrychuk/python-for-beginners-resources | /final-code/debugging/functions.py | 208 | 3.875 | 4 | def add(x, y):
"""Add two numbers together and return result."""
result = x + y
return result
output_prefix = 'Total:'
total = add(7, 3)
message = f'{output_prefix} {total}'
print(message) |
6aad83aafd452319c09635ba4b99b1f3cfb87122 | Nadine-Waggoner/Python | /TextAdventure.py | 5,448 | 4.21875 | 4 |
start = input("Type 'start' to begin adventure. Type anything else to exit. ")
if start == "start":
print("""
You find yourself standing in a foot of murky black water.
Dim green light comes from a source somewhere behind you.
You're wearing boots, a thick waterproof coat, and at your waist is a sheath with a heavy sword.
You consider turning to see the source of the green tinted light, but you're also curious about your sword.
You feel as if you are being watched, but that might just be your overactive imagination.""")
print("""
Your options are:""")
print("""
a) Press onward into the dark.
b) Turn around to face the dim green light.
c) Unsheath sword.""")
letter = input("""
Type the letter of the action you wish to take. """)
if letter == ("a") or letter == ("b") or letter == ("c"):
if letter == ("a"):
print("""
Your foot hits a rock, a bump, something under the water.
A chill goes up your spine and you lose balance, toppling with a splash and a cry of terror into the black water.
A foul taste fills your mouth, and you go limp, losing consciousness, with your head under the water.
Your corpse joins the many unfortunate others that have fallen here.""")
if letter == ("b"):
print("""
The dim green light was coming from the glowing eyes of a large statue of a toad.
The glow is caused by small green fires glowing in the stone eye sockets.
The entire statue is damp and slimy, and seems to be ancient and magical.
The toad's mouth is open wide and it looks as if it is the entrance to a small tunnel leading down.
You're curious where it leads.
However, the large stone base of the statue has writing on either side, which you can't discern from this distance.
You hear footsteps coming swiftly from behind you.
Quick. Time is of the essence. Would it be worth it to try and read the writing?
The footsteps sound big, and the space you're in is large and open. The small tunnel may be the only place you'd be safe.
However, you do have a sword. The footsteps get closer. You must choose quickly.
""")
print("""
Your options are:""")
print("""
a) Draw your sword and turn around to face the footsteps.
b) Read the writing at the base of the statue.
c) Run for the tunnel as fast as you can.
""")
letter2 = input("""
Type the letter of the action you wish to take. """)
if letter2 == ("a") or letter == ("b") or letter == ("c"):
if letter2 == ("a"):
print("""
The blade glows brightly, and after a second to adjust, you see a large slimy golem only a few feet in front of you.
It has stopped coming towards you, however, and it's eyes are full of terror.
Too late, you hear angry hissing and clicking echo around you and large spiders descend swiftly on delicate strings from the ceiling.
You attempt to sheath the sword, but it's too late.
The last thing your eyes will ever see are five giant spiders tearing the large golem to pieces, and the last thing you hear are your own shrill screams.""")
if letter2 == ("b"):
print("""
You run to the base of the statue.
With the footsteps approaching, you read frantically.
"Beware spiders!" is the first thing your eyes fall on. "Do not disturb the darkness."
'It's not like I have a light,' you think.
You duck as your brain alerts you to the swish of a weapon just in time.
The footsteps came from a large, slimy golem wielding a heavy club.
You draw your sword.
The blade glows brightly.
The golems face fills with fear.
"Oh." you think.
Your only consolation is that death comes quickly.""")
if letter2 == ("c"):
print("""
You slide into the open entrance of the tunnel and run down the slippery stairs until you are sure you've lost whoever was making the footsteps.
Immediately after you entering the tunnel, the feeling of being closely watched goes away.
A large sigh of relief escapes your lips.
You feel as if you have escaped some great danger, but you don't know what.
You guess you should be glad you don't have to find out.
You draw your sword, and the light illuminates the way ahead.
Luck seems to be on your side.
You prepare to continue to see where this strange adventure will lead.
THE END""")
if letter == ("c"):
print("""
The sword comes free of its sheath with a satisfying 'chiink' sound of metal on metal.
The blade is glowing brightly, and for a moment you are blinded by the sudden light.
Your eyes adjust, and you realize your mistake.
The water, now clear enough to see through, shows that all around you are drowned and bloody corpses.
You look up quickly, trying to rid the image from your mind, and see large spiders coming angrily for the source of the light that so rudely awakened them.
You turn to run. There are too many. You splash through the water, over the uneven ground. Foul water splashes up to your face and burns your skin.
The first three spiders reach you at once.
For an instant there is pain when three pairs of sharp mandibles pierce you at once, then there is nothing.
""")
else:
print("""
That is not an option.""")
|
1b06ddc7dc6f4e14ec69665d1b6ba3f1d318d155 | aly22/cspython | /week1/circle_area.py | 134 | 4.4375 | 4 | pi=3.14159
radius=(float(input("Please enter the radius of the circle: ")))
area=radius**2*pi
print("The area of the circle is:",area) |
e96eeeb67d8ced9462532592660918841aea3715 | lotterombaut/LotteRombaut_Oefeningen_BasicProgr | /OefQWeek/Week05/Oef01.py | 371 | 4.03125 | 4 | #Maak volgende tuplesaan:
# tuple1
# met de elementen 1NMCT, 2NMCT, 3NMCT
# -tuple2
# met de elementen 1Devine, 2Devine,3Devine
# -tuple3
# met elementen van verschillende datatypes: “test”, True, 3.2 , 1
tuple1 = ("1NMCT", "2NMCT", "3NMCT")
tuple2= ("1Devine", "2Devine","3Devine")
tuple3 = ("test", True, 3.2 , 1)
print(tuple1.index("1NMCT"))
print(tuple1+tuple2) |
bd9f2c8045f8957dca20747de0a803937e687a38 | sphinx2001/gb-python-course | /lesson1/task3.py | 338 | 4.09375 | 4 | '''
3. Узнайте у пользователя число n.
Найдите сумму чисел n + nn + nnn.
Например, пользователь ввёл число 3.
Считаем 3 + 33 + 333 = 369.
'''
n = int(input("Введите n: "))
# сократим формулу :)
num = 3 * n + n * 20 + n * 100
print(num) |
c8a2dc5529def788ce82c280d266c942d439b61e | Dioclesiano/Estudos_sobre_Python | /Exercícios/ex028 - Usando Random e Sleep.py | 1,672 | 4.40625 | 4 | '''
Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para
o usuário tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.
import random
n = int(input('Digite o número do seu bilhete: '))
c = random.randint(1, 5)
if n == c:
print('Você digitou {} e o número sorteado foi {}. Parabéns Você ganhou!'.format(n,c))
else:
print('Infelizmente você não ganhou.')
O exercício acima eu fiz. O exercício abaixo o professor fez:
Começa importando o método randint() da biblioteca RANDOM
Também vou importar método sleep() da biblioteca time para simular tempo de processamento
from random import randint
from time import sleep
computador = randint(0, 5) #Faz o computador "PENSAR"
print('-=-'*20)
print('Vou pensar em um número entre 0 e 5. Tente adivinhar...')
print('-=-'*20)
jogador = int(input('Em que número eu pensei? ')) # Jogador tenta adivinhar
print('Processando...')
sleep(2)
if jogador == computador:
print('PARABÊNS! Você conseguiu me vencer!')
else:
print('GANHEI! Eu pensei no número {} e não no {}!'.format(computador, jogador))
'''
from random import randint
n = int(input('Você tem 3 tentativas para acertar o meu número. Digite aqui sua opção » '))
lista = []
cont = 0
for c in range(1, 4):
sorteio = randint(0, 10)
lista.append(sorteio)
if n == sorteio:
cont += 1
for k, v in enumerate(lista):
print(f'O {k+1}° número sorteado foi {v}')
if n in lista:
print(f'Você acertou {cont} vez(es). Parabéns!')
else:
print(f'Você não acertou nenhuma vez.')
|
9948b8a163196deb629f55697810272ea29781ec | gregfabian/PythonNIIT | /NIIT.py | 5,729 | 4.40625 | 4 | '''convert celsius to fahrenheit'''
# celsius=float(input("Enter temperature in celsius: "))
'''calculate tempersture in fahrenheit'''
# fahrenheit= (celsius*1.8)+32
# print("%.2f celsius= %0.2f fahrenheit"%(celsius,fahrenheit))
# name = input("What is your name?: ")
# print("Hello,",name,"you are welcome back!" )
# def my_function(fname):
# print("Hello," + fname + " welcome home!")
# my_function(input("what is your name: "))
# def greet_user():
# name = input("Enter your name: ")
# print("Hello ",name)
# greet_user()
# def greet_user(name: str):
# print("Hello", name)
# greet_user("Emil")
# def add_num(num1, num2):
# sum = num1 + num2
# return sum
# # result = add_num(1, 3)
# # print(result)
# def hello_worl():
# print("Hello world")
# def add():
# a = 1 + 1
# print(a)
# ben = add()
# ben = hello_worl()
# print(ben)
# hello_worl()
# hello_worl()
# hello_worl()
# hello_worl()
# hello_worl()
# def add():
# a = 1 + 1
# return a
# ben = add()
# print(ben)
# '''User input supplies function parameter'''
# def happyBirthday(person):
# print("Happy Birthday to you!")
# print("Happy Birthday to you!")
# print("Happy Birthday, dear " + person + ".")
# print("Happy Birthday to you!")
# def main():
# userName = input("Enter the Birthday person's name: ")
# happyBirthday(userName)
# main()
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))
'''Display any number of sum problems with a function.
Handle keyboard input separately.
'''
def sumProblem(x, y):
sum = x + y
sentence = 'The sum of {} and {} is {}.'.format(x, y, sum)
print(sentence)
def main():
sumProblem(2, 3)
sumProblem(1234567890123, 535790269358)
a = int(input("Enter an integer: "))
b = int(input("Enter another integer: "))
sumProblem(a, b)
main()
'''Display a sum problems with a function returning a string,
not printing directly.
'''
def sumProblemString(x, y):
sum = x + y
return 'The sum of {} and {} is {}.'.format(x, y, sum)
def main():
print(sumProblemString(2, 3))
print(sumProblemString(1234567890123, 535790269358))
a = int(input("Enter an integer: "))
b = int(input("Enter another integer: "))
print(sumProblemString(a, b))
main()
'''Illustrate a global constant being used inside functions.'''
PI = 3.14159265358979 # global constant -- only place the value of PI is set
def circleArea(radius):
return PI*radius*radius # use value of global constant PI
def circleCircumference(radius):
return 2*PI*radius # use value of global constant PI
def main():
print('circle area with radius 5:', circleArea(5))
print('circumference with radius 5:', circleCircumference(5))
main()
menu = raw_input ("Hello, please choose form following options (1,2,3) and press enter:\n"
"Option 1\n"
"Option 2\n"
"Option 3\n")
if menu == str("1"):
savinginfile = raw_input ("Please, state your name: ")
option1()
elif menu == str("2"):
print ("Option 2")
elif menu == str("3"):
print ("Option 3")
def option1():
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
import time
import os
print("Welcome!")
name = input("Please enter your name: ")
print("Hello",name, "! I am going to guess your most favorite type of music.")
time.sleep(2)
print("Please, choose from one of the following: ")
listening_time = ["1 - One hour a day", "2 - About two hours per day", "3 - three to four hours per day", "4 - Most of the day"]
print(listening_time)
how_often = int(input("I find myself listening to music..."))
def add_file_1(new_1):
f = open("music.txt", "a")
f.write("1 Hour")
def add_file_2(new_2):
f = open("music.txt", "a")
f.write("2 Hours")
def add_file_3(new_3):
f = open("music.txt", "a")
f.write("3 - 4 Hours")
def add_file_4(new_4):
f = open("music.txt", "a")
f.write("Most of the day")
if how_often == str('1'):
add_file_1(new_1)
elif how_often == str('2'):
add_file_2(new_2)
elif how_often == str('3'):
add_file_3(new_3)
else:
add_file_4(new_4)
import time
import os
print("Welcome!")
name = input("Please enter your name: ")
print("Hello",name, "! I am going to guess your most favorite type of music.")
time.sleep(2)
print("Please, choose from one of the following: ")
listening_time = ["1 - One hour a day", "2 - About two hours per day", "3 - three to four hours per day", "4 - Most of the day"]
print(listening_time)
how_often = int(input("I find myself listening to music..."))
f =open("music.txt", "a")
if how_often == 1:
f.write("1 Hour")
elif how_often == 2:
f.write("2 Hours")
elif how_often == 3:
f.write("3 - 4 Hours")
else:
f.write("Most of the day")
print("Please, choose from one of the following: ")
listening_times = {1:"One hour a day",
2:"About two hours per day",
3:"Three to four hours per day",
4:"Most of the day"}
for k in listening_times:
print " %d - %s" % (k, listening_times[k])
how_often = int(input("I find myself listening to music..."))
with open("music.txt", 'a') as f:
f.write(listening_times[how_often])
def add_file(new_1, usr_hours_choise):
with open("music.txt", "a") as f:
f.write(usr_hours_choise)
if how_often == 1:
add_file(new_1, "1 hour.")
elif how_often == 2:
add_file(new_2, "2 hour.")
elif how_often == 3:
add_file(new_3, "3 - 4 hour.")
elif how_often == 1:
add_file(new_4, "most of the day.") |
11baeb950fb3a978507fc81b2560359d0bd3c7ac | swain-s/lc | /-二叉树-二叉搜索树与双向链表.py | 2,296 | 3.59375 | 4 | # 问题描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向
# 模板: 7
# 3 10
# 1 5 9 12
# 4 14
#
from a_bin_tree import root, tin_travel
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class TreeToList(object):
def __init__(self):
pass
#辅助函数:查找二叉树或者双向链表(输入为任一节点)的最大节点
def find_max(self, root):
if root == None:
return None
if root.right == None:
return root
return self.find_max(root.right)
# 辅助函数:查找二叉树或者双向链表(输入为任一节点)的最小节点
def find_min(self, root):
if root == None:
return None
if root.left == None:
return root
return self.find_min(root.left)
#辅助函数:自己调试的时候用
def print_node(self, node1, node2):
if not node1 and not node2:
return [-1, -1]
if node1 and node2:
return [node1.val, node2.val]
if node1 and not node2:
return [node1.val, -1]
return [-1, node2.val]
#方法一:按后续遍历顺序
def tree_to_list(self, root):
if root == None:
return
#if root.left == None and root.right == None:
#return
self.tree_to_list(root.left)
self.tree_to_list(root.right)
print(root.val, end=": ")
print(self.print_node(root.left, root.right), end=" ---> ")
le_node = self.find_max(root.left)
root.left = le_node
if le_node:
le_node.right = root
ri_node = self.find_min(root.right)
root.right = ri_node
if ri_node:
ri_node.left = root
print(self.print_node(le_node, ri_node))
return root
if __name__ == "__main__":
S = TreeToList()
r = S.tree_to_list(root)
rr = r
while r:
print(r.val)
r = r.right
while rr:
print(rr.val)
rr = rr.left
|
062d6ebb9850a8a608584e6c20e03dc01d975337 | edoakes/bittorrent-simulator | /jellyfish_sampling.py | 2,581 | 3.515625 | 4 | import random
import argparse
parser = argparse.ArgumentParser(description='Simulate incrementally generating a random graph')
parser.add_argument('--n', default=50, type=int, help='number of vertices')
parser.add_argument('--k', default=10, type=int, help='edges per vertex')
class Node(object):
def __init__(self, name, degree):
self.name = name
self.degree = degree
self.neighbors = {}
self.connects = 0
self.disconnects = 0
def is_full():
return len(self.neighbors) >= self.degree
def connect(self, other):
if self.is_full() or other.is_full():
return False
#TODO
if other.name in self.neighbors:
return False
if len(self.neighbors) == self.degree or len(other.neighbors) == self.degree:
return False
self.neighbors[other.name] = other
other.neighbors[self.name] = self
self.connects += 1
other.connects += 1
return True
def disconnect(self, other):
if other.name not in self.neighbors:
return False
del self.neighbors[other.name]
del other.neighbors[self.name]
self.disconnects += 1
other.disconnects += 1
return True
def reconnect(self, new_node):
old_node = self.neighbors[random.choice(list(self.neighbors))]
if not self.disconnect(old_node):
raise RuntimeError("couldn't disconnect existing connected node")
if not self.connect(new_node):
return False
if not old_node.connect(new_node):
if not self.disconnect(new_node):
raise RuntimeError("couldn't disconnect newly connected node")
return False
return True
def add_edges(self, candidates):
candidates = random.sample(candidates, len(candidates))
for candidate in candidates:
if len(self.neighbors) == self.degree:
break
if not self.connect(candidate):
candidate.reconnect(self)
def print_summary(self):
print(self.disconnects)
class Graph(object):
def __init__(self, n, k):
self.nodes = []
for i in range(n):
new_node = Node(i, k)
new_node.add_edges(self.nodes)
self.nodes.append(new_node)
def print_summary(self):
for node in self.nodes:
node.print_summary()
def main(args):
graph = Graph(args.n, args.k)
graph.print_summary()
if __name__== "__main__":
main(parser.parse_args())
|
fd62663410da8d044ce8fda279b5df74007fa998 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/strings/domain_extractor.py | 941 | 4.40625 | 4 | """
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string.
Examples:
domain_name("http://github.com/SaadBenn") == "github"
domain_name("http://www.zombie-bites.com") == "zombie-bites"
domain_name("https://www.cnet.com") == "cnet"
Note: The idea is not to use any built-in libraries such as re (regular expression) or urlparse except .split() built-in function
"""
# Non pythonic way
def domain_name_1(url):
#grab only the non http(s) part
full_domain_name = url.split('//')[-1]
#grab the actual one depending on the len of the list
actual_domain = full_domain_name.split('.')
# case when www is in the url
if (len(actual_domain) > 2):
return actual_domain[1]
# case when www is not in the url
return actual_domain[0]
# pythonic one liner
def domain_name_2(url):
return url.split("//")[-1].split("www.")[-1].split(".")[0]
|
0e96f0088a883bb97cd51012977631c0e9b4d4d6 | AhmedBreak-HM/Python | /python.py | 417 | 3.703125 | 4 | # helpe function
# to get any information in python
help(print)
# first commit
print('hello python','hello world')
# change seprator
print('python','sep',sep='>>>>>')
# write in file
# f=open('demofile.txt','w')
# print('write in file', 'test',sep='***',file=f)
# Variables
# Variables is ref type to call new obj
x=10
print('x is int',x)
y='string'
print('y is',y)
x=y
print('this is ref type new obj from x',x)
|
c91e9eaa751e33d380e8c5bcb31795681fa426fe | tsar0720/HW_python | /HW17/HW17.py | 961 | 3.546875 | 4 | """
Написать скрипт, который будет вытаскивать gps данные
из фотографии (jpg файл) и передавать их на вход программе
из hw16.txt
"""
"""
pip3 install piexif
pip3 install gpsphoto
python3 -m pip install --upgrade Pillow
"""
from GPSPhoto import gpsphoto
from HW16 import HW16
# использую модуль GPSPhoto
data_one = gpsphoto.getGPSData('one.jpg')
data_two = gpsphoto.getGPSData('two.jpg')
# помещаю координаты в словарь
dict_coordinates = {data_one['Latitude'] : data_one['Longitude'],
data_two['Latitude']: data_two['Longitude']}
# сохраняю в файл
with open("coordinates_from_photo.txt", "w") as file:
for key, value in dict_coordinates.items():
file.write(str(key) + " " + str(value) + "\n")
# запускаю метод из HW16
HW16.find_coordinates("coordinates_from_photo.txt") |
aa3dbfe8cf83fc3c9d6dea0e9ee0c96dd1a0b97f | kvnrd/Heap-Sort | /Heap.py | 4,555 | 4.15625 | 4 | '''
Created by: Kevin Rodriguez
Last Modified: November, 26
Professor: Diego Aguirre
Purpose: In this lab, I had to finish the class for a Min Heap. We had to create a function that will create the min heap as well
as being able to create a function that extracts the min and keep the Min_Heap property. By using the extract min method, I was
able to create a the Heap_Sort method that was part of the lab as well.
BIG O Notation: Heap Sort's Big O is O(n log n). The advantage that this sorting algorithm has over something like Quick Sort, is that
Heap Sort has a worst case scenario with a running time of O(n log n) comparing to Quick Sort's worst case of O(n^2)
'''
class Heap:
def __init__(self):
self.heap_array = []
def insert(self, k):
self.heap_array.append(k)
self.creating_min_heap()
"""this method is used in order heapify the heap whenever is created"""
def heapify(self, index):
#starting from the end of the list to check every index to its parent
while index > 0:
parent = (index - 1) // 2
#if the son is greater than parent, minHeap property holds
if self.heap_array[index] >= self.heap_array[parent]:
index = parent
#violates minHeap property swap parent with child
else:
temp = self.heap_array[index]
self.heap_array[index] = self.heap_array[parent]
self.heap_array[parent] = temp
index = parent
'''This method extracts the min from the heap and heapifies in order to preserve min_heap
properties'''
def extract_min(self):
if self.is_empty():
return None
#smallest element is the first element
min_elem = self.heap_array[0]
#hold value of the last element in the list
replacement = self.heap_array[len(self.heap_array) - 1]
#remove the last element from the list
self.heap_array.remove(self.heap_array[len(self.heap_array) - 1])
#replace the first element with the last element of the list
self.heap_array[0] = replacement
#heapify to maintain minHeap property
self.creating_min_heap()
return min_elem
'''this method extracts the min from the heap until it is empty in order to do heap sort'''
def heap_sort(self):
sorted_list = []
while len(self.heap_array) is not 1:
min_val = self.extract_min()
sorted_list.append(min_val)
sorted_list.append(self.heap_array[0])
return sorted_list
'''This method is used in order to create a min heap from a file reader'''
def creating_min_heap(self):
if len(self.heap_array) == 1:
return self
child = len(self.heap_array) - 1
while child > 0:
parent = (child - 1) // 2
if self.heap_array[child] < self.heap_array[parent]:
temp = self.heap_array[child]
self.heap_array[child] = self.heap_array[parent]
self.heap_array[parent] = temp
child -= 1
return self
'''checks if the heap is empty'''
def is_empty(self):
return len(self.heap_array) == 0
'''prints the heap'''
def print_heap(self):
for i in range(len(self.heap_array)):
print(self.heap_array[i])
def read_file(file):
heap_array = Heap()
for line in file:
number = line.split(",")
for i in range(len(number)):
heap_array.insert(int(number[i]))
file.close()
return heap_array
def print_list(list):
for i in range(len(list)):
print(list[i])
'''function in order to test program if it works by inserting random numbers'''
def creating_min_heap():
min_heap = Heap()
min_heap.insert(5)
min_heap.insert(10)
min_heap.insert(2)
min_heap.insert(1)
min_heap.insert(1)
print("----------MIN_HEAP----------------")
min_heap.print_heap()
print("----------HEAPSORT----------------")
sorted_list = min_heap.heap_sort()
print_list(sorted_list)
'''Method in order to test program to see if it works with a CSV file'''
def from_file():
min_heap = Heap()
file = open('numbers.txt','r')
min_heap = read_file(file)
print("----------MIN_HEAP----------------")
min_heap.print_heap()
print("----------HEAPSORT----------------")
sorted_heap = min_heap.heap_sort()
print_list(sorted_heap)
creating_min_heap()
from_file() |
63c5fa630e59632cef33c2ea392ef2eec0826d78 | ushanirtt55/python | /Python Basics/Python_proj/String/reverse_str.py | 163 | 4.125 | 4 | def reverse(input):
print input
if len(input) <= 1:
return input
return reverse(input[1:]) + input[0]
s = 'reverse'
print(reverse(s)) |
82685290d923fdbf731cde29fd6397cc1758ad10 | ASAD2723/Rani.ai | /Rani.ai/python_program_to_reverse_a_list.py | 122 | 3.5 | 4 | def Reverse(lst):
mod_lst = lst[::-1]
return mod_lst
lst = [1, 76, 14, 10, 24, 31]
print(Reverse(lst)) |
b669c7eeddeb4363afbfbe31d3e3b5147409e28d | melardev/PythonAlgorithmSnippets | /reverse_words_sentence.py | 279 | 4.125 | 4 | sentence = "If you wait, all that happens is you get older ."
# split by spaces, get list of strings
words = sentence.split()
# reverse each item in the list and concatenate the items between them with space
reversed_sentence = " ".join(reversed(words))
print(reversed_sentence)
|
132a10bee355b0773e11854eb991d47ae6242198 | NotaCSstudent/leetcode | /python/linkedlist.py | 593 | 3.984375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def Insert_Node(root, data):
if(root == None):
root = Node(data)
return root
root.next = Insert_Node(root.next,data)
return root
def Remove_Node(root):
if(root.next == None)
head = None
head = Insert_Node(head,1)
head = Insert_Node(head,2)
head = Insert_Node(head,3)
head = Insert_Node(head,4)
temp = head
while(temp != None):
print(temp.data)
temp = temp.next
Remove_Node(head)
temp = head
while(temp != None):
print(temp.data)
temp = temp.next |
2fb332b397f6d0d995951f02337be0f45a785ea4 | pyq881120/pn | /pnwtl/pypn/scripts3k/pypn/utils/documentfile.py | 2,572 | 3.75 | 4 | import pn, scintilla
class DocumentFile(object):
"""file-like interface to new Scintilla document editor
DocumentFile() -> file object
Open a file on a new Scintilla document editor.
Provide the ability to add text to a new document
editor using the python file idiom.
Also allows you to treat an existing document as
a file by passing document to constructor."""
def __init__(self, pndoc = None):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature"""
self._closed = False
self._softspace = 0
if not pndoc == None:
self.doc = pndoc
self.__editor = scintilla.Scintilla(self.doc)
else:
doc = pn.NewDocument(None)
self.__editor = scintilla.Scintilla(pn.CurrentDoc())
self.__editor.BeginUndoAction()
def close(self):
"""close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing."""
if not self._closed:
self.__editor.EndUndoAction()
self._closed = True
self.__editor = None
def flush(self):
"""flush() -> None. Flush the internal I/O buffer. In this case, a no-op"""
pass
def write(self,s):
"""write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written."""
if self._closed:
return
self.__editor.AppendText(len(s), s)
def writelines(self,ss):
"""writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string."""
for s in ss:
self.write(s)
def _get_closed(self): return self._closed
def _set_closed(self,_closed): self._closed = _closed
closed = property(_get_closed,_set_closed,None,
"True if the file is closed")
def _get_softspace(self): return self._softspace
def _set_softspace(self,_softspace): self._softspace = _softspace
softspace = property(_get_softspace,_set_softspace,None,
"flag indicating that a space needs to be printed; used by print") |
7037eed7ecc8216fc525e2793f39975ccc057192 | Mohanskarri/MyPython | /CI,Dice,Coins,Temperature using_if.py | 3,999 | 3.984375 | 4 |
# coding: utf-8
# In[1]:
#this program calculates the compound intrest
print('calculate the compound intrest')
P = float(input('Enter the value of the principle amount : '))
r = float(input('Enter the rate of intrest: '))
R = float(r/100)
n = int(input('enter the coumpound intrest frequency :1 ,2 , 4, 12 :'))
T = float(input('enter time in years :'))
import math
A = float(P * math.pow((1 + (R/n)),n*T))
print ('Total Amount is :', round(A,2))
# In[3]:
# Swapping numbers with out using temp variable
A = int(input('Enter 1st number A : '))
B = int(input('Enter 2nd number B : '))
A = A * B
B = A / B
A = A / B
print('A = ', int(A))
print('B = ', int(B))
# In[37]:
# E = mc^2
m = float(input('Enter weight of the object in KG : '))
c = float(input('Enter the speed of the object in meters per sec :'))
K = float(m*(c**2))
print('Kinetic Energy of the object with weight {0} KG with speed {1} m/sec in jouls is :'.format(m,c), K)
# In[12]:
#temperature convertor from c to f
c = int(input('the temperature in centigrade :'))
f = float((c*9/5)+32)
print('The temperature in Fahrenheit :', f)
# In[38]:
#Converting Farhen heat to celsius scale reading
x = int(input('Enter 1 for (C to F) or 2 for (F to C):'))
if x == 1:
X1 = int(input('enter temperature in centigrade :'))
F = ((X1*9)/5) + 32
print('The temperature in Fahrenheit is :',F)
elif x == 2:
X1 = int(input('enter temperature in Fahrenheit :'))
C = ((5/9)*(X1-32))
print('The temperature in Centigrade is :',C)
else:
print('You entered wrong value')
# In[4]:
#****remind it
import random as r
a = r.randint(1,10)
b = r.randint(1,10)
c = int(input('what is the value of '+ str(a)+'+'+str(b)+': ')) #it shows what is the input that it has been randomly taken, according to that take the input
#print(c)
if c == a+b:
print('congratulations .. you won')
else:
print('sorry, try again')
# In[4]:
#rolling a dice and check you won or lost:
import random as r
a = r.randint(1,6)
b = int(input('Dice Rolled...guess your number from 1 to 6 :'))
if a == b:
print('jackpot ..you won')
else:
print('number on the dice is :',a)
print('sorry ..you lost')
# In[65]:
#won or loss while rolling a coin and say its head or tails:
import random as r
a = ['h','t']
A = r.choice(a)
#print(A)
B = input('coin tossed..heads(h) or tails(t) : ')
if B == A:
print('congrats you won the toss its :', A)
else:
print('Sorry you lost the toss its :', A)
# In[47]:
import random
x = ['a', 'b', 'c', 'd', 'e']
print(random.choice(x))
# In[12]:
import random as r
a = ['t','h']
A = r.choice(a)
print(A)
# In[90]:
#Head and toss
import random as r
a = ['h','t']
A = r.choice(a)
if A == 'h':
x = 'HEADS'
else:
x = 'TAILS'
B = input('coin tossed..heads(h) or tails(t) : ')
if B == A:
print('congrats you won the toss its :', x)
else:
print('Sorry you lost the toss its :', x)
# In[12]:
#guess either head or toss -if ur guess true:"you won" by using predefined fn @choice()
import random as r
a=['h','t']
c=r.choice(a) # @choice() ok, @choice[] not predefined
#print('randon variable is:',c)
b=str(input("enter either t or h:"))
if c==b:
print('You won')
else:
print('You loss')
# In[11]:
#guess either head or toss -if ur guess true:"you won" by @randint()
import random as r
a = int(r.randint(1,2))
print(a)
if a == 1:
A = 'HEADS'
else:
A = 'TAILS'
b = input('coin tossed..heads(h) or tails(t) : ')
if b == 'h':
B = 'HEADS'
else:
B = 'TAILS'
if A == B:
print('CONGRATS you won the toss its :', A)
else:
print('SORRY you lost the toss its :', A)
# In[40]:
#guess either head or toss -if ur guess true:"you won" by @randint()
import random
a=random.randint(1,2)
print("the random variable:",a)
if a==1:
a='h'
else:
a='t'
b=str(input("enter toss(t) or heads(h)="))
if a==b:
print('you won')
else:
print('you loss')
|
10c23bab8fea24f8303f4aa9f357d010787c95f4 | WikiWikiWasp/ascii-crush | /ascii_crush.py | 2,147 | 3.734375 | 4 | ########################################
# ASCII CRUSH
# Author: Jason Flinn
# Date: September 11th 2018
########################################
import sys
#terminal text colors
BLUE = '\033[0;34m'
RED = '\033[0;31m'
GREEN = '\033[;32m'
NC = '\033[0m' #no color
def title():
print('='*30)
print('-'*7 + ' ASCII CRUSH ' + '-'*7)
print('='*30)
print
# TODO: pythonic formating
# TODO: Help message
# TODO: determine if menu() should return a value or serve as a "main" function and call the other game's functions
# TODO: docstrings for functions
def menu():
while True:
print('1. Play\n2. Help\n3. Quit\n')
# input validation
try:
choice = int(input('> '))
except NameError:
print('Error. Invalid input. Enter a value between 1 - 3.\n')
continue
if not choice in range(1, 4):
print('Error. Invalid input. Enter a value between 1 - 3.\n')
continue
# menu actions
if choice == 1:
# print('Please choose difficulty:')
# print('1. Easy\n2. Medium\n3. Hard\n')
# diff = input('> ')
# TODO: draw and populate board
# TODO: have selected difficulty determine size of board
draw_board(5, 5, 3)
break
elif choice == 2:
print('<Help Message>\n')
elif choice == 3:
print('Quiting...\n')
sys.exit()
else:
print('Please enter a valid menu choice:\n')
choice = input('> ')
# TODO: separate into smaller functions
# TODO: figure out how to fill_board() without having to resize board
def draw_board(rows, cols, ascii):
print('\n\n')
for x in range(cols):
print ' ' if x == 0 else ' ',
print str(chr(65+x)),
print
for x in range(rows):
print ' ---' + ' ---'*cols
print(str(x+1) + ' ' + '| '*(cols+2))
print ' ---' + ' ---'*cols
print '\n\n'
def fill_board():
pass
def match_chars():
pass
def remove_match():
pass
if __name__ == '__main__':
title()
menu() |
7f0f617b72833ada86f344ea45df7d7e69709ac3 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_14_number_od_days_between.py | 412 | 4.03125 | 4 | from datetime import datetime
def day_difference(two_dates):
_daty = []
for date in two_dates:
date = datetime.strptime(date, '%d/%m/%Y').date()
_daty.append(date)
difference = abs((_daty[0] - _daty[1]).days)
return print("Between {} and {} there are {} days difference".format(_daty[0],_daty[1], difference))
two_dates = ['24/07/2021', '21/07/2021']
day_difference(two_dates) |
dd91988031b3f659a0df46244e87f57fa9e9987f | shuihan0555/100-days-of-python | /day004/main.py | 1,067 | 3.875 | 4 | """Day 004 - Everything can be an iterable.
This example covers how to make iterable an non built-in class.
"""
from fruits import FruitPack
from random import choice
def run():
fruit_pack = FruitPack()
print("All fruits: ")
for fruit in fruit_pack:
print(fruit)
# >>> All fruits:
# Strawberry
# Grape
# Kiwifruit
# Blackberry
# Orange
# Watermelon
# Apple
# Lemon
# Papaya
# Cherry
print("FruitPack length: %d" % len(fruit_pack))
# >>> FruitPack length: 10
print("FruitPack first item: %s" % fruit_pack[0])
# >>> FruitPack first item: Strawberry
print("FruitPack first-two item: %s" % fruit_pack[0:2])
# >>> FruitPack first-two item: ['Strawberry', 'Grape']
print("Random fruit: %s" % choice(fruit_pack))
print(
"Is Lemon in FruitPack? %s" % "True" if "Lemon" in fruit_pack else "False"
)
# >>> Is Lemon in FruitPack? True
if __name__ == '__main__':
run()
|
278afc75760720906ed04346c169e7ffa86bd34f | shomikg/The-Complete-Python-Developer-Course | /Variables/variables4.py | 570 | 3.59375 | 4 | parrot = "Norwegian Blue"
print(parrot)
print(parrot[0])
print(parrot[3])
print(parrot[-1])
print(parrot[0:6])
print(parrot[:6])
print(parrot[6:])
print(parrot[-4:-2])
print(parrot[0:6:2])
print(parrot[0:6:3])
number = "9,223,372,036,854,775,807"
print(number[1::4])
numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9"
print(numbers[0::3])
string1 = "he's"
string2 = "probably"
print(string1 + string2)
print("he's probably pining")
print("Hello" *5)
print("Hello" *5+"4")
today = "friday"
print("day" in today)
print("fri" in today)
print("thur" in today)
print("parrot" in "fjord") |
9934eeb6311b3d239cb0c880411ca28318d9a50b | johncmk/Python | /Divide_and_Conquer/closest_unsorted.py | 895 | 3.53125 | 4 | import random
def closest_unsorted(li,x, k):
if li == [] or len(li) == k:
return li
p_adr = random.randrange(0,len(li))
pivot = abs(x-li[p_adr])
l,eq,r = [],[],[]
for i in range(len(li)):
if i == p_adr:
continue
else:
temp = abs(x-li[i])
if temp < pivot:
l.append(li[i])
elif temp > pivot:
r.append(li[i])
else:
eq.append(li[i])
pivot = li[p_adr]
if len(l) + len(eq) + 1 == k:
return l+eq+[pivot]
if len(l) + len(eq) >= k:
return closest_unsorted(l+eq,x,k)
k = k- (len(l) + len(eq) + 1)
return l+eq+closest_unsorted(r,x,k)
if __name__ == "__main__":
x = 5.2
k = 2
li = [4,1,3,2,7,4]
print closest_unsorted(li, x, k)
x = 6.5
k = 3
print closest_unsorted(li, x, k) |
97a42a77c3f85710f8ea665e8c43cd1463f059ea | srikanthpragada/PYTHON_10_JULY_2020 | /demo/libdemo/list_broken_links.py | 682 | 3.609375 | 4 | import requests
from bs4 import BeautifulSoup
website = "http://www.srikanthtechnologies.com" # Website we want to use
resp = requests.get(website)
bs = BeautifulSoup(resp.text, "html.parser")
anchors = bs.find_all("a")
for a in anchors:
if 'href' in a.attrs:
url = a['href']
if url == "#": # ignore these URLs
continue
# find out whether url starts with http
if not url.startswith("http"):
url = website + "/" + url
# Check whether URL is valid
resp = requests.get(url)
if resp.status_code == 404:
print(f"{url} is invalid!")
else:
print(f"{url} is valid!")
|
58e3cc00491d7a598ff0ce31f9a1e9c7e9fbd236 | Skishta/Project-5-Employee-Psitions-using-regression | /Project 5 (Employee Psitions and salaries) using sheet excel of real employees.py | 3,846 | 4 | 4 | '''بسم الله الرحمن الرحيم'''
#Project 5 (Employee Psitions and salaries) using sheet excel of real employees
##ANOTHER PROJECT FOR POLYNOMIAL REGRESSION
#Import all liberaries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Import Sklearn with the function (train_test_split)
from sklearn.model_selection import train_test_split
#Import LinearRegression
from sklearn.linear_model import LinearRegression
#Import the file sheet
data=pd.read_csv(r"H:\NEW PARTITION (F)\deploma\PYTHON\sample sheets\Position_Salaries.csv")
#Assign the input "level(of the postition title)" for X
X=data["Level"]
print(X)
#Import the output(that i will predict) for Salary As [Y]
Y=data["Salary"]
print(Y)
#reshape X & Y to an (-1,1) array(جرب الكود من غيرها وهتفهم لية عملناها وشوف الخطا)
x=np.array(X).reshape(-1,1)
y=np.array(Y).reshape(-1,1)
#دلوقتى انا ظهر ليا الpattern بس ماينفعش معاها الlinearRegression عشان الpattern مش مظبوطة
#import the function of PolynomialFunction from Sklearn liberary
#the math liberary of (sklearn.preprocessing & the function of PolynomialFeatures) is used to make a function of degrees to predict optimum line solution for the pattern
from sklearn.preprocessing import PolynomialFeatures
#دلوقتى انا همشى بالمعادلة بتاعى الpolynomial اللى هيا فيها درجات للاسس من معادلات من الدرجة الثانية او الثالثة او اى درجة (ابحث بجوجل)
'''poly_obj=PolynomialFeatures(degree=2)'
'poly_obj=PolynomialFeatures(degree=3)'
'poly_obj=PolynomialFeatures(degree=4)'
'poly_obj=PolynomialFeatures(degree=5)'
'poly_obj=PolynomialFeatures(degree=6)'
'poly_obj=PolynomialFeatures(degree=7)'''
#باستخدام المكتبة السابق ذكرها (polynomialfeatures) تقوم بعمل المعادلة الخاصة بالpolynomial وتقوم برفع الX للاوسس (Xpower 2) او زيادة درجة المعادلة(إبحث جوجل)..وبيكون عندة القدرة انة يش على المعادلة يخليهاأوس الرقم اللى محددة فى الdegree
#بعد تجربة الدرجة الثانية لم نجد ان الارقام اللى تم التبوء بها قريبة من الارقام الحقيقية
#فضلنا نجرب للدرجة الثالثة والرابعة والخامسة حتى وصلنا للدرجة السادسة(وبعدها جربت الدرجة السابعة ولاقيت ان الارقام بدات تبعد تانى-فرجعت تانى لافضل تنبوء اللى هوة الoptimum) فى المعادلة اللى هعمل بيها التنبوء وهى كالاتى:
poly_obj=PolynomialFeatures(degree=6)
#the code to tell the compiler to transform the polynomial frunction to the degree supported
#الامر دة عشان اقول للكومبيلر خش على الpoly_obj واعملها تحويل للدرجة المذكورة
xpoly=poly_obj.fit_transform(x)
print(xpoly)
#Import the Function of (train_test_split) for X & Y And specify the percentage for the prediction
#(random state) to take aspecific raw constant and for not change it every time the compiler make the prediction
X_train,X_test,Y_train,Y_test=train_test_split(xpoly,Y,test_size=0.2,random_state=0)
#to make the linear regression for drawing the represented line for the pattern
reg=LinearRegression()
#train the level of the careers & their salary
reg.fit(X_train,Y_train)
#to make the prediction for the (X_test) the level of the career
ypred=reg.predict(X_test)
print(ypred)
print(Y_test)
#Draw the pattern for X & Y with the polynomial line prediction
plt.scatter(x,y)
plt.plot(xpoly,reg.predict(xpoly))
plt.show() |
1b33e8ac94e8beb1365eb01513a0c4648a4059d4 | harshilphs/AkashTechnolabInternshipTasks | /Day-3_27-05-21/break_continue.py | 172 | 4.0625 | 4 | print("break---->")
for i in range(1,6):
if i == 3:
break
print(i)
print("continue---->")
for i in range(1,6):
if i == 3:
continue
print(i) |
39f6de220e518f7f9bab8870a399b9f587369b37 | lucashsouza/Desafios-Python | /CursoEmVideo/Aula22/ex110/moeda.py | 2,521 | 3.78125 | 4 | def aumentar(preco, taxa=0, formatado=False):
"""
Função com o objetivo de calcular o aumento de
determinada porcentagem parametrizada.
:param preco: Valor a ser calculado
:param taxa: Porcentagem a ser calculada
:param formatado: Valor será apresentado com o formato(R$00,00) ou não?
:return: Valor calculado, formatado ou não.
"""
resposta = preco + (preco * taxa/100)
return resposta if formatado is False else moeda(resposta)
def diminuir(preco=0, taxa=0, formatado=False):
"""
Função com o objetivo de calcular o desconto de
determinada porcentagem parametrizada.
:param preco: Valor a ser calculado
:param taxa: Porcentagem a ser calculada
:param formatado: Valor será apresentado com o formato(R$00,00) ou não?
:return: Valor calculado, formatado ou não.
"""
resposta = preco - (preco * taxa/100)
if formatado:
return moeda(resposta)
else:
return resposta
def dobro(preco=0, formatado=False):
"""
Função com o objetivo de calcular o dobro do
valor parametrizado.
:param preco: Valor a ser calculado
:param formatado: Valor será apresentado com o formato(R$00,00) ou não?
:return: Valor calculado, formatado ou não.
"""
resposta = preco * 2
if formatado:
return moeda(resposta)
else:
return resposta
def metade(preco=0, formatado=False):
"""
Função com o objetivo de calcular a metade do
valor parametrizado.
:param preco: Valor a ser calculado
:param formatado: Valor será apresentado com o formato(R$00,00) ou não?
:return: Valor calculado, formatado ou não.
"""
resposta = preco / 2
if formatado:
return moeda(resposta)
else:
return resposta
def moeda(preco=0, moeda='R$'):
"""
:param preco: Valor a ser calculado
:param moeda: Valor a ser acrescentado 'R$'
:return: Valor calculado Formatado para duas casas decimais
"""
return f"{moeda}{preco:.2f}".replace('.', ',')
def resumo(preco=0, taxaa=10, taxar=5):
print()
print('~' * 30)
print("Resumo do valor".center(30))
print('~' * 30)
print(f"Preço analisado: {moeda(preco)}")
print('~' * 30)
print(f"Dobro: {dobro(preco, True).center(32)}")
print(f"Metade: {metade(preco, True).center(30)}")
print(f"10% Acrescimo: {aumentar(preco, 10, True).center(15)}")
print(f"13% Desconto: {aumentar(preco, 13, True).center(17)}")
print('-'*30)
|
343c0f44c05302445634cc99c1147dfa0c3dd13c | ne1son172/GB2-algo-and-data-structures | /HW1/task8.py | 498 | 4.0625 | 4 | # Определить, является ли год, который ввел пользователем, високосным или не високосным
while True:
year = input('Enter q for quit or enter some year >>> ')
if year == 'Q' or year == 'q':
break
else:
year = int(year)
temp = year % 4
if temp == 0:
print('{} year is leap-year'.format(year))
else:
print("{} is regualr year".format(year))
|
a08a9cc05a4c91a8d58642577eca38596d83c3cf | Choijonghun/jhchoi_gitTest | /연습_src/0421_cordingStemp/practice_3.py | 702 | 3.578125 | 4 | #0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, ... 과 같이, 0 이상의 앞뒤가 같은 수를 크기 순으로 나열할 때, n 번째 수를 계산하는 프로그램을 작성하라.
'''count = int(input("시작\n"))
pal_list=[]
num = 0
def dec_pal(num):
a = list(str(num))
b = list(reversed(a))
if a==b:
pal_list.append(num)
while len(pal_list) < count:
# palindromic number list의 수가 지정한 숫자에 이를 때까지 리스트에 palindrome 추가
dec_pal(num)
num += 1
print(pal_list[-1])
'''
i = '1032002305'
a = list(i)
b = list(reversed(a))
if a == b:
print("True")
if str(i) ==str(i)[::-1]:
print("TTrue")
print(str(i)[::-1])
|
88f8018380404a76f38e852176d7a00ca3da835b | shaozhenyu/pythontool | /leetcode/solution.py | 304 | 3.515625 | 4 | #!/bin/python
def moveZeroes(nums):
# length = len(nums)
# i = 0
# num = 0
# while i < length:
# if nums[i] == 0 and i < length - num:
# del nums[i]
# nums.append(0)
# num += 1
# else:
# i += 1
nums.sort(key=lambda x:x==0)
nums = [0, 1, 0, 2, 0, 0, 4, 4, 4, 0]
moveZeroes(nums)
print nums
|
9426b194c83afee4d37f7e8bc1e8507516af6dfe | zbyszek111/python_bootcamp | /zjazd1/podstawy_zad07.py | 191 | 3.640625 | 4 | print('podal liczbę A:')
A = int(input('liczba A:'))
print(A%2==0 and A%3==0 \
and A>10 or A==7)
# do obcięcia linii kodu stosowany jest \
print((A%2==0) & (A%3==0) \
& (A>10) | (A==7)) |
36a48f14c8b4315e618033d6a671e08d086b4759 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/1-200/000048/000048.py | 1,444 | 3.703125 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# 通过观察可以发现,替换的规律是这样的:
## (旧的)第 i 行会变成(新的)第 n-1-i 列;(旧的)第 j 列会变成(新的)第 j 行。
# 比如例子里那个四阶矩阵:
## 第0行会变成第3列;第1行会变成第2列;依次类推。。。
## 第3列会变成第3行;第2列会变成第2行;依次类推。。。
## 所以原来第 i 行第 j 列的元素,会跑到新的第 j 行第 n-1-i 列处。
# 这里先流氓一下,申请一个同样大小的矩阵,从而避免变量覆盖的问题。但是有可能空间会超?
n = len(matrix)
tmp = [[-1 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
tmp[j][n-1-i] = matrix[i][j]
for i in range(n):
for j in range(n):
matrix[i][j] = tmp[i][j]
"""
https://leetcode-cn.com/submissions/detail/132109553/
21 / 21 个通过测试用例
状态:通过
执行用时: 20 ms
内存消耗: 13 MB
执行用时:20 ms, 在所有 Python 提交中击败了56.97%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了28.13%的用户
"""
|
8e8836389ab4d005e066dd97d87e07c34129e9fa | amitesh1201/python_training | /for_loop3.py | 626 | 4.375 | 4 | #!/usr/bin/python
# Declaration of list
list1 = ["one", "two", "three", "four", "five"]
print (list1)
# Print the value in 2nd position
print (list1[2])
# Print the index of two
index = list1.index('two')
print ("Index of two: ", index)
print("")
for x in list1:
print ("The index of ",x,": ",list1.index(x))
# Print the length of list1
print ("Length: ", len(list1))
print ("")
# Replace the value in 2nd postision in list
list1[2] = 10
print (list1)
print("")
# Added a list in 1st position of list1
list1 [1] = [22, 33, 44]
print (list1)
# Print the value of 2nd position
word = "Python"
print (word[2])
|
09d4827626d3be94d010782ba8b2eb5fd78825f3 | axetang/AxePython | /60days/19.py | 3,898 | 4.0625 | 4 | from math import ceil
'''
直观理解 yield
要想通俗理解 yield,可结合函数的返回值关键字 return,yield 是一种特殊的 return。
说是特殊的 return,是因为执行遇到 yield 时,立即返回,这是与 return 的相似之处。
不同之处在于:下次进入函数时直接到 yield 的下一个语句,而 return 后再进入函数,
还是从函数体的第一行代码开始执行。带 yield 的函数是生成器,通常与 next 函数结合用。
下次进入函数,意思是使用 next 函数进入到函数体内。
'''
def f():
print("enter f()...")
yield 4
print("i am next sentence of yield.")
g = f()
active = True
i = 0
while(active):
i += 1
try:
next(g)
except StopIteration:
print(f"%d times, Iteration Stop" % i)
break
# yield 与生成器
# 函数带有 yield,就是一个生成器,英文 generator,它的重要优点之一节省内存。
def myrange(stop):
start = 0
while start < stop:
yield start
start += 1
for i in myrange(10):
print(i)
# send 函数
# 带 yield 的生成器对象里还封装了一个 send 方法。
# 下例暂时send用法,send函数赋值给yield左侧的result变量,然后继续执行yield的下一句
def f():
print('enter f...')
while True:
result = yield 4
if result:
print('send me a value is:%d' % (result,))
return
else:
print('no send', result)
g = f()
print(next(g))
print('ready to send')
print(g.send(None))
print(g.send(''))
print(g.send(False))
# print(g.send(10))
# 1. 完全展开 list
# 下面的函数 deep_flatten 定义中使用了 yield 关键字,实现嵌套 list 的完全展开。
def deep_flatten(lst):
for i in lst:
if type(i) == list:
yield from deep_flatten(i)
else:
yield i
gen = deep_flatten([1, ['s', ['a', 'b'], 3], 4, 5])
print(gen)
for i in gen:
print(i)
# 2. 列表分组
#from math import ceil
def divide_iter(lst, n):
if n <= 0:
yield lst
return
i, div = 0, ceil(len(lst) / n)
while i < n:
yield lst[i * div: (i + 1) * div]
i += 1
print(list(divide_iter([1, 2, 3, 4, 5], 0))) # [[1, 2, 3, 4, 5]]
print(list(divide_iter([1, 2, 3, 4, 5], 2))) # [[1, 2, 3], [4, 5]]
'''
nonlocal 关键字
关键词 nonlocal 常用于函数嵌套中,声明变量为非局部变量。
'''
def ff():
i = 0
def auto_increase():
nonlocal i # 使用 nonlocal 告诉编译器,i 不是局部变量
if i >= 10:
i = 0
i += 1
ret = []
for _ in range(28):
auto_increase()
ret.append(i)
print(ret)
ff()
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4,5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8]
#######################
#global 关键字
# 先回答为什么要有 global。
# 一个变量被多个函数引用,想让全局变量被所有函数共享。
# 有的伙伴可能会想这还不简单,这样写:
i = 5
def f():
print(i)
def g():
print(i)
pass
f()
g()
# f 和 g 两个函数都能共享变量 i,程序没有报错,所以,至此依然没有真正解释global 存在的价值。
# 但是,如果某个函数要修改 i,实现递增,这样:
def h():
i += 1
h()
# 此时执行程序,就会出错,抛出异常 UnboundLocalError,原来编译器在解释 i += 1 时,
# 会解析 i 为函数 h() 内的局部变量。很显然,在此函数内,解释器找不到对变量 i 的定义,所以报错。
# global 在此种场景下,会大显身手。
# 在函数 h 内,显示地告诉解释器 i 为全局变量,然后,解释器会在函数外面寻找 i 的定义,
# 执行完 i += 1 后,i 还为全局变量,值加 1:
i = 0
def hh():
global i
i += 1
h()
print(i)
|
d2a3fe523551a05c22b96507a170e1a16e085887 | shamim-21/fsdp2019 | /day6/height.py | 875 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 14 10:19:14 2019
@author: Sammu
"""
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},{'name': 'Mary', 'height': 150},
{'name': 'Isla', 'height': 20} ,{'name': 'Sam'}
]
#
#height_total = 0
#height_count = 0
#for person in people:
# if 'height' in person:
# height_total += person['height']
# height_count += 1
#
#if height_count > 0:
# average_height = height_total / height_count
#
# print (average_height)
list3=[]
def func(x):
if 'height' in x:
list3.append(x['height'])
list(map(func,people))
def add(x,y):
return x+y
from functools import reduce
avg=reduce(add,list3)/len(list3)
print(avg)
#list1=list(map([height_total += person['height'] height_count += 1 if 'height' in person for person in people]))
|
78c650860cfef1eb7306bcf91c6193ede054f8ec | lakshmi2812/dive_into_python | /late_ride.py | 611 | 3.53125 | 4 | def late_ride(n):
#coding and coding..
hrs = n//60
mins = n%60
hrs_str = str(hrs)
mins_str = str(mins)
hrs_list = list(hrs_str)
mins_list = list(mins_str)
time1 = 0
for i in hrs_list:
time1 = time1 + int(i)
time2 = 0
for j in mins_list:
time2 = time2 + int(j)
time_taken = time1 + time2
return time_taken
if __name__ == '__main__':
print("Basic Tests")
print(late_ride(240) == 4)
print(late_ride(808) == 14)
print(late_ride(1439) == 19)
print(late_ride(0) == 0)
print(late_ride(23) == 5)
print(late_ride(8) == 8) |
3b37213485d2bcf83d1812868992cfffe7c9364d | pedrolp85/Python_test_repo | /python_test_repo/test.py | 903 | 3.9375 | 4 | """def aprobados(alumnos):
decision = []
suspendido= False
for alumno in alumnos:
if alumno.alumno_aprobado():
decision.append(False)
else:
decision.append(True)
return(decision) """
class Alumno():
def __init__(self, nombre, nota, clase):
self._nombre = nombre
self.nota = nota
self.clase = clase
notas = [10, 9, 8, 7, 6, 5]
nombres= [ 'Luis', "Carlos", "Pedro", 'Alberto', "Victor"]
clases = [ 'a', 'b', 'a', 'a', 'b' ]
alumno = Alumno("Dani", "nota", "clase")
print(alumno._nombre)
"""
alumnos = []
for nombre, nota, clase in zip(nombres,notas,clases):
alumnos.append(Alumno(nombre, nota, clase))
"""
"""
alumnos = [ Alumno(nombre, nota, clase) for nombre, nota, clase in zip(nombres,notas,clases)]
#clase b, notas <7 suspendido, Alberto == suspendido
resultado= aprobado(alumnos)
print(resultado)"""
|
fcebe3b1f1549b702fd4a4fdb6fdd6d763ccea70 | anikoszo/code_sample | /random/palindrom.py | 235 | 3.984375 | 4 | class Palindrome:
@staticmethod
def is_palindrome(word):
if word.lower() == word.lower()[::-1]:
return "true"
else:
return "false"
word = input()
print(Palindrome.is_palindrome(word))
|
f88e893a8b0513a35a597e88a4c7d228b689dc57 | headsoft-mikhail/adpy_01 | /iterators_generators/main.py | 588 | 3.625 | 4 | import iterator
import hashlib
filename = 'countries.json'
countries_iterator = iterator.CountriesIterator(filename, start=0, stop=3)
filename = filename.replace('.json', '.txt')
with open(filename, 'w', encoding='utf-8') as write_file:
for item in countries_iterator:
write_file.writelines(item + '\n')
print(item)
def hash_generator(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
yield hashlib.md5(line.encode()).hexdigest()
for item in hash_generator(filename):
print(item)
|
570b39242fc618cea05c78f3079f8b65f59d6a8c | akhilavemuganti/HelloWorld | /CSV.py | 1,299 | 3.984375 | 4 | import csv
# Display all the Column Names
#
# with open("School_Nutrition.csv") as csv_file:
# csv_reader=csv.reader(csv_file)
# print("Column names are")
# i=next(csv_reader)
# print(i)
column_names=['ProgramYear', 'ReportType', 'CEID', 'CEName', 'CECounty', 'ESC']
# Display first 10 column names in a List
with open("School_Nutrition.csv",encoding='utf-8-sig') as file:
reader = csv.reader(file)
for i, row in reader:
print(row[i])
row_count = sum(1 for row in reader)
print(row_count)
# header=next(reader)
# print(reader)
# print(header)
# list1=[]
# for i in range(1,10):
# for row in header:
# list1.append(row)
# print(list1)
# # Display first 10 column names in a List
# with open("School_Nutrition.csv",encoding='utf-8-sig') as file:
# data=csv.reader(file,delimiter=',')
# header=next(data)
# list1=[]
# for i in range(1,10):
# for row in header:
# list1.append(row)
# print(list1)
import pandas
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }
|
e95e049464e634bdea48137a8d8a3f1568954041 | naamikaze/ejercicio-py-fundamentos-2021 | /Estructuras de control/ej1.py | 328 | 3.734375 | 4 | #EJERCICIO 1
num1 = int(input('Ingrese el primer nro: '))
num2 = int(input('Ingrese el segundo nro: '))
num3 = int(input('Ingrese el tercer nro: '))
num4 = int(input('Ingrese el cuarto nro: '))
num5 = int(input('Ingrese el quinto nro: '))
suma = num1+num2+num3+num4+num5
promedio = suma/5
print('El promedio es: ', promedio)
|
82e4e5e00f44ecc223f533ef3b26ef0420af77b0 | yueoka/python_exercises | /04_class/yueoka_ex04.py | 691 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import unittest
class Bot():
def __init__(self, owner_name):
self.owner_name=name
"""
WRITE YOUR CODE HERE
"""
def reply(self, call):
if call=="Hello":
print("Hi, I'm Bill.aaa")
elif call=="Hello my Boss!":
print("Hi, I'm Angy.")
"""
WRITE YOUR CODE HERE
"""
class TestBot(unittest.TestCase):
def test_bot_reply(self):
bot = Bot("Angy")
self.assertEqual("Hello", bot.reply("Hi, I'm Bill."))
self.assertEqual("Hello my Boss!", bot.reply("Hi, I'm Angy."))
if __name__=='--main--':
unittest.main()
aaa=Bot('Hello')
aaa.reply()
|
daff7c1704d372e01f67d404b57840a6128de5b3 | iamakkkhil/DailyCoding | /Day_16.py | 1,782 | 4 | 4 | """
DAY 16 : Different Operations on Matrices.
https://www.geeksforgeeks.org/different-operation-matrices/
QUESTION : Perform Addititon, Subtraction and Multiplication on given Matrices.
"""
def add(matrix1, matrix2, n1, m1, n2, m2):
# n = no of rows
# m = no of columns
add = []
if n1 == n2 and m1 == m2:
for i in range(n1):
inner = []
for j in range(m1):
sum_ = matrix1[i][j] + matrix2[i][j]
inner.append(sum_)
add.append(inner)
print(f'Addition is : {add}')
else:
print(f'Addition not possible')
def sub(matrix1, matrix2, n1, m1, n2, m2):
# n = no of rows
# m = no of columns
sub = []
if n1 == n2 and m1 == m2:
for i in range(n1):
inner = []
for j in range(m1):
sum_ = matrix1[i][j] - matrix2[i][j]
inner.append(sum_)
sub.append(inner)
print(f'Subtraction is : {sub}')
else:
print(f'Subtraction not possible')
def multiply(matrix1, matrix2, n1, m1, n2, m2):
# n = no of rows
# m = no of columns
multiply = []
if m1 == n2:
for i in range(len(matrix1)):
inner = []
sum = 0
for j in range(len(matrix2[0])):
sum = 0
for k in range(len(matrix2)):
sum += matrix1[i][k] * matrix2[k][j]
inner.append(sum)
multiply.append(inner)
print(f'Multiplication is : {multiply}')
else:
print(f'Multiplication not possible')
matrix1 = [[1,2], [3,4], [5,6]]
matrix2 = [[5,6,7], [7,8,9]]
add(matrix1, matrix2, 2,3,3,2)
|
d6743b2a0c42455c8347c3f87376bee074550fea | fengt/py-leetcode | /src/77. Combinations.py | 535 | 3.546875 | 4 | # Approach 1: Recursive
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k == 1:
return [[i] for i in range(1, n + 1)]
elif k == n:
return [[i for i in range(1, n + 1)]]
else:
rs = []
rs += self.combine(n - 1, k)
part = self.combine(n - 1, k - 1)
for ls in part:
ls.append(n)
rs += part
return rs
if __name__ == '__main__':
s = Solution()
print(s.combine(4, 2)) |
5eca61765f62ccb5cf66bbcb8f09b6907ae74cc6 | benLbishop/chess | /chess_game/pieces/queen.py | 644 | 3.96875 | 4 | """Module containing the Queen class."""
from .piece import Piece
class Queen(Piece):
"""class for the queen Piece."""
def can_reach_square(self, start, end):
"""checks to see if movement from start_square to end_square is possible
for a queen, pretending that no other pieces exist on the board.
Returns a boolean.
"""
row_dist = abs(start.row_idx - end.row_idx)
col_dist = abs(start.col_idx - end.col_idx)
is_valid_bishop_move = row_dist == col_dist
is_valid_rook_move = row_dist == 0 or col_dist == 0
return is_valid_bishop_move or is_valid_rook_move
|
0109fa9d727393cc6d1c737d4d99a3d7e103e718 | dashwaiss20/dashwaiss-python | /Unit2BLab/Unit2BLab.py | 677 | 3.9375 | 4 | numGrade=input('what grade did you get? ')
print(numGrade)
if int(numGrade)>=90:
print('yahoo you got an A!')
elif int(numGrade)>=80:
print('good you got a B')
elif int(numGrade)>=70:
print('Okay you got a C')
else:
print('you need to study more')
color=input('what is your favorite color? ')
print(color)
if (color)==('blue'):
print('blue like the sky')
elif (color)==('green'):
print('grenn like the forest')
elif (color)==('red'):
print('i love red even though i ama computor that is not capable of love')
elif (color)==('yellow'):
print('yuck i dont like yellow')
else:
print('i am a dumb computor--i dont know more than four colors')
|
902b948eed20696404843fd33044702771e79b6f | jaywin2u/practices | /obits.py | 200 | 3.875 | 4 | #!/usr/bin/env python
num = int(input('Input a number: '))
if num//10000:
print("5")
elif num//1000:
print("4")
elif num//100:
print("3")
elif num//10:
print("2")
else:
print("1")
|
52a34757efac717687a65ad2f47233d020521c77 | rifanarasheed/PythonDjangoLuminar | /FILEIO/filewordcount.py | 486 | 3.84375 | 4 | read = open("demo","r") # to read file
dict = {} # creating an empty dictionary for counting words
for line in read: # iterating each line
words = line.rstrip("\n").split(" ")
for wrd in words: # iterating each word of each line
if(wrd not in dict):
dict[wrd] = 1
else:
dict[wrd]+=1
# to print key and values present in the dictionary
for key,value in dict.items():
print(key,value)
|
8ea8b9a8a9b42bca81b2e850cedd495611c8de15 | heikalb/sql-cats-dogs | /explore_data.py | 2,393 | 4.375 | 4 | """
Perform data exploration on the database.
Heikal Badrulhisham, 2020 <heikal93@gmail.com>
"""
import sqlite3
def main():
# Create database
conn = sqlite3.connect('shelter_animals.db')
c = conn.cursor()
# Show sample data
c.execute("SELECT * FROM animals")
print('Showing sample data')
for row in c.fetchmany(10):
print(row)
print('\n')
# Show number of animals in shelter
c.execute("SELECT * FROM animals")
print('Number of animals in shelter: ', len(c.fetchall()))
c.execute("SELECT * FROM animals WHERE animal_type='Cat'")
print('Number of cats in shelter: ', len(c.fetchall()))
c.execute("SELECT * FROM animals WHERE animal_type='Dog'")
print('Number of dogs in shelter: ', len(c.fetchall()), '\n')
# Show cat outcomes
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Cat'")
num_cats = len(c.fetchall())
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Cat' AND outcome_type='Adoption'")
cats_adopted = len(c.fetchall())
print('Cats adopted: ', cats_adopted, f'{round(100*cats_adopted/num_cats, 2)}%')
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Cat' AND outcome_type<>'Adoption'")
cats_not_adopted = len(c.fetchall())
print('Cats not adopted: ', cats_not_adopted, f'{round(100*cats_not_adopted/num_cats, 2)}%')
# Show dog outcomes
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Dog'")
num_dogs = len(c.fetchall())
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Dog' AND outcome_type='Adoption'")
dogs_adopted = len(c.fetchall())
print('Dogs adopted: ', dogs_adopted, f'{round(100 * dogs_adopted / num_dogs, 2)}%')
c.execute("SELECT outcome_type FROM animals WHERE animal_type='Dog' AND outcome_type<>'Adoption'")
dogs_not_adopted = len(c.fetchall())
print('Dogs not adopted: ', dogs_not_adopted, f'{round(100 * dogs_not_adopted / num_dogs, 2)}%', '\n')
# Show unusual pets
c.execute("""
SELECT DISTINCT animal_type, breed FROM animals
WHERE animal_type<>'Cat' AND animal_type<>'Dog'
ORDER BY breed ASC
""")
unusual_animals = c.fetchall()
print('Unusual pets (not cat or dog):')
for animal in unusual_animals:
print(animal[1])
# Done
conn.commit()
conn.close()
if __name__ == '__main__':
main()
exit(0)
|
05de7da9a732f3954d21a44c9aaab60283b2d03b | fares-ds/Algorithms_and_data_structures | /02_stacks_queues_deques/queue.py | 572 | 4.0625 | 4 | class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def __str__(self):
return f"<Queue Object> : {[item for item in self.items]}"
queue = Queue()
print(queue.is_empty())
queue.enqueue("one")
queue.enqueue("two")
queue.enqueue("three")
print(queue)
print(f"Queue size : {queue.size()}")
queue.dequeue()
print(queue)
|
dcd4d901ba2b63a79f7c3eef5c9ae229c8eff108 | licornes-fluos/Robot-Wars | /old/main files/main3.1.py | 10,768 | 3.671875 | 4 | import pygame
import random
import time
pygame.init() #initialises the window
size = (800, 600) # width,height
screen = pygame.display.set_mode(size) #sets size of popup window
pygame.display.set_caption("Robot Wars") # sets title of game window
# Defining some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
PURPLE = (150, 0, 255)
open = True # Boolean for if window is open or closed
game_start = False # Boolean for if game has been started
clock = pygame.time.Clock() # Used to manage how fast the screen updates
clock.tick(60) # 60 fps limit
# ---------------------------- will need to be put in separate "player" module and imported here
class Player(pygame.sprite.Sprite):
'''
this class defines the first player
it uses 'Sprite' class in Pygame
'''
def __init__(self, colour, width, height):
'''
this is a constructor
in the parameters, there is the colour, the width and the height
that are used to define the sprite
'''
#calls the class (Sprite) constructor, allows the sprite to initialise
super().__init__()
# creates an image of the block
# fills it with a colour.
self.image = pygame.Surface([width, height])
self.image.fill(colour)
# to use an image instead of a colour:
#def __init__(self):
# calls the class (Sprite) constructor, allows the sprite to initialise
#super().__init__()
# loads the image
#self.image = pygame.image.load("player.png").convert()
# set the white background of the image to transparent colour
#self.image.set_colorkey(WHITE)
# fetches the rectangle object that has the dimensions (of the image)
# updates the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
# -------------------------
class Bombs(pygame.sprite.Sprite):
'''
J'ai repris le code de Rachel pour créer le sprite "Bombs".
Faudrait cacher les bombes au début parce qu'elles apparaissent dans le coin par défaut.
'''
def __init__(self, colour, width, height):
#calls the class (Bombs) constructor, allows the sprite to initialise
super().__init__()
# creates an image of the block
# fills it with a colour.
self.image = pygame.Surface([width, height])
self.image.fill(colour)
# updates the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
player1Up = bool() # boolean values will be true if player is going in associated direction, false if not.
player1Down = bool()
player1Left = bool()
player1Right = bool()
player1Attack = bool()
player2Up = bool()
player2Down = bool()
player2Left = bool()
player2Right = bool()
player2Attack = bool()
player1Keys = {"up":pygame.K_w,"down":pygame.K_s,"left":pygame.K_a,"right":pygame.K_d,"attack":pygame.K_c}
player2Keys = {"up":pygame.K_i,"down":pygame.K_k,"left":pygame.K_j,"right":pygame.K_l,"attack":pygame.K_n}
player1Facing = str() # string variables for direction players are facing, will be used to direct attacks.
player2Facing = str()
# creates a list of every sprite, only contains the player for now, but will eventually contain the bombs as well
all_sprites_list = pygame.sprite.Group()
# creates the players and their bomb which is and adds it to the list
player1 = Player(RED, 30, 30)
player2 = Player(BLUE, 30, 30)
bomb1 = Bombs(BLACK, 20, 20)
bomb2 = Bombs(BLACK, 20, 20)
all_sprites_list.add(player1,player2,bomb1,bomb2)
player1.rect.x = 250 #sets player 1 base position to x=230 y=290
player1.rect.y = 290
player2.rect.x = 550 #sets player 2 base position to x=550 y=290
player2.rect.y = 290
screen.fill(WHITE) # fills window with white
pygame.display.flip() # updates display window
print("Press SPACE to start.")
print("Press either CTRL to change keys.")
while open:
# main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
open = False
if event.type == pygame.KEYDOWN: # user presses a key
if not(game_start):
if event.key == pygame.K_SPACE: # pressing space starts the game
game_start = True
# this block can be made into a separate function that takes player key dictionary as argument
if event.key == pygame.K_RCTRL or event.key == pygame.K_LCTRL: # changing key settings on CTRL hit
print("changing player 1's keys.")
print("press ESC to skip a key.")
for i in player1Keys: # browses and prints each element in dictionary
next_key = False
print(i)
while not(next_key): # while loop that stops when user presses desired key
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key != pygame.K_ESCAPE: # if user didn't press ESCAPE, key is changed.
player1Keys[i]=event.key
#print(player1Keys[i]) # for debug; shows number of key added to dictionnary
next_key = True # ends while loop to start algorithm for next move
print("changing player 2's keys.")
print("press ESC to skip a key.")
for i in player2Keys: # same things for player 2
next_key = False
print(i)
while not(next_key):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key != pygame.K_ESCAPE:
player2Keys[i]=event.key
#print(player2Keys[i])
next_key = True
#print(player1Keys,player2Keys) # also for debug; prints both dictionnaries.
else:
if event.key == pygame.K_ESCAPE:
game_start = False
if event.key == player1Keys["up"]:
player1Up = True
if event.key == player2Keys["up"]:
player2Up = True
if event.key == player1Keys["down"]:
player1Down = True
if event.key == player2Keys["down"]:
player2Down = True
if event.key == player1Keys["left"]:
player1Left = True
if event.key == player2Keys["left"]:
player2Left = True
if event.key == player1Keys["right"]:
player1Right = True
if event.key == player2Keys["right"]:
player2Right = True
if event.key == player1Keys["attack"]:
player1Attack = True
if event.key == player2Keys["attack"]:
player2Attack = True
elif event.type == pygame.KEYUP: # user stops pressing a key
if game_start:
if event.key == player1Keys["up"]:
player1Up = False
if event.key == player2Keys["up"]:
player2Up = False
if event.key == player1Keys["down"]:
player1Down = False
if event.key == player2Keys["down"]:
player2Down = False
if event.key == player1Keys["left"]:
player1Left = False
if event.key == player2Keys["left"]:
player2Left = False
if event.key == player1Keys["right"]:
player1Right = False
if event.key == player2Keys["right"]:
player2Right = False
if event.key == player1Keys["attack"]:
player1Attack = False
if event.key == player2Keys["attack"]:
player2Attack = False
# elif event.type == pygame.MOUSEBUTTONDOWN: # user clicks
# print("User pressed a mouse button")
# --- Game logic
pygame.time.delay(30) # updates screen every 30 ms = lowers speed of players (lower = faster, higher = slower)
if player1Up and player1.rect.y >= 0 + 120 :
player1Facing = "up"
player1.rect.y -= 10
pygame.display.flip()
if player1Down and player1.rect.y <= size[1]-20 - 70:
player1Facing = "down"
player1.rect.y += 10
pygame.display.flip()
if player1Left and player1.rect.x >= 0 + 90:
player1Facing = "left"
player1.rect.x -= 10
pygame.display.flip()
if player1Right and player1.rect.x <= size[0]-20 - 90:
player1Facing = "right"
player1.rect.x += 10
pygame.display.flip()
if player1Attack :
bomb1.rect.x = player1.rect.x + 5 # le "+5" c'est juste pour centrer la bombe
bomb1.rect.y = player1.rect.y + 5
if player2Up and player2.rect.y >= 0 + 120 :
player2Facing = "up"
player2.rect.y -= 10
pygame.display.flip()
if player2Down and player2.rect.y <= size[1]-20 - 70:
player2Facing = "down"
player2.rect.y += 10
pygame.display.flip()
if player2Left and player2.rect.x >= 0 + 90:
player2Facing = "left"
player2.rect.x -= 10
pygame.display.flip()
if player2Right and player2.rect.x <= size[0]-20 - 90:
player2Facing = "right"
player2.rect.x += 10
pygame.display.flip()
if player2Attack :
bomb2.rect.x = player2.rect.x + 5
bomb2.rect.y = player2.rect.y + 5
# --- Drawing code
# gets the mouse position
# returns it as a list of two numbers
#pos = pygame.mouse.get_pos()
# fetches the x and y out of the list
# sets the player object to the mouse location
#player1.rect.x = pos[0]-10
#player1.rect.y = pos[1]-9
if game_start:
#loads background image
background_image = pygame.image.load("C:/Users/Aline/Documents/0 Docs/Devoirs/1ere/robotwars/assets/bg.png").convert()
screen.blit(background_image, [0, 0])
# draws all the spites
all_sprites_list.draw(screen)
pygame.display.flip()
#else:
# quits window once while loop is closed (open = False)
print("Quit")
pygame.quit()
|
0bb34c6d9971caca886ebad79a06d7b20f44f3bd | nzkim1234/Codeup_Python | /086.py | 101 | 3.5 | 4 | a = int(input())
s = 0
c = 1
while True:
s += c
c += 1
if s >= a:
break
print(s)
|
a9fc299165599aa32223e598aebf5006658a8e41 | xuhyang/algo-practice | /sequence/queue.py | 5,306 | 4.21875 | 4 | class Queue:
"""
22. Flatten List
https://www.lintcode.com/problem/flatten-list/description
Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers.
"""
def flatten(self, a):
ans, q = [], collections.deque(a)
while q:
e = q.popleft()
if isinstance(e, list):
for e2 in reversed(e):
q.appendleft(e2)
else:
ans.append(e)
return ans
"""
494. Implement Stack by Two Queues
https://www.lintcode.com/problem/implement-stack-by-two-queues/description
Implement a stack by two queues. The queue is first in first out (FIFO).
That means you can not directly pop the last element in a queue.
"""
class Stack:
"""
@param: x: An integer
@return: nothing
"""
def __init__(self):
self.q1, self.q2 = deque(), deque()
def push(self, x):
self.q1.append(x)
"""
@return: nothing
"""
def pop(self):
if self.isEmpty():
return None
for _ in range(len(self.q1) - 1):
self.q2.append(self.q1.popleft())
rslt = self.q1.popleft()
self.q1, self.q2 = self.q2, self.q1
return rslt
"""
@return: An integer
"""
def top(self):
return self.q1[-1]
"""
@return: True if the stack is empty
"""
def isEmpty(self):
return len(self.q1) <= 0
"""
540. Zigzag Iterator
https://www.lintcode.com/problem/zigzag-iterator/description
Given two 1d vectors, implement an iterator to return their elements alternately.
Input: v1 = [1, 2] and v2 = [3, 4, 5, 6] Output: [1, 3, 2, 4, 5, 6]
"""
class ZigzagIterator:
"""
@param: v1: A 1d vector
@param: v2: A 1d vector
"""
def __init__(self, v1, v2):
self.v = collections.deque([collections.deque(v) for v in (v1, v2) if v])
"""
@return: An integer
"""
def next(self):
nxt = self.v.popleft()
val = nxt.popleft()
if nxt:
self.v.append(nxt)
return val
"""
@return: True if has next
"""
def hasNext(self):
return self.v
"""
541. Zigzag Iterator II
https://www.lintcode.com/problem/zigzag-iterator-ii/description
Follow up Zigzag Iterator: What if you are given k 1d vectors? How well can your
code be extended to such cases? The "Zigzag" order is not clearly defined and
is ambiguous for k > 2 cases. If "Zigzag" does not look right to you,
replace "Zigzag" with "Cyclic".
"""
class ZigzagIterator2:
"""
@param: vecs: a list of 1d vectors
"""
def __init__(self, vecs):
self.v = collections.deque([collections.deque(v) for v in vecs if v])
"""
@return: An integer
"""
def next(self):
nxt = self.v.popleft()
val = nxt.popleft()
if nxt:
self.v.append(nxt)
return val
"""
@return: True if has next
"""
def hasNext(self):
return self.v
"""
577. Merge K Sorted Interval Lists
https://www.lintcode.com/problem/merge-k-sorted-interval-lists/description
Merge K sorted interval lists into one sorted interval list.
You need to merge overlapping intervals too.
Input: [
[(1,3),(4,7),(6,8)],
[(1,2),(9,10)]
] Output: [(1,3),(4,8),(9,10)]
Input: [
[(1,2),(5,6)],
[(3,4),(7,8)]
] Output: [(1,2),(3,4),(5,6),(7,8)]
其他解法: heap, dvcq
"""
def mergeKSortedIntervalLists(self, itrvls):
q = collections.deque(itrvls)
while len(q) > 1:
l, r = q.popleft(), q.popleft()
ans, e, i, j = [], None, 0, 0
while i < len(l) and j < len(r):
if l[i].start < r[j].start:
e, i = l[i], i + 1
else:
e, j = r[j], j + 1
self.append(ans, e)
while i < len(l):
self.append(ans, l[i])
i += 1
while j < len(r):
self.append(ans, r[j])
j += 1
q.append(ans)
return q.popleft()
def append(self, ans, e):
if not ans or ans[-1].end < e.start:
ans.append(e)
else:
ans[-1].end = max(ans[-1].end, e.end)
"""
104. Merge K Sorted Lists
https://www.lintcode.com/problem/merge-k-sorted-lists/description
Merge k sorted linked lists and return it as one sorted list.
Example Input: [2->6->null,5->null,7->null] Output: 2->5->6->7->null
#其他解法: heap, dvcq_merge
"""
#两两归并
def mergeKLists(self, l):
q = collections.deque(l)
while len(q) > 1:
q.append(self.merge(q.popleft(), q.popleft()))
return q[0]
def merge(self, p1, p2):
d = p = ListNode(sys.maxsize)
while p1 and p2:
if p1.val <= p2.val:
p.next = p1
p1 = p1.next
else:
p.next = p2
p2 = p2.next
p = p.next
p.next = p1 or p2
return d.next
|
910efd6c56ff43635e4efaa034a3c4fe6061e297 | Antohnio123/Python | /Practice/n.emelin/lesson9/1.py | 1,839 | 3.546875 | 4 | import datetime
import threading
import multiprocessing
class Timer:
t1=0
def __enter__(self):
self.t1=datetime.datetime.now()
def __exit__(self, exc_type, exc_val, exc_tb):
t2 = datetime.datetime.now()
print("Время выполнения = "+str(t2-self.t1))
def find_primes(start,end): #### применяем решето Эратосфера
numbers = list(range(start, end + 1))
for number in numbers:
if number != 0:
for candidate in range(start * number, end + 1, number):
numbers[candidate - start] = 0
a=(list(filter(lambda x: x != 0, numbers)))
return f"{a}"
def prosto_potoki():
print("Последовательно")
with Timer():
find_primes(3,10000)
find_primes(10001,20000)
find_primes(20001,30000)
def miltipocessing_potoki ():
if __name__ == '__main__':
print("Мультипроцесс")
with Timer():
t1 = multiprocessing.Process(target=find_primes, args=(3, 10000))
t2 = multiprocessing.Process(target=find_primes, args=(10001, 20000))
t3 = multiprocessing.Process(target=find_primes, args=(20001, 30000))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
def Thread_potoki ():
print("Многопоточно")
with Timer():
t1 = threading.Thread(target=find_primes, args=(3, 10000))
t2 = threading.Thread(target=find_primes, args=(10001, 20000))
t3 = threading.Thread(target=find_primes, args=(20001, 30000))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
if __name__ == '__main__':
prosto_potoki()
miltipocessing_potoki()
Thread_potoki() |
8a4bb51922f2adcca558e3f43f0360c7a3534a91 | Draster51/Py_basics | /listas.py | 1,134 | 4.03125 | 4 | my_list = [1,2,3] ##Definir una lista
print(my_list[0]) ##Llamar un elemento
print(my_list[1:]) ##Llamar una serie de elementos segun posicion
my_list.append(4) ##Agregar un elemento al final de la lista
print(my_list) ##imprimir toda la lista
my_list[0] = 'a' ##Modificar la lista
print(my_list)
my_list.pop() ##Eliminar el ultimo valor de la lista
print(my_list)
for element in my_list:
print(element)
list_a = [1,2,3]
b = list_a
print(id(list_a)) ##Ver que una lista y otra es peligroso pues ahora 2 variables apuntan al
print(id(b)) ##mismo espacio de memoria
c = [1,2,3]
d = c
e = list(c) ##CLonar una lista de esta forma evita ver dos variables apuntando al mismo objeto
f = c[::] ##Otra forma de clonar la lista c sin apuntar al mismo objeto de memoria
g = list(range(0, 100, 1))
doble = [i * 2 for i in g] ##multiplica por dos todos los elementos i de la lista g
print (doble)
pares = [i for i in g if i % 2 == 0] ##Solo saca los pares de la lista g con la funcion % modulo
print(pares)
|
4a304aec2d376a60798d79cf43f3940e47849980 | Preetpalkaur3701/python-programmes | /mycalendar.py | 389 | 4.40625 | 4 | import calendar
#(calendar.textcalendar),this means that we want written calendar where as calendar sunday means that we want our calendar to start from sunday.
c = calendar.TextCalendar(calendar.SUNDAY)
# we can change the year and month as we want by giving required information.
year = input("Enter the year")
month = input("Enter the month")
str= c.formatmonth(year,month)
print str
|
14568370dd895d5119bb3aacbf5a2c0c8fd3f38b | AlexLemesPiva/Programas | /funciones_con_argumentos2.py | 450 | 3.921875 | 4 | '''
script que retorne conversión de horas a minutos e segundos. deve retornar o equivalente em segndos e segundos
'''
def hor_segundo(horas):
return h * 3600
def hor_minuto(minuto):
return h * 60
print('Conversor de Horas a minutos e segundos')
h = int(input('Ingrese a quantidade de horas: '))
print(f'El equivalente de {h} horas en segundos es: {hor_segundo(h)}')
print(f'El equivalente de {h} horas en minutos es: {hor_minuto(h)}')
|
d44a7617911c2dd65a2cdf91ae7473596c311c92 | JScarlet/leetcode | /rough_solution/506_find_relative_ranks.py | 821 | 3.578125 | 4 | class Solution:
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
nums_dict = {}
sorted_nums = sorted(nums, reverse=True)
for i in range(0, len(sorted_nums)):
nums_dict[sorted_nums[i]] = i+1
result = []
for i in range(0, len(nums)):
score = nums_dict[nums[i]]
if score == 1:
result.append('Gold Medal')
elif score == 2:
result.append('Silver Medal')
elif score == 3:
result.append('Bronze Medal')
else:
result.append(str(score))
return result
if __name__ == "__main__":
solution = Solution()
nums = [5, 4, 3, 2, 1]
print(solution.findRelativeRanks(nums)) |
d665317db1b78e8e8849418ec149ea2676b1116b | cococonuts/leetcode | /154_Find_Minimum_in_Rotated_Sorted_Array_II.py | 1,513 | 3.9375 | 4 | """
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
"""
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0;
end = len(nums) - 1
if len(nums) == 0:
return -1;
if len(nums) == 1:
return nums[0]
def helper(nums, start, end):
if start == end:
return nums[start]
while start < end:
mid = (start + end ) / 2
s_num = nums[start]
e_num = nums[end]
m_num = nums[mid]
if start + 1 == end:
return min(s_num, e_num)
if s_num < e_num:
return s_num
if s_num == e_num:
if m_num == e_num:
return min(helper(nums, mid, end), helper(nums, start, mid))
if m_num >= s_num:
start = mid
else:
end = mid
return helper(nums, start, end)
|
509c645ee145bc057f4b186d68067585c4fce261 | sakuya13/Study | /python/py/exercises/6.6_displayPattern.py | 322 | 4.0625 | 4 | def displayPattern(n):
for i in range(1, n + 1):
for j in range(n, 0, -1):
if j > i:
print(format(" ", "3s"), end="")
else:
print(format(j, "3d"), end="")
print()
def main():
n = int(input("Enter a number: "))
displayPattern(n)
main()
|
1f247c0a6af0d37ae568c4e0d349ec2a09166e5a | DoMinhTri/OpenCV-Python | /opencv-python-examples-master/11_webcam_features.py | 677 | 3.546875 | 4 | """
Example:
Detect corners from a webcam video stream.
"""
import cv2
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
raise IOError("Cannot open webcam")
while True:
ret, img = cap.read()
if not ret:
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(
gray, maxCorners=30, qualityLevel=0.05, minDistance=25)
red_color = (0, 0, 255)
for item in corners:
x, y = item[0]
cv2.circle(img, (x, y), 6, red_color, -1)
cv2.imshow("Input", img)
# Wait press ESC
c = cv2.waitKey(1)
if c == 27:
break
cap.release()
|
0666b07659198d35cae96f9b55ca00825ba23edb | eroneko/yihleego | /Python/listAndTuple.py | 1,768 | 4.1875 | 4 | classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
print('classmate length:',len(classmates))
print(classmates[0])
print(classmates[1])
print(classmates[2])
#索引超出了范围
#print(classmates[3])
# -1做索引 直接获取最后一个元素
print(classmates[-1])
#以此类推,可以获取倒数第2个、倒数第3个
print(classmates[-2])
print(classmates[-3])
#list是一个可变的有序表,所以,可以往list中追加元素到末尾:
classmates.append('Adam')
print(classmates)
#也可以把元素插入到指定的位置,比如索引号为0的位置:
classmates.insert(0, 'Yihleego')
print(classmates)
#要删除list末尾的元素,用pop()方法:
classmates.pop()
print(classmates)
#要删除指定位置的元素,用pop(i)方法,其中i是索引位置:
classmates.pop(1)
print(classmates)
#要把某个元素替换成别的元素,可以直接赋值给对应的索引位置:
classmates[1] = 'Sarah'
print(classmates)
#list里面的元素的数据类型也可以不同,比如:
L = ['Apple', 123, True]
print(L)
#list元素也可以是另一个list,比如:
s = ['python', 'java', ['asp', 'php'], 'scheme']
print(len(s))
print(s[2][1])
#p = ['asp', 'php']
#s = ['python', 'java', p, 'scheme']
#另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改,比如同样是列出同学的名
classmatesTuple = ('Michael', 'Bob', 'Tracy')
#只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:
t = (1,)
#请用索引取出下面list的指定元素:
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[2][-1])
input() |
ca6da4ae7b0f8e28f743ae9d404089149ada6492 | tazuddinleton/basic_algorithms_and_data_structures | /hackerrank/interview_preparation_kit/arrays/left_rotation.py | 218 | 3.75 | 4 | def rotLeft(a, d):
for i in range(0, d):
a.append(a.pop(0))
return a
print(rotLeft([1, 2, 3, 4, 5], 2))
print(rotLeft([33, 47, 70, 37, 8, 53, 13,
93, 71, 72, 51, 100, 60, 87, 97], 13))
|
29a2d6e1f86c891f4a000ad810ad1919f9088e36 | whldk/study_py | /day02/tryc.py | 1,345 | 3.65625 | 4 | # coding:utf-8
"""
常用的异常类型集合
:exception 通用异常类型(基类)
:ZeroDivisionError 不能为0
AttributeError 对象没有这个属性
IOError 输入输出
自定义抛出异常函数 --raise
用法:
raise 异常类型(msg)
"""
def test():
try:
print("upupup")
except (ZeroDivisionError, NameError) as e:
print(e)
except Exception as e:
print(e)
except (AttributeError, ValueError, IOError,KeyError, TypeError) as e:
print(e)
finally:
print('eee')
def test1(num):
if num == 100:
raise ValueError('num not eq 100')
return num
ras = test1(50)
def test2(num):
try:
return test1(num)
except ValueError as e:
return e
re = test2(100)
print(re)
class NumLimitError(Exception):
def __init__(self, msg):
self.msg = msg
class NameLimitError(Exception):
def __init__(self, msg):
self.msg = msg
def test5(name):
if name == 'ldk':
raise NameLimitError('ldk no no')
return name
def test6(num):
if num > 100:
raise NumLimitError('num > 100')
return num
print('--------------')
try:
test5('ldk')
except NameLimitError as e:
print(e)
try:
test6(101)
except NumLimitError as e:
print(e)
test6(100) |
25d4b7055d381cc3d4c7c7456013d976290caabf | Twest19/prg105 | /6-2_sales_totals.py | 1,058 | 4.25 | 4 | """
Open the file sales_totals download in read mode
Read in all the lines using a loop
Strip the newline symbol and convert each line to a float
Add each number to the running total
Count the number of lines
Format and display each number
Outside of the loop format and display the total, the count, and the average
Do this in functions
"""
# create a main function to do the reading of the lines and printing of the total, average, entries
def main():
sales_file = open('sales_totals-1.txt', 'r')
count = 0
total = 0
line = sales_file.readline()
while line != '':
print(f"{float(line):,.2f}")
total += float(line)
line = sales_file.readline()
count += 1
sales_file.close()
avg = average(total, count)
print(f"Total: {total:,.2f}")
print(f"Number of entries: {count}")
print(f"Average: {avg:,.2f}")
# created an average function to find the average
def average(x, y):
avg = x / y
return avg
main()
|
e04ee1520cd65cab03de8c6fa54585c962181eb5 | Chuckboliver/Data-structure-and-Algorithms | /lab06/lab6_g_4.py | 893 | 3.546875 | 4 | def display(A,B,C,i ):
if i < 0:
return
poleA = list(*filter(lambda x:x[0] == 'A',(A,B,C)))[1]
poleB = list(*filter(lambda x:x[0] == 'B',(A,B,C)))[1]
poleC = list(*filter(lambda x:x[0] == 'C',(A,B,C)))[1]
print(poleA[i] if i < len(poleA) else "|",end=" ")
print(poleB[i] if i < len(poleB) else "|",end=" ")
print(poleC[i] if i < len(poleC) else "|")
display(A,B,C,i-1)
def toh(n,fp,tp,axp,maxn):
if n == 1:
tp[1].append(fp[1].pop())
print(f"move 1 from {fp[0]} to {tp[0]}")
display(fp,tp,axp,maxn)
return
toh(n-1,fp,axp,tp,maxn)
tp[1].append(fp[1].pop())
print(f"move {n} from {fp[0]} to {tp[0]}")
display(fp,tp,axp,maxn)
toh(n-1,axp,tp,fp,maxn)
n = int(input("Enter Input : "))
fp,tp,axp = ('A',list(reversed(range(1,n+1)))),('C',list()),('B',list())
display(fp,tp,axp,n)
toh(n,fp,tp,axp,n) |
68234e41260fb6fa337206cfb879eadc77bcc540 | mathankrish/Infy-Programs | /InfyTq Basic Programming/Practice Programs/Level 3/Pro 45.py | 703 | 3.8125 | 4 | # PF-Prac-45
def longest_common_substring(string1, string2):
# start writing your code here
l1 = [string2[i2:j2] for i2 in range(len(string2)) for j2 in range(i2+1, len(string2)+1)]
l2 = [string1[i1:j1] for i1 in range(len(string1)) for j1 in range(i1+1, len(string1)+1)]
l3, l4 = sorted(l2, key=len), sorted(l1, key=len)
l5 = [i for i in l3 if i in l4]
return l5[-1]
output = longest_common_substring("discatenation", "concatenation")
print("The longest overlap of characters between string1 and string2:", output)
output1 = longest_common_substring("assured", "measured")
print("The longest overlap of characters between string1 and string2:", output1) |
68f0ee983c2a48cd5154e297cc6be36a20d21e68 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2189/60692/266383.py | 470 | 3.5625 | 4 | def square(m):
str_m = str(m)
res = 0
for i in str_m:
res += int(i) ** 2
return res
def ishappy(x):
x = square(x)
list1 = []
while x != 1:
if x not in list1:
list1.append(x)
else:
return False
x = square(x)
return True
num = int(input())
res = []
for i in range(num):
n = int(input()) + 1
while not ishappy(n):
n += 1
res.append(n)
for i in res:
print(i) |
ae23deeed78740ff742b3c59f4b39cde697607b5 | porrametict/learningSpace | /PythonWithChulalondkorn/string_method2.py | 545 | 3.640625 | 4 | #strip / trim
def strio_demoo():
s = "Thailand"
t = " Thailand "
u = t.strip()#del spaecbar before str and After str
print(s==t)
print(s==u)
def demo_isdigit(p):
total = 0
for c in p :
#print(c)
if c.isdigit():
# print(c)
total += int(c)
return total
def removenondigit(s):
t = ""
for c in s:
if c.isdigit():
t+=c
return t
# plate = "1mf 4567"
# print(demo_isdigit(plate))
card_id = "(444)-123-15-4564 51"
print(removenondigit(card_id)) |
69c383f8f357ff277ad7903a45c7f876509f6b9b | mattkosi/small-projects | /games/hangman/game.py | 1,203 | 3.671875 | 4 | from hangmantextart import hangmanPics, wordToBlanks
import random
selection = random.choice(list(open('phrases.txt')))
lowerCase = selection.lower()
blanks = list(wordToBlanks(selection))
i = 0
alreadyGuessed = []
while(True):
if '-' not in blanks:
print('\n' + "".join(blanks).capitalize() + '\n' + 'YOU WIN!')
break
print(hangmanPics[i] + '\n\n' + "".join(blanks) + '\n')
guess = input("Guess your letter: ")
formattedGuess = guess.lower()
if (len(formattedGuess) != 1 or not formattedGuess.isalpha()):
print('\n' + 'INVALID GUESS')
continue
if formattedGuess in alreadyGuessed:
print('\n' + "YOU'VE ALREADY GUESSED THAT LETTER")
continue
if formattedGuess in lowerCase:
alreadyGuessed.append(formattedGuess)
occurances = []
for x in range(len(lowerCase)):
if formattedGuess == lowerCase[x]:
occurances.append(x)
for y in occurances:
blanks[y] = formattedGuess
else:
i += 1
if (i == (len(hangmanPics) - 1)):
print(hangmanPics[i] + '\n\n' + 'GAME OVER! The phrase was:')
print('\n' + selection)
break
#for x in range(0, len(hangmanPics)):
# print(hangmanPics[x]) |
90a6e95832b2614542e1a7c38b05e367914efe6b | frsilent/challenges | /frequency_count.py | 744 | 4.1875 | 4 | #Given N terms, your task is to find the k most frequent terms from given N terms.
#Output format :
#Print the k most frequent terms in descending order of their frequency. If two terms have same frequency print them in lexicographical order.
f = open('test_data/ft_input01.txt')
terms = []
for x in range(min(int(f.readline()), 300000)):
terms.append(f.readline().strip())
terms_dict = {}
for item in terms:
terms_dict[item] = terms_dict.get(item, 0) + 1
#TODO: Need to find a way to sort these so that it's sorted primarily by frequency & then alphabetical
terms = sorted(terms_dict.items(), key=lambda item: item[1], reverse=True)
terms.sort(key=lambda tup: tup[0])
for term in range(int(f.readline())):
print terms[term][0]
|
e6b14d5459d2fc17e3fb8cedc2a787b3e2aa4fcd | texttest/storytext-selftest | /swing/text_field/target_ui.py | 1,077 | 3.515625 | 4 | from java.awt import BorderLayout
from javax.swing import JFrame, JLabel, JPanel, JButton, JTextField, JSeparator
class MyTextFieldSubClass(JTextField):
pass
class TextFieldApp:
def make_ui(self):
frame = JFrame("Text field demo")
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
frame.setLayout(BorderLayout())
frame.setSize(300, 200)
button = JButton("Do nothing")
panel2 = JPanel(BorderLayout())
textLabel = JLabel("Some Text: ")
textField = MyTextFieldSubClass()
panel2.add(textLabel, BorderLayout.WEST)
panel2.add(textField, BorderLayout.CENTER)
panel = JPanel(BorderLayout())
panel.add(button)
frame.getContentPane().add(panel, BorderLayout.NORTH)
frame.getContentPane().add(JSeparator(), BorderLayout.CENTER)
frame.getContentPane().add(panel2, BorderLayout.SOUTH)
#frame.pack()
frame.setVisible(True)
@staticmethod
def main():
app = TextFieldApp()
app.make_ui()
TextFieldApp.main()
|
706acc49291a872862e9653b58f965a8a62c45a3 | litichevskiydv/PythonStudies | /functions_composition.py | 457 | 3.53125 | 4 | def f(x):
return x + 2
def g(x):
return x - 3
def compose(f, g):
return lambda x: f(g(x))
class Composable(object):
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
def __and__(self, other):
return Composable(compose(self.fn, other))
print((Composable(lambda x: x * 2) & f & g & g)(17) == 26)
print(compose(f, g)(3) == 2)
print(f(g(3)) == 2) |
a7d5ae6dbb20291f9437460f0fc6e1e3bbeeea9a | aroraakshit/coding_prep | /valid_parentheses.py | 1,042 | 3.703125 | 4 | class Solution: # 36ms
def isValid(self, s: str) -> bool:
stack = []
closing = [']','}',')']
opening = ['[','{','(']
for i in s:
if i in closing:
if stack != [] and opening[closing.index(i)] == stack[-1]:
stack.pop()
else:
return False
elif i in opening:
stack.append(i)
else:
return False
# print(stack)
if stack == []:
return True
return False
# 16ms, Credits - LeetCode
class Solution:
def isValid(self, s: str) -> bool:
stack = []
symbols = {")": "(", "}": "{", "]": "["}
for c in s:
if c in symbols:
top = stack.pop() if stack else '#'
if symbols[c] != top:
return False
else:
stack.append(c)
return not stack |
9229dbf2de5856bd02cf222209ca96bf573722e4 | shifty049/LeetCode_Practice | /Medium/429. N-ary Tree Level Order Traversal.py | 839 | 3.734375 | 4 | class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return root
queue = [root]
level = 0
level_list = []
while queue:
level_list.append([])
next_queue = []
for node in queue:
level_list[level].append(node.val)
for child in node.children:
if child:
next_queue.append(child)
queue = next_queue
level+=1
return level_list
#Runtime: 52 ms, faster than 63.70% of Python3 online submissions for N-ary Tree Level Order Traversal.
#Memory Usage: 15.9 MB, less than 17.30% of Python3 online submissions for N-ary Tree Level Order Traversal.
#Fu-Ti, Hsu
#shifty049@gmail.com |
ff6a9a35482f6531760115c159718283591b1309 | Rohithyeravothula/Artificial-Intelligence-Projects | /lizards_java/scripts/generator.py | 1,089 | 3.640625 | 4 | import random
#max board size
n = 10
#max num of trees
t = 3
methods = ["DFS", "BFS", "SA"]
class Node(object):
def __init__(self, board, size, lizCount, methodName):
self.board = board
self.size = size
self.lizCount = lizCount
self.methodName = methodName
def write_board_to_file(node):
l = len(node.board)
w = ""
for i in range(0, l):
s = "".join(str(x) for x in node.board[i])
w += s+"\n"
w = w[:-1]
f=open("input.txt", 'w')
f.write(node.methodName+"\n")
f.write(node.size+"\n")
f.write(node.lizCount+"\n")
f.write(w)
f.close()
def get_lizard(n, l):
r = random.randint(1, n+l)
t = random.randint(0, 1)
return [r, n][t]
def generate():
cur_n = random.randint(1, n)
cur_t = random.randint(1, cur_n)
cur_liz = get_lizard(cur_n, cur_t)
methodName = methods[random.randint(0, 2)]
board = []
for i in range(0, cur_n):
d=[0]*cur_n
board.append(d)
i=0
while i<t:
x,y=(random.randint(0, cur_n-1), random.randint(0, cur_n-1))
board[x][y] = 2
i+=1
cur_node = Node(board, str(cur_n), str(cur_liz), methodName)
write_board_to_file(cur_node)
|
55990bcfd4e67c4fb3162f619405a81bfa734e93 | gspeiliu/MITx6001x | /statements/practice.py | 1,284 | 4.0625 | 4 | low = 0
high = 100
half = 50
print 'Please think of a number between 0 and 100!'
print 'Is your secret number 50?'
print "Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter 'c'\
to indicate I guessed correctly." ,
charin = str(raw_input())
while True:
if charin == 'h':
high = half
half = (low + high) / 2
print 'Is your secret number ' + str(half)
print "Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter 'c'\
to indicate I guessed correctly." ,
elif charin == 'l':
low = half
half = (low + high) / 2
print 'Is your secret number ' + str(half)
print "Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter 'c'\
to indicate I guessed correctly." ,
elif charin == 'c':
print 'Game over.',
print 'Your secret number was: ' + str(half)
break;
else:
print 'Sorry, I did not understand your input.'
print 'Is your secret number ' + str(half) + '?'
print "Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter 'c'\
to indicate I guessed correctly." ,
charin = str(raw_input()) |
abc14400c14af8721116249f29b3ec427aa4b95c | mglaros/Python-Data-Structures-and-Algorithms-Udemy-Course | /avl.py | 3,037 | 3.84375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.height = 0
self.leftChild = None
self.rightChild = None
class AVL:
def __init__(self):
self.root = None
def insert(self, data):
self.root = self.insertNode(data, self.root)
def insertNode(self, data, node):
if not node:
return Node(data)
else:
if data < node.data:
node.leftChild = self.insertNode(data, node.leftChild)
else:
node.rightChild = self.insertNode(data, node.rightChild)
node.height = max(self.calcHeight(node.leftChild), self.calcHeight(node.rightChild)) + 1
return self.settleViolation(data, node)
def settleViolation(self, data, node):
balance = self.calcBalance(node)
#case 1 -> left left heavy --> single right rotation
if balance > 1 and data < node.leftChild.data:
print("Left left heavy situation...")
return self.rotateRight(node)
#case 2 -> right right heavy --> single left rotation
if balance < -1 and data > node.rightChild.data:
print("Right right heavy situation...")
return self.rotateLeft(node)
if balance > 1 and data > node.leftChild.data:
print("Left right heavy situation...")
node.leftChild = self.rotateLeft(node.leftChild)
return self.rotateRight(node)
if balance < -1 and data < node.rightChild.data:
print("Right left heavy situation...")
node.rightChild = self.rotateRight(node.rightChild)
return self.rotateLeft(node)
return node
def calcHeight(self, node):
if not node:
return -1
return node.height
#if it returns value > 1, then it is a left heavy tree --> right rotation
#if it return value < -1, then it is a right heavy tree --> left rotation
def calcBalance(self, node):
if not node:
return 0
return self.calcHeight(node.leftChild) - self.calcHeight(node.rightChild)
def traverse(self):
if self.root:
self.traverseInOrder(self.root)
def traverseInOrder(self, node):
if node.leftChild:
self.traverseInOrder(node.leftChild)
print("%s " %node.data)
if node.rightChild:
self.traverseInOrder(node.rightChild)
def rotateRight(self, node):
print("Rotating to the right on node", node.data)
tempLeftChild = node.leftChild
t = tempLeftChild.rightChild
tempLeftChild.rightChild = node
node.leftChild = t
node.height = max(self.calcHeight(node.leftChild), self.calcHeight(node.rightChild)) + 1
tempLeftChild.height = max(self.calcHeight(tempLeftChild.leftChild), self.calcHeight(tempLeftChild.rightChild)) + 1
return tempLeftChild
def rotateLeft(self, node):
print("Rotating to the left on node", node.data)
tempRightChild = node.rightChild
t = tempRightChild.leftChild
tempRightChild.leftChild = node
node.rightChild = t
node.height = max(self.calcHeight(node.leftChild), self.calcHeight(node.rightChild)) + 1
tempRightChild.height = max(self.calcHeight(tempRightChild.leftChild), self.calcHeight(tempRightChild.rightChild)) + 1
return tempRightChild
#testing our avl tree
avl = AVL()
avl.insert(6)
avl.insert(4)
avl.insert(5)
avl.traverse()
|
777c4775dcf9b8ab708274816ed2733861ed8147 | j1hwang/doodles | /py-data-structure/binary-search.py | 533 | 4.03125 | 4 | def binary_search(input_array, value):
first = 0
last = len(input_array)-1
found = -1
while first<=last:
mid = (first + last)//2
if input_array[mid] == value:
return mid
else:
if value < input_array[mid]:
last = mid-1
else:
first = mid+1
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print binary_search(test_list, test_val1)
print binary_search(test_list, test_val2)
|
3a2f25b9a3edb79d439852cf7c5739261a4dae65 | victorsemenov1980/MIT_6.0001_6.0002 | /2/PS1/temp.py | 2,997 | 3.890625 | 4 | # #!/usr/bin/env python3
# # -*- coding: utf-8 -*-
# """
# Created on Mon Apr 20 12:53:58 2020
# @author: user
# """
# from ps1_partition import get_partitions
# import time
# import timeit
# cows={}
# with open('ps1_cow_data.txt','r') as file:
# for row in file:
# text=row.split(sep=',')
# cows.update({text[0]:int(text[1].strip('\n'))})
# # print (cows)
# cows_sorted={k: v for k, v in sorted(cows.items(), key=lambda item: item[1], reverse=True)}
# # print(cows_sorted)
# # for k,v in cows_sorted:
# # print(k)
# def greedy_cow_transport(cows,limit=10):
# """
# Uses a greedy heuristic to determine an allocation of cows that attempts to
# minimize the number of spaceship trips needed to transport all the cows. The
# returned allocation of cows may or may not be optimal.
# The greedy heuristic should follow the following method:
# 1. As long as the current trip can fit another cow, add the largest cow that will fit
# to the trip
# 2. Once the trip is full, begin a new trip to transport the remaining cows
# Does not mutate the given dictionary of cows.
# Parameters:
# cows - a dictionary of name (string), weight (int) pairs
# limit - weight limit of the spaceship (an int)
# Returns:
# A list of lists, with each inner list containing the names of cows
# transported on a particular trip and the overall list containing all the
# trips
# """
# cows_sorted={k: v for k, v in sorted(cows.items(), key=lambda item: item[1], reverse=True)}
# trips2=[]
# total_weight=0
# for i in range(len(cows_sorted)):
# trips=[]
# total_weight=0
# for k,v in cows_sorted.items():
# if total_weight+cows_sorted[k]<=limit:
# trips.append(k)
# total_weight+=cows_sorted[k]
# cows_sorted[k]=limit+10
# if trips!=[]:
# trips2.append(trips)
# print(trips2)
# def brute_force_cow_transport(cows,limit=10):
# trips2=[]
# for partition in get_partitions(cows):
# trips=[]
# total_weight=0
# for i in partition:
# for k in i:
# if k in cows:
# total_weight+=cows[k]
# if total_weight<=limit:
# trips.append(i)
# total_weight=0
# if len(trips)!=len(partition):
# trips=[]
# if trips!=[]:
# trips2.append(trips)
# trips2.sort(key=len)
# print(trips2[0])
# # greedy_cow_transport(cows)
# # brute_force_cow_transport(cows)
# start = time.time()
# greedy_cow_transport(cows)
# end = time.time()
# print (end,start)
# x1=10
# x2=5
# x3=1
# x=25
# n=99
# y=n//x
# print(y)
# y2=(n-x*y)//x1
# print(y2)
# y3=(n-x*y-x1*y2)//x2
# print(y3)
# y3=(n-x*y-x1*y2)//x3
# print(y3)
x = (1, 5, 10, 25)
for i in range(len(x) - 1, -1, -1):
print(x[i])
|
22dcdb4ad7bcab03891102c9318d7035de806924 | vipulwairagade/IVP | /Assignment 2/Histogram/hist.py | 972 | 3.5625 | 4 | import sys # For taking argument through terminal
import numpy as np
import matplotlib.pyplot as plt # Plotting of Histogram
import cv2
# Taking Argument Through Terminal and Validating
if len(sys.argv)>1:
fname = sys.argv[1]
else :
print("usage : python hist.py <image_file>")
im = cv2.imread(fname)
if im is None:
print('Failed to load image file:', fname)
sys.exit(1)
def generateHistogram(im):
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # Coverting into gray image
hist = cv2.calcHist([gray],[0],None,[256],[0,256]) # cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
plt.plot(hist) # Plotting using matplotlib
plt.xlabel('Pixel Values')
plt.ylabel('No. of Pixels')
plt.title('Histogram of Image')
plt.grid(True)
plt.show() # Displaying histogram
cv2.imshow('image',im) # Display original image
generateHistogram(im) # Display loaded image
|
54b3176e700e4202b846a5c297b55f7565b89ba1 | nerdpollyanna/Natural_language_processing_book_100_knock | /answer10.py | 924 | 3.90625 | 4 | #hightemp.txtは,日本の最高気温の記録を「都道府県」「地点」「℃」「日」のタブ区切り形式で格納したファイルである.
# 以下の処理を行うプログラムを作成し,hightemp.txtを入力ファイルとして実行せよ.
# さらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ.
#10. 行数のカウント
#行数をカウントせよ.確認にはwcコマンドを用いよ.
#coding:utf-8
import os.path as path
def count_number(filename):
#入力はファイル名
#出力は、行数のcount数
return_count=0
if path.exists(filename):
for i in open(filename, "r",encoding="utf-8"):
print(i)
return_count=+return_count+1
else:
print("can't found a file")
return_count=-1
return return_count
print(count_number("hightemp.txt")) |
9bc31ad18d550e8f302026bf46d54be55633eea6 | Soham2020/Python-basic | /lists/printDuplicate.py | 89 | 3.984375 | 4 | x = [1,2,3,5,3,2]
y = []
for a in x:
if not a in y:
y.append(a)
print(a) |
a279162d261e204b05d50a490fd89aa08340a627 | Netra-Bahadur-khatri/Python_Geeks_For_Geeks | /GFG_06_Sets.py | 389 | 3.984375 | 4 |
"""
Set is an undordered collection of data type that is iterable
mutable and has no duplicate elements.
"""
# Creating an sets
string = "Hello, this is Netra kc"
set1 = set(string)
print(set1)
a = 4
b = 5
set_add = set()
set_add.add(a)
set_add.add(b)
print(set_add)
# update() --> takes elements as list
# remove() or discard() --> pass an elements to the function
# pop() --> takes an |
b7335fb30b822050372934bed00d33dd815d72b1 | RyanRasi/Python-Sudoku-Solver | /gui.py | 5,870 | 3.640625 | 4 | from tkinter import *
# Start of GUI
win = Tk ()
win.title("Sudoku Solved!")
win.geometry("475x470")
win.resizable(0, 0)
w = Canvas(win, width=475, height=470)
# w.create_rectangle(50, 0, 100, 50, fill="white", outline = 'black')
bOne = 1
for x in range(3):
# First Row of Boxes
w.create_rectangle(5, (50 * bOne) - 45, 55, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(55, (50 * bOne) - 45, 105, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(105, (50 * bOne) - 45, 160, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(165, (50 * bOne) - 45, 215, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(215, (50 * bOne) - 45, 265, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(265, (50 * bOne) - 45, 315, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(320, (50 * bOne) - 45, 370, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(370, (50 * bOne) - 45, 420, (50 * bOne) + 5, fill="white", outline = 'black')
w.create_rectangle(420, (50 * bOne) - 45, 470, (50 * bOne) + 5, fill="white", outline = 'black')
# Second Row of Boxes
w.create_rectangle(5, (50 * bOne) + 110, 55, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(55, (50 * bOne) + 110, 105, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(105, (50 * bOne) + 110, 160, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(165, (50 * bOne) + 110, 215, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(215, (50 * bOne) + 110, 265, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(265, (50 * bOne) + 110, 315, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(320, (50 * bOne) + 110, 370, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(370, (50 * bOne) + 110, 420, (50 * bOne) + 160, fill="white", outline = 'black')
w.create_rectangle(420, (50 * bOne) + 110, 470, (50 * bOne) + 160, fill="white", outline = 'black')
# Third Row of Boxes
w.create_rectangle(5, (50 * bOne) + 265, 55, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(55, (50 * bOne) + 265, 105, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(105, (50 * bOne) + 265, 160, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(165, (50 * bOne) + 265, 215, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(215, (50 * bOne) + 265, 265, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(265, (50 * bOne) + 265, 315, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(320, (50 * bOne) + 265, 370, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(370, (50 * bOne) + 265, 420, (50 * bOne) + 315, fill="white", outline = 'black')
w.create_rectangle(420, (50 * bOne) + 265, 470, (50 * bOne) + 315, fill="white", outline = 'black')
bOne += 1
# Labels
ROne = 1
for x in range(3):
mylabel = w.create_text((ROne * 50) - 20, 30, text=ROne)
mylabel = w.create_text((ROne * 50) + 140, 30, text=ROne + 3)
mylabel = w.create_text((ROne * 50) + 295, 30, text=ROne + 6)
ROne += 1
RTwo = 1
for x in range(3):
mylabel = w.create_text((RTwo * 50) - 20, 80, text=RTwo + 9)
mylabel = w.create_text((RTwo * 50) + 140, 80, text=RTwo + 12)
mylabel = w.create_text((RTwo * 50) + 295, 80, text=RTwo + 15)
RTwo += 1
RThree = 1
for x in range(3):
mylabel = w.create_text((RThree * 50) - 20, 130, text=RThree + 18)
mylabel = w.create_text((RThree * 50) + 140, 130, text=RThree + 21)
mylabel = w.create_text((RThree * 50) + 295, 130, text=RThree + 24)
RThree += 1
RFour = 1
for x in range(3):
mylabel = w.create_text((RFour * 50) - 20, 185, text=RFour + 27)
mylabel = w.create_text((RFour * 50) + 140, 185, text=RFour + 30)
mylabel = w.create_text((RFour * 50) + 295, 185, text=RFour + 33)
RFour += 1
RFive = 1
for x in range(3):
mylabel = w.create_text((RFive * 50) - 20, 235, text=RFive + 36)
mylabel = w.create_text((RFive * 50) + 140, 235, text=RFive + 39)
mylabel = w.create_text((RFive * 50) + 295, 235, text=RFive + 42)
RFive += 1
RSix = 1
for x in range(3):
mylabel = w.create_text((RSix * 50) - 20, 285, text=RSix + 45)
mylabel = w.create_text((RSix * 50) + 140, 285, text=RSix + 48)
mylabel = w.create_text((RSix * 50) + 295, 285, text=RSix + 51)
RSix += 1
RSeven = 1
for x in range(3):
mylabel = w.create_text((RSeven * 50) - 20, 340, text=RSeven + 54)
mylabel = w.create_text((RSeven * 50) + 140, 340, text=RSeven + 57)
mylabel = w.create_text((RSeven * 50) + 295, 340, text=RSeven + 60)
RSeven += 1
REight = 1
for x in range(3):
mylabel = w.create_text((REight * 50) - 20, 390, text=REight + 62)
mylabel = w.create_text((REight * 50) + 140, 390, text=REight + 66)
mylabel = w.create_text((REight * 50) + 295, 390, text=REight + 69)
REight += 1
RNine = 1
for x in range(3):
mylabel = w.create_text((RNine * 50) - 20, 440, text=RNine + 72)
mylabel = w.create_text((RNine * 50) + 140, 440, text=RNine + 75)
mylabel = w.create_text((RNine * 50) + 295, 440, text=RNine + 78)
RNine += 1
#solve(board)
#print_board(board)
w.pack()
win.mainloop ()
|
7087bb73910aa057c02bd3734efa0387ddd147f4 | cruecker/programmieren_lernen | /kurs-python-lernen/for.py | 207 | 3.625 | 4 | #for entspricht for-each in ps
#zv ist keine zählvariable daher kein i
zitat = "werft den purschen zu poden"
zv = 0
for x in zitat:
zv += 1
print("Zeichen ", zv, ":\t", x)
print("Schleife beendet")
|
f784ca35f272ce466c8a4576108be5326419370a | happylay-cloud/python | /code/Set.py | 758 | 4.25 | 4 | # 声明集合:set
s1 = set() # 创建空集合,只能使用set()
s2 = {1,2,3} # 字典{key:value} 集合{元素}
print(type(s1))
print(type(s2))
list1 = [1,2,3,4,5,3,4,5]
s3 = set(list1)
print(s3)
# 增加一个元素
s1.add('hello')
s1.add('lay')
t1 = ('hello','world')
# 添加多个元素
s1.update(t1)
s1.add(t1)
print('--->',s1)
s3.discard(1)
print(s3)
set1 = {1,2,3}
set2 = {2,3,4}
set3 =set2-set1 # 差集 difference()
print(set3)
set5 = set2.difference(set1)
print(set3)
set6 = set2 & set1 # 交集 intersection()
print(set6)
set7 = set2.intersection(set1)
print(set7)
set8 = set2 | set1 # 并集 union()
print(set8)
set9 =set2.union(set1)
print(set9)
# 不可变类型 int str float 元组
# 可变类型 字典dict 列表list |
186fdc9484d2e7a5972013b0fdcf14681dfb5d20 | ANASTANSIA/PythonRepo | /02.py | 353 | 3.96875 | 4 | """
Prints Letter A
"""
size=eval(input('Height:'))
for i in range(size):
for j in range((size//2)):
if((j == 0 or j== size//2) and i !=0 or i==0 and j!=0 and j !=size//2 or i==size//2):
print("*", end = "")
else:
print("" ,end= "")
print()
|
4254ea42c2be99e0884cd961380320c17a8f45c7 | Cpzty/proy1-compis | /abtreelist.py | 1,266 | 3.828125 | 4 | class Tree():
def __init__(self):
self.nodes = []
self.count = 0
def add_entree(self, left, op, right):
if len(self.nodes) == 0:
if right == ' ':
node = [left, op]
elif right == ' ' and left == ' ':
#node = [self.count, op]
node = [op]
elif left == ' ':
#node = [self.count, op, right]
node = [op, right]
else:
node = [left, op, right]
self.nodes.append(node)
else:
if right == ' ' and left == ' ':
#node = [self.count, op]
node = [op]
elif left == ' ':
#node = [self.count, op, right]
node = [op, right]
elif right == ' ':
node = [left, op]
else:
node = [left, op, right]
#self.count += 1
self.nodes.append(node)
#op nunca es vacia
def see_tree(self):
print(self.nodes)
#sin_tree = Tree()
#sin_tree.add_entree(str(ord('a')), '|', str(ord('b')))
#sin_tree.add_entree(str(ord('a')), '|', str(ord('b')))
#sin_tree.add_entree(str(ord('a')), '|', str(ord('b')))
#sin_tree.see_tree() |
5e589a8a6e823f1abcf5f4d041d6e8be418eb509 | 1363653611/zbcn-py | /algorithm/duplicate_data_test.py | 966 | 3.90625 | 4 | def swap(nums, i, j):
"""
将第i个元素的值,复制到第i个元素上
:param nums:
:param i:
:param j:
:return: null
"""
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def duplicate(nums, duplication):
"""
长度为n的数组里的所有数字都在0到n-1的范围内。查出数组中某个重复的数据
:param nums:
:param duplication:
:return:
"""
# 1. 非法的数据,则返回false
if nums is None or len(nums) < 0:
return False
# 2.遍历查找第一个重复的数
for i in range(0, len(nums)):
while (nums[i] != i):
# 第i个元素和第i个元素值的位置的值相等
if nums[i] == nums[nums[i]]:
duplication.insert(0, nums[i])
return True
swap(nums, i, nums[i])
if __name__ == '__main__':
i = [2, 3, 1, 0, 2, 5, 3]
temp = []
duplicate(i, temp)
print(temp)
|
06cef42ac056d6e25185bbe62ca4af0431e76e35 | dennis-omoding3/firstPython | /operators.py | 789 | 4.21875 | 4 | # arithmetic operators
# + addition
# -subtraction
# *multiplication
# /division
print(2**3) # **used in exponential
# % modulo operator returns the remainder of the division
print(10%3)
print(48%2)
# // floor dividion truncates the answer.
print(49//3)
# assignment operators
# = assigns to an identifier
add=2+2
# add +=1 increment operator
# add -=1 decrement operator
# comparison operators
# > greater than
# >= greater than or equals to
# < less than
# <= less than or equal to
# == equal to
# != not equal to
# logical operators
# add - all conditions need to evaluate to true to be true
# False and False= False
# False and True= False
# True and True= True
# or
# True or True= True
# True or False= True
# False or False= False
# not negates.
# not False or False=True |
45a2623530d919e8ed7486957523824edd530de8 | mercurium/proj_euler | /test160.py | 702 | 3.890625 | 4 | import time
start = time.time()
from math import factorial as fact
def fa(n):
if n == 0 or n == 1:
return 1
prod = 1
for i in xrange(2,n+1):
prod *= i
while prod % 10 == 0:
prod /= 10
prod = prod % (10**5)
return prod
val = fa(10**5)
#last 4 digits of factorial(10**5) are 2496
print val
print pow(val,10**7,10**10)
print "Time Taken:", time.time() -start
#ahh, dammit >.>;; The reason for the incongrinuity... is because if we have like... 12300000000, it becomes 123, not another random number we cancel out... T___T
#okay, so I'm going to test first ignoring all numbers that are divisible by 10, then move up to ignoring those divisible by 100, then 1000, etc.
|
bb6a448843cddd66bd70e5beb4a4cdba5780c52a | makhmudislamov/coding_challanges_python3 | /module_6/bubble_sort.py | 1,693 | 4.40625 | 4 | """
Given an unsorted list of integers, sort those integers using the Bubble Sort algorithm.
Return the number of swaps required to sort the list.
Bubble Sort is a simple sorting algorithm that works as follows:
1. Start at the beginning of the list, and traverse through each element.
2. For each element, if the element is larger than the one that comes after it, swap them.
3. Once you reach the end of the list, if you have not made any swaps, you are done, and the list is sorted.
4. Otherwise, go back to step 1.
Given a list of numbers to sort, return the count of swaps you must make when using the Bubble Sort Algorithm that will result in a sorted list.
Example:
[6, 2, 4, 3]
[2, 6, 4, 3]; swap 6 with 2
[2, 4, 6, 3]; swap 6 with 4
[2, 4, 3, 6]; swap 6 with 3. End of the list has been reached, go back to the beginning.
[2, 3, 4, 6]; swap 4 with 3
Done! Total swaps: 4.
"""
def bubble_sort_swaps(nums):
count_swaps = 0
index = 0
last_unsorted_indx = len(nums)
not_swapped = True
while not_swapped:
# until the last element of the list:
not_swapped = False
while index < last_unsorted_indx - 1:
if nums[index] > nums[index + 1]:
nums[index], nums[index + 1] = nums[index + 1], nums[index]
count_swaps += 1
index += 1
not_swapped = True
else:
index += 1
print(nums)
last_unsorted_indx = last_unsorted_indx - 1
index = 0
return count_swaps
# increment count_swaps
# increment index
# else just increment the index
nums = [6, 2, 4, 3]
print(bubble_sort_swaps(nums))
|
2376fde0641b55e1bfd4ecf8e5aa16c5ff649a6d | ttnguyen2203/code-problems-python | /contains_duplicates.py | 649 | 4.125 | 4 | '''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Difficult: Easy
Solution Notes:
1. Use the property of sets (unique).
2. Alternatively, use a hash map to keep track of how many times elements appear.
Time: O(n)
Space: O(1)
'''
# one line Solution
def contains_duplicates(nums):
return len(nums) > len(set(nums))
# hash_map Solution
def contains_duplicates(nums):
dup_map = {}
for num in nums:
if num in dup_map:
return True
else:
dup_map[num] = 1
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.