blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ffb3365365e3aafce6973b75ac277e40b5afa3b5 | pranshul2112/HackerRank | /Algorithms/Implementation/Kangaroo.py | 285 | 3.671875 | 4 |
def kangaroo(x1, v1, x2, v2):
if v1 <= v2 or (x2 - x1) % (v1 - v2) != 0:
print("NO")
else:
print("YES")
x1V1X2V2 = input().split()
x1 = int(x1V1X2V2[0])
v1 = int(x1V1X2V2[1])
x2 = int(x1V1X2V2[2])
v2 = int(x1V1X2V2[3])
kangaroo(x1, v1, x2, v2)
|
03321db9a9285ee319ac4bfd85dd9a8e3c3b15a9 | z2140684/audio | /双向链表.py | 1,004 | 3.875 | 4 | class node():#ʵڵ
def __init__(self,value,next=None,front=None):
self.value=value
self.next=next
self.front=front
def creat_list(n):
if n<=0:
return (False)
else:
root=node(0)
tmp=root
for i in range(n-1):
tmp.next=node(i+1)
tmp.next.front=tmp
tmp=tmp.next
tmp.next=root
root.front=tmp
return root
def insert(root,n,t):
p=root
for i in range(1,n-1):
p=p.next
tem=node(t)
tem.next=p.next
p.next=tem#ȫֵ
def delet(root,n):
p=root
for i in range(1,n-1):
p=p.next
p.next=p.next.next
def search(root,value):
p=root
i=0
while(1):
if p.value==value:
return i
i+=1
if p.next==root:
break
p=p.next
root=creat_list(5)
p=root
for i in range(5):
print(p.value)
p=p.next
insert(root,4,77)
p=root
for i in range(8):
print(p.value)
p=p.next
delet(root,4)
p=root
for i in range(8):
print(p.value)
p=p.next
print ('qweqwe'+str(search(root,3)))
|
b5660433b14a7521b8069d77ad52f5310be3fee1 | MaksimVlasenko2006/git_python | /lesson3/5.py | 151 | 3.703125 | 4 | a=float(input("Сколько вы положите="))
b=float(input("Procent"))
c=5
for y in range(c):
y+=1
a=a+(a*b/100)
print(y," ",a)
|
485841b8418a8e848f45473bd5e7fc788b448056 | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_03_functions/negative_exponent.py | 270 | 4.1875 | 4 | def power(a, n):
if n < 0:
a = 1 / a
n = -n
result = 1
for k in range(n):
result *= a
return result
print("Calculates a^n (a to the power of n).")
a = float(input("Give a: "))
n = int(input("Give n: "))
print(power(a, n))
|
b12a37f1cc6433c72762d9a14bd356f4c314c597 | NuneTon/Introduction_to_Data_Science_with_Python | /src/second_month/task_2_1_numpy.py | 835 | 4.09375 | 4 | # task_1
# Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array.
import numpy as np
def print_arr(a):
return np.array(a)
l = [5, 3, 6, 8, 7]
# task_2
# Write a NumPy program to create a NumPy array with values ranging from 2 to 10.
def array_range(a, b):
return np.arange(a, b)
# task_3
# Write a NumPy program to create a null vector of size 10 and update sixth to eight values to 11.
def update(a, b):
arr2 = np.zeros(a)
arr2[5:8] = b
return arr2
# task_4
# Write a NumPy program to test whether each element of a 1-D array is also present in a second array.
arr3 = np.array([[1, 3, 6, 7, 8], [3, 2, 5, 7, 8]])
l1 = arr3[0]
l2 = arr3[1]
def main():
print(print_arr(l))
print(array_range(2, 10))
print(update(10, 11))
np.in1d(l1, l2)
main()
|
3d302ac67c939e7ebf182cab7a2b7d6b10e19520 | bitterbooher/Projects | /Quiz Maker/qm.py | 649 | 3.703125 | 4 | #quiz maker
#how to read in files
x = 0
useranswers = []
realanswers = []
with open("sample1.txt") as f:
for line in f:
print line,
var = raw_input("Your answer :")
useranswers.append(var.lower())
#print useranswers
with open("key1.txt") as b:
for line in b:
#print line,
realanswers.append(line.rstrip()) #rstrip will rid of \n
print realanswers
"""
print useranswers[0] == realanswers[0]
print useranswers[1] == realanswers[1]
print useranswers[2] == realanswers[2]
"""
#print key versus answers
while x < len(useranswers):
print useranswers[x] == realanswers[x]
x+= 1
#answer each question in line
#randomly select questions
|
bb8b6ca05ba9b6a8c7c4ac93c192d9b84b2a3dd0 | danieljobvaladezelguera/CYPDANIELJVE | /libro/Problemas_resueltos/Capitulo1/Ejemplo1_4.py | 357 | 3.703125 | 4 | print ("Programa de gasolina y galones")
GAL = int(input("Deme la cantidad de gasolina que necesita en galones: "))
GASL = GAL * 3.785
TOTAL = GASL * 8.20
print (f " Usted pidio { GAL } de galones de gasolina" )
print (f " En total de gasolina en Lts es de { GASL }" )
print (f " El total es de ${TOTAL}" )
print (" Gracias por su preferencia :)" )
|
def032171b684270808fb3f1a9394dc35937dc06 | Suriya0404/Algorithm | /pzl/vertical_traverse_of_binary_tree.py | 935 | 3.609375 | 4 |
from collections import defaultdict
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
trav = {root.val: 0}
output = defaultdict(list)
queue = [root]
output[0].append(root.val)
for root in queue:
if root.left is not None:
trav[root.left.val] = trav[root.val] - 1
output[trav[root.val] - 1].append(root.left.val)
queue.append(root.left)
if root.right is not None:
trav[root.right.val] = trav[root.val] + 1
output[trav[root.val] + 1].append(root.right.val)
queue.append(root.right)
return [i for i in output.values()]
if __name__ == '__main__':
|
30a7e86214f14a74e2fdfda1041075f081d2a7f0 | NewMai/PythonCode | /Practice/continue.py | 135 | 3.65625 | 4 | #
for num in range(2, 10):
if(num % 2 == 0):
print(num, "是一个偶数");
continue
print(num, "不是一个偶数")
|
3e4f696e5425fc5b974d4ca75591b9a13f3258ca | luc-daumas/essaisPython | /essais/AnneeBisextile.py | 986 | 3.890625 | 4 | #!/usr/bin/python3
def estBisextile(annee):
"""Retourne true si l'annee est bisextile, false sinon
un annee est bisextile si elle est divisible par 4 et non divisible par 100, ou si elle est divisible par 400
>>> estBisextile(2021)
False
>>> estBisextile(1900)
False
>>> estBisextile(2020)
True
>>> estBisextile(2000)
True
"""
if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0):
return True
return False
anneeYYYY = lambda annee : annee + 2000
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
import doctest
doctest.testmod()
while (True):
annee = input("Entrez une année : ")
if not annee:
print("Fin")
exit()
annee = anneeYYYY(int(annee))
if estBisextile(annee):
print("L'année {} est bisextile".format(annee))
else:
print("l'année {} n'est pas bisextile".format(annee))
|
5112ca77acbe9f37a15e446adc8d4c905cb62c19 | RVaishnavi-999/Advanced-Python-Programs | /file handling exceptions.py | 753 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Vaishnavi R
"""
"""9. Program to demonstrate file handling exceptions."""
def main():
cl=[0] *26
try:
fn=input("Enter file name: ")
infile=open(fn,"r")
for line in infile:
print(line)
cls(line,cl)
infile.close
except FileNotFoundError:
print(fn,"is not found")
else:
f=0
for i in range(len(cl)):
if cl[i]!=0:
f=1
print(" char ",chr(ord('a')+ i) + " appears "+str(cl[i])+" times ")
if f==0:
print("no character found")
def cls(line,c):
for ch in line:
if ch.isalpha():
p=ord(ch.upper()) - ord('a')
c[p]+=1
main() |
a30c63c824cd39b878d1f708d821fb579acd46f6 | mradrianhh/Introduction-to-scientific-programming | /03/interest1.py | 371 | 3.734375 | 4 | initial_amount = 100
interest_rate = 5.0
num_of_years = 0
# The while-loop runs until the conditional-statement evaluates to false.
while num_of_years <= 10:
final_amount = initial_amount * (1 + interest_rate/100) ** num_of_years
print(f"\tYear: {num_of_years}\tInitial Amount: {initial_amount}\tFinal Amount: {final_amount}")
num_of_years = num_of_years + 1 |
80413822696b8a0d26de59eb6a905b80364ee080 | xdzjcoll/chat | /thread_attr.py | 347 | 3.515625 | 4 | from threading import Thread
from time import sleep
def fun():
sleep(3)
print("线程属性测试")
t = Thread(target=fun,name = "Tarena")
# 主线程退出分支线程也退出
t.setDaemon(True)
t.start()
# 线程名称
t.setName("Tedu")
print("Thread name:",t.getName())
# 线程生命周期
print("is alive:",t.is_alive())
|
6c06b0d545e6e2ddab23ad42003554928ce60f99 | RaunakMandal/Python-CWM | /5 - Data Structures/lists.py | 187 | 3.59375 | 4 | letters = ["a", "b", "c"]
martrix = [[0, 1], [2, 3]]
zeroes = [0] * 5
combined = zeroes + letters
nums = list(range(20)) # list till range
chars = list("Hello World")
print(len(chars))
|
c32a7fc78f4a13befd340b40ff4069f72d7cf70f | biswaranjanroul/Python-Logical-Programms | /Fresher Lavel Logical Programms/Program to print ASCII Value of a character.py | 76 | 3.5 | 4 | c=input("Enter the charactor:")
print("the AsCCII value of ",c,"is",ord(c))
|
fea699b5a82f92167eda1d1cc575f1204587f9fb | PhoebeDreamer/leetcode | /src/lc53.py | 764 | 3.515625 | 4 | class Solution1:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = float('-inf')
min_sum = 0
tmp_sum = 0
for n in nums:
tmp_sum += n
max_sum = max(max_sum, tmp_sum-min_sum)
min_sum = min(min_sum, tmp_sum)
return max_sum
class Solution2:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = float('-inf')
min_sum = 0
tmp_sum = 0
for n in nums:
if tmp_sum<0:
tmp_sum=0
tmp_sum += n
max_sum = max(max_sum, tmp_sum)
return max_sum
|
92a900e53730763dace3a77aedeb842eb1933eba | AnaTrzeciak/Curso_Python | /6-Listas/lista1.py | 372 | 3.875 | 4 | #Programa feito 07/11/2019
#Feito por Ana Maria Trzeciak
#Adicionar itens em uma lista: append()
#sintaxe: nome_da_lista.append(item a ser adicionado)
#ecoding:utf-8
comida=[]
while True:
op = int(input("1-Adicionar Comida Favorita 2-Exibir Comidas Favoritas \n"))
if(op==1):
comidafav=input("Digite nome da comida: ")
comida.append(comidafav)
if(op==2):
print(comida)
|
60474bd348d317228371524bc2a8a53b83f88617 | rafaelperazzo/programacao-web | /moodledata/vpl_data/60/usersdata/251/27186/submittedfiles/formula.py | 186 | 3.671875 | 4 | # -*- coding: utf-8 -*-
p = float (input('Insira o valor 1: '))
i = float (input('Insira o valor 2: '))
n = float (input('Insira o valor 3: '))
v = p*((((1+i)**n)-1)/i)
print ('%.2f'%v)
|
b313ddbf76f32fc76bd926f37d36c84b4f80d403 | rasztadani/Python | /01_fizzbuzz.py | 497 | 4.09375 | 4 | print("Welcome to the FizzBuzz!")
while True:
end = int(raw_input("Please give a number betwen 1 and 100: "))
print(end)
if end < 100:
for num in range(1, end+1):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print num
break
else:
print ("The number is incorrect!") |
7d3ff889e5a6dc0df276166d750af6402c3b23f9 | alexinder/tealight-files | /art/alexpaint.py | 917 | 3.515625 | 4 | from tealight.art import (color, line, spot, circle, box, image, text, background)
def DrawPalette(x,y, colors, w, h):
for c in colors:
if c == "rainbow":
color("blue")
box(x,y, w/3, h)
color("red")
box(x+h/3, y, w/3, h)
color("limegreen")
box(x+2*h/3, y, w/3, h)
else:
color(c)
box(x, y, w, h)
y = y + h
colors = ["black",
"grey",
"red",
"magenta",
"pink",
"blue",
"indigo",
"purple",
"limegreen",
"forestgreen",
"orange",
"gold",
"yellow",
"rainbow"]
x = 15
y = 5
w = 55
h= 55
DrawPalette(x,y, colors , w, h)
def color_click(mx,my):
if mx > x and mx < x+w and my > y and my < y+(h*len(colors)):
RowNo = (my-y)/h
#color(colors[RowNo])
print RowNo
return colors[RowNo]
|
13a2bd969cb76f5020d3d95a73df87d996285693 | karthik-siru/practice-simple | /graph/alien.py | 1,718 | 3.53125 | 4 | from collections import defaultdict , deque
class Graph :
def __init__(self, vertices):
self.v = vertices
self.adj = {i:[] for i in range(vertices)}
def addEdge (self, word1 , word2 ):
n = len(word1)
m = len(word2)
i = 0
while i < n and i < m :
a = word1[i]
b = word2[i]
if a == b :
i += 1
continue
if a != b :
k1 = ord(a) - ord('a')
k2 = ord(b) - ord('a')
if k2 not in self.adj[k1] :
self.adj[k1].append(k2)
break
def TopologicalSort(self, visited , finished , src , time ):
visited[src] = True
time += 1
for v in self.adj[src] :
if not visited[v] :
time = self.TopologicalSort(visited , finished , v , time )
finished[time] = src
time += 1
return time
def findOrder(dict, N, k):
g = Graph(k)
for i in range(N) :
for j in range(i+1, N) :
g.addEdge(dict[i] , dict[j])
visited =[False]*(k)
time = 0
finished = [-1]*(2*k)
for i in range(k) :
if not visited[i] :
time = g.TopologicalSort(visited , finished , i , time )
res = ""
for i in reversed(range(2*k)) :
if finished[i] != -1 :
res += chr(finished[i] + ord('a'))
return res
N = 5
K = 4
dict = ["baa","abcd","abca","cab","cad"]
print(findOrder(dict , N , K )) |
fc419e083d5b22eb47f6b8aa245e12b4a7487918 | mo-dt/PythonDataScienceCookbook | /ch 2/Recipe_3a.py | 986 | 3.625 | 4 | from sklearn.datasets import load_iris,load_boston,make_classification,\
make_circles, make_moons
# Iris dataset
data = load_iris()
x = data['data']
y = data['target']
y_labels = data['target_names']
x_labels = data['feature_names']
print
print x.shape
print y.shape
print x_labels
print y_labels
# Boston dataset
data = load_boston()
x = data['data']
y = data['target']
x_labels = data['feature_names']
print
print x.shape
print y.shape
print x_labels
# make some classification dataset
x,y = make_classification(n_samples=50,n_features=5, n_classes=2)
print
print x.shape
print y.shape
print x[1,:]
print y[1]
# Some non linear dataset
x,y = make_circles()
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
plt.figure(1)
plt.scatter(x[:,0],x[:,1],c=y)
x,y = make_moons()
import numpy as np
import matplotlib.pyplot as plt
plt.figure(2)
plt.scatter(x[:,0],x[:,1],c=y)
plt.show() |
c611359f0fd54b9552c1c663b27a5d4bb7bd8973 | HorseSF/xf_Python | /day09/code/06-函数的注意事项.py | 412 | 4 | 4 | # 函数的三要素:函数名,参数,返回值
# 在有一些编程语言里,函数可以重名,在python里不能重名,如果重名会覆盖
# def test(a, b):
# print("hello,a={},b={}".format(a, b))
#
#
# def test(x):
# print("good,x={}".format(x))
#
#
# test(3, 4)
# python里函数名也可以理解为变量名
# def test(x):
# print("good,x={}".format(x))
#
# test = 5
# test(3)
|
10e3b65050a49315e5dbce2e265ff2f6a4e77e65 | HJCHOI910828/python | /Ch02/2_1_Variable.py | 296 | 3.53125 | 4 | """
날짜 : 2021/07/12
이름 : 임진슬
내용 : 파이썬 변수 실습하기 교재 p34
변수(Variable)
- 데이터를 처리하기 위한 메모리 공간
- 임시 데이터를 보관 처리하기 위한 메모리 영역
"""
var1 = 1
var2 = 2
var3 = var1 + var2
print('var3 :', var3)
|
5423f2c1d2a75cd525c78243786053bc3243d6df | conradh1/PythonHacks | /HackerRank/Sets/setOps.py | 934 | 3.90625 | 4 | #!/usr/bin/python
#Python use of set Operations
#See: https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem
import sys
import string
def doOps(setN, commands):
# execute discard(), .remove() & .pop()
for i in range(len(commands)):
command = commands[i].split(' ') # split command
if (command[0] == 'pop'):
setN.pop()
elif (command[0] == 'remove'):
n = int(command[1])
setN.remove(n)
elif (command[0] == 'discard'):
n = int(command[1])
setN.discard(n)
total = 0
for j in setN:
total += j
return total
if __name__ == '__main__':
n = int(raw_input())
commands = {};
setN = set(map(int, raw_input().split()))
N = int(raw_input())
for i in range(N):
commands[i] = raw_input()
print doOps(setN, commands) |
c8b4fea6ce31a3e357437a0d294a933e8a756b68 | PES-Innovation-Lab/git-practice-workshop | /2020-test.py | 244 | 3.515625 | 4 | import time
def test(x, y):
if(y==0):
return x
return test(y, y%x)
for i in range(0, 10):
print('GCD of {} with 2 : '.format(i), test(2, 10))
for i in range(0, 10):
print('GCD of {} with 2 : '.format(i), test(2, 10))
|
0c30dd84144fe742b78c0b1b42231bdf9ee3de07 | wma8/PythonClass | /Week 2/quiz1_solution.py | 440 | 4.15625 | 4 | """
PIC 16 - Winter 2019
QUIZ 1 SOLUTION
"""
"""The function mylists(L) that takes as input a list of numbers
L = [a, b, c, . . .], and outputs a list of k lists (where k is the number of elements in L)
one with elements a+1, b+1, c+1, . . ., one with elements a+2, b+2, c+2, . . .,
etc, all the way up to a+k, b+k, c+k, . . ."""
def mylists(L):
return [[i+(j+1) for i in L] for j in range(len(L))]
L = [2,3,1]
print mylists(L) |
32a4981b7b6bd0865c1020d91281d0c832c3dfa0 | antoniobarbozaneto/Tecnicas-Avancadas-em-Python | /03_represent_tarefa.py | 1,209 | 3.984375 | 4 | # Personalizando representações string de classes
class Pessoa():
def __init__(self):
self.nome = "Jessica"
self.sobrenome = "Temporal"
self.idade = 25
# TODO: Use __repr__ para criar uma string que seja útil para debug
def __repr__(self):
texto = "<Classe Pessoa - nome: {0}, sobrenome: {1}, idade: {2}>"
return texto.format(self.nome, self.sobrenome, self.idade)
# TODO: Use __str__ para criar uma string amigável para humanos
def __str__(self):
texto = "Pessoa {0} {1} tem {2} anos"
return texto.format(self.nome, self.sobrenome, self.idade)
# TODO: Use bytes para converter a string em um objeto bytes
def __bytes__(self):
dados = [self.nome, self.sobrenome, self.idade]
para_bytes = "Pessoa: {0}:{1}:{2}".format(*dados)
return para_bytes.encode('utf-8')
def main():
# Criando uma instância de Pessoa
pessoa = Pessoa()
# Usando as funções embutidclear
# as de Python para representar a pessoa
# numa string
print(repr(pessoa))
print(str(pessoa))
print("Formatado: {0}".format(pessoa))
print(bytes(pessoa))
if __name__ == "__main__":
main()
|
673c6cd359954cfed56467e7093ceefc4966b4f4 | kyanyoga/pythonSamples | /bin/fizzbuzz.py | 1,188 | 4.3125 | 4 | #!/usr/bin/env python
# imports if needed
# print fizz is divisible by 3
# print buzz if divisible by 5
# print the number in other cases
def checkio(number):
#Your code here
#It's main function. Don't remove this function
#It's using for auto-testing and must return a result for check.
res = ""
if number%3 == 0:
res = "Fizz"
if number%5 == 0:
res = "Buzz"
if (number%3 == 0) and (number%5 == 0):
res = "Fizz Buzz"
if (number%3 != 0) and (number%5 != 0):
res = str(number)
return res
''' -or-
if number%15== 0:
return "Fizz Buzz"
if number%3 == 0:
return "Fizz"
if number%5 == 0:
return "Buzz"
return str(number)
'''
#Some hints:
#Convert a number in the string with str(n)
print checkio(30)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
assert checkio(6) == "Fizz", "6 is divisible by 3"
assert checkio(5) == "Buzz", "5 is divisible by 5"
assert checkio(7) == "7", "7 is not divisible by 3 or 5"
print "done Testing..."
|
fe104395ca0695f7e4a183175e57b5244a90cb99 | S-Birch2/Bright-network-IEUK-code | /python/src/video_player.py | 11,831 | 3.765625 | 4 | """A video player class."""
import random
from .video_library import VideoLibrary
from .video_playlist import Playlist
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self._playlist = {}
self.current_video = ""
self.play_state = "stopped"
def number_of_videos(self):
num_videos = len(self._video_library.get_all_videos())
print(f"{num_videos} videos in the library")
def show_all_videos(self):
"""Returns all videos."""
print("Here's a list of all available videos:")
for video in self._video_library.get_all_videos():
if video.flag:
print(f"{video} - FLAGGED (reason: {video.flag_reason})")
else:
print(video)
def play_video(self, video_id):
"""Plays the respective video.
Args:
video_id: The video_id to be played.
"""
try:
video = self._video_library.get_video(video_id)
title = video.title
except AttributeError as error:
print(f"Cannot play video: Video does not exist")
return
if video.flag:
print(f"Cannot play video: Video is currently flagged (reason: {video.flag_reason})")
return
if self.play_state != "stopped":
self.stop_video()
self.current_video = self._video_library.get_video(video_id)
self.play_state = "playing"
print(f"Playing video: {self.current_video.title}")
def stop_video(self):
"""Stops the current video."""
if self.play_state != "stopped":
self.play_state = "stopped"
print(f"Stopping video: {self.current_video.title}")
self.current_video = ""
else:
print(f"Cannot stop video: No video is currently playing")
def play_random_video(self):
"""Plays a random video from the video library."""
ids = []
for video in self._video_library.get_all_videos():
if not video.flag:
ids.append(video.video_id)
if not ids:
print("No videos available")
return
rand = random.randint(0, len(ids)-1)
self.play_video(ids[rand])
def pause_video(self):
"""Pauses the current video."""
if self.play_state == "stopped":
print(f"Cannot pause video: No video is currently playing")
elif self.play_state == "paused":
print(f"Video already paused: {self.current_video.title}")
elif self.play_state == "playing":
print(f"Pausing video: {self.current_video.title}")
self.play_state = "paused"
def continue_video(self):
"""Resumes playing the current video."""
if self.play_state == "stopped":
print(f"Cannot continue video: No video is currently playing")
elif self.play_state == "paused":
print(f"Continuing video: {self.current_video.title}")
self.play_state = "playing"
elif self.play_state == "playing":
print(f"Cannot continue video: Video is not paused")
def show_playing(self):
"""Displays video currently playing."""
if self.play_state == "playing":
print(f"Currently playing: {self.current_video}")
elif self.play_state == "paused":
print(f"Currently playing: {self.current_video} - PAUSED")
elif self.play_state == "stopped":
print("No video is currently playing")
def create_playlist(self, playlist_name):
"""Creates a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
lowercase_name = playlist_name.lower()
if lowercase_name in self._playlist:
print("Cannot create playlist: A playlist with the same name already exists")
return
self._playlist[lowercase_name] = Playlist(playlist_name)
print(f"Successfully created new playlist: {playlist_name}")
def add_to_playlist(self, playlist_name, video_id):
"""Adds a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be added.
"""
#This checks the called playlist exists
playlist = self._playlist.get(playlist_name.lower(), None)
if playlist is None:
print(f"Cannot add video to {playlist_name}: Playlist does not exist")
return
#This checks the mentioned video exists
try:
video = self._video_library.get_video(video_id)
title = video.title
except AttributeError:
print(f"Cannot add video to {playlist_name}: Video does not exist")
return
video = self._video_library.get_video(video_id)
if video in playlist.playlist_videos:
print(f"Cannot add video to {playlist_name}: Video already added")
return
if video.flag:
print(f"Cannot add video to {playlist_name}: Video is currently flagged (reason: {video.flag_reason})")
return
playlist.playlist_videos.append(video)
print(f"Added video to {playlist_name}: {video.title}")
def show_all_playlists(self):
"""Display all playlists."""
if not self._playlist:
print("No playlists exist yet")
else:
print("Showing all playlists:")
playlists_sorted = sorted(self._playlist.values(), key=lambda p: p.playlist_name)
for playlist in playlists_sorted:
print(f"{playlist}")
def show_playlist(self, playlist_name):
"""Display all videos in a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
playlist = self._playlist.get(playlist_name.lower(), None)
if playlist is None:
print(f"Cannot show playlist {playlist_name}: Playlist does not exist")
return
print(f"Showing playlist: {playlist_name}")
if not playlist.playlist_videos:
print("No videos here yet")
return
for video in playlist.playlist_videos:
if video.flag:
print(f"{video} - FLAGGED (reason: {video.flag_reason})")
else:
print(video)
def remove_from_playlist(self, playlist_name, video_id):
"""Removes a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be removed.
"""
playlist = self._playlist.get(playlist_name.lower(), None)
if playlist is None:
print(f"Cannot remove video from {playlist_name}: Playlist does not exist")
return
video = self._video_library.get_video(video_id)
if not video:
print(f"Cannot remove video from {playlist_name}: Video does not exist")
return
for v in playlist.playlist_videos:
if video == v:
playlist.playlist_videos.remove(video)
print(f"Removed video from {playlist_name}: {video.title}")
return
print(f"Cannot remove video from {playlist_name}: Video is not in playlist")
def clear_playlist(self, playlist_name):
"""Removes all videos from a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
playlist = self._playlist.get(playlist_name.lower(), None)
if playlist is None:
print(f"Cannot clear playlist {playlist_name}: Playlist does not exist")
return
print(f"Successfully removed all videos from {playlist_name}")
playlist.playlist_videos = []
def delete_playlist(self, playlist_name):
"""Deletes a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
playlist = self._playlist.get(playlist_name.lower(), None)
if playlist is None:
print(f"Cannot delete playlist {playlist_name}: Playlist does not exist")
return
playlist.playlist_videos = []
self._playlist.pop(playlist_name.lower())
print(f"Deleted playlist: {playlist_name}")
def search_videos(self, search_term):
"""Display all the videos whose titles contain the search_term.
Args:
search_term: The query to be used in search.
"""
results = []
for video in self._video_library.get_all_videos():
if search_term.lower() in video.title.lower():
if not video.flag:
results.append(video)
self.display_search(results, search_term)
def display_search(self, results, search_term):
"""Displays the search results from both video searches and tag searches
Args:
results: a list of the search results
search_term: the term used for a search
"""
if not results:
print(f"No search results for {search_term}")
return
results = sorted(results, key=lambda x: x.title)
print(f"Here are the results for {search_term}:")
video_num = 1
for v in results:
print(f"{video_num}) {v}")
video_num += 1
print("Would you like to play any of the above? If yes, specify the number of the video.")
print("If your answer is not a valid number, we will assume it's a no.")
num = input()
try:
num = int(num)
except ValueError:
return
if num <= 0:
return
try:
chosen_vid = results[num-1]
except IndexError:
return
self.play_video(chosen_vid.video_id)
def search_videos_tag(self, video_tag):
"""Display all videos whose tags contains the provided tag.
Args:
video_tag: The video tag to be used in search.
"""
results = []
for video in self._video_library.get_all_videos():
for tag in video.tags:
if video_tag.lower() == tag.lower():
if not video.flag:
results.append(video)
self.display_search(results, video_tag)
def flag_video(self, video_id, flag_reason=""):
"""Mark a video as flagged.
Args:
video_id: The video_id to be flagged.
flag_reason: Reason for flagging the video.
"""
if not flag_reason:
flag_reason = "Not supplied"
video = self._video_library.get_video(video_id)
if not video:
print(f"Cannot flag video: Video does not exist")
return
if video.flag:
print(f"Cannot flag video: Video is already flagged")
return
if video == self.current_video:
self.stop_video()
video._flag = True
video._flag_reason = flag_reason
print(f"Successfully flagged video: {video.title} (reason: {video.flag_reason})")
def allow_video(self, video_id):
"""Removes a flag from a video.
Args:
video_id: The video_id to be allowed again.
"""
video = self._video_library.get_video(video_id)
if not video:
print(f"Cannot remove flag from video: Video does not exist")
return
if not video.flag:
print(f"Cannot remove flag from video: Video is not flagged")
return
video._flag = False
video._flag_reason = "Not currently flagged"
print(f"Successfully removed flag from video: {video.title}")
|
244dfc54afe6eeaf735ad0762227bb925054dd06 | joshdavham/Starting-Out-with-Python-Unofficial-Solutions | /Chapter 2/Q8.py | 430 | 3.671875 | 4 | #Question 8
percentTip = 0.15 #15% tip
percentTax = 0.07 #7% tax
mealCost = float(input("How much did your meal cost? "))
tipCost = percentTip * mealCost
taxCost = percentTax * mealCost
total = mealCost + tipCost + taxCost
print("Meal Price: $", format(mealCost, '.2f'), \
"\nTip: $", format(tipCost, '.2f'), \
"\nTax: $", format(taxCost, '.2f'),
"\nTotal: $", format(total, '.2f'), sep = "")
|
1b7914db3737570a00085014946106b5fec82c53 | huhudaya/leetcode- | /程序员面试金典/面试题 17.21. 直方图的水量.py | 1,186 | 4.0625 | 4 | '''
给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的直方图,在这种情况下,可以接 6 个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
通过次数2,896提交次数4,526
在真实的面试中遇到过这道题?
'''
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
# 双指针优化版本
# 只考虑当前的柱子
if not height:
return 0
n = len(height)
left = 0
right = n - 1
l_max = height[0]
r_max = height[n-1]
res = 0
while left < right:
# 更新左端和右端的最大值
l_max = max(height[left], l_max)
r_max = max(height[right], r_max)
if height[left] < height[right]:
res += l_max - height[left]
left += 1
else:
res += r_max - height[right]
right -= 1
return res |
c0aeb5fc690ebdc9b10727c02b05dad974c53146 | llpuchaicela/Proyecto-Primer-Bimestre-2- | /Factura.py | 790 | 3.921875 | 4 | print("Ejercicio12")
print("Programa para calcular el total de una factura de venta")
print("Lilibeth Puchaicela")
#Declaración e inicialización de variables
subtotal=0
total=0
descuento=0
limite1=200
limite2=500
#Ingrese las variables
print ("Factura de Venta")
print("Por compar mayores o iguales a 200$, se le aplicara un descuento del 10%")
print("Por comprar mayores o iguales a 500$, se le aplicara un descuento del 15%")
subtotal=float(input("Ingrese el subtotal de la compra: "))
subtotal= float(subtotal)
# Proceso
if subtotal >= limite1 and subtotal< limite2:
descuento =0.10
else:
decuento =0.15
if subtotal<limite1:
decuento=0.0
print("No tiene decuento")
total=subtotal-(subtotal*descuento)
#Salida de datos
print("El total de la compra es", total, "con un descuento de" , descuento) |
a494c64ff67f20413ca5fb3dfc27ee815162270d | Mr-Phoebe/ACM-ICPC | /OJ/Leetcode/Algorithm/257. Binary Tree Paths.py | 700 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
l = self.binaryTreePaths(root.left)
r = self.binaryTreePaths(root.right)
if l == [] and r == []:
return [str(root.val)]
ans = set()
for s in l:
ans.add(str(root.val) + "->" + s)
for s in r:
ans.add(str(root.val) + "->" + s)
return list(ans)
|
1b730aa90c76e764e4b4678b4da33f8d07be4c4b | chrismilson/random-fibonacci | /coinflip.py | 346 | 3.671875 | 4 | import random
def randomBool(probabilityOfTrue: float = .5) -> bool:
"""Return a random bool"""
return random.uniform(0, 1) < probabilityOfTrue
def coinflip(probabilityOfHeads: float = .5) -> str:
"""Flip a (fair by default) coin.
Returns:
str: heads or tails.
"""
return 'heads' if randomBool(probabilityOfHeads) else 'tails'
|
9943550c24d908d87aa65467476767c54943d9d2 | sreepygithub/practice | /manage.py | 134 | 3.59375 | 4 | def add(x,y):
return x+y
def sub(x,y):
return x-y
def mult(x,y):
return x*y
def div(a,b):
return a%b
print(add(9,10)) |
73bfcbaac769b34cef685240de9bb9b5e5dc7820 | Wizmann/ACM-ICPC | /Exemplars/杂项/表达式求值.py | 639 | 3.671875 | 4 | import re
class Evaluation:
def evaluate(self, expr):
expr = re.split(r"([\+\-\*])", str(expr))
return self.do_evaluate(expr)
def do_evaluate(self, expr):
for op in "+-*":
try:
idx = (len(expr) - 1) - expr[::-1].index(op)
except:
idx = -1
if idx != -1:
a = self.do_evaluate(expr[:idx])
b = self.do_evaluate(expr[idx + 1:])
return {
"+": a + b,
"-": a - b,
"*": a * b
}[op]
return int(expr[0])
|
62a6bc462d84232a40e590b96d2a5e74462733a7 | KISS/udacity | /practice_problems/graphs/graph_dfs_solution_2.py | 793 | 4.0625 | 4 | # Solution
def dfs_recursion_start(start_node, search_value):
visited = set() # Set to keep track of visited nodes.
return dfs_recursion(start_node, visited, search_value)
# Recursive function
def dfs_recursion(node, visited, search_value):
if node.value == search_value:
found = True # Don't search in other branches, if found = True
return node
visited.add(node)
found = False
result = None
# Conditional recurse on each neighbour
for child in node.children:
if (child not in visited):
result = dfs_recursion(child, visited, search_value)
# Once the match is found, no more recurse
if found:
break
return result |
ea0b745862c2ba0aab74133e32958a2fbe9317b7 | Crystalleaf/OpenCV_Learning | /OpenCV test/3.1 BasicOperation.py | 1,654 | 3.515625 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("1.jpg")
#px = img[100,100]
#print(px)
#blue = img[100,100,0]
#print(blue)
# Better pixel accessing and editing method :
#img[100,100] = [255,255,255]
#print(img[100,100])
# Accessing Image Properties
#print(img.shape)
#print(img.size)
#print(img.dtype)
# img.dtype is very important while debugging
# because a large number of errors in OpenCV-Python code is caused by invalid datatype.
# copy sth to another region in the image:
#ball = img[280:340, 330:390]
#img[273:333, 100:160] = ball
#cv2.imshow("IMAGE", img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
# split image:
#b,g,r = cv2.split(img)
#cv2.imshow("image", r)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
# Making Borders for Images (Padding)
BLUE = [255,0,0]
img1 = cv2.imread('opencv-logo.png')
replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show() |
182ec72c7a151dbce5f89adaf5634588b75e284b | gavaskarrathnam/learn_python_the_hard_way | /ex14.py | 720 | 4.09375 | 4 | from sys import argv
script, user_name, education = argv
prompt = '==> '
print "Hi {}, I'm the {} script.".format(user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me {}?".format(user_name)
likes = raw_input(prompt)
print "Where do you live {}?".format(user_name)
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print "How was your education in {}?".format(education)
edu_description = raw_input(prompt)
print """
Alright, so you said {!r} about liking me.
You live in {!r}. Not sure where that is.
Your education in {!r} was {!r}.
And you have a {!r} computer. Nice.
""".format(likes, lives, education, edu_description, computer)
|
e1630e5511790d4a5269b08cb274efb6d5acbe90 | msg430/Project-Euler | /problem35.py | 1,669 | 3.640625 | 4 | import math
class PrimeCheck:
def __init__(self, upperLimit):
self.highestNumber = 1
self.primes = [2]
self.given = -1
self.used = []
self.upperLimit = upperLimit
for d in range(3, int(math.sqrt(upperLimit))+1):
isPrime = True
for p in self.primes:
if d % p == 0:
isPrime = False
if isPrime:
self.primes.append(d)
def check(self, number):
for p in self.primes:
if number % p == 0:
if number != p:
return False
else:
return True
return True
def nextPrime(self):
while True:
self.highestNumber += 1
if self.highestNumber > self.upperLimit:
return 0
if self.check(self.highestNumber):
return self.highestNumber
def rearranger(number):
numbers = set()
numbers.add(number)
number = str(number)
for w in range(len(number)-1):
number = number[1:] + number[0]
numbers.add(int(number))
return list(numbers)
if __name__ == '__main__':
upperLimit = 1000000
checker = PrimeCheck(upperLimit)
current = checker.nextPrime()
goodOnes = set()
while current != 0:
combo = rearranger(current)
works = True
for c in combo:
if not checker.check(c):
works = False
break
if works:
for c in combo:
goodOnes.add(c)
current = checker.nextPrime()
print(goodOnes)
print(len(goodOnes))
|
fdf3df61b7bf7c489d854247b7703281469c382f | orlandoacosta99/python | /tersersemestre_vectores/menu.py | 5,336 | 3.96875 | 4 | from tersersemestre_vectores.vectores import *
vectores = {}
def ingresar_vector():
"""
Permite leer un vector del usuario
:return: list of num el vector ingresado por el usuario
"""
vector = [input('¿Cual es el nombre de su vector? ')]
while True:
num = input('Ingrese su escalar o "s" para terminar ')
if num.lower() != 's':
try:
num = int(num)
vector.append(num)
except:
print(num, 'no es un escalar')
else:
break
print('su vector', vector[0], 'es', vector[1:])
return vector
def mostrar_vectores():
for nombre in vectores:
print(nombre, 'contiene', vectores[nombre])
def op_producto_escalar():
while True:
escalar = input('Ingrese su escalar ')
try:
escalar = int(escalar)
break
except:
print(escalar, 'no es un escalar')
print('Cual es el nombre de su vector')
mostrar_vectores()
seleccion = input()
print('El producto escalar es', producto_escalar(escalar, vectores[seleccion]))
nombreVector = input('Indique el nombre del vector: ')
print('El vector', nombreVector, 'contiene', vectores[nombreVector])
def Suma_vectores():
while True:
vector1 = input('Indique el nombre del vector 1: ')
print('El vector 1', vector1, 'contiene', vectores[vector1])
vector2 = input('Indique el nombre del vector 2: ')
print('El vector 2', vector2, 'contiene', vectores[vector2])
if len(vectores[vector1]) == len(vectores[vector2]):
print('La suma de los vectores es:', suma_productos(vectores[vector1], vectores[vector2]))
break
else:
print('Los vectores no tiene la misma longitud.')
def Producto_punto ():
while True:
vector1 = input('Indique el nombre del vector 1: ')
print('El vector 1', vector1, 'contiene', vectores[vector1])
vector2 = input('Indique el nombre del vector 2: ')
print('El vector 2', vector2, 'contiene', vectores[vector2])
if len(vectores[vector1]) == len(vectores[vector2]):
print('El producto punto de los vectores es:', producto_puntos(vectores[vector1], vectores[vector2]))
break
else:
print('Los vectores no tiene la misma longitud.')
def Mayor_elemento():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('El mayor elemento del vector es: ', elemento_mayor(vectores[vector]))
def Menor_elemento ():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('El menor elemento del vector es: ', elemento_menor(vectores[vector]))
def Promedio ():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('El promedio del vector es: ', prom(vectores[vector]))
def Desviacion_estandar():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('La desviacion estandar del vector es: ', desviacion_est(vectores[vector]))
def Comparar ():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('El mayor elemento del vector es: ', elemento_mayor(vectores[vector]))
print('El menor elemento del vector es: ', elemento_menor(vectores[vector]))
print('El elemento igual del vector es: ', elemento_igual(vectores[vector]))
def Norma ():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('La norma del vector es: ', Norma_vec(vectores[vector]))
def Moda():
vector = input('Indique el nombre del vector: ')
print('El vector ', vector, 'contiene', vectores[vector])
print('La moda del vector es: ', Moda_vec(vectores[vector]))
def principal():
MENSAJE = '''Seleccione una opcion:
0. Salir
1. Ingresar Vector
2. Mostrar Vectores
3. Producto escalar
4. Suma de vectores
5. Producto punto
6. Mayor elemnto
7. Menor elemento
8. Promedio
9. Desviación estandar
10. Comparar
11. Norma
12. Moda del vector
'''
while True:
opcion = input(MENSAJE)
if opcion == '0':
print('Gracias')
break
elif opcion == '1':
vector = ingresar_vector()
vectores[vector[0]] = vector[1:]
elif opcion == '2':
mostrar_vectores()
elif opcion == '3':
op_producto_escalar()
elif opcion == '4':
Suma_vectores()
elif opcion == '5':
Producto_punto()
elif opcion == '6':
Mayor_elemento()
elif opcion == '7':
Menor_elemento()
elif opcion == '8':
Promedio()
elif opcion == '9':
Desviacion_estandar()
elif opcion == '10':
Comparar()
elif opcion == '11':
Norma()
elif opcion == '12':
Moda()
else:
print('Seleccione una opcion valida')
if __name__ == '__main__':
principal() |
ebf126352e0ff91dbc3bb0fb81737159193ebbce | danielfess/Think-Python | /invert_dict.py | 559 | 4.09375 | 4 | def invert_dict(d):
"""Inverts the dictionary d.
d: dictionary
returns: dictionary
"""
inverse = {}
print(type(inverse))
for key in d:
val = d[key]
test = inverse.setdefault(val,[key])
if test != [key]:
inverse[val].append(key)
return inverse
print(invert_dict({'p':1, 'a':1, 'r':2, 'o':1, 't':1}))
print(invert_dict({'p':2, 'p':1, 'a':1, 'r':2, 'o':1, 't':1}))
print(invert_dict({'p':1, 'p':2, 'a':1, 'r':2, 'o':1, 't':1}))
#Strange....dictionaries with identical keys behave badly. |
80a11ffa961d83208461d324062f37d9f7b1d830 | yesusmigag/Python-Projects | /Functions/two_numberInput_store.py | 444 | 4.46875 | 4 | #This program multiplies two numbers and stores them into a variable named product.
#Complete the missing code to display the expected output.
# multiply two integers and display the result in a function
def main():
val_1 = int(input('Enter an integer: '))
val_2 = int(input('Enter another integer: '))
multiply(val_1, val_2)
def multiply(num_1, num_2):
product = num_1*num_2
print ('The result is', product)
main() |
74759d1e9c2f443ff69c241aeb3d490ffef8ce14 | CyberLions/Competition-Scripts | /crypto/transposition.py | 1,957 | 4.03125 | 4 | # Transposition Cipher Decryption
# Created by inventwithpython
# Adapted by pbwaffles
import math
def main(myMessage):
"""
myMessage is the encrypted string that will be attempted to be decrypted.
calls decryptMessage x amount of times in order to brute force the decryption.
Returns None, prints plaintext as output.
"""
for myKey in range(1,10): #number of keys to brute force
plaintext = decryptMessage(myKey, myMessage)
print('using key: %i' % myKey)
print(plaintext)
def decryptMessage(key, message):
"""
key is a decimal number to try as the key. message is a string of the encrypted text.
key represents the number of columns to try. For example, a key of 3 with encrypted string
abcdefg will be written as...
abc
def
g
which will result in a decrpyted string of adgbecf.
The decrypted string is returned.
"""
numOfColumns = math.ceil(float(len(message)) / float(key))
numOfRows = key
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
plaintext = [''] * int(numOfColumns)
# The col and row variables point to where in the grid the next
# character in the encrypted message will go.
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1 # point to next column
# If there are no more columns OR we're at a shaded box, go back to
# the first column and the next row.
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
# If transpositionDecrypt.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
message = 'Cenoonommstmme oo snnio. s s c' # example of encrypted string "Common sense is
# not so common."
main(message)
|
ee71d07f60334d24362f4ba2cfb1d83be34171c2 | maty1990rc/reparacion-de-pc | /estados.py | 2,253 | 3.5625 | 4 | #! /usr/bin/env python3
from datetime import datetime,timedelta
from contacto import Contacto
from clientes import Clientes
from pedido import Pedido
from Pedidos import Pedidos
class Estados():
def __init__(self):
self.estados=["Recibido","Presupuestado","Reparado","Entregado","Demorado"]
def pedidos_por_vencer(self,pedidos):
'''recibe un número "n" como parámetro, y retorna una lista de
los contactos que cumplen años en los próximos "n" días.'''
lista=[]
contador=0
formato=("%d/%m/%Y")
n=int(5)
fecha_busqueda=datetime.today()
while contador < n:
contador +=1
for xx in pedidos:
x=xx.fecha_prev
x=datetime.strptime(xx.fecha_prev,formato)
resultado=x-fecha_busqueda
print(x)
print(resultado)
if (int(resultado.days) < 5) and (int(resultado.days) > 0):
lista.append(xx)
pedidos.remove(xx)
fecha_busqueda = fecha_busqueda + timedelta(days=1)
print(fecha_busqueda)
return lista
def pedidos_vencidos(self,pedidos):
lista=[]
contador=0
formato=("%d/%m/%Y")
n=int(5)
fecha_busqueda=datetime.today()
for xx in pedidos:
x=xx.fecha_prev
x=datetime.strptime(x,formato)
print(x)
resultado=x-fecha_busqueda
if int(resultado.days)<0:
lista.append(xx)
pedidos.remove(xx)
return lista
#for x in self.contactos:
# if x.nacimiento.month == fecha_busqueda.month:
# if x.nacimiento.day == fecha_busqueda.day:
# lista.append(x)
#nacimiento=fecha_busqueda
#formato=("%d,%m,%Y")
#nacimiento=datetime.strptime(nacimiento,formato)
#self.nacimiento=nacimiento
|
d748eb9f72235b2947501a03a1825d6dea7734d4 | amit-mittal/Programming-Questions-Practice | /py/cd202.py | 145 | 3.6875 | 4 | string=raw_input()
i=0
out=''
while i<len(string):
if string[i] in 'aeiou':
out+=string[i]
i+=3
else:
out+=string[i]
i+=1
print out
|
d2d3a343d7bb2e9b775a3218feb0773c86ca8a64 | Mat-Nishi/labs-do-uri-2k21-python | /lab 5/O jogo Matematico de Paula.py | 253 | 3.609375 | 4 | for i in range(int(input())):
val1, op, val2 = input().strip()
val1, val2 = map(int, (val1, val2))
if val1 == val2:
print(val1*val2)
elif op == op.upper():
print(val2-val1)
else:
print(val1+val2) |
57dce894269a208f3acdeabe72eec2629aa040a4 | Aboghazala/AwesomeTkinter | /awesometkinter/text.py | 5,292 | 3.53125 | 4 | """
AwesomeTkinter, a new tkinter widgets design using custom styles and images
:copyright: (c) 2020 by Mahmoud Elshahat.
"""
import tkinter as tk
from tkinter import ttk
from .utils import *
from .scrollbar import SimpleScrollbar
class ScrolledText(tk.Text):
"""Scrolled multiline entry good for log output
has both horizontal and vertical scrollbar
auto-scroll vertically by default, if you move vertical scrollbar it will stop auto scroll until vertical
scroll bar moved back to bottom
undo action disabled to save memory
basically, this is a Text widget inside an outer Frame with scrolllbars,
pack, grid, and place methods for Text will be replaced by outer frame methods
"""
def __init__(self, parent, bg='white', fg='black', bd=0, wrap=None, vscroll=True, hscroll=True, autoscroll=True,
max_chars=None, sbar_fg=None, sbar_bg=None, vbar_width=10, hbar_width=10, **kwargs):
"""initialize
Args:
parent (tk.Frame): parent widget
bg (str): background color
fg (str): foreground color
bd (int): border width
wrap (bool): wrap text, if omitted it will be true if no hscroll
vscroll (bool): include vertical scrollbar
hscroll (bool): include horizontal scrollbar
autoscroll (bool): automatic vertical scrolling
max_chars (int): maximum characters allowed in Text widget, text will be truncated from the beginning to
match the max chars
sbar_fg (str): color of scrollbars' slider
sbar_bg (str): color of scrollbars' trough, default to frame's background
vbar_width (int): vertical scrollbar width
hbar_width (int): horizontal scrollbar width
"""
self.bd = bd
self.bg = bg
self.fg = fg
self.vscroll = vscroll
self.hscroll = hscroll
self.autoscroll = autoscroll
self.max_chars = max_chars
self.sbar_bg = sbar_bg
self.sbar_fg = sbar_fg
self.var = tk.StringVar()
# wrap mechanism
if wrap or not hscroll:
wrap = tk.WORD
else:
wrap = 'none'
# create outside frame
self.fr = tk.Frame(parent, bg=bg)
self.fr.rowconfigure(0, weight=1)
self.fr.columnconfigure(0, weight=1)
# initialize super class
tk.Text.__init__(self, self.fr, bg=self.bg, fg=self.fg, bd=self.bd, wrap=wrap, undo='false', **kwargs)
self.grid(sticky='ewns')
if self.vscroll:
self.vbar = SimpleScrollbar(self.fr, orient='vertical', command=self.yview, slider_color=self.sbar_fg,
bg=self.sbar_bg, width=vbar_width)
self.vbar.grid(row=0, column=1, sticky='ns')
self.config(yscrollcommand=self.vbar.set)
if self.hscroll:
self.hbar = SimpleScrollbar(self.fr, orient='horizontal', command=self.xview, slider_color=self.sbar_fg,
bg=self.sbar_bg, width=hbar_width)
self.hbar.grid(row=1, column=0, sticky='ew')
self.config(xscrollcommand=self.hbar.set)
# bind mouse wheel to scroll
scroll_with_mousewheel(self)
# use outer frame geometry managers
self.pack = self.fr.pack
self.pack_forget = self.fr.pack_forget
self.grid = self.fr.grid
self.grid_forget = self.fr.grid_forget
self.grid_remove = self.fr.grid_remove
self.place = self.fr.place
self.place_forget = self.fr.place_forget
# for compatibility
self.text = self
def set(self, text):
"""replace contents"""
self.clear()
if self.max_chars:
count = len(text)
if count > self.max_chars:
delta = count - self.max_chars
text = text[delta:]
self.insert("1.0", text)
self.scrolltobottom()
def clear(self):
"""clear all Text widget contents"""
self.delete("1.0", tk.END)
def append(self, text, text_color=None, text_bg=None):
"""append text with arbitrary colors"""
color_tags = []
if text_color:
self.tag_configure(text_color, foreground=text_color)
color_tags.append(text_color)
if text_bg:
self.tag_configure(text_bg, foreground=text_bg)
color_tags.append(text_bg)
self.insert(tk.END, text, ','.join(color_tags))
self.remove_extra_chars()
self.scrolltobottom()
def remove_extra_chars(self):
"""remove characters from beginning of Text widget if it exceeds max chars"""
if self.max_chars:
# get current text characters count
count = len(self.get("1.0", tk.END))
if count > self.max_chars:
delta = count - self.max_chars
self.delete("1.0", f"1.0 + {delta} chars")
def scrolltobottom(self):
"""scroll to bottom if autoscroll enabled and scrollbar position at the bottom"""
try:
if self.autoscroll and self.vbar.get()[1] == 1:
self.yview_moveto("1.0")
except:
pass
|
c5a8e5296125e70a28c0fd924de6120afefab7cc | sharevong/algothrim | /rotate_list.py | 1,153 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
问题:旋转单链表
如链表1->2->3->4->5 旋转2步变成 4->5->1->2->3
链表0->1->2 旋转4步变成 2->0->1
"""
from single_linked_list import array_to_single_linked_list
def rotate_list(linked_list, k):
"""
算法思路:先把单链表成环,然后走len-k%len步,得到新的头节点,再断开环即可
断开环的位置在len-k%len-1的节点处(即新的头节点在环状链表中的前一个节点)
"""
node = linked_list.head
l = len(linked_list) # 计算单链表长度需要在成环之前
while node.next:
node = node.next
node.next = linked_list.head # 单链表成环
node = linked_list.head
i = l - k % l - 1
while i > 0:
node = node.next
i -= 1
linked_list.head = node.next
node.next = None
if __name__ == '__main__':
array = [1,2,3,4,5]
linked_list = array_to_single_linked_list(array)
rotate_list(linked_list, 2)
print(linked_list)
array = [0,1,2]
linked_list = array_to_single_linked_list(array)
rotate_list(linked_list, 4)
print(linked_list)
|
f6c83013dc593d370fe4b0f2b3b51b581259c575 | kougianos/python-quizzes | /poker_hand_ranking.py | 3,148 | 4.125 | 4 | # Poker Hand Ranking
# Quiz URL:
# https://edabit.com/challenge/C6pHyc4iN6BNzmhsM
# Quiz description
# In this challenge, you have to establish which kind of Poker combination is present in a deck of five cards. Every card is a string containing the card value (with the upper-case initial for face-cards) and the lower-case initial for suits, as in the examples below:
# "Ah" ➞ Ace of hearts
# "Ks" ➞ King of spades
# "3d" ➞ Three of diamonds
# "Qc" ➞ Queen of clubs
def poker_hand_ranking(deck):
# Error handling
if len(deck) != 5:
return "Invalid input - Deck should contain exactly 5 cards"
deck = split_deck(deck)
flush = False
straight = True
cards = deck[0]
suits = deck[1]
if(len(set(suits)) == 1):
flush = True
if(len(set(cards)) == len(cards)):
noDuplicates = True
elif(len(set(cards)) == 2):
for card in cards:
if(cards.count(card) == 4):
return "Four of a Kind"
return "Full House"
elif(len(set(cards)) == 3):
for card in cards:
if(cards.count(card) == 3):
return "Three of a Kind"
return "Two Pair"
elif(len(set(cards)) == 4):
return "Pair"
if(noDuplicates):
for key, card in enumerate(cards):
if(key <= (len(cards) - 2)):
if((int(cards[key+1]) - int(cards[key])) != 1):
straight = False
if straight and flush and (cards[0] == "10"):
return "Royal Flush"
elif straight and flush:
return "Straight Flush"
elif straight:
return "Straight"
elif flush:
return "Flush"
else:
return "High Card"
# Replace letters with numbers according to dictionary below, and sort deck
# Return object with two lists, one with only numbers of the cards and another one with the suits
def split_deck(deck):
dictionary = {
"J" : "11",
"Q" : "12",
"K" : "13",
"A" : "14",
}
sortedDeck = []
suits = []
objectToReturn = []
for card in deck:
suits.append(card[-1])
if card[0] in dictionary:
sortedDeck.append(dictionary[card[0]])
elif(len(card)==2):
sortedDeck.append("0" + card[0])
else:
sortedDeck.append(card[0:2])
sortedDeck.sort(key=int)
objectToReturn.append(sortedDeck)
objectToReturn.append(suits)
return objectToReturn
print(poker_hand_ranking(["10h", "Jh", "Qh", "Ah", "Kh"]))
print(poker_hand_ranking(["3h", "5h", "Qs", "9h", "Ad"]))
print(poker_hand_ranking(["10s", "10c", "8d", "10d", "10h"]))
print(poker_hand_ranking(["4h", "9s", "2s", "2d", "Ad"]))
print(poker_hand_ranking(["10s", "9s", "8s", "6s", "7s"]))
print(poker_hand_ranking(["10c", "9c", "9s", "10s", "9h"]))
print(poker_hand_ranking(["8h", "2h", "8s", "3s", "3c"]))
print(poker_hand_ranking(["Jh", "9h", "7h", "5h", "2h"]))
print(poker_hand_ranking(["Ac", "Qc", "As", "Ah", "2d"]))
print(poker_hand_ranking(["Ad", "Kd", "Qd", "Jd", "9d"]))
print(poker_hand_ranking(["10h", "Jh", "Qs", "Ks", "Ac"]))
print(poker_hand_ranking(["3h", "8h", "2s", "3s", "3d"]))
print(poker_hand_ranking(["4h", "Ac", "4s", "4d", "4c"]))
print(poker_hand_ranking(["3h", "8h", "2s", "3s", "2d"]))
print(poker_hand_ranking(["8h", "8s", "As", "Qh", "Kh"]))
print(poker_hand_ranking(["Js", "Qs", "10s", "Ks", "As"]))
print(poker_hand_ranking(["Ah", "3s", "4d", "Js", "Qd"]))
|
c540bc3b0c0addb993ff3ae3160cdb92ec9dc9ef | kenifranz/pylab | /places.py | 332 | 4.28125 | 4 | # Print raw list as it is
places = ['Nairobi', 'Kisumu', 'Eldoret','Kisii','Voi','Bungoma']
print(places)
# Print the list using sorted
print(sorted(places))
# Print original list
print (places)
# use sorted in reverse
sorted(places, reverse = True)
print (places)
# Original order
sorted(places, reverse = True)
print(places)
|
8da8f0a22c00853924048bf29570070cb2063a59 | LanaTch/Algorithms | /Lesson1/Lesson1_t7_hw.py | 1,106 | 4.09375 | 4 | # 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним.
a = int(input('введите сторону треугольника a'))
b = int(input('введите сторону треугольника b'))
c = int(input('введите сторону треугольника c'))
if (a < (b + c) and b < (a + c) and c < (a + b)):
if a == b and b == c:
print('треугольник равносторонний')
elif a == b or b == c or a == c:
print('треугольник равнобедренный')
else:
print('треугольник разносторонний')
else:
print('такого треугольника не существует') |
ad2b63813317d978ee12d5942e7582535a22442c | jiangshanmeta/lintcode | /src/0428/solution.py | 483 | 3.515625 | 4 | class Solution:
"""
@param x {float}: the base number
@param n {int}: the power number
@return {float}: the result
"""
def myPow(self, x, n):
if n == 0 :
return 1
if x == 0 :
return 0
if n<0 :
x = 1/x
n = -n
result = 1
while n :
if n&1 :
result *= x
n >>= 1
x *= x
return result |
da74a36739bd32af31d0bba2c42c251b41b5fef5 | lanjar17/Python-Project | /Chapter 5/Latihan 1/Latihan 1_1.py | 544 | 3.8125 | 4 | # program hitung syarat kelulusan
# input nilai
# Bahasa Indonesia
BahasaIndonesia = int(input('Nilai Bahasa Indonesia :'))
if(BahasaIndonesia >= 0 and BahasaIndonesia <= 100):
# Matematika
Matematika = int(input('Nilai Matematika :'))
if(Matematika >=0 and Matematika <= 100):
# IPA
IPA = int(input('Nilai IPA :'))
if(IPA >=0 and IPA <= 100):
# Status Kelulusan
if(BahasaIndonesia > 60 and IPA > 60 and Matematika > 70):
print('Status Kelulusan : LULUS')
else:
print('Status Kelulusan : TIDAK LULUS')
|
f53a82a414ed151320b22a7252d0ae812c4856f9 | eldss-classwork/MITx | /6.00.1x Intro to Comp Sci/CreditCardDebt3.py | 1,325 | 4.125 | 4 | # Evan Douglass
# This program calculates the minimum fixed monthly payment
# that will pay off a given debt in less than one year.
# initialize values
balance = 320000
annualInterestRate = 0.2
def findEndBalance(balance, monthlyRate, payment):
'''
balance (float or int): Original balance in account.
monthlyRate (float): Monthly interest rate.
payment (int or float): Monthly payment.
returns the ending balance after 12 months as a float or int.
'''
test_balance = balance
for month in range(12):
test_balance -= payment
test_balance += (test_balance * monthlyRate)
return test_balance
# initial calculations
monthlyRate = annualInterestRate / 12
upper_bound = (balance * (1 + monthlyRate)**12) / 12
lower_bound = balance / 12
test = (upper_bound + lower_bound) / 2
# bisection search to find lowest payment
bal = findEndBalance(balance, monthlyRate, test)
while not(-0.01 <= bal <= 0):
if bal < 0:
upper_bound = test
test = (upper_bound + lower_bound) / 2
bal = findEndBalance(balance, monthlyRate, test)
elif bal > 0:
lower_bound = test
test = (upper_bound + lower_bound) / 2
bal = findEndBalance(balance, monthlyRate, test)
print('Lowest Payment:', round(test, 2))
|
3310012232e34d19e22052c3240609dd49075398 | sht3898/TIL | /python/problems/my_join.py | 252 | 3.5625 | 4 | def my_join(target, word):
result = ''
for idx in range(len(target)):
if idx == len(target)-1:
result += target[idx]
else:
result += target[idx] + word
return result
print(my_join('배고파','.'))
|
6b3f727229e5c597488975e78552c215bee6f9a1 | WilsonAceros/Python | /PythonBasicoFacundo/funciones.py | 677 | 3.984375 | 4 | """def imprimir_mensaje():
print("Mensaje especial 1: ")
print("Estoy aprendiendo a usar funciones:")
imprimir_mensaje()
imprimir_mensaje()
imprimir_mensaje()"""
opcion=int(input("Elige una opcion (1,2,3): "))
def conversacion(mensaje):
print("Hola")
print("Como estas")
print(mensaje)
print("Adios")
if opcion==1:
conversacion("Elegiste la opcion 1")
elif opcion==2:
conversacion("Elegiste la opcion 2")
elif opcion==3:
conversacion("Elegiste la opcion 3")
else:
print("Elige una opcion correcta")
def suma(a,b):
print("Se suman dos numeros")
resultado=a+b
return resultado
sumatoria=suma(1,4)
print(sumatoria) |
3dbc4abeb4c963d5c31e19db06b1244f8b3caec0 | adwanAK/adwan_python_core | /think_python_solutions/chapter-12/exercise-12.4.py | 1,453 | 3.96875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-12.4.py
Created by Terry Bates on 2013-02-04.
Copyright (c) 2013 http://the-awesome-python-blog.posterous.com. All rights reserved.
"""
import sys
import os
import collections
import cPickle
#word_list = "food doof ape pea pole lope".split()
word_list_file = open('/Users/tbates/python/Think-Python/think-python/words_list', 'rb')
word_list = cPickle.load(word_list_file)
def main():
total_words_dict = dict()
for word in word_list:
# Create a dictionary value
word_dict = dict()
for char in word:
# Use setdefault method to create new key if need be, update current key
word_dict[char] = word_dict.setdefault(char,0) + 1
# Once we have word_dict populated, we must sort it, due to random acccess nature.
# Use the 'collections' module because we are lazy. http://docs.python.org/2/library/collections.html
# Section 8.3.5
sorted_word_dict = collections.OrderedDict(sorted(word_dict.items(), key=lambda t: t[0]))
letter_count_t = tuple(sorted_word_dict.items())
#print letter_count_t
# Use letter_count_t as a dictionary
total_words_dict.setdefault(letter_count_t,[]).append(word)
# Pretty print the anagrams
for anagram_list in total_words_dict.values():
if len(anagram_list) > 1:
print anagram_list
if __name__ == '__main__':
main()
|
5e00f304da76905b6a597e171b96d76c6e2a21bf | QuteSaltyFish/python | /python_basics/ex.py | 256 | 3.921875 | 4 | x1 = 10
x2 = 20
numbers = []
for number in range(1, x2, 2):
print(number)
tmp = number ** 2
numbers.append(tmp)
print(numbers)
print(min(numbers))
print(max(numbers))
print(sum(numbers))
square = [x**2 for x in range(1, 10)]
print(square[-3:])
|
e8bd5aa1be156bf8b58f64f5b7b53410f66261aa | SuLab/crowd_cid_relex | /crowd_only/src/filter_data.py | 641 | 3.546875 | 4 | """
Tong Shu Li
Last updated 2015-10-22
"""
import os
import pandas as pd
def filter_data(settings):
"""Filters raw CrowdFlower output down to data we care about.
Formatting the data is left to another program.
"""
data = pd.read_csv(os.path.join(settings["loc"], settings["fname"]), sep = ",",
dtype = settings["dtype"])
if settings["data_subset"] == "gold":
data = data.query("_golden")
elif settings["data_subset"] == "normal":
data = data.query("~_golden")
data = (data.query("{0} <= _trust <= {1}".
format(settings["min_accuracy"], settings["max_accuracy"])))
return data
|
737ae5ed42da8f4ab76dca2262a6c06e8233fb64 | fergusodowd/countdown | /teatime_teaser.py | 274 | 3.765625 | 4 | import nltk
from nltk.corpus import words
letters = input("Please enter the nine letters: \n")
def teatimeteaser(letters):
word = [w for w in nltk.corpus.words.words() if nltk.FreqDist(w) == nltk.FreqDist(letters)]
print(word)
return word
teatimeteaser(letters)
|
cafbbe845cd6aca7eb7e81f80fabcbe825cb5ff3 | minshyee/Algorithm | /study_07/bestrang.py | 500 | 3.78125 | 4 | n_list = []
def count_prime(n):
# res = n
test = list(range(n+1,2*n+1))
for i in range(n+1, 2*n + 1):
for j in range(2, int(round(i**0.5, 0))+1):
if i % j == 0:
# print(i,'not')
test.remove(i)
# res -= 1
break
print(test, len(test))
return test
# 입력
while True:
n = int(input())
if n == 0:
break
else:
n_list.append(n)
sorted(n_list)
p_list = count_prime(n_list.pop)
for n in n_list:
print(count_prime(n))
|
a007b9a30e80bbbc20ffe5059c1458f36b3858eb | doyu/hy-data-analysis-with-python-summer-2021 | /part02-e01_integers_in_brackets/src/integers_in_brackets.py | 692 | 4.4375 | 4 | #!/usr/bin/env python3
'''
Exercise 1 (integers in brackets)
Write function integers_in_brackets that finds from a given string all integers that are enclosed in brackets.
Example run: integers_in_brackets(" afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx") returns [12, -43, 12].
So there can be whitespace between the number and the brackets, but no other character besides those that make up the integer.
Test your function from the main function.
'''
import re
def integers_in_brackets(s):
return list(map(int, re.findall(r'\[\s*([\-+]?\d+)\s*\]', s)))
def main():
print(integers_in_brackets(" afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx"))
if __name__ == "__main__":
main()
|
5d74f11d2abaa44e54d6ba02e0b995a627ffe113 | Ankirama/Epitech | /B4---Elementary-Programming---Special-Project/trade/trade | 2,553 | 3.578125 | 4 | #!/usr/bin/env python2.7
import sys, os
from math import *
def raw_input_checked(str_ = ""):
done = False
value = 0
while done == False:
done = True
try:
data = raw_input(str_)
value = (int(data))
if (value < 0):
raise ValueError("Negative Number")
except (ValueError):
print("error: [{}] must be a number and positive".format(data))
done = False
return value
def buy(portefeuille, cours):
buy_actions = floor((portefeuille[0]) / cours)
commission = cours * buy_actions + ceil((0.15 / 100.0 * (cours * buy_actions)))
if (portefeuille[0] - commission < 0):
buy_actions = buy_actions - 1
if (buy_actions > 0):
portefeuille[0] = portefeuille[0] - cours * buy_actions - ceil((0.15 / 100.0 * (cours * buy_actions)))
portefeuille[1] = portefeuille[1] + buy_actions
os.write(1, "buy {}\n".format(buy_actions))
else:
os.write(1, "wait\n")
def wait():
os.write(1, "wait\n")
def sell(portefeuille, cours):
if (portefeuille[1] > 0):
os.write(1, "sell {}\n".format(portefeuille[1]))
portefeuille[0] = portefeuille[0] + portefeuille[1] * cours - ceil((0.15 / 100.0 * (portefeuille[1] * cours)))
portefeuille[1] = 0
else:
os.write(1, "wait\n")
# Calcul de la moyenne mobile exponentielle
def calcul_mme(prev_mme, cours, day):
C = 2.0 / (day + 1.0)
return (C * cours + (1.0 - C) * prev_mme)
def analyse(informations, portefeuille, cours):
if (informations.get("mme_50") > informations.get("mme_150")):
buy(portefeuille, cours)
elif (informations.get("mme_50") < informations.get("mme_150")):
sell(portefeuille, cours)
def getIn(portefeuille, max_day):
info = raw_input()
day = 1
informations = {}
informations["mme_50"] = 0.0
informations["mme_150"] = 0.0
while (info.lower() != "--end--"):
try:
cours = (int(info))
except (ValueError):
print("error: [{}] must be a number and positive".format(info))
info = raw_input()
continue
if (day == max_day and portefeuille[1] > 0):
sell(portefeuille, cours)
else:
informations["mme_50"] = calcul_mme(informations.get("mme_50"), cours, 50)
informations["mme_150"] = calcul_mme(informations.get("mme_150"), cours, 150)
analyse(informations, portefeuille, cours)
day = day + 1
info = raw_input()
def main():
capital = raw_input_checked()
day = raw_input_checked()
portefeuille = []
actions = 0
portefeuille.append(capital)
portefeuille.append(actions)
getIn(portefeuille, day)
if __name__ == "__main__":
main()
|
955cb987f012dbf7bdc14e47bea747160ed46ac2 | hitomitak/qiskit-benchmark | /application/counterfeit_coin.py | 2,797 | 3.59375 | 4 | """
To generate a circuit for counterfeit-coin finding
algorithm using 15 coins and the false coin is the third coin,
type the following.
python cc_gen.py -c 15 -f 3
@author Raymond Harry Rudy rudyhar@jp.ibm.com
"""
import random
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
class CounterfeitCoin:
"""
CC Generator
"""
def __init__(self, seed):
self.name = "cc"
self.seed = seed
@classmethod
def generate_false(cls, ncoins):
"""
generate a random index of false coin (counting from zero)
"""
return random.randint(0, ncoins-1)
@classmethod
def gen_cc_main(cls, ncoins, index_of_false_coin):
"""
generate a circuit of the counterfeit coin problem
"""
# using the last qubit for storing the oracle's answer
nqubits = ncoins + 1
# Creating registers
# qubits for querying coins and storing the balance result
q_r = QuantumRegister(nqubits)
# for recording the measurement on qr
c_r = ClassicalRegister(nqubits)
cccircuit = QuantumCircuit(q_r, c_r)
# Apply Hadamard gates to the first ncoins quantum register
# create uniform superposition
for i in range(ncoins):
cccircuit.h(q_r[i])
# check if there are even number of coins placed on the pan
for i in range(ncoins):
cccircuit.cx(q_r[i], q_r[ncoins])
# perform intermediate measurement to check if the last qubit is zero
cccircuit.measure(q_r[ncoins], c_r[ncoins])
# proceed to query the quantum beam balance if cr is zero
cccircuit.x(q_r[ncoins]).c_if(c_r, 0)
cccircuit.h(q_r[ncoins]).c_if(c_r, 0)
# we rewind the computation when cr[N] is not zero
for i in range(ncoins):
cccircuit.h(q_r[i]).c_if(c_r, 2**ncoins)
# apply barrier for marking the beginning of the oracle
cccircuit.barrier()
cccircuit.cx(q_r[index_of_false_coin], q_r[ncoins]).c_if(c_r, 0)
# apply barrier for marking the end of the oracle
cccircuit.barrier()
# apply Hadamard gates to the first ncoins qubits
for i in range(ncoins):
cccircuit.h(q_r[i]).c_if(c_r, 0)
# measure qr and store the result to cr
for i in range(ncoins):
cccircuit.measure(q_r[i], c_r[i])
return cccircuit
def gen_application(self, app_arg):
"""
generate application
"""
random.seed(self.seed)
qubits = app_arg["qubit"]
qubits = qubits - 1
falseindex = None
if falseindex is None:
falseindex = self.generate_false(qubits)
circ = self.gen_cc_main(qubits, falseindex)
return circ
|
8068b81849be3e1cf7c7de2379339d2ba731afa0 | bapillai/python-learning-excercises | /python-excercises/excercise-1.py | 1,253 | 4.3125 | 4 | # Write a Python Program that uses three variables.The variables in your program will be animal, vegetable and a mineral.Assign a string value to each one of the variables.Your program should display “Here is an animal, a vegetable, and a mineral.”Next, display the value for animal, followed by vegetable, and finally mineral. Each one of the values should be printed on their own line. Your program will display four lines in total
animal = "cat"
vegetable = "broccoli"
mineral = "gold"
sentence = animal + " "+ vegetable + " " + mineral + "."
print(sentence)
print(animal)
print(vegetable)
print(mineral)
print("--" * 16)
# Write a python program that prompts the user and simply repeats what the user entered.
userInput = input("Please type something and press enter: ")
print("You Entered: {}".format(userInput))
print("--" * 16)
# Write a Python program that prompts for input and displays a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.
userInput = input("What do you want the cat to say: ")
print("-" * (len(userInput)+4))
print("< {} >".format(userInput))
print("-" * (len(userInput)+4)) |
8a13e25428ef5e805d9adb5ad2884d2e1d292f68 | ElkinAMG/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 307 | 3.625 | 4 | #!/usr/bin/python3
'''
This module has a class `MyList` that
inherits from `list`.
'''
class MyList(list):
'''
This class has the method `print_sorted`.
'''
def print_sorted(self):
'''
This function prints in sorted way the list.
'''
print(sorted(self))
|
75b2633eaae035b4a24f6178211faa6e53ece36b | tarapulka26/Python_school | /Lesson06_easy.py | 2,677 | 4.21875 | 4 | # Задача - 1
# Опишите несколько классов TownCar, SportCar, WorkCar, PoliceCar
# У каждого класса должны быть следующие аттрибуты:
# speed, color, name, is_police - Булево значение.
# А так же несколько методов: go, stop, turn(direction) - которые должны сообщать,
# о том что машина поехала, остановилась, повернула(куда)
class Car:
def __init__( self, speed, color, name,):
self.speed = speed
self.color = color
self.name = name
def car_go( self):
print ('машина {} поехала!'.format (self.name))
def car_stop( self ):
print ('Машина {} остановилась!'.format (self.name))
def car_turn ( self , direction ):
print('Машина {} повернула {}!'.format (self.name , direction))
class TownCar(Car):
def __init__ (self, speed, color, name):
Car.__init__(self,speed,color,name)
class SportCar(Car):
def __init__(self, speed, color, name):
Car.__init__(self, speed, color, name)
class WorkCar(Car):
def __init__(self, speed, color, name):
Car.__init__(self, speed, color, name)
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police = False):
Car.__init__(self, speed, color, name)
self.is_police = is_police
# Задача - 2
# Посмотрите на задачу-1 подумайте как выделить общие признаки классов
# в родительский и остальные просто наследовать от него.
class Car:
def __init__( self, speed, color, name,):
self.speed = speed
self.color = color
self.name = name
def car_go( self):
print ('машина {} поехала!'.format (self.name))
def car_stop( self ):
print ('Машина {} остановилась!'.format (self.name))
def car_turn ( self , direction ):
print('Машина {} повернула {}!'.format (self.name , direction))
class TownCar(Car):
def __init__ (self, speed, color, name):
Car.__init__(self,speed,color,name)
class SportCar(Car):
def __init__(self, speed, color, name):
Car.__init__(self, speed, color, name)
class WorkCar(Car):
def __init__(self, speed, color, name):
Car.__init__(self, speed, color, name)
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police = False):
Car.__init__(self, speed, color, name)
self.is_police = is_police |
b60d1963a61fcc09f8ab6e3cf6a09043e60ca499 | wonbuu/PyIntro | /grading.py | 351 | 4.0625 | 4 | #accepting the input from the user
grade = int(input("What grade did you get?"))
#building the results
print('You get ')
if (grade > 100):
print("EXPELLED FOR CHEATING")
elif (grade > 89):
print("A")
elif (grade > 79):
print("B")
elif (grade > 69):
print("C")
elif (grade > 59):
print("D")
else:
print("F")
|
b907e376e1afb23c3017b8a55732462010edc8be | allypreston/pythonday3 | /03Methods_and_modules.py | 325 | 3.96875 | 4 | class Dog:
animal_kind = "Canine"
def __init__(self, name):
self.name = name
def speak(self):
return "woof"
dog1 = Dog("Charlie")
dog2 = Dog("Don")
print(dog1.name)
print(dog2.name)
# constructor - a method that is used automatically when a
# object is created to assign a variable property
|
17a40a340aec360dbe856c4f106f7844876bca8d | ciptah/dl_1008 | /hw1/models/pseudo_label.py | 318 | 3.5 | 4 | """
Functions for pseudo label
"""
def default_pseudo_label_func(unlabel, t):
T1 = 200
T2 = 800
alpha_f = 3.0
if not unlabel:
return 1
else:
if t < T1:
return 0
elif t < T2:
return float(t-T1)/(T2-T1)*alpha_f
else:
return alpha_f |
fd95127703b641b670e1e759f2cdf06eb6ae5e97 | Mniharbanu/guvi | /codekata/holiday.py | 203 | 3.828125 | 4 | a1 = 'Monday'
b1 = 'Tuesday'
c1 = 'Wednesday'
d1= 'Thursday'
e1 = 'Friday'
f1 = 'Saturday'
g1= 'Sunday'
i = str(input())
if(i==a1 or i==b1 or i==c1 or i==d1 or i==e1):
print("no")
else:
print("yes")
|
bf74dc3829b4c3a8c776405a96b9dac0167d9fef | DavidAmison/natural_time | /natural_time/num_parse.py | 5,994 | 3.890625 | 4 |
"""
Created on Sat Mar 4 21:17:28 2017
Converts written numbers to integers: Currenlty designed only for positive whole numbers.
@author: David
"""
d_numbers = {
'eleven':11,
'twelve':12,
'thirteen':13,
'fourteen':14,
'fifteen':15,
'sixteen':16,
'seventeen':17,
'eighteen':18,
'nineteen':19,
'twenty':20,
'thirty':30,
'fourty':40,
'forty':40,
'fifty':50,
'sixty':60,
'seventy':70,
'eighty':80,
'ninety':90,
'one':1,
'a': 1,
'an': 1,
'two':2,
'three':3,
'four':4,
'five':5,
'six':6,
'seven':7,
'eight':8,
'nine':9,
'ten':10,
'hundred':100,
'thousand':1000,
'million':1000000,
}
d_positions = {
'first':1,
'second':2,
'third':3,
'fourth':4,
'fifth':5,
'sixth':6,
'seventh':7,
'eighth':8,
'ninth':9,
'tenth':10,
'eleventh':11,
'twelth':12,
'thirteenth':13,
'fourteenth':14,
'fifteenth':15,
'sixteenth':16,
'seventeenth':17,
'eighteenth':18,
'nineteenth':19,
'twentieth':20,
'thirtieth':30,
'fourtieth':40,
'fiftieth':50,
'sixtieth':60,
'seventieth':70,
'eightieth':80,
'ninetieth':90,
'hundreth':100,
'thousandth':1000,
'millienth':1000000,
}
def convert(s):
'''Convert all numbers in the string to digits'''
numbers = extract_num(s)
#Is there any millions, thousands or hundreds?
i = 0
mi = -1
th = -1
hu = -1
#Find indices of million, thousands and hundreds
for num in numbers:
if num == 1000000:
mi = i
th = i
hu = i
break
i += 1
i = mi if mi>-1 else 0
for num in numbers[i:]:
if num == 1000:
th = i
hu = i
break
i += 1
i = th if th>-1 else 0
for num in numbers[i:]:
if num == 100:
hu = i
break
i += 1
total = 0
total += convert_prefix(numbers[0:mi]) * 1000000 if mi > -1 else 0
total += convert_prefix(numbers[mi+1:th]) * 1000 if th > -1 else 0
total += convert_prefix(numbers[th+1:hu]) * 100 if hu > -1 else 0
total += convert_prefix(numbers[hu+1:])
return total
def convert_prefix(numbers):
total = 0
last = 0
for num in numbers:
if num in [100,1000]:
#Take away the number that would have been added
if last == 0:
last = num
total += last
else:
total -= last
last = num*last
total += last
else:
total += num
last = num
return total
#Read character by character from the right until something matches, store that number
#empty string and continue from that point.
def extract_num(s):
'''
Returns all numbers in a string as a list in the order that they appear.
Note that it does not interpret the meaning but simply writes the numbers: e.g
one-hundred and ninety nine will return [1,100,90,9]
'''
check_str = ''
numbers = []
for c in reversed(s):
#Start building the string
check_str = c + check_str
#Check if it matches anything in the dictionary
for num in d_numbers:
if num in check_str:
numbers.insert(0,d_numbers[num])
check_str = ''
break
for num in d_positions:
if num in check_str:
numbers.insert(0,d_positions[num])
check_str = ''
break
return numbers
def convert_num(s):
'''
Returns the input string with all numbers converted to digit format
Currently only works for simple numbers
'''
s = s.split() #split up all the words
#Check whether each word is a number in written form
output_w = []
previous_num = 0
for w in s:
check_str = ''
numbers = []
positional = False
for c in reversed(w):
check_str = c + check_str
for num in d_numbers:
if num in check_str:
numbers.insert(0,d_numbers[num])
check_str = ''
break
for num in d_positions:
if num in check_str:
numbers.insert(0,d_positions[num])
positional = True
check_str = ''
break
#Try to understand the number (assumption that only two maximum will be found e.g twenty-three)
n = 0
if len(numbers) > 1:
if numbers[0] > numbers[1]:
n = numbers[0]+numbers[1]
else:
n = numbers[0]*numbers[1]
elif len(numbers) == 0:
n = w
elif numbers[0] < previous_num:
n += previous_num + numbers[0]
elif previous_num == 0:
n = numbers[0]
else:
n = previous_num * numbers[0]
#Delete the previous number if this value includes it
if previous_num > 0 and isinstance(n,int):
del output_w[-1]
#Add the word into the list (adjusting if it is a positional number)
output_w.append(str(n)+'st') if positional==True else output_w.append(str(n))
try:
previous_num = int(n)
except ValueError:
previous_num = 0
output = ' '.join(str(w) for w in output_w)
return output |
982b5138c478fb07fa8a9c92f7de6d76200ee0a4 | kimurakousuke/MeiKaiPython | /chap06/list0610.py | 192 | 4.0625 | 4 | # 使用enumerate函数反向遍历并输出字符串的所有字符
s = input('字符串:')
for i, ch in enumerate(reversed(s), 1):
print('倒数第{}个字符:{}'.format(i, ch)) |
85463364722193d5bacf26e53c0fce0010a9dc7c | Babawale/WeJapaInternship | /Labs/Wave_3_labs/zip_dict.py | 342 | 3.90625 | 4 | #Zip Lists to a Dictionary
#Use zip to create a dictionary cast that uses names as keys and heights as values.
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
# replace with your code
cast = dict(zip(cast_names, cast_heights)) # zips both list together and converts to dictionary
print(cast)
|
d5e49a938222e0ce73fe69f82a8288f4dd55a7fe | qilaidi/leetcode_problems | /leetcode/127WordLadder.py | 1,468 | 3.59375 | 4 | # -*- encoding: utf-8 -*-
# Create by zq
# Create on 2020/2/22
import collections
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
if endWord not in wordList or not beginWord or not endWord or not wordList:
return 0
mask_dict, res = collections.defaultdict(list), None
word_len = len(endWord)
for word in wordList:
for i in range(word_len):
mask_dict[word[:i] + "*" + word[i+1:]].append(word)
beginq = [(beginWord, 1)]
endq = [(endWord, 1)]
begin_visited = {beginWord: 1}
end_visited = {endWord: 1}
def trans_word(queue, queue_visited, other_visited):
current_word, level = queue.pop(0)
for i in range(word_len):
mask_word = current_word[:i] + "*" + current_word[i+1:]
for word in mask_dict[mask_word]:
if word in other_visited:
return level + other_visited[word]
if word not in queue_visited:
queue_visited[word] = level + 1
queue.append((word, level + 1))
return None
while beginq and endq:
res = trans_word(beginq, begin_visited, end_visited)
if res:
return res
res = trans_word(endq, end_visited, begin_visited)
if res:
return res
return 0
|
c9c5576f07784304246819c3a5c9c572a15808a0 | jmmunoza/ST0245-008 | /Talleres/Taller_6_ordenacion/Ejercicio_12.py | 4,392 | 3.78125 | 4 | # El algoritmo de RadixSort consiste en tomar los valores de la lista que se
# ingrese y tomar el último dígito de cada valor, y dependiendo de dicho dígito,
# el valor se almacenará en una nueva lista en la posición que coincida con el
# dígito. Si no queda claro, acá un ejemplo:
#
# Ingresamos la lista [23,43,57,132,2]
# entonces el algoritmo empezará con 23, toma su último dígito, que es 3, y almacena
# el número 23 en una nueva lista en la posición que coincide con el último digito 3
# Por lo que quedaría así:
# ListaNueva = [[],[],[],[23],[],[],[],[],[],[]]
# Repetirá este proceso hasta terminar de recorrer la lista, quedando la lista nueva así:
# ListaNueva = [[],[],[132, 2],[23, 43],[],[],[],[57],[],[]]
# Tras esto, se vaciará la lista y se agregarán los valores de la lista nueva en el orden
# en que está, quedando así:
# lista = [132, 2, 23, 43, 75]
# Se vaciará la lista nueva y se repetirá el proceso, pero ahora no con los últimos dígitos,
# si no con los penúltimos, posteriormente con los antepenúltimos y así sucesivamente hasta
# llegar al número de dígito que sea igual al número de digitos del número con más dígitos
# en la lista, por lo que si por ejemplo, en la lista el elemento 354321 es el número con más
# dígitos, el proceso de ordenamiento descrito previamente se debe repetir 6 veces, que son los
# dígitos de 354321.
#
# Abajo dejo el código que hice yo mismo.
# Nota: no sé si sea que implementé mal el algoritmo o sean limitaciones del mismo, pero me presenta
# fallas con los números negativos.
def RadixSort(lista):
decimales = [[],[],[],[],[],[],[],[],[],[]]
max,div = 0, 1
def cuantos_digitos(n):
ind = 1
while n > 9:
n = n / 10
ind = ind + 1
return ind
for i in lista:
if cuantos_digitos(i) > max:
max = cuantos_digitos(i)
for i in range(max):
for j in lista:
decimales[(j//div)%10].append(j)
lista = []
for j in decimales:
lista.extend(j)
decimales = [[],[],[],[],[],[],[],[],[],[]]
div *= 10
return lista
lista = [64,56,1,54,654,654,646,546,210,20]
# El algoritmo de Binsort consiste en tomar una lista y separar sus elementos en unas "casillas".
# En estas casillas solo pueden haber números con unas condiciones únicas que varían dependiendo
# de cada casilla. Por ejemplo, en una casiila solo se guardan los números entre el 1 al 10,
# en otra los números entre el 11 al 20, y así sucesivamente.
# Una vez están separados los números en sus respectivas casillas, se ordenan las casillas individualmente
# con el método de ordenamiento que se prefiera, se puede utilizar burbuja, selección, inserción,
# quick, shell, mezcla, etc.
# Ya que estén ordenadas todas las casillas, estas se agregan a la lista inicial, obviamente vaciándola para
# que no se acumulen elementos. Y ya que las casillas ordenadas se agregaron en la lista, se retorna.
# Para este ejemplo de Binsort, me basé en código externo, ya que sinceramente me dio dificultad implementar
# el método por mi propia cuenta. El método que utilicé para ordenar cada casilla fué el de inserción.
# Nota: Me ocurrió algo similar que con el RadixSort, cuando ingreso valores negativos pero me presenta
# fallas y no ordena correctamente.
def BinSort(lista):
def insercion(lista):
for i in range(1, len(lista)):
valor_a_ordenar = lista[i]
while lista[i-1] > valor_a_ordenar and i > 0:
lista[i], lista[i-1] = lista[i-1], lista[i]
i -= 1
return lista
max_valor = max(lista)
size = max_valor/len(lista)
lista_nueva= []
for i in range(len(lista)):
lista_nueva.append([])
for i in range(len(lista)):
j = int (lista[i] / size)
if j != len(lista):
lista_nueva[j].append(lista[i])
else:
lista_nueva[len(lista)-1].append(lista[i])
for i in range(len(lista)):
insercion(lista_nueva[i])
lista_ordenada = []
for i in range(len (lista)):
lista_ordenada = lista_ordenada + lista_nueva[i]
return lista_ordenada
lista = BinSort(lista)
print(lista) |
4b25a9a9797a24fb1d7db9038825440f26ff709e | Jecleet/Programming2 | /Problems/Sorting/05_sorting_problems.py | 3,762 | 4.15625 | 4 | '''
Sorting and Intro to Big Data Problems (22pts)
Import the data from NBAStats.py. The data is all in a single list called 'data'.
I pulled this data from the csv in the same folder and converted it into a list for you already.
For all answers, show your work
Use combinations of sorting, list comprehensions, filtering or other techniques to get the answers.
'''
def split_line(line):
# This function takes in a line of text and returns
# a list of words in the line.
return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line)
from NBAStats import data
#1 Pop off the first item in the list and print it. It contains the column headers. (1pt)
print(data.pop(0))
#2 Print the names of the top ten highest scoring single seasons in NBA history?
# You should use the PTS (points) column to sort the data. (4pts)
pts_list = []
data_point = data[2]
length = len(data_point) - 1
for i in range(len(data)):
pts_list.append(data[i][length])
print# Why doesn't this work??
pts_list2 = pts_list[:]
print (pts_list2)
for i in range(10):
max_value = max(pts_list) # finds the max of the list
max_value_index = pts_list.index(max_value) # finds the place in the list where this value occurs
pts_list.pop(max_value_index) # removes this from pts_list so that next time it will find the next biggest number
max_value_index = pts_list2.index(max_value) # checks a list which has not had anything popped off so the numbers still align with the names
print(data[max_value_index][2]) #uses the index from the list which doesn't have values popped off to find the name corresponding with each number??
#3 How many career points did Kobe Bryant have? Add up all of his seasons. (4pts)
name = ''
goal_name = "Kobe Bryant"
career_points = 0
done = False
for i in range(len(data)):
name = data[i][2]
if name.upper() == goal_name.upper():
length = len(data[i]) - 1
career_points += data[i][length]
print(career_points)
#4 What player has the most 3point field goals in a single season. (3pts)
points_list = []
for i in range(len(data)):
points_list.append(data[i][-19])
index = points_list.index(max(points_list))
print(data[index][2])
#5 One stat featured in this data set is Win Shares(WS). -28
# WS attempts to divvy up credit for team success to the individuals on the team.
# WS/48 is also in this data. It measures win shares per 48 minutes (WS per game).
# Who has the highest WS/48 season of all time? (4pts)
win_shares_list = []
for i in range(len(data)):
win_shares_list.append(data[i][-28])
index = win_shares_list.index(max(win_shares_list))
print(data[index][2])
#6 Write your own question that you have about the data and provide an answer (4pts)
# Maybe something like: "Who is the oldest player of all time?" or "Who played the most games?" or "Who has the most combined blocks and steals?".
# Who is the oldest player of all time?
age_list = []
for i in range(len(data)):
age_list.append(data[i][4])
index = age_list.index(max(age_list))
print(data[index][2])
#7 Big challenge, few points. Of the 100 highest scoring single seasons in NBA history, which player has the
# worst free throw percentage? Which had the best? (2pts)
most_pts = 0
current_pts = 0
player = ''
list_100_players_points = []
list_100_players = []
data2 = data[:]
for m in range(100):
for i in range(len(data2)):
current_pts = data2[i][-1]
if current_pts > most_pts:
most_pts = current_pts
player = data2[i][2]
player_place = i
list_100_players.append(data2[player_place][2])
list_100_players_points.append(data2[player_place][-1])
data2.pop(player_place)
index = int(min(list_100_players_points))
print(list_100_players[index])
|
a54407745689f3bbd03aab5b12114ce3fe35d126 | justinclark-dev/CSC110 | /code/Chapter-10/coin_demo3.py | 1,106 | 4.25 | 4 | import random
# The Coin class simulates a coin that can
# be flipped.
class Coin:
# The __init__ method initializes the
# __sideup data attribute with 'Heads'.
def __init__(self):
self.__sideup = 'Heads'
# The toss method generates a random number
# in the range of 0 through 1. If the number
# is 0, then sideup is set to 'Heads'.
# Otherwise, sideup is set to 'Tails'.
def toss(self):
if random.randint(0, 1) == 0:
self.__sideup = 'Heads'
else:
self.__sideup = 'Tails'
# The get_sideup method returns the value
# referenced by sideup.
def get_sideup(self):
return self.__sideup
# The main function.
def main():
# Create an object from the Coin class.
my_coin = Coin()
# Display the side of the coin that is facing up.
print('This side is up:', my_coin.get_sideup())
# Toss the coin.
print('I am going to toss the coin ten times:')
for count in range(10):
my_coin.toss()
print(my_coin.get_sideup())
# Call the main function.
main()
|
e8c21029a809f2a75c0abfee23963a6fffce0f1d | Shristi19/DataStructuresInPython | /Insertion Sort.py | 451 | 3.875 | 4 |
li=[7,8,1,23,4,5]
def insertion_sort(li):
j=1
for i in range(1,len(li)):###ggoing from the 1st element to the end
j=i-1
key=li[i]
while j>=0 and li[j]>key:##j till we find where to put the ith element
li[j+1]=li[j]####move the elemnts one step ahead eg: jj=1 then li[2]=li[1] becomes==[7,8,8] then j=0 then li[1]=li[0] ==[7,7,8] yhen li[0]=keyy
j-=1
li[j+1]=key
insertion_sort(li)
|
1e38934663d8b2ffe8bd9bb840fc56d16ad749f1 | ak-b/Problem-Solving | /binary_search/binary_search06.py | 1,552 | 4.09375 | 4 | '''
Given an array of numbers sorted in ascending order, find the element in the array that has the minimum difference with the given ‘key’.
Example 1:
Input: [4, 6, 10], key = 7
Output: 6
Explanation: The difference between the key '7' and '6' is minimum than any other number in the array
Example 2:
Input: [4, 6, 10], key = 4
Output: 4
Example 3:
Input: [1, 3, 8, 10, 15], key = 12
Output: 10
Example 4:
Input: [4, 6, 10], key = 17
Output: 10
Time complexity #
Since, we are reducing the search range by half at every step, this means the time complexity of our algorithm will be O(logN)O(logN) where ‘N’ is the total elements in the given array.
Space complexity #
The algorithm runs in constant space O(1)O(1).
'''
def search_min_diff_element(arr, key):
if key < arr[0]:
return arr[0]
n = len(arr)
if key > arr[n - 1]:
return arr[n - 1]
start, end = 0, n - 1
while start <= end:
mid = start + (end - start) // 2
if key < arr[mid]:
end = mid - 1
elif key > arr[mid]:
start = mid + 1
else:
return arr[mid]
# at the end of the while loop, 'start == end+1'
# we are not able to find the element in the given array
# return the element which is closest to the 'key'
if (arr[start] - key) < (key - arr[end]):
return arr[start]
return arr[end]
def main():
print(search_min_diff_element([4, 6, 10], 7))
print(search_min_diff_element([4, 6, 10], 4))
print(search_min_diff_element([1, 3, 8, 10, 15], 12))
print(search_min_diff_element([4, 6, 10], 17))
main()
|
ccd34758a68f9d07d1f2b75aef0c7ced5e8558bb | AkshayGuptaK/cs61a | /midterm1.py | 3,674 | 3.796875 | 4 | aaron, burr = 2, 5
aaron, burr = 4, aaron + 1
hamil = 10
def alex(hamil):
def g(w):
hamil = 2 * w
print(hamil, w)
w = hamil
return hamil
w = 5
alex = g(w + 1)
print(w, alex, hamil) # 5 12 3
def el(i, za):
def angelica():
return i + 1
if i > 10:
return za()
elif i > 4:
print(angelica())
return el(i * i, za)
else:
return el(i * i, angelica)
K = lambda x: lambda y: x
def pr(x):
print(x)
return x
# Q3 onwards
def triangle(a, b, c):
"""Return whether a, b, and c could be the legs of a triangle.
>>> triangle(3, 4, 5)
True
>>> triangle(3, 4, 6)
True
>>> triangle(6, 3, 4)
True
>>> triangle(3, 6, 4)
True
>>> triangle(9, 2, 2)
False
>>> triangle(2, 4, 2)
False
"""
longest = max(a, b, c)
sum_of_others = a + b + c - longest # or min(a+b, a+c, b+c)
return longest < sum_of_others
def collapse(n):
"""For non-negative N, the result of removing all digits that are equal
to the digit on their right, so that no adjacent digits are the same.
>>> collapse(1234)
1234
>>> collapse(12234441)
12341
>>> collapse(0)
0
>>> collapse(3)
3
>>> collapse(11200000013333)
12013
"""
left, last = n // 10, n % 10
if left == 0:
return last
elif left % 10 == last:
return collapse(left)
else:
return collapse(left) * 10 + last
def find_pair(p):
"""Given a two-argument function P, return a function that takes a
non-negative integer and returns True if and only if two adjacent digits
in that integer satisfy P (that is, cause P to return a true value).
>>> z = find_pair(lambda a, b: a == b) # Adjacent equal digits
>>> z(1313)
False
>>> z(12334)
True
>>> z = find_pair(lambda a, b: a > b)
>>> z(1234)
False
>>> z(123412)
True
>>> find_pair(lambda a, b: a <= b)(9753)
False
>>> find_pair(lambda a, b: a == 1)(1) # Only one digit; no pairs.
False
"""
def find(n):
while n > 9:
if p((n // 10) % 10, n % 10):
return True
else:
n = n // 10
return False
return find
def confirmer(code):
"""Return a confirming function for CODE.
>>> confirmer(204)(2)(0)(4) # The digits of 204 are 2, then 0, then 4.
True
>>> confirmer(204)(2)(0)(0) # The third digit of 204 is not 0.
False
>>> confirmer(204)(2)(1) # The second digit of 204 is not 1.
False
>>> confirmer(204)(20) # The first digit of 204 is not 20.
False
"""
def confirm1(d, t):
def result(digit):
if d == digit:
return t
else:
return False
return result
def extend(prefix, rest):
"""Return a confirming function that returns REST when given the digits of PREFIX.
For example, if c = extend(12, confirmer(34)), then c(1)(2) returns confirmer(34),
so that c is a confirming function for 1234."""
left, last = prefix // 10, prefix % 10
if left == 0:
return confirm1(last, rest)
else:
return extend(left, confirm1(last, rest))
return extend(code, True)
def decode(f, y=0):
"""Return the code for a confirming function f.
>>> decode(confirmer(12001))
12001
>>> decode(confirmer(56789))
56789
"""
d = 0
while d < 10:
x, code = f(d), 10*y + d
if x == True:
return code
elif x == False:
d += 1
else:
return decode(x, code) |
d32d1e5436ff92efee9f1debbf0406f417140dcb | elijahanderson/Python-Practice | /lab3.py | 1,400 | 3.90625 | 4 | import sys, numpy as np, matplotlib.pyplot as plt
def getNumbers(i) :
NUMBER = i+1
theList = []
print('Please enter ' + str(i) + ' numbers.')
while i > 0 :
num = int(input('Number ' + str(NUMBER-i) + ': '))
theList.append(num)
i -= 1
print('Here are the values you entered: ' + str(theList))
arr = np.array([theList[i] for i in range(len(theList))])
smallCount = 0
largeCount = 0
smallest = np.amin(arr)
largest = np.amax(arr)
for i in range(len(arr)) :
if arr[i] == smallest :
smallCount += 1
for i in range(len(arr)) :
if arr[i] == largest :
largeCount += 1
print('The smallest item in the list is ' + str(smallest) + ', and it occurs ' + str(smallCount) + ' times.')
print('The largest item in the list is ' + str(largest) + ', and it occurs ' + str(largeCount) + ' times.')
print('The mean of the items in the list is ' + str(np.mean(arr)) + '.')
print('The median of the items in the list is ' + str(np.median(arr)) + '.')
print('The range of the items in the list is ' + str(np.amax(arr)-np.amin(arr)) + '.')
plt.plot(arr)
plt.show()
#-------Main-------
print('How many numbers would you like to enter?')
i = int(input())
getNumbers(i)
|
b305067cd353a5ffe7e292fdc6a783497bcc23f2 | digitaldna4/helloworld | /codingdojang-com/445.py | 608 | 3.875 | 4 | """
https://codingdojang.com/scode/445
비슷한 단어 찾기
Lv. 2
OneEditApart("cat", "dog") = false
OneEditApart("cat", "cats") = true
202010414
(완성 못함)
"""
def OneEditApart(s1, s2):
if len(s1) == len(s2):
#
for i in range(len(s1)):
chk = 0
if s1[i] != s2[i]:
chk += 1
if chk <= 1:
return True
else:
return False
elif abs(len(s1)-len(s2)) == 1:
#
for i in range(len(s1)):
#
else:
return false
|
07da9096b7a00148eae24cd31be45bc562e1338b | Anderson1201/Anderson-Salazar-Guevara | /ejemplo18.py | 417 | 3.90625 | 4 | #Calcular la fuerza mediante la segunda ley de Newton
fuerza, masa, aceleracion=0.0, 0.0, 0
#Asignacion de valores
masa=4.5
aceleracion=8
#Calculo
fuerza=(masa*aceleracion)
#Mostrar valores
print ("masa", masa)
print ("aceleracion", aceleracion)
print ("la fuerza es", fuerza)
#Verificaciones
masa, aceleracion=4.5, 8
producto=(masa*aceleracion)
a=(producto<35)
print ("el producto es:", a)
|
a90e93f36775f9dcaeb275587f8d60d315cbf0f7 | lanpartis/jianzhiOffer_practice | /28_moreThanHalf.py | 925 | 3.515625 | 4 | # -*- coding:utf-8 -*-
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
'''
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
now = None
counter = 0
for i in numbers:
if now == None:
now = i
counter = 1
continue
if i == now:
counter+=1
else:
counter-=1
if counter is 0:
now=None
if counter>0:
check=0
for i in numbers:
if i == now:
check+=1
if check>=(len(numbers))/2:
return now
return 0
|
6cd844ff465b7c55034588f55e94fa033f45eec9 | jgathogo/python_level_1 | /week6/problem4.py | 386 | 3.5 | 4 | import os
import random
import sys
"""
Note:
- Good try but this does not double!
"""
def main():
f_l = []
for num in range(15):
f_l.append(round(random.uniform(1, 10), 2))
print(f"List of floats: {f_l}")
double = list(map(lambda x: round(x ** 2, 2), f_l))
print(f"Doubles: {double}")
return os.EX_OK
if __name__ == "__main__":
sys.exit(main())
|
cb5fe45861f5d90b68fb2cd36f18585cfa6e1ea2 | qqryq/testypythona | /1421.py | 804 | 3.890625 | 4 | #! /usr/bin/env python3
#-*- coding: utf-8 -*-
lista = []
op = "t"
while op == "t":
while not len(lista) == 3:
lista = input('Podaj trzy liczby oddzielone spacjami: ').split(",")
#lista = [a, b, c]
if len(lista) < 3:
print('Wprowadzono za mało liczb.')
elif len(lista) > 3:
print('Wprowadzono za dużo liczb.')
a = lista[0]
b = lista[1]
c = lista[2]
print('Wprowadzono liczby: ', a, b, c,)
print ('\nNajmniejsza: ')
if a < b:
if a < c:
najmniejsza = a
else:
najmniejsza = c
elif b < c:
najmniejsza = b
else:
najmniejsza = c
print(najmniejsza)
op = input('Jeszcze raz t/n? ')
lista = []
print('Koniec.')
|
716c3b56d7c0f656a4e192e1b0926b0aba1a8cb7 | yesin25/Casos-Aplicados-de-Python | /Web Scraping/websc_hiraoka.py | 2,447 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Abner Francisco Casallo Trauco
Spyder Editor
This is a temporary script file.
"""
#Primero hemos instalado request es el terminal
#Tmb beautiful soup:$ pip3 install beautifulsoup4
from bs4 import BeautifulSoup
import pandas as pd
import requests
URL = 'https://hiraoka.com.pe/tecnologia/computadoras/laptops'
page = requests.get(URL)
print(page)
soup = BeautifulSoup(page.content)
print(soup)
prices_t = soup.find_all('span', class_ = "price")
print(prices_t)
prices_text=[item.text for item in prices_t]
print(prices_text)
text2=[]
for i in prices_text:
a=i.replace(',','')
b=a.replace('S/ ','')
c=b.replace('.00','')
text2.append(c)
print(text2)
num_prices_1=[]
for a in text2:
num_prices_1.append(int(a))
print(num_prices_1)
#AVERAGE:
total_pag1=0
for i in num_prices_1:
total_pag1=total_pag1+i
print(total_pag1)
av_price_pag1=total_pag1/len(num_prices_1)
print(av_price_pag1)
#########AHORA HACER UN BUCLE PARA TODAS LAS PÁGINAS CON FOR
#prices_text=[]
prices=[]
for i in range(1,5):#1,2,3,4
if i==1:
URL = 'https://hiraoka.com.pe/tecnologia/computadoras/laptops'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
prices_t = soup.find_all('span', class_ = "price")
prices_text=[item.text for item in prices_t]
for i in prices_text:
a=i.replace(',','')
b=a.replace('S/ ','')
c=b.replace('.00','')
prices.append(int(c))
else:
a=str(i)
URL = 'https://hiraoka.com.pe/tecnologia/computadoras/laptops'+'?p='+a
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
prices_t = soup.find_all('span', class_ = "price")
prices_text=[item.text for item in prices_t]
for i in prices_text:
a=i.replace(',','')
b=a.replace('S/ ','')
c=b.replace('.00','')
prices.append(int(c))
print(prices)
#ARMAMOS EL DATA FRAME
#df_11nov = pd.DataFrame(prices, columns =['Precios al 12/11/2020'])
df = pd.DataFrame(prices, columns =['Precios al 17/11/2020'])
print(df)
total=0
for i in prices:
total=total+i
print(total)
print(total/len(prices)) ####SALE MÁS DE 5000, RAZÓN: OUTLIERS(10 MIL, 15 MIL...)
df.to_csv(r'D:\GITHUB\Web-Scraping-de-lap-tops-con-Python\Data generada\17 de nov.csv',
sep=';')
|
3464b56f4791a2efa7da77d7fcdee61fa4ff5fa2 | EmilyOng/cp2019 | /data_structures/phone_book.py | 4,526 | 4.5 | 4 | #A phone book stores names with their contact numbers.
#Write a phone book application which will allow you to
#search for an entry
#insert an entry
#update an entry
#delete an entry
#display all entries
#quit
#Your program should continue until the user chooses to quit.
#Assume that one name is only associated with one contact number.
'''
Phone Book Application
'''
phone_book=dict()
def search_entry(entry_key):
print("SEARCH")
if entry_key in phone_book:
print(entry_key+":",phone_book[entry_key])
return
else:
print("User "+entry_key+" is not found, would you like to try again?")
try_again=input("[Y/N]")
if try_again=='Y':
new_entry_key=input("Who do you want to search for?")
search_entry(new_entry_key)
else:
display_menu()
return
def insert_entry(entry_key,entry_value):
print("INSERT")
if entry_key in phone_book:
print("User "+entry_key+" already exists, would you like to try again?")
try_again=input("[Y/N]")
if try_again=='Y':
new_entry_key=input("Name: ")
new_entry_value=int(input("Number: "))
insert_entry(new_entry_key,new_entry_value)
else:
display_menu()
return
else:
phone_book[entry_key]=entry_value
print("Inserted new user "+entry_key+" with number",entry_value)
return
def update_entry(entry_key,entry_value):
print("UPDATE")
if entry_key in phone_book:
phone_book[entry_key]=entry_value
print("Updated user "+entry_key+" with number",entry_value)
else:
print("User "+entry_key+" is not found, would you like to try again?")
try_again=input("[Y/N]")
if try_again=='Y':
new_entry_key=input("Name: ")
new_entry_value=int(input("New number: "))
update_entry(new_entry_key,new_entry_value)
else:
display_menu()
return
def delete_entry(entry_key):
print("DELETE")
if entry_key in phone_book:
phone_book.pop(entry_key)
print("Deleted user "+entry_key)
return
else:
print("User "+entry_key+" is not found, would you like to try again?")
try_again=input("[Y/N]")
if try_again=='Y':
new_entry_key=input("Name: ")
delete_entry(new_entry_key)
else:
display_menu()
return
def display_entry(entry_key):
print("DISPLAY ENTRY")
if entry_key in phone_book:
print("Name: "+entry_key)
print("Number:",phone_book[entry_key])
else:
print("User "+entry_key+" is not found, would you like to try again?")
try_again=input("[Y/N]")
if try_again=='Y':
new_entry_key=input("Name: ")
display_entry(new_entry_key)
else:
display_menu()
return
def display_all():
print("DISPLAY ALL")
for i in phone_book:
print("Name: "+i,"\t","Number:",phone_book[i])
def display_menu():
print("APPLICATION")
options=["Search for a user","Insert new user","Update existing user",
"Delete existing user","Display existing user", "Display all users",
"Quit Application"]
for i in range(len(options)):
print("("+str(i+1)+")","\t",options[i])
display_menu()
option=int(input("What is your option?"))
while option!=7:
if option==1:
entry_key=input("Who do you want to search for?")
search_entry(entry_key)
display_menu()
option=int(input("What is your option?"))
elif option==2:
entry_key=input("Name: ")
entry_value=int(input("Number: "))
insert_entry(entry_key,entry_value)
display_menu()
option=int(input("What is your option?"))
elif option==3:
entry_key=input("Name: ")
entry_value=int(input("Number: "))
update_entry(entry_key,entry_value)
display_menu()
option=int(input("What is your option?"))
elif option==4:
entry_key=input("Who do you want to delete?")
delete_entry(entry_key)
display_menu()
option=int(input("What is your option?"))
elif option==5:
entry_key=input("Who do you want to see?")
display_entry(entry_key)
display_menu()
option=int(input("What is your option?"))
else:
display_all()
display_menu()
option=int(input("What is your option?"))
|
387d38b7209805510441071d5a6b7b7f4fd3c7ee | IpsumDominum/etudes | /03-floatingpoint/main.py | 967 | 3.515625 | 4 | import os
import sys
from sys import argv
from floating import *
if sys.version_info >= (3,0):
version = 3
else:
version = 2
if __name__ =="__main__":
if(len(argv)>=2):
outputhex = True if(argv[1].lower()=="true")else False
else:
outputhex = True
if(version==3):
print("Python 3 not supported, please use python 2")
exit()
try:
print("Please enter an input file path")
inputpath = raw_input() if version==2 else input()
print("And the precision?")
inputprecision = raw_input() if version==2 else input()
print("Please enter an output file path")
outputpath = raw_input() if version==2 else input()
print("And the precision?")
outputprecision = raw_input() if version==2 else input()
ieee = parseIBMfloating(inputpath,inputprecision)
writeIEEE(outputpath,ieee,outputprecision,outputhex)
except EOFError:
exit()
|
b7374fbb058e0f95375e6edf6b2b3a7c1929333f | andrewc91/Python_Fundamentals | /Python/scores_grades.py | 447 | 4 | 4 | def grades():
user_input = input()
if 90 < user_input < 101:
print "Score:", user_input, "; Your grade is A"
elif 80 < user_input < 90:
print "Score:", user_input, "; Your grade is B"
elif 70 < user_input < 80:
print "Score:", user_input, "; Your grade is C"
elif 0 < user_input < 70:
print "Score:", user_input, "; Your grade is D"
else:
print "End of the program. Bye!"
grades()
|
3f6a0446e2c88f20fe9ac6a6ff126f1c6e552bf0 | Hasibur-R/Python_class | /prac_16.py | 158 | 3.84375 | 4 | ax=input()
if ax.isalpha():
print("This is Alphabet")
elif ax.isdigit():
print("This is Digit")
else:
print("This is special character")
|
187e0e3ad235a8083f1e2e16a035907e2f09941f | AndreyIvantsov/PythonSchool | /03_While_For/ex6_zip.py | 1,409 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# //////////////////////////////////////////////////////////
# //
# // Функция zip(), объединяет два списка попарно в картежи
# //
from typing import Dict, Any
HEADLINE: str = ' Функция zip(), объединяет два списка попарно в картежи '
print('\n')
print(HEADLINE.center(80, '*'), '\n')
login = ['login1', 'login2', 'login3', 'login4']
password = ['password1', 'password2', 'password3']
# в python3 перед использованием zip() необходимо вызвать
# list(), в отличии от python2
a = list(zip(login, password))
print(a)
# применение for к zip()
images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']
print('\n')
for (x, y, z) in zip(login, password, images):
print(x, y, z)
# применение for к zip()
a = [1, 2, 3]
b = [4, 5, 6]
print('\n')
for (x, y) in zip(a, b):
assert isinstance(y, object)
print(x, '+', y, '=', x + y)
# создание словаря при помощи цикла for
d = {'1': 'moon', '2': 'satellite', '3': 'earth'}
print('\n')
print(d)
keys = ['1', '2', '3']
values = ['moon', 'satellite', 'earth']
d1 = list(zip(keys, values))
print(d1)
d2: Dict[Any, Any] = {}
# преобразуем список картежей в словарь
for (k, v) in d1:
d2[k] = v
print(d2)
|
3393aec7327d3d83f1915152cf5f3b4648a29918 | enthusiasm99/crazypython | /08/P194_compare_test.py | 1,417 | 3.953125 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def setSize(self, size):
self.width, self.height = size
def getSize(self):
return self.width, self.height
size = property(getSize, setSize)
# 能比较大,则能比较小
def __gt__(self, other):
# 要求参与运算的另一个操作数必须是Rectangle类
if not isinstance(other, Rectangle):
raise TypeError('+运算要求目标是Rectangle类')
return True if self.width * self.height > other.width * other.height else False
# 能比较相等,则能比较不相等
def __eq__(self, other):
if not isinstance(other, Rectangle):
raise TypeError('+运算要求目标是Rectangle类')
return True if self.width * self.height == other.width * other.height else False
# 能比较大于等于 ,则能比较小于等于
def __ge__(self, other):
if not isinstance(other, Rectangle):
raise TypeError('+运算要求目标是Rectangle类')
return True if self.width * self.height >= other.width * other.height else False
def __repr__(self):
return 'Rectangle(width = %g, height = %g)' % (self.width, self.height)
r1 = Rectangle(4, 5)
r2 = Rectangle(3, 4)
print(r1 > r2)
print(r1 >= r2)
print(r1 < r2)
print(r1 == r2)
print(r1 != r2)
print(r1)
|
1662da373bad1c0e4d00ab1259adae2dcd25d7cc | Rizian/PythonExercises | /Perimeter of a Triangle.py | 732 | 4.5 | 4 | '''
Perimeter of a Triangle
1. Input = 3 float variables, one for each side of the triangle.
3. check if the sum of two sides is greater than the one remaining side; if yes = 4.; If no = 5.
4. Output = Calculate the sum of all three sides and return the value.
5. Output = Returns an error message.
'''
print("Triangle Perimeter")
side1 = float(input("Enter the length of side 1: "))
side2 = float(input("Enter the length of side 2: "))
side3 = float(input("Enter the length of side 3: "))
if side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1:
print(f"The perimeter of the triangle is {side1+side2+side3}!")
else:
print("invalid input. Values don't represent a triangle and cannot be calculated!") |
706ec22c86387834d7d39b25609be7cc887a21f3 | fabiodarice/Python | /PyCharm/Exercicios/Aula15/ex071.py | 1,271 | 3.75 | 4 | # Importação de bibliotecas
# Título do programa
print('\033[1;34;40mSIMULADOR DE CAIXA ELETRÔNICO\033[m')
# Objetos
nota50 = 0
nota20 = 0
nota10 = 0
nota1 = 0
# Lógica
print('\033[34m=\033[m' * 50)
print(f'\033[1;33m{"BANCO CEV":^50}\033[m')
print('\033[34m=\033[m' * 50)
valor = int(input('\033[30mQue valor você que sacar R$:\033[m '))
while True:
if valor >= 50:
nota50 = valor // 50
resto = valor % 50
if resto == 0:
break
else:
valor = valor - (nota50 * 50)
if valor >= 20:
nota20 = valor // 20
resto = valor % 20
if resto == 0:
break
else:
valor = valor - (nota20 * 20)
if valor >= 10:
nota10 = valor // 10
resto = valor % 10
if resto == 0:
break
else:
valor = valor - (nota10 * 10)
if valor >= 1:
nota1 = valor // 1
break
print(f'Total de \033[1;31m{nota50}\033[m cédulas de R$50')
print(f'Total de \033[1;32m{nota20}\033[m cédulas de R$20')
print(f'Total de \033[1;33m{nota10}\033[m cédulas de R$10')
print(f'Total de \033[1;34m{nota1}\033[m cédulas de R$10')
print('\033[34m=\033[m' * 50)
print('Volte sempre ao BANCO CEV! Tenha um bom dia!') |
3aff9023a057199b96582522c8dd7ec433fd3b75 | phuocidi/fun | /Dynamic Programming/Edit Distance/main.py | 3,274 | 4.21875 | 4 | #! /usr/bin/env python3
"""
Input: str1 = "geek", str2 = "gesek"
Output: 1
We can convert str1 into str2 by inserting a 's'.
Input: str1 = "cat", str2 = "cut"
Output: 1
We can convert str1 into str2 by replacing 'a' with 'u'.
Input: str1 = "sunday", str2 = "saturday"
Output: 3
Last three and first characters are same. We basically
need to convert "un" to "atur". This can be done using
below three operations.
Replace 'n' with 'r', insert t, insert a
The idea is process all characters one by one staring from either from left or right sides of both strings.
Let us traverse from right corner, there are two possibilities for every pair of character being traversed.
m: Length of str1 (first string)
n: Length of str2 (second string)
If last characters of two strings are same, nothing much to do.
Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.
Else
(If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values.
Insert: Recur for m and n-1
Remove: Recur for m-1 and n
Replace: Recur for m-1 and n-1
"""
def min(x,y,z):
"""
Aux function to calculate minimum of 3 variable
- Args
x (int): first value
y (int): second value
z (int): third value
- Returns
int: The minimum value
"""
if x <= y:
return x if x < z else z
if y <= x:
return y if y < z else z
def editDistanceRecursive(str1, str2, m, n):
"""
Find the minimum cost to edit str1 to become str2
- Args
str1 (str): string 1
str2 (str): string 2
m (int): (last) index of str1
n (int): (last) index of str2
- Returns
int: minimum cost to edit str1 to become str2
"""
if m == 0: # str1 is empty, only need to add to str1 all characters of str2
return n
if n == 0: # str2 is empty, only need to remove all characters of str1
return m
if str1[m-1] == str2[n-1]:
return editDistanceRecursive(str1, str2, m-1, n-1)
else:
return 1 + min(editDistanceRecursive(str1, str2, m-1, n), # remove
editDistanceRecursive(str1, str2, m-1, n-1), # replace
editDistanceRecursive(str1, str2, m, n-1)) # insert
def editDistanceTabulation(str1, str2,m, n):
sol = [[0 for _ in range(n+1)] for _ in range(m+1)]
sol[0][0]= 1
for i in range(m+1):
for j in range(n+1):
if i == 0: # fisrt string is empty
sol[i][j] = j # given max cost is j
if j == 0: # second string is empty
sol[i][j] = i # given max cost is i
if str1[i-1] == str2[j-1]:
sol[i][j] = sol[i-1][j-1]
else:
sol[i][j] = 1 + min(sol[i-1][j],
sol[i-1][j-1],
sol[i][j-1])
printMat(sol)
return sol[m][n]
def printMat(mat):
for i in mat:
row = '|'
for j in i:
c = str(j)
row += ' ' + c if len(c)==2 else ' ' + c
row += " |"
print(row)
print()
def test():
str1 = "sunday"
str2 = "saturday"
m = len(str1)
n = len(str2)
print(editDistanceTabulation(str1,str2,m,n))
def main():
test()
if __name__=="__main__":
main() |
c1c317542eeb10946e5d33a9751485bea4ff60a4 | surapat12/DataStructAlgo-Grader-KMITL | /Exam2/StackAction.py | 2,484 | 4.0625 | 4 | '''
* กลุ่มที่ : 20010101
* 62010356 ธนพล วงศ์อาษา
* chapter : 14 item : 1 ครั้งที่ : 0001
* Assigned : Friday 9th of October 2020 01:44:21 PM --> Submission : Friday 9th of October 2020 01:51:11 PM
* Elapsed time : 6 minutes.
* filename : StackAction.py
'''
"""
__str__ สำหรบแสดงข้อมูลที่อยู่ใน stack
push(data) สำหรับเก็บข้อมูล data
pop() สำหรับนำข้อมูลออก
isEmpty() สำหรับตรวจสอบว่า stack ว่างไหม ถ้าว่าง ให้เป็น True
size() สำหรับแสดงขนาดของ stack ว่ามีข้อมูลกี่ตัว
peek() สำหรับแสดงค่าข้อมูลที่อยู่ที่อยู่บนสุด
bottom() สำหรับแสดงค่าข้อมูลที่อยู่ล่างสุด
"""
class Stack:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def is_empty(self):
return len(self.items) == 0
def push(self,value):
self.items.append(value)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
def bottom(self):
if not self.is_empty():
return self.items[0]
return None
def __str__(self):
if not self.is_empty():
out = "Data in Stack is : "
for item in self.items:
out += str(item)+' '
return out
return 'Empty'
if __name__ == '__main__':
s1 = Stack()
choice = int(input("Enter choice : "))
if choice == 1:
s1 = Stack()
s1.push(10)
s1.push(20)
print(s1)
s1.pop()
s1.push(30)
print("Peek of stack :",s1.peek())
print("Bottom of stack :",s1.bottom())
elif choice == 2:
s1 = Stack()
s1.push(100)
s1.push(200)
s1.push(300)
s1.pop()
print(s1)
print("Stack is Empty :",s1.is_empty())
elif choice == 3:
s1 = Stack()
s1.push(11)
s1.push(22)
s1.push(33)
s1.pop()
print(s1)
print("Stack size :",s1.size())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.