blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2c97a48761b3ce1a69c5da43f174c27fff401af0 | KatsunoriWa/slowCodingCV | /samples_Python/ex_argsort.py | 410 | 3.734375 | 4 | import numpy as np
a=np.array([ [ 6, 22, 14, 4, 22],
[10, 11, 18, 1, 4],
[1, 13, 7, 13, 0],
[23, 18, 1, 17, 3],
[ 3, 18, 0, 14, 23]])
print a
print "ROW|ASCENDING"
print np.argsort(a, axis=1)
print "ROW|DESCENDING"
print np.argsort(a, axis=1)[:, ::-1]
print "COLUMN|ASCENDING"
print np.argsort(a, axis=0)
print "COLUMN|DESCENDING"
print np.argsort(a, axis=0)[::-1, :]
|
32ca10a765afb01cb4727a51459de8b201f54f72 | ValeriyMartsyshyn/BLITZ_LABs | /Lab3/Task[13-15].py | 1,914 | 4.59375 | 5 | """ Task 1
A simple way of encrypting a message is to rearrange its characters. One way to rearrange the characters is to pick out
the characters at even indices, put them first in the encrypted string, and follow them by the odd characters.
For example, the string message would be encrypted as msaeesg because the even characters are m, s, a, e (at indices 0, 2, 4, and 6)
and the odd characters are e, s, g (at indices 1, 3, and 5).
1) Write a function that asks the user for a string and uses this method to encrypt the string.
2) Write a function that decrypts a string that was encrypted with this method. """
#1)
def encrypted():
message=input("Write your message to encrypt: ")
e=message[::2] #even
o=message[1::2] #odd
return print(e+o)
encrypted()
#2)
def decr():
message=input("Write your message to decrypt: ")
length=len(message) #length of the input
hl=(length+1)//2 #half length
e=message[:hl]#even
o=message[hl:]#odd
decrypt=''
if length%2==0:
for i in range (hl): #if even
join=e[i]+o[i]
decrypt=decrypt+join
else:
for i in range (1,hl+1): #if odd
neparne=i-1
join=e[neparne:i]+o[neparne:i]
decrypt=decrypt+join
return print(decrypt)
decr()
""" Task 2
Write a function that for 2 given
dictionaries find their common keys. """
def sneakers():
Shop = {"Nike": "Airmax", "Adidas": "Hoops", "Puma": "Rebound JOY", "New Balance": "574"}
Client = { "Nike": "Airmax", "Puma": "Rebound JOY"}
for key in Shop:
if key in Client:
print (key, Shop[key])
sneakers()
""" Task 3
Create a function which reverts a dictionary
(keys become values, values become keys). """
def to_revert():
normal = {"Hello": "Python", "I'm": "Bohdan"}
reverted = {v: k for k, v in normal.items()}
return print (reverted)
to_revert()
|
a3f31675ef114ec39ec6a9f1bde755dac240b561 | Rutie2Techie/Hello_python | /function/add_num_map.py | 213 | 4.09375 | 4 | ## add some constant value to each member of the list.
values=[2,4,6,8]
#We convert the returned map object to
# a list data structure for printing purpose
addition=list(map(lambda x:x+10,values))
print(addition) |
23658f7404592d5344616599dcb05085adf94ff5 | luisotaviocap98/Radix_Implementation | /telefone.py | 6,359 | 3.703125 | 4 | import sys
class No:
def __init__(self,dado, telefone):
self.dado = dado #palavra a ser mostrada no Nó
self.listaNos = list() #lista contendo os filho daquele Nó
self.ePalavra = True #se a palavra é valida, se pode ser encontrada
self.pOriginal = dado #a palavra completa, usada na busca
self.telefone = telefone #o telefone de cada contato
def addNo(root, entrada,recurso, tel):
#percorrer as duas string para conferir compatibilidades
match=0
#percorrer ate o tamanho da palavra de entrada
for i in range(0,len(entrada)):
#percorrer ate o tamanho do dado do root
if i<len(root.dado) :
if entrada[i]!=root.dado[i] :
#se possuem diferenças entre as strings
break
else:
#quantidade de carcteres iguais
match+=1
else:
#se ultrapssou o tamanho da string dado em root
break
#mostrar a entrada , o root, ate que posiçao percorreu nas string, e qual atitude a ser tomada
print('entrada',entrada.upper(),'root'.rjust(14-len(entrada)),root.dado.upper(),'resultado:'.rjust(12),end=' ')
#4 casos :
#primeiro caso: inserindo uma palavra que ja existe na arvore
if entrada == root.dado:
if(root.ePalavra == False):
root.ePalavra = True
root.pOriginal = entrada
print('nao precisa fazer nada, sao iguais'.capitalize(),entrada[:match].upper())
elif match < len(root.dado) :
#segundo caso: palavras diferentes
if match==0:
#print('nao tem nada a ver, criar nó nulo'.capitalize())
new=No('','')
new.ePalavra=False
word = No(entrada, tel)
word.pOriginal = entrada
root.pOriginal = root.dado
new.listaNos.append(root)
new.listaNos.append(word)
root = new
#terceiro caso: prefixo em comum, podendo esse prefixo ser a entrada ou parte dela
else:
print('criar nó nulo a cima com palavra nova'.capitalize(),entrada[:match].upper())
new=No(entrada[:match], '') #Nó Acima Cortado
if match != len(entrada): #verificar a necessidade de criar um ou dois nós
other=No(entrada[match:], tel)
other.pOriginal = recurso
new.listaNos.append(other)
other2=No(root.dado[match:], root.telefone)
other2.pOriginal = root.pOriginal.replace("\n", '')
other2.dado = other2.dado.replace("\n", '')
other2.ePalavra = root.ePalavra
#fazer com que o novo nó (other2) receba os filhos de root, visto que other2 é o antigo root
for i in root.listaNos:
i.dado = i.dado.replace("\n", '')
other2.listaNos.append(i)
new.listaNos.append(other2)
new.ePalavra = False
new.pOriginal = entrada[:match]
root = new
return root
elif match == len(root.dado):
#quarto caso: prefixo em comum, sendo esse prefixo o root
if len(entrada) > len(root.dado):
print('inserir como filho de root a palavra'.capitalize(),entrada[match:].upper())
#recursao, precisa verificar na lista de filhos, se possui algum filho com o novo prefixo
flag = False
if len(root.listaNos) > 0:
for j,i in enumerate(root.listaNos):
if i.dado[0] == entrada[match:][0]:
flag =True
#print('\nRECURSAO',entrada,' ',entrada[match:])
x=addNo(i,entrada[match:], entrada, tel)
x.pOriginal = entrada
root.listaNos[j]= x
#print('\nTESTE',x.dado,x.listaNos[0].dado,x.listaNos[1].dado,j,root.listaNos[j].dado)
#se não possui filho com este prefixo, ou ainda não possui filhos
if len(root.listaNos) == 0 or flag == False:
new=No(entrada[match:], tel)
new.pOriginal=entrada
root.listaNos.append(new)
print()
return root
def imprimindoAll(root):
#função para imprimir todos nós validos
if(len(root.listaNos)!=0):
for i in root.listaNos:
if i.ePalavra == True:
print('[', end='')
print(i.pOriginal, i.telefone, end='')
print(']',end='')
for i in root.listaNos:
imprimindoAll(i)
def imprimindo(root):
#função para imprimir todos nós presente na arvore
if(len(root.listaNos)!=0):
print('\n*',root.dado,root.ePalavra)
for i in root.listaNos:
print('[', end='')
print(i.dado,'*',i.ePalavra,'*' ,end='')
print(']',end='')
for i in root.listaNos:
imprimindo(i)
def buscando(root, prefixo):
#função para mostrar os nós que tenham como prefixo a entrada
if root.pOriginal[:len(prefixo)] in prefixo:
if root.ePalavra == True and len(root.pOriginal) >= len(prefixo):
print(root.pOriginal, root.telefone)
if len(root.listaNos)>0:
for i in root.listaNos:
buscando(i,prefixo)
def main():
#abrindo o arquivo para leitura
arq = sys.argv[1]
f = open(arq, 'r')
line = f.readline().lower().split() #Linha 1 - root
x=str()
for i in line:
if i.isalpha():
x= x+' '+i
else:
y=i
x=x.strip()
root = No(x,y)
x=''
#contruir a arvore
for line in f:
trans = line.replace("\n", '').lower().split()
for i in trans:
if i.isalpha():
x= x+' '+i
else:
y=i
x=x.strip()
root = addNo(root,x,x,y)
x=''
print('\n--------PRINT Todos---------------')
imprimindoAll(root)
print()
print('\n--------PRINT com Nos---------------')
imprimindo(root)
print()
print('\n')
#loop para receber a entrada digitada pelo usuario
while 1:
tmp = input('-Digite o Nome para Buscar? (Para Sair Digite 0)\n')
if tmp == '0':
break
print('\n-------BUSCANDO------')
buscando(root, tmp)
if __name__ == "__main__":
main()
|
eac2ad217899883d06da84eb3efbd0aa424e34bb | romkravets/python-data | /41/list_and_if/list_numbers.py | 1,600 | 3.671875 | 4 | #Напишіть програму Python, щоб роздрукувати всі парні числа із заданого списку чисел у тому самому порядку та зупинити друк,
#якщо в послідовності є числа, що приходять після 237.
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
https://www.programiz.com/python-programming/examples/calculator
Напишіть функцію score(pupil, hw, exam), яка приймає на вхід ім'я учня(pupil),
кортеж, що містить його оцінки за домашні завдання (hw), а також його оцінку за іспит (exam),
і видає рядок pupil, твоя загальна оцінка grade.
pupil-ім'я учня;
grade - його підсумкова оцінка за курс, що є цілим числом.
Відомо, що підсумкова оцінка обраховується так: Підсумок = 0.4 * ДЗ + 0.6 * exam,
де ДЗ - середнє арифметичне оцінок за домашні завдання. Підсумок повинен бути заокруглений до цілого числа.
приклад: score( "Іван", (7, 7, 5, 9, 5, 2), 6)
Іван, твоя загальна оцінка 6.
|
094f58bd7c6dcf83cb8327cbe9f5c9929df77842 | Rohit263/python-practice | /soln3_smallest_divisible.py | 963 | 4.15625 | 4 | def div():
#l_lim = lower limit of the searching range
#u_lim = upper limit of the searching range
#declaring x,y,l_lim,u_lim as global variable
global x,y,l_lim,u_lim
l_lim =1
u_lim =1
values = []
# Getting the value of lower limit and upper limit of the search for any x and y
for i in range(x-1):
l_lim = 10*l_lim
u_lim = ((l_lim*10)-1)
#Appending all the values that are in search area and is divisible by any given y to a list
for r in range(l_lim,u_lim+1):
if r%y==0:
values.append(r)
# Finding the smallest value among all the feasible values
smallest = min(values)
print('')
print(f'Smallest {x} digit number divisible by {y} is: {smallest}')
# Start of main function block
if __name__ == '__main__':
x= int(input("Enter no. of digit: "))
y= int(input("Enter divisibility number: "))
#Calling of the div() function
div()
|
b451ff30f233891bdb0c4aabb3e96818666583bd | benlinhuo/algorithmpy | /leetcode/Array/Simple/question_53.py | 696 | 3.75 | 4 | #!/usr/bin/python3
'''
对应链接:https://leetcode-cn.com/problems/maximum-subarray/
53. 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
'''
class Solution(object):
# 复杂度为 O(n)
# 因为是需要连续的子数组,所以我们
def maxSubArrayOn(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
|
98779b523fe47886dfa7999416d96a021e524ee6 | wsysissi/NanYang-program-interview | /question_1/code_question_1_1.py | 7,102 | 4.28125 | 4 | #Since the value of each member in a row of the matrix given in the example is
#equal to the number of that row, the matrix generated in this code is also of this form,
#but can be replaced with other matrices in other cases.
'''
README
input of the code is like the example below:
e.g.we want to find the operations of a mxn matrix with the sum=k
type"outf.write(main(m,n,k))"at the end of this program
'''
class Node :
def __init__ (self,val_site,lft=None,rt=None,baba=None):
self.val = val_site
self.lftChd = lft
self.rtChd = rt
self.father = baba
class Null_Node:
def __init__(self,val_site=[-1,-1],lft="null",rt="null",baba=None):
self.val = val_site
self.lftChd = lft
self.rtChd = rt
self.father = baba
class Root :
def __init__ (self,val_site=[0,0],lft=None,rt=None,baba=None):
self.val = val_site
self.lftChd = lft
self.rtChd = rt
self.father = baba
class Tree :
def __init__ (self,val_site=[0,0],lft=None,rt=None):
self.root = Root(val_site) #建立根节点只需要输入根节点数字值
self.left_subT = None
self.right_subT = None
#用来记录每一个节点是否已满
self.list = []
self.list.append(self.root)
def add_node(self,tree,val_site,hang,lie):
baba_node = self.list[0] #顺序取未满的节点的第一个
new_node = Node (val_site)
baba_x = baba_node.val[0]
baba_y = baba_node.val[1]
new_x = new_node.val[0]
new_y = new_node.val[1]
#添加新节点的顺序为先左后右,左=下,右=右
if baba_node.lftChd == None and baba_x+1==new_x:#往下走没到最后一行
baba_node.lftChd = new_node
#print("new",new_node.val,"lft",baba_node.lftChd.val)
#print("new",new_node.val,"list",self.list[len(self.list)-1].val)
#print(baba_node.lftChd.val)
new_node.father = baba_node
self.list.append(new_node)#新添加的节点记录到列表中
elif baba_node.lftChd==None and baba_x==hang-1 :#往下走到了最后一行
null_node = Null_Node( )
baba_node.lftChd = null_node
null_node.father = baba_node
baba_node.rtChd = new_node
new_node.father = baba_node
#print("lft",baba_node.lftChd.val,"rt",new_node.val)
self.list.append(new_node)
self.list.pop(0)
elif baba_node.lftChd!=None and baba_node.lftChd!="null": #往右走
if baba_y+1==new_y:
if new_node.val == baba_node.lftChd.val:
null_node = Null_Node( )
baba_node.rtChd = null_node
null_node.father = baba_node
#print("Rnull:",baba_node.rtChd.val)
self.list.pop(0)
tree.add_node(tree,new_node.val,hang,lie)
else:
baba_node.rtChd = new_node
#print("R:",baba_node.rtChd.val)
new_node.father = baba_node
self.list.append(new_node)
#此时爸爸节点已满,从列表中除去
self.list.pop(0)
elif baba_y == lie-1:
null_node = Null_Node( )
baba_node.rtChd = null_node
null_node.father = baba_node
#print("Rnull:",baba_node.rtChd.val)
self.list.pop(0)
tree.add_node(tree,new_node.val,hang,lie)
def leave(self,node):
if node.lftChd == None and node.rtChd == None:
return [node]
elif node.lftChd == "null" and node.rtChd == "null":
return [node]
elif node.lftChd != None and node.rtChd != None :
return (self.leave(node.lftChd)+self.leave(node.rtChd))
elif node.lftChd != None and node.rtChd == None :
return (self.leave(node.lftChd))
elif node.lftChd == None and node.rtChd != None :
return (self.leave(node.rtChd))
def set_matrix(hang,lie):
m = hang
n = lie
matrix = []
for i in range(1,m+1):
matrix.append([i]*n)
return matrix
def put_in_tree(hang,lie):
hang = int(hang)
lie = int(lie)
#设list作为树节点队列[行,列]
list1 = [[0,0]]
#设tree_list作为最终记录树节点的列表
tree_list = []
#当list里没有元素时结束循环
while (len(list1)!= 0):
if list1[0][0]+1<hang and list1[0][1]+1<lie :
D = [list1[0][0]+1,list1[0][1]]
R = [list1[0][0],list1[0][1]+1]
list1.append(D)
list1.append(R)
tree_list.append(list1.pop(0))
elif list1[0][0]+1<hang and list1[0][1]+1==lie:#一行顶到头了,只能往下走
D = [list1[0][0]+1,list1[0][1]]
list1.append(D)
tree_list.append(list1.pop(0))
elif list1[0][0]+1==hang and list1[0][1]+1<lie:#一列顶到头了,只能往右走
R = [list1[0][0],list1[0][1]+1]
list1.append(R)
tree_list.append(list1.pop(0))
elif list1[0][0]+1==hang and list1[0][1]+1==lie:#到右下角了
tree_list.append(list1.pop(0))
#print("list:",list1)
#print("tree_list: ",tree_list)
#print(tree_list)
#print("out")
return tree_list
def main (hang,lie,k):
tree = Tree([0,0])
tree_val_list = put_in_tree(hang,lie)
tree_val_list.pop(0)
for val in tree_val_list:
tree.add_node(tree,val,hang,lie)
matrix = set_matrix(hang,lie)
leave_list = tree.leave(tree.root)
for leave in leave_list:
node = leave
sum = hang
node_list = []
#print("start:",node.val)
if node.val != [-1,-1] :
while node.father != None:
#print(node.father.val)
x = node.father.val[0]
y = node.father.val[1]
#print("xy:",matrix[x][y])
sum = sum + matrix[x][y]
node_list.append(node)
node = node.father
#print("sum:",sum)
if sum == k:
node = node_list[0]
break
actions = ""
while node.father != None:
f_site = node.father.val
n_site = node.val
if n_site[0]-f_site[0]== 1:
actions = actions + "D"
elif n_site[1]-f_site[1]==1:
actions = actions + "R"
node = node.father
actions = actions[::-1]
return(str(k)+" "+actions)
outf=open("output_question_1","a")
outf.write(main(9,9,65))
outf.write("\n")
outf.write(main(9,9,72))
outf.write("\n")
outf.write(main(9,9,90))
outf.write("\n")
outf.write(main(9,9,110))
outf.write("\n\n")
outf.close()
|
0a91d3ec66ec1a74bfdbfb24e213ce56b8d531d0 | wangmj88/TestCode | /TestMianShi-1/TestList.py | 726 | 3.8125 | 4 | #python 查找重复项
l = [1,2,3,2,1]
for i in l:
print("this %s ha fount %s" %(i,l.count(i)))
print('split line----------------------------')
s = set(l)
for j in s:
print("the %s has fount %s" %(j,l.count(j)))
#删除重复元素
listA = ['python','语','言','是','一','门','动','态','语','言']
print(sorted(set(listA)))
#[python] 查找列表中重复的元素
a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
#写法1:
import collections
l =[item for item,count in collections.Counter(a).items() if count >1]
print(l)
print('collections.Counter(a).items()'.center(50,'*'))
print(collections.Counter(a).items())
print(collections.Counter(a))
l1 = [item for item ,count in collections.Counter(a).items() if count >1] |
1682220ba56697cfb665856e989f6af1bfea5c07 | ben174/stickerletters | /sticker.py | 3,658 | 3.96875 | 4 | # importing Numpy for Calculations on Arrays
# i would recommend avoiding numpy for a problem as simple as this one.
import numpy as np
# importing Money for Proper Handinling of Currency
# definitely avoid importing libraries that aren't a part of the
# standard library unless completely necessary.
from money import Money
# Sticker Costs
cost = Money(amount='2.00', currency='USD')
# so using the standard libarary, cost would just be
COST = 2
# note use of all-caps for constants - a constant is a fixed value
# Clean Facebook Input
freshbook = list("facebook")
# this is good. using list() on a string is the ideal way to convert
# it to a list of characters
# Checker for Proper Input
good_word = True
# not necessary, and since the original test instructions explicity
# say you can assume that the input is only going to have the letters
# f,a,c,e,b,o,o,k this would actually be considered a bad thing to
# check for. simplicity is better and you want to do the minimal
# work to get the job done. I know it seems counterintuitive, but
# trust me on that. if a interview problem says "you can expect", it
# means "you _should_ expect". But it never hurts to say 'in the
# real world i would put error checking here if i didn't know exactly
# who was calling the function. especially if it's user input from
# a web form or something'
#Facebook Letter Array
facebook = list("facebook")
#Terminal User Input
userInput = raw_input("Please enter word to see how many stickers you will need: ")
# the instructions just say to 'create a function that'.. so
# an interactive terminal program isn't exactly what they asked
# for. it's probably fine though and this is just a bit nit
# picky
# Counter for Stickers
counter = 1
# global variables are generally regarded as bad.
# what if i wanted to use this function multiple times in
# this file? keep your variables inside your function
#Function to Solve Sticker Count
# this function name doesn't tell me much, maybe
# calculate_sticker_cost ?
def printinfo( word ):
# Takes a word makes sure its a string
# turns it to lower case
lword = str(word).lower()
# this is good, the instructions didn't say the
# cause would be all lower, i probably would have
# missed that check.
# but if you're not going to use the orignal word
# just reassign to the original word variable:
# word = word.lower()
# remove unnecessary comments
#print "Word: ", lword
# Turns Word to Array of single characters
# not necessary - you can just loop through the word
warray = list(lword)
# print(warray)
# For Loop for each Character in String
# could just be:
# for letter in lword:
for x in xrange(0,len(warray)):
# this check would be unecessary as stated above
if warray[x] in freshbook:
# this would be unnecessary if looping as stated above
letter = warray[x]
# print(letter)
if letter in facebook:
facebook.remove(letter);
# print(facebook)
# If not in current facebook letters
else:
global counter
counter += 1
for x in xrange(0,len(freshbook)):
facebook.append(freshbook[x])
# print(facebook)
else:
global good_word
good_word = False;
print("Sorry Word Must Contain F, A, C, E, B, O, O, K try again.")
return
# Use Print Info with User Input
printinfo(userInput);
# Only show if a Good Word
if good_word == True:
#Print Out
print("----LETTERS LEFT-----");
for x in facebook: print x,
print("");
print("----STICKER COUNT----");
print(counter);
print("----COSTS OF STICKERS----");
total = counter * cost
# Total You Win
print(total);
|
f6feb5c320cd61dacdb28672d34869193e6f8d35 | worksking/algrithm | /MergeSort.py | 1,940 | 3.96875 | 4 | import numpy as np
def Merge(left, right):
output = []
while len(left) > 0 and len(right)>0:
if left[0] <= right[0]:
output.append(left.pop(0))
else:
output.append(right.pop(0))
#while循环出来之后 说明其中一个数组没有数据了,我们把另一个数组添加到结果数组后面
output += left
output += right
print('output is :', output, '\n')
return output
def MergeSort(a):
'''
归并排序
算法描述:
1.把长度为n的输入序列分成两个长度为n/2的子序列;
2.对这两个子序列分别采用归并排序;
3.将两个排序好的子序列合并成一个最终的排序序列。
参考:
https://www.cnblogs.com/Lin-Yi/p/7309143.html
'''
# 不断递归调用自己一直到拆分成成单个元素的时候就返回这个元素,不再拆分了
if len(a) == 1:
return a
length= len(a)
# 取拆分的中间位置
middle = length // 2
#拆分过后左右两侧子串
left = a[:middle]
right = a[middle:]
print('left and right:',left, right)
# 对拆分过后的左右再拆分 一直到只有一个元素为止
# 最后一次递归时候lef和rig都会接到一个元素的列表
# 最后一次递归之前的lef和rig会接收到排好序的子序列
lef = MergeSort(left)
rig = MergeSort(right)
print('lef and rig:',lef, rig, '\n')
# 我们对返回的两个拆分结果进行排序后合并再返回正确顺序的子列表
# 这里我们调用拎一个函数帮助我们按顺序合并lef和rig
return Merge(lef, rig)
if __name__ == '__main__':
# a = np.random.permutation(10)
a = [0, 1, 9, 3, 2, 4, 5, 8, 7, 6]
print('original array is:', a, '\n')
b = MergeSort(a)
# print('output array is:', b)
|
20897130ff998a3c1a89846b0a42195d9eedb69f | Prerna983/260567_PythonPractiseLTTS | /Assignments1/if_elseQ4.py | 177 | 4.125 | 4 | # Write a python program to check if the input number is
# -real number
# -float numner
# -string-
# complex number
# -Zero (0)
x=eval(input("Enter a number: "))
print(type(x)) |
539f5b058b05a1b441c4459bf99803536f9823cb | Christyan-Cyan/py_training | /Belajar Mandiri/array.py | 336 | 3.65625 | 4 | kondisi = True
basic = ["ipan suki", "maman", "hizbool", 'cyan']
def fungsi() :
inp = input("siapa yg ingin di eksekusi? ")
for i in basic :
if i == inp :
print(i + " telah rip")
break
else :
print("ok sip")
while kondisi == False :
fungsi()
if inp == "end" :
break |
d0cfa3fa4d3d966db5ab0d10b1dc1710ffbc5203 | shulyak86/hillel_ira | /homework 7 lesson/task2.py | 635 | 3.734375 | 4 | a = input('vvedite temperaturu: ')
b = input('vvedite shkalu (C, K, F): ')
def isx_c():
print(a, 'C', '\n',
int(a)+273, 'K', '\n',
int(a)*1.8, 'F')
def isx_k():
print(a, 'K', '\n',
int(a) - 273, 'C', '\n',
int((int(a)-273) * 1.8), 'F')
def isx_F():
print(a, 'F', '\n',
int((int(a) + 459)*5/9), 'K', '\n',
int(int(a) / 1.8), 'C')
def calculator():
if b.lower() == 'c':
isx_c()
elif b.lower() == 'k':
isx_k()
elif b.lower() == 'f':
isx_F()
else:
print('ne znau shkalu')
calculator()
|
a8a2cb9b762028044d5648ea69d5f4530adf9368 | cu-swe4s-fall-2019/version-control-sahu0957 | /calculate.py | 549 | 3.71875 | 4 | import argparse
import math_lib as ml
parser = argparse.ArgumentParser()
parser.add_argument("numerator", help="first number to add, and numerator", type=int)
parser.add_argument("denominator", help="second number to add, and denominator", type=int)
args = parser.parse_args()
if __name__ == '__main__':
x3 = ml.add(args.numerator,args.denominator)
x4 = ml.div(args.numerator,args.denominator)
print("your two numbers added together are:")
print(x3)
print("your first number divided by your second number:")
print(x4)
|
1d709a79f7e5c4ff49397091fe76ebd51e4e48f6 | Ashish9426/Python-Tutorials | /6. frozenset_dictionary/Page2_Dictionary.py | 3,612 | 3.765625 | 4 | def function1():
# empty list
l1 = []
print(f"l1 = {l1}, type = {type(l1)}")
# empty list
l2 = list()
print(f"l2 = {l2}, type = {type(l2)}")
# empty tuple
t1 = ()
print(f"t1 = {t1}, type = {type(t1)}")
# empty tuple
t2 = tuple()
print(f"t2 = {t2}, type = {type(t2)}")
# empty set
s1 = set()
print(f"s1 = {s1}, type = {type(s1)}")
# empty set
s3 = {10,20,30}
print(f"s3 = {s3}, type = {type(s3)}")
# empty fozenset
s2 = frozenset()
print(f"s2 = {s2}, type = {type(s2)}")
# empty dictionary
d1 = {}
print(f"d1 = {d1}, type = {type(d1)}")
# empty dictionary
d2 = dict()
print(f"d2 = {d2}, type = {type(d2)}")
# function1()
def function2():
name1 = 'person1'
address1 = 'allahabad'
email1 = 'ashishm26s94@gmail.com'
name2 = 'person2'
address2 = 'lucknow'
email2 = 'person2@gmail.com'
# list
person1 = ["person1","allahabad","ashishm26s94@gmail.com"]
person2 = ["person2","lucknow","person2@gmail.com"]
# set
person1 = {"person1", "allahabad", "ashishm26s94@gmail.com"}
person2 = {"person2", "lucknow", "person2@gmail.com"}
# tuple
person1 = ("person1", "allahabad", "ashishm26s94@gmail.com")
person2 = ("person2", "lucknow", "person2@gmail.com")
print(f"name = {person1[0]}")
print(f"address1 = {person1[1]}")
print(f"email = {person1[2]}")
print("-*-" * 20)
print(f"name = {person2[0]}")
print(f"address2 = {person2[1]}")
print(f"email = {person2[2]}")
# function2()
def function3():
# dictionary
# collection of key-value pairs
person1 = {"name": "person1", "address": "pune", "email": "person1@test.com"}
print(f"person1 = {person1}, type = {type(person1)}")
# the second email will be kept
person2 = {"address": "mumbai", "name": "person2", "email": "person2@test.com", "email": "person3@test.com"}
print(f"person2 = {person2}, type = {type(person2)}")
print(f"name = {person1['name']}")
print(f"address = {person1['address']}")
print(f"email = {person1['email']}")
print("-" * 20)
print(f"name = {person2['name']}")
print(f"address = {person2['address']}")
print(f"email = {person2['email']}")
print("-" * 20)
print("-" * 20)
print(f"keys = {person1.keys()}")
print(f"values = {person1.values()}")
# function3()
def function4():
person1 = {
"name": "person1",
"age": 40,
"salary": 10.50,
"address": {
"city": "pune",
"state": "MH",
"country": "india",
"pin code": 21207
},
"CanVote": True,
"email":[
"person1@home.com",
"person1@company.com",
"person1@special.com"
]
}
# print(f"name: {person1['name']}")
# print(f"age: {person1['age']}")
# print(f"address: {person1['address']}")
print(f"address: {person1['address']['city']}, {person1['address']['state']}, {person1['address']['country']}")
print(f"home email = {person1['email'][0]}")
print(f"company email = {person1['email'][1]}")
print(f"special email = {person1['email'][2]}")
print(f"-" * 20)
keys = person1.keys()
for key in keys:
print(f"{key} = {person1[key]}")
# function4()
def function5():
d1 = {'k1': 'v1', 'k2': 'v2'}
d2 = {}
for key in d1.keys():
value = d1[key]
d2[value] = key
print(d1)
print(d2)
# function5()
def function6():
person = {}
print("enter name:")
person['name'] = input()
print("enter address:")
person['address'] = input()
print("Enter email id")
person['email id'] = input()
print(person)
function6()
|
b5ef1196655dbc592960c0732fc9ae824f66fb74 | navneet28/PythonForBeginners | /learnURLlib.py | 553 | 3.625 | 4 | import urllib.request
import urllib.parse
'''
req=urllib.request.urlopen('https://www.google.com')
print(req.read())
'''
values = {'q':'python programming tutorials'}
data = urllib.parse.urlencode(values)
url = 'https://www.google.com/search?'+data
print(data)
#data = data.encode('utf-8')
#oop
#self,*args,**kwargs
headers={}
headers['User-Agent']="Mozilla/5.0 (X11; Linux i686)"
req = urllib.request.Request(url,headers=headers)
#req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
resp_data = resp.read()
print(resp_data)
|
f6a01745223aea375c255875c8d1de978200c522 | Aujasvi-Moudgil/Classification-and-Representation-Learning | /Lab_Tutorials/Tutorial2/Tutorial 2.a code.py | 1,987 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 10:34:48 2017
@author: Aujasvi
"""
from numpy import *
import matplotlib.pyplot as plt
#Load the data set
data = loadtxt('nonlinear_classification.data')
X = data [:, :2]
T = data [:,2]
N, d = X.shape
#Parameters
eta = 0.05 #Learning rate
K = 15 #Number of hidden neurons
#weights and biases
max_val = 0
W_hid = random.uniform(-max_val, max_val,(d,K)) #all are small function
b_hid = random.uniform(-max_val, max_val, K)
W_out = random.uniform(-max_val, max_val, K)
b_out = random.uniform(-max_val,max_val, 1)
#Logistic transfer function for the hidden neurons
def logistic(X):
return 1.0/(1.0 + exp(-X))
#Threshold transfer function for the output neuron
def threshold (X):
data = X.copy()
data[data > 0.] = 1.
data[data < 0.] = -1.
return data
def feedforward (X, W_hid, b_hid, W_out, b_out):
#Hidden layer
Y = logistic (dot(X, W_hid) + b_hid)
#Output layer
O = threshold (dot(Y, W_out) + b_out)
return Y, O
#Backproppgation Algo
errors = []
for epoch in range (100): #first try epoch 100 K= 4
nb_errors = 0
for i in range (N):
x = X[i, :]
t = T[i]
Y, O = feedforward (x, W_hid, b_hid, W_out, b_out)
if t != O:
nb_errors +=1
delta_out = (t-O)
delta_hidden = Y*(1-Y)*delta_out*W_out
W_out += eta*Y*delta_out
b_out += eta*delta_out
for k in range (K):
W_hid[ :, k] += eta*x*delta_hidden[k]
b_hid += eta*delta_hidden
errors.append(nb_errors/float(N))
plt.plot(errors)
Mean = mean(epoch)
print('Mean:',Mean)
Variance = var(epoch)
print('Variance:', Variance)
#Question 2 : Convergence speed as no of hidden neurons are increasing
#Question 3:
#Question 4: When weights are initialised between at max_val = 0 then error is
#incresing.
#Question 5: Mean of the number of the epochs needed is 9 and variance is 0.
|
5579bec4095292b0de8968de0de25447a991dca4 | xexxatechng/MyGitProfile | /Python/furniture_pricing.py | 705 | 4.03125 | 4 | #Code written by: Christian Nwachukwu
#Date: 25/05/2019
#Application puppose: Application gives the correct price if the right options and chosen else prompts for re-entry.
while True:
print()
print("Enter 1, 2 or 3 to obtain prices")
option = int(input())
if option == 1:
print("Pine Table = $100")
elif option == 2:
print("Oak Table = $225")
elif option == 3:
print("Mahogany Table = $310")
else:
print("Invalid code, price = $0")
print("Enter 1, 2 or 3 to obtain prices")
print("Press 'y' to re-enter")
selection = input()
if selection != 'y':
break
else:
continue
|
7edf55548f01de3c27bc3ae4bfb26ea7d884c649 | ChenFu0420/leranpython | /part6/item.py | 240 | 3.75 | 4 | class Item:
#直接在类命名空间中放置可以执行的代码
print("正在定义Item类")
for i in range(10):
if i % 2 == 0:
print("偶数", i)
else:
print("奇数", i)
|
5c5352f4e10a55c33a50dd66527cf91fc5a86c80 | aaryanredkar/prog4everybody | /L1C7_Game.py | 734 | 3.984375 | 4 | import random
guessesLeft = 15
userName = input("Please enter your Name :")
number = random.randint(1, 1000)
print("Hello", userName, "I'm thinking of a number between 0 and 1000.")
while guessesLeft > 0:
print("You have", guessesLeft, "guesses left")
guess = int(input("Guess a number : "))
guessesLeft = guessesLeft - 1
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
elif guess == number:
print("Good job,",userName,"! You guessed my number in",(15-guessesLeft),"guesses!")
break
if guessesLeft == 0:
print("Sorry. The number I was thinking of was", number)
break
print("Have a Nice Day...")
|
3245fb0dacbbd460dee45333a339bb08b813da9f | aasthaagrawal/Algorithms_and_Data_Structures | /leetcode/268_Missing_Number.py | 284 | 3.5625 | 4 | #https://leetcode.com/problems/missing-number/
#Complexity: O(n)
class Solution:
def missingNumber(self, nums: List[int]) -> int:
lenArr=len(nums)
sumres=int(((lenArr+1)*lenArr)/2)
for i in range(lenArr):
sumres-=nums[i]
return sumres
|
04968513d8fbf1de1c7bc477b1ccf4ee9d6a34d5 | Techfighter/Histoires | /debug.py | 412 | 3.578125 | 4 | liste_arme = ["épée", "fusil", "baton", "knif", "lame", "styleto", "canon", "pistolet", "revolver", "fusil-a-pompe"]
inventaire = ["épée", "bananas"]
equiper = 0
dommage = 10
key = input("?>")
if key == "attaquer":
if (inventaire[equiper] in liste_arme):
print("Vous frapper avec", inventaire[equiper]+",", dommage, "point de dommage.")
else:
print("Vous n'est pas armé!")
|
f7dae2eafc2fd07ccb8e1563a68d6093b25fd3c8 | genii01/coding_test | /yb/Q_12_max-profit.py | 369 | 3.578125 | 4 | from typing import List
import sys
class Solution :
def maxProfit(self,prices:List[int]) -> int:
profit = 0
min_price = sys.maxsize
for price in prices:
min_price = min(min_price,price)
profit = max(profit,price - min_price)
return profit
prices = [7,1,5,3,6,4]
s = Solution()
print(s.maxProfit(prices)) |
136464443538c5b2dd6bca897a1439b244c3ad91 | mccmrunal/TIC-TAC-TOE | /TICTACTOE.py | 2,957 | 3.671875 | 4 | #board
import sys
import os
from os import system, name
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
table = ["-","-","-",
"-","-","-",
"-","-","-",]
count = 0
lis = []
def boardreset():
for i in range(0,9):
table[i] = "-"
global count
count = 0
def check_row(table):
for i in range(0,9,3):
if table[i] == table[i+1] == table[i+2] and (table[i]=="X" or table[i] == "O"):
print(table[i]+"WINS IN ROW")
menu()
def check_col(table):
for i in range(0,3):
if table[i] == table[i+3] == table[i+6] and (table[i]=="X" or table[i] == "O"):
print(table[i]+"WINS IN COLOUMN")
menu()
def check_diag(table):
if table[0] == table[4] == table[8] and (table[0] == "X" or table[0] == "O"):
print(table[0]+" WINS IN DIAGONAL")
menu()
elif table[2] == table[4] == table[6] and (table[2] == "X" or table[2] == "O"):
print(table[2]+" WINS IN DIAGONAL")
menu()
def check_win(table):
check_row(table)
check_col(table)
check_diag(table)
def handle_turn_o():
print("ENTER THE POSTION FOR ' O' YOUR MARK(1-9)")
x_pos = int(input())
table[x_pos - 1] = "O"
def handle_turn_x():
print("ENTER THE POSTION FOR ' X' YOUR MARK(1-9)")
x_pos = int(input())
table[x_pos - 1] = "X"
def check_full():
global count
count+=1
if count < 9:
return True
else:
print("GAME TIE")
menu()
def display_board():
print("---||-----||----")
print(table[0] + " || " + table[1] + " || " + table[2])
print("---||-----||----")
print(table[3] + " || " + table[4] + " || " + table[5])
print("---||-----||----")
print(table[6] + " || " + table[7] + " || " + table[8])
print("---||-----||----")
def handle_turn():
x = True
while x :
handle_turn_x()
clear()
display_board()
check_win(table)
check_full()
handle_turn_o()
clear()
display_board()
check_win(table)
check_full()
handle_turn_x()
check_win(table)
def display_board():
print("---||-----||----")
print(table[0] + " || " + table[1] + " || " + table[2])
print("---||-----||----")
print(table[3] + " || " + table[4] + " || " + table[5])
print("---||-----||----")
print(table[6] + " || " + table[7] + " || " + table[8])
print("---||-----||----")
def play_game():
display_board()
handle_turn()
print("GAME OVER")
def menu():
print("1. START GAME\n2.END GAME")
choice = int(input("MAKE YOUR CHOICE"))
clear()
if choice == 1:
boardreset()
print("WELCOME ABOARD")
play_game()
else:
print("THANK YOU")
sys.exit()
menu()
|
f155ec6fa9cac1f2f8634e36e89d9ece1762cdd3 | Namdrib/adventofcode | /src/main/template/day.py | 929 | 3.640625 | 4 | #!/usr/bin/python3
import sys
class DayXX:
"""
Solution for https://adventofcode.com/2022/day/XX
"""
def __init__(self) -> None:
"""
Constructor
"""
self.input: list = None
def read_input(self) -> None:
"""
Read input from stdin and parse it into a useful data structure
In this case, each line ...
"""
raw_input = sys.stdin.read()
self.input = raw_input.splitlines()
for item in self.input:
pass
def part_one(self) -> int:
"""
Return the ...
"""
return 0
def part_two(self) -> int:
"""
Return the ...
"""
return 0
def main() -> None:
"""
Main
"""
solver = DayXX()
solver.read_input()
print(f'Part 1: {solver.part_one()}')
print(f'Part 2: {solver.part_two()}')
if __name__ == '__main__':
main()
|
921594ef34d6b55242c598ca970c95c5a7aae821 | hyunjun/practice | /python/problem-dynamic-programming/climbing_stairs.py | 640 | 3.84375 | 4 | # https://leetcode.com/explore/featured/card/recursion-i/255/recursion-memoization/1662
class Solution:
# runtime; 32ms, 32.63%
# memory; 13.7MB
def climbStairs(self, n: int) -> int:
dp = [0] * (n + 1)
for i in range(1, len(dp)):
if i == 1:
dp[i] = 1
elif i == 2:
dp[i] = 2
else:
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
s = Solution()
data = [(2, 2),
(3, 3),
]
for n, expected in data:
real = s.climbStairs(n)
print(f'{n} expected {expected} real {real} result {expected == real}')
|
b87ff2d1d673b90c9ef0bd9c92c25b3d50f7dade | Chukwunonso/Rot13 | /main.py | 960 | 3.875 | 4 | def collect(word):
small_alphabet = range(97,123) #Ascii characters for small letters
cap_alphabet = range(65, 91) #Ascii characters for cap letters
encrypt_word = ""
for i in word:
if ord(i) not in range(97,123) + range(65,91):
new_i = str(i)
else:
if ord(i) in range(97,123):
alphabet = range(97,123)
if ord(i) in range(65,91):
alphabet = range(65,91)
'''the next line will find the modulo 26 of the difference of
the last letter and the ascii character of i, make it negative
so that it starts counting from behind and then adds 13.
Modulo allows the code to be cyclical around the alphabet
so that it never is never out of range'''
add_13 = -(((alphabet[-1] + 1) - ord(i)) % 26) + 13
new_i = chr(alphabet[add_13])
encrypt_word += new_i
return encrypt_word
|
25c8221b67029fb85b3a0943f9b28ee59174e4c1 | akhil960/akhilnmgd | /flow controls/decisionMaking/2ndLargest.py | 274 | 4.0625 | 4 | n1=int(input("enter n1:"))
n2=int(input("enter n2:"))
n3=int(input("enter n3:"))
if(n1==n2)&(n2==n3):
print("numbers are equal")
elif(n1>n2):
if(n1<n3):
print(n1)
else:
print(n3)
else:
if(n2<n3):
print(n2)
else:
print(n3)
|
cab6caf9c012d5f2306a78d3ad5c8c93aade350d | soply/curve_interpolation | /geometry_tools/utils.py | 747 | 4 | 4 | # coding: utf8
import numpy as np
def means_per_label(X, labels):
"""
Calculates the means of all subsets of X. Subset membership is indicated by
labels.
Parameters
=================
X : np.array of floats, size D x N
Data points
labels : np.array of ints, size N
Indicates the membership of a data point.
Returns
=================
means : np.array of floats, size D x #different labels
Means of the data points belonging to a group, for each group.
"""
D, N = X.shape
J = len(set(labels)) # No of different labels
means = np.zeros((D, J))
for i, label in enumerate(set(labels)):
means[:,i] = np.mean(X[:,labels == label], axis = 1)
return means
|
757f26c9dd7bfbb900594c2100db19d4f8700279 | chagaleti332/HackerRank | /Practice/Python/Itertools/itertools_combinations.py | 1,454 | 3.921875 | 4 | """
Question:
itertools.combinations(iterable, r)
This tool returns the r length subsequences of elements from the input
iterable.
Combinations are emitted in lexicographic sorted order. So, if the input
iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code:
>>> from itertools import combinations
>>>
>>> print list(combinations('12345',2))
[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'),
('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
>>>
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,4))
[(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)]
Task:
You are given a string S.
Your task is to print all possible combinations, up to size k, of the string
in lexicographic sorted order.
Input Format:
A single line containing the string S and integer value k separated by a
space.
Constraints:
The string contains only UPPERCASE characters.
Output Format:
Print the different combinations of string S on separate lines.
Sample Input:
HACK 2
Sample Output:
A
C
H
K
AC
AH
AK
CH
CK
HK
"""
# Solution:
from itertools import combinations
if __name__ == '__main__':
S = input().strip().split()
st = S[0]
r = int(S[1])
for j in range(1, r + 1):
for i in combinations(sorted(list(st)), j):
print(''.join(i))
|
50a68ed30ff2205d1a013eb9a14bf76fdd364789 | Jose-Humberto-07/pythonFaculdade | /jogo-tabuleiro/jogo.py | 852 | 3.859375 | 4 | import funcoes as f
casas = 17
fim = casas - 1
vencedor = ""
print(("+"*23)+" O JOGO "+("+"*23))
print("Quanto jogadores vão jogar? ")
quant = int(input())
if quant > 4 : quant = 4;
jogadores = f.RecebeJogadores(quant)
tabuleiro = f.IniciaTab(casas, quant, jogadores)
print(("+"*23)+" Inicio "+("+"*23))
f.MontaTab(quant,tabuleiro,jogadores)
rod = 1
while vencedor == "":
print(('+'*21)+"{}° RODADA ".format(rod)+('+'*21))
for j in range(1, quant+1):
if vencedor == "":
r = f.LancaDado(j,jogadores)
tabuleiro = f.MoverJogador(j,r,jogadores,tabuleiro,fim)
f.MontaTab(quant, tabuleiro, jogadores)
f.VerificaPrenda(j,quant,jogadores,tabuleiro,fim)
f.VerificaBonus(j,quant,jogadores,tabuleiro,fim)
vencedor = f.VerificaVencedor(quant,jogadores,tabuleiro,fim)
rod += 1
print()
f.Finaliza(quant,jogadores,vencedor,tabuleiro,fim)
|
a0d1124a99d029736f384745258fe284720f1ceb | rajlath/rkl_codes | /Helpers/random_array_integers.py | 548 | 3.765625 | 4 | import random
def create_random_int_arr(element_count, range_start, range_end, distinct= True):
'''
create an array of integers haveing number of element=element_count
having values between range_start and range_end - inclusive
:type element_count int
:type range_start int
:type range_end int
:rtype [] of int
'''
if distinct:
return random.sample(range(range_start, range_end+1), element_count)
else:
return [random.randint(range_start, range_end+1) for _ in range(element_count)]
|
6a7cfdc49852c592a2d8049d249fb8af5508443d | Clara-Kloster/Guldkorpus | /code/python/find_problem_pos.py | 2,447 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# This program takes user input of lemma, pos to find which files contain the problematic pos
import re
import csv
import os
import sys
# Find relative path
sys.path.append(os.path.realpath('../..'))
directory = sys.path[-1] + '/transcriptions/org/lemmatisation/'
print("This program searches for lemma-POS pairs")
while True:
user_input = input("Please provide a lemma and POS-tag separated with a space: ")
user_input = user_input.split()
while len(user_input) != 2:
user_input = input("Oops try again: ")
user_input = user_input.split()
prob_lemma = user_input[0]
prob_pos = user_input[1]
for filename in os.listdir(directory):
if filename.endswith(".org"):
problematic = False
number_of_problems = 0
working_file = directory + filename
shortname = filename.replace(".org", "")
data = open(working_file).read()
mo = re.search("Transcription\n.*\n(\n|$)", data, re.S)
mytable = mo.group(0)
d = csv.DictReader(mytable.splitlines(), delimiter = '|')
for row in d:
lemma = row[None][2].strip()
pos = row[None][3].strip()
if lemma == prob_lemma and pos == prob_pos:
problematic = True
number_of_problems += 1
if problematic == True:
print(shortname, " : ", number_of_problems)
continue_check = input("Press enter to continue or [q] to quit: ")
if continue_check == "q":
quit()
for filename in os.listdir(directory):
if filename.endswith(".org"):
problematic = False
number_of_problems = 0
working_file = directory + filename
shortname = filename.replace(".org", "")
data = open(working_file).read()
mo = re.search("Transcription\n.*\n(\n|$)", data, re.S)
mytable = mo.group(0)
d = csv.DictReader(mytable.splitlines(), delimiter = '|')
for row in d:
lemma = row[None][2].strip()
pos = row[None][3].strip()
if lemma == prob_lemma and pos == prob_pos:
problematic = True
number_of_problems += 1
if problematic == True:
print("WARNING: ", shortname, " : ", number_of_problems)
|
7e62557d91d43b54b628d79eb56793fbd6ead435 | zhangchizju2012/LeetCode | /551.py | 597 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 15 19:24:46 2017
@author: zhangchi
"""
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
count = 0
countL = 0
for i in s:
if i == "A":
count += 1
countL = 0
elif i == "L":
countL += 1
else:
countL = 0
if count > 1:
return False
if countL > 2:
return False
return True |
fb2242c69e389637d9de6d8dd6da7cf1f390048b | ask4physics/python-ICDL | /Day 1 (28012021)/Name.py | 169 | 4.4375 | 4 | Name = input ("What is your name? ") #ask the user to input. Variable will be stored in #name variable.
print("Your name is:", Name) #print message and variable value.
|
f8b50b147dda8588396bdef5c1d845cb2154d72e | rajdharmkar/Python2.7 | /math/matrixprod1.py | 286 | 3.609375 | 4 | X = [[1,2,3],[4,5,6],[7,8,9]]
Y = [[1,2,3],[4,5,6],[7,8,9]]
product = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):#why len(Y[0])taken?
for k in range(len(Y)):
product[i][j]+=X[i][k]*Y[k][j]
for r in product:
print(r)
|
287caa285aeb7989b8277d10df668d2ac99c22cc | hwanginbeom/TIL | /algorithms/source/42.loop1.py | 387 | 3.890625 | 4 | # 문제 1.
# 10보다 작은 자연수 중에서 3 또는 5의 배수는
# 3,5,6,9가 존재해요! 이것들의 합은 23입니다.
# 1000보다 작은 자연수 중에서 3 또는 5의 배수들을
# 구해서 모두 합하면 얼마인가요?
sum_value = 0
for i in range(1,1000):
if i % 3 == 0 or i % 5 == 0:
sum_value += i
print("문제 1번 : {} ".format(sum_value))
|
5693f1d1aaba7b34ac168da108a62f555833bef5 | ngvinay/python-projects | /spring-2017/src/python-onramp/hw3/Assignment3.py | 3,830 | 3.9375 | 4 | # 1. You have been given a barGraph.csv file. Using the data of this file you have to draw a bar graph showing all 8 emotions corresponding to each business.
import pandas
import os
import matplotlib.pyplot as plt
import numpy as np
relativePath=os.getcwd()
dataFilePath=relativePath+"/Resources/barGraph.csv"
data = pandas.read_csv(dataFilePath)
index = np.arange(len(data.enjoyment))
barWidth = 0.1
opacity = 0.4
a = data.columns
count = 0
for column in a.tolist()[1:]:
plt.bar(index+count*barWidth,data[column].tolist(),barWidth,label=column)
count+=1
if count==int(len(a.tolist())/2):
plt.xticks(index+count*barWidth,data['Business'].tolist())
plt.legend()
loc, labels = plt.xticks()
plt.setp(labels,rotation=-8)
plt.show()
# 2. Using the data present in barGraph.csv file generate pie-chart showing percentage of emotions for each business.
import pandas
import os
import matplotlib.pyplot as plt
import numpy as np
relativePath=os.getcwd()
dataFilePath=relativePath+"/Resources/barGraph.csv"
data = pandas.read_csv(dataFilePath)
labels = data.columns[1:].tolist()
count = 1
a, b = plt.subplots(3,2)
for i in range(3):
for j in range(2):
# count+=1
b[i,j].pie(data.loc[i+j][1:].tolist(),autopct='%1.1f%%', radius=0.8)
b[i,j].set_title(data.loc[i+j][0])
b[i,j].legend(labels,loc="upper left", fontsize=6)
plt.show()
# 3. Generate a word cloud of your favorite news article or story or anything. This word cloud should contain words having 4 letters or more.
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import re
d = os.getcwd()
filepath=d+"/Resources/article.txt"
# Read the whole text.
def wordCloud(path):
text = open(path, encoding="utf8").read() #read the entire file in one go
text = text.replace("\n", " ").split(" ")
text = " ".join([word for word in text if len(word)>4])
wordcloud = WordCloud().generate(text)
# Display the generated image:
# the matplotlib way:
plt.imshow(wordcloud)
plt.axis("off")
# take relative word frequencies into account, lower max_font_size
wordcloud = WordCloud(background_color="white", max_words=2000,max_font_size=40, relative_scaling=.4).generate(text)
plt.figure()
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordCloud(filepath)
# 4. You have been given a file ReviewID.txt. It has 10646 records in it, each record is made up of two fields separated by a colon: like AzSn8aTOyVTUePaIQtTUYA:es . The first field is review ID and the second field is language in which reviews has been written. Read this file and create a bar graph showing the percentage of the reviews written in a particular language. The aim of this problem is to generate a graph using which we can do a comparative analysis of the languages used for writing reviews.
import os
import matplotlib.pyplot as plt
import numpy as np
relativePath=os.getcwd()
dataFilePath=relativePath+"/Resources/ReviewID.txt"
filePointr=open(dataFilePath,"r")
v = {}
d = {}
f = {}
for line in filePointr:
key,value = line.strip("\n").split(":")
v[key]=value
count = 0
for key, value in v.items():
if value in d.keys():
d[value] = d[value] + 1
else:
d[value] = 1
count += 1
for key, value in d.items():
f[key]=round((float(value)/count)*100, 2)
sorted_dict = sorted(f.items(),key=lambda x: x[1],reverse=True)
index = np.arange(len(sorted_dict))
barWidth = 0.35
opacity = 0.4
plt.bar(index, [value for key, value in sorted_dict], barWidth, alpha=opacity, color = 'r', align='center' )
plt.xticks(index,[key for key, value in sorted_dict])
plt.xlabel("Review Language")
plt.ylabel("Percentage")
plt.show()
|
ed3965619cc03879b693814a582591e634c17250 | backtrunck/learning_python2 | /alo.mundo.py | 275 | 3.625 | 4 | print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
print "alo mundo"
h=raw_input("digite uma tecla")
for k in range(999):
print "%d alo mundo 2"%k
print "tchau"
|
6f8a42c59558282b81dd86a4112ba9e3729ddcb8 | drifftingcanoncuddle/szawiola-zadanie | /simulation/SimFrame.py | 692 | 3.515625 | 4 | from typing import *
from simulation.Particle import Particle
class SimFrame:
"""
One state of world in some moment in time
"""
def __init__(self, particles: List[Particle]):
"""
:param particles: list with particles in world
"""
self.particles = particles
def get_particle(self, number) -> Particle:
"""
getter for one particle
:param number: number of particle in world
:return: Particle
"""
return self.particles[number]
def get_particles(self) -> List[Particle]:
"""
getter for whole list with particles
:return:
"""
return self.particles
|
eb81acc6086d947fa43beabda7027ef68621f1f1 | heldaolima/Exercicios-CEV-Python | /ex012.py | 305 | 3.890625 | 4 | print('--- CALCULADOR DE DESCONTO ---\n')
prod = float(input('Qual o preço produto em questão? R$'))
desc = (5/100) * prod
final = prod - desc
print('----')
print(f'Estamos oferecendo 5% de desconto. Serão descontados R${desc:.2f}.\n'
f'Portanto, a sua compra terá novo valor de R${final:.2f}.') |
cc497e6af1dac8bdbd0c0391ea5aa53bd701ef27 | slvborisov/slvborisov.github.io | /exs1.py | 323 | 4.03125 | 4 | print ("Greetings!")
name = input("What is your name? ")
print ("Nice to meet you " +name+"!")
age = int(input("Now, what is your age? "))
year = str((2020 - age)+100)
message = name + ", you will be one hundred in " + year
print (message)
repeat = int(input("Now give me a random number: 1-10 "))
print (message * repeat)
|
1cda1300b8ad592a57f61ecdb1e541803ec53e20 | bhulet/courseraRicePython | /stopwatch.py | 2,191 | 3.640625 | 4 | "Stopwatch: The Game"
import simplegui
# define global variables
interval = 100
count, sec, min, y, x = 0, 0, 0, 0, 0
ratio = str(x) + "/" + str(y)
time = str(min) + ":" + str(sec) + "." + str(count)
game = True
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
global count, sec, min, time
t = count
if (t==10):
sec += 1
if (sec == 60):
min += 1
sec = 0
count = 0
if (sec < 10) and (min < 10):
time = str(0) + str(min) + ":" + str(0) + str(sec) + "." + str(count)
elif (sec >= 10) and (min < 10):
time = str(0) + str(min) + ":" + str(sec) + "." + str(count)
elif (min >= 10) and (sec >= 10):
time = str(min) + ":" + str(sec) + "." + str(count)
elif (min >= 10) and (sec < 10):
time = str(min) + ":" + str(0) + str(sec) + "." + str(count)
return time
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_button_handler():
global game
game = True
timer.start()
def stop_button_handler():
global x, y, ratio, game, count
if game and (count == 0):
y += 1
x += 1
ratio = str(x) + "/" + str(y)
game = False
elif game:
y += 1
ratio = str(x) + "/" + str(y)
game = False
timer.stop()
def reset_button_handler():
global count, min, sec, x, y, ratio, game
count, min, sec, x, y = 0, 0, 0, 0, 0
ratio = str(x) + "/" + str(y)
timer.stop()
# define event handler for timer with 0.1 sec interval
def tick():
global count
count += 1
# define draw handler
def draw_handler(canvas):
canvas.draw_text(format(count), [65, 105], 24, "White")
canvas.draw_text(ratio, [155, 30], 24, "Yellow")
# create frame
frame = simplegui.create_frame("Stopwatch", 200, 200)
frame.add_button("Start", start_button_handler, 80)
frame.add_button("Stop", stop_button_handler, 80)
frame.add_button("Reset", reset_button_handler, 80)
frame.set_draw_handler(draw_handler)
timer = simplegui.create_timer(interval, tick)
# register event handlers
# start frame
frame.start()
|
ac603dcf32df70fb56a6d5347b76850a63628cd0 | FelipeECarvalho/Primeiros-Projetos | /Estrutura de Dados/funcao_recursiva.py | 857 | 4.09375 | 4 | def soma(array):
if len(array) == 0:
return 0
else:
return array[0] + soma(array[1:])
def conta(array):
if len(array) == 0:
return 0
else:
return 1 + conta(array[1:])
def maior(array):
if len(array) == 2:
return array[0] if array[0] > array[1] else array[1]
val_max = maior(array[1:])
return array[0] if array[0] > val_max else val_max
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
lista = [0, 5, 3, 7, 4, 10, 100, 2, 5, 6, 8, 9, 44, -3]
n = lista[10]
print(f"A soma entre os termos da lista é igual: {soma(lista)}")
print(f"A quantidade de termos da lista é igual: {conta(lista)}")
print(f"O maior elemento do array é igual: {maior(lista)}")
print(f"O indice {n} na sequência fibonacci é igual a: {fibonacci(n)}")
|
b2961dbcfd0c81266f1ff45e66e27bd61deb87d8 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2732/60723/272851.py | 139 | 3.6875 | 4 | num=int(input())
for i in range(num):
temp=input().split()
A=int(temp[0])
B=int(temp[1])
C=int(temp[2])
print((A**B)%C) |
81684f580271eeb483768bcce6d0a4be721e68c2 | LeoAuyeung/Leo-assignments-12700 | /05/cipher.py | 1,191 | 3.84375 | 4 | def encode_letter(c,r):
#Low & Up alphabets to account for both lower and upper case letters
alph_low='abcdefghijklmnopqrstuvwxyz'
alph_up='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#Lower Case:
if c in alph_low:
c_loc = alph_low.index(c)
new_loc = c_loc + r
#Only 26 letters in alphabet, so accounts for large ranges if necesary
if new_loc > 25 or new_loc < -25:
new_loc = new_loc % 26
return alph_low[new_loc]
#Upper Case:
elif c in alph_up:
c_loc = alph_up.index(c)
new_loc = c_loc + r
#Only 26 letters in alphabet, so accounts for large ranges if necesary
if new_loc > 25 or new_loc < -25:
new_loc = new_loc % 26
return alph_up[new_loc]
#If c is a non-letter, return itself
else:
return c
def encode_string(s,r):
new_str = ''
for x in s:
new_str += encode_letter(x,r)
return new_str
def full_encode (s):
ans = ""
for i in range (26):
ans += str(i) + ": " + encode_string(s,i)
ans += "\n"
return ans
#print (encode_letter('t',3))
#print (encode_string('hello',1))
print (full_encode('Hello World!!!')) |
dfd1f733f503c204481f226cb48c2343313811f4 | shreyakapadia10/PythonProjects | /Python Programs/file_reading.py | 1,399 | 4.28125 | 4 | """
r = Opens file in read mode = default mode
w = Opens file in write mode
x = Creates file if not exists
a = Appends to file
t = Opens file in text mode
b = Opens file in binary mode
+ = Opens file in read and write mode
"""
# File reading and printing entire file using read
print("# File reading and printing entire file using read")
f = open("file.txt")
contents = f.read()
print(contents)
f.close()
print()
print("# File reading and printing some characters of file using read(no of characters)")
print()
# File reading and printing some characters of file using read(no of characters)
f = open("file.txt")
contents = f.read(5)
print(contents)
f.close()
print()
print("# File reading and printing line by line")
print()
# File reading and printing line by line
f = open("file.txt", "rt")
for line in f:
print(line, end="")
f.close()
print()
print("# File reading and printing using readline(), it will print only one line")
print()
# File reading and printing using readline(), it will print only one line
f = open("file.txt", "rt")
print(f.readline())
f.close()
print()
print("# File reading and printing using readlines(), it will convert file lines into list of lines")
print()
# File reading and printing using readlines(), it will convert file lines into list of lines
f = open("file.txt", "rt")
contents = f.readlines()
print(contents)
f.close() |
31595b9759e11d1cd797bca1b0d5237b6b8232c6 | Ecqonline/streamlit-example | /streamlit_app.py | 2,076 | 3.734375 | 4 | # IMPORTAR AS BIBLIOTECAS NECESSÁRIAS E O ALGORIMO K-NN
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler()
# CRIAR FUNÇÕES NECESSÁRIAS PARA CARREGAR DADOS E TREINAR MODELO.
# Função para treinar o modelo
def treinar_modelo(df):
X_atributos_preditores = df.iloc[:,1:4].values
y_atributo_alvo = df.iloc[:,4].values
# Normalização Min-Max para a os preditores
sc.fit(X_atributos_preditores)
X_atributos_preditores_scaled = sc.transform(X_atributos_preditores)
modelo_knn_classificacao = KNeighborsClassifier(n_neighbors=5,metric='minkowski', p=2)
modelo_knn_classificacao.fit(X_atributos_preditores_scaled,y_atributo_alvo)
return modelo_knn_classificacao
# SITE
# Título do site
st.title("Site para classificar empréstimo.")
# Subtítulo
st.subheader("Insira seus dados.")
# Recebendo o arquivo
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
# Recebendo os dados do usuário.
salario = st.number_input("Salário", value=0)
idade = st.number_input("Idade", value=0)
valor_emprestimo = st.number_input("Valor empréstimo", value=0)
# Aplicar a normalização Min-Max dos preditores nos novos dados
new_data = [salario, idade, valor_emprestimo]
# Botão para realizar a avaliação de crédito.
botao_realizar_avaliacao = st.button("Realizar avaliação")
# SE o botão seja acionado.
# 01.Coletar todos os dados que o usuário informou.
# 02.Usar os dados para predizer o resultado. Crédito aprovado ou reprovado.
# 03.Mostrar o resultado da avaliação.
if botao_realizar_avaliacao:
# MODELO DE CLASSIFICAÇÃO
# treinando o modelo
modelo = treinar_modelo(df)
new_data_scaled = sc.transform([new_data])
resultado = modelo.predict(new_data_scaled)
st.subheader("Resultado: ")
if resultado == 0:
resultado_avaliacao = "crédito aprovado"
else:
resultado_avaliacao = "crédito reprovado"
st.write(resultado_avaliacao)
|
26de4009fd3a4ac208ef9adb1e8577968c2064b4 | yedaloc/proyecto-paradigmas | /Main.py | 1,209 | 4 | 4 | #! /usr/bin/python3
#Main.py
import os
from controller import Controller
c = Controller()
def menu():
"""
Función que limpia la pantalla y muestra nuevamente el menu
"""
os.system('clear')
print ("Sistema de Auditoria")
print ("\t1 - Agregar empresa")
print ("\t2 - Realizar Auditoria")
print ("\t3 - listar Empresa")
print ("\t9 - salir")
while True:
# Mostramos el menu
menu()
# solicituamos una opción al usuario
opcionMenu = input("inserta un numero valor >> ")
if opcionMenu=="1":
#ingresando para crear una empresa
c.agregarEntidad()
input("Se ha Agregado una empresa \npulsa una tecla para continuar")
elif opcionMenu=="2":
#realizar auditoria
print("Elija Empresa a tomar auditoria")
c.listarEntidad()
c.realizarPruebas()
input("Has pulsado la opción 2...\npulsa una tecla para continuar")
elif opcionMenu=="3":
#genera reportes e imprime los reportes obtenidos
c.listarEntidad()
print ("")
input("Has pulsado la opción 3...\npulsa una tecla para continuar")
elif opcionMenu=="9":
break
else:
print ("")
input("No has pulsado ninguna opción correcta...\npulsa una tecla para continuar") |
a4d5231c5454746cd2db7531394d3e3071c5462c | manishcomp1/Python | /code/decorator.py | 254 | 3.578125 | 4 | def sample_decorator(addition):
def wrapper(x, y):
print x,y
return addition(x, y)
return wrapper
@sample_decorator
def addition1(x, y):
result = x + y
print "result",result
return result
x = 5
y = 10
result = addition1(x , y)
print result
|
c06c6d4afe2ba57f18640eee73ea4bb0fc73fa6f | MartinPSE/E.T.C | /Codesignal/Hello_Python/bit_length.py | 370 | 3.640625 | 4 | n = 5
n.bit_length() # 이렇게 활용할 수도 있고
# bit 수에 맞게 print를 하고 싶으면?
# 예를 들면 integer "5"을 0'b0101 네자리 표현을 하고 싶을 경우
BitLen = n.bit_length() # bit length를 구하고 bit length는 3
BitLen = 4
Form = '0' + '{0}'.format(BitLen) + 'b' # '04b'
print("Binary Format : 0'b{0}".format(format(n, Form))) |
219b6380c85dbffd5bcb0a52d35dac28beb1e60f | mucciz/News | /tests/news_test.py | 1,043 | 3.765625 | 4 | import unittest
from app.models import News
# News = news.News
class NewsTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Movie class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_news = News('abc-news','ABC NEWS','Your trusted source for breaking news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.','http://www.abc.net.au/news','business','au')
def test_instance(self):
self.assertTrue(isinstance(self.new_news,News))
def test_init(self):
self.assertEqual(self.new_news.id,'abc-news')
self.assertEqual(self.new_news.name,'ABC NEWS')
self.assertEqual(self.new_news.description,'Your trusted source for breaking news, analysis, exclusive interviews, headlines, and videos at ABCNews.com.')
self.assertEqual(self.new_news.url,'http://www.abc.net.au/news')
self.assertEqual(self.new_news.country,'au')
# if __name__ == '__main__':
# unittest.main()
|
f502ed2a1e7245e8eb8b06c9a022d82d19d85aba | robinyms78/My-Portfolio | /Exercises/Python/Learning Python_5th Edition/Chapter 5_Numeric Types/Examples/Other Numeric Types/Fractions/Example6/Example6/Example6.py | 505 | 3.796875 | 4 | from fractions import Fraction
# Float object method
print((2.5).as_integer_ratio())
# Convert float -> fraction: two args
# Same as fraction (5,2)
f = 2.5
z = Fraction(*f.as_integer_ratio())
print(z)
# x from prior interaction
x = Fraction(1,3)
# 5/2 + 1/3 = 15/6 + 2/6
print(x + z)
# Convert fraction -> float
print(float(x))
print(float(z))
print(float(x + z))
print(17/6)
# Convert float -> fraction: other way
print(Fraction.from_float(1.75))
print(Fraction(*(1.75).as_integer_ratio()))
|
0629358a5f590905fad4baae5fb634af853ed89e | jiaqiyusun/Python | /1_3.py | 1,541 | 3.9375 | 4 | #String
print(type("hi hello i am here!"))
username = 'supercoder'
password = 'supersecret'
long_string ='''
WPW
= =
...
''' # long string with three single quotes
print(long_string)
first_name = "jiaqi"
last_name = "Yu"
full_name = first_name +' '+ last_name #space between last name and first name
print(full_name)
#string concatenation
print('hello' + ' Jiaqi')
#print('hello' + 5) does not work, because print just for str
print(type(str(100))) # converted int for string
print(type(int(str(100))))
a = str(100)
b = int(a)
c = type(b)
print(c)
#Type conversion
#Escape Sequence
weather = "\tit\'s \"kind of\" sunny\n hope you have a good day!"
print(weather)
#formatted strings
name = 'Jonhny'
age = 55
print('hi '+name+'. You are '+str(age)+' years old.')
#print(f'hi{name}, you are{age} years old.') python3
#print('hi{}, you are{} years old.').format('jonny','56')
#print('hi{}, you are{} years old.').format(name,age)
#print('hi{1}, you are{0} years old.').format(name,age)
#print('hi{new_name}, you are{age} years old.').format(new_name='sally',age=100)
#String index
#'mem mem mem'# m is stolen in space 0, e is stolen in space 1 etc
selfish = 'me me me'
print(selfish[0])# grab in location 0
#[start:stop:stepover] stop the letter before stop location
print(selfish[0:8:2])
print(selfish[1:])
print(selfish[:5])
print(selfish[-1])# end one
print(selfish[::-1])#reverse an order
print(selfish[::-2])
#Immutability
#we can not change what we create, we can create new thing
selfish = selfish +'8'
print(selfish) |
fc3b8a2eee36062324c6f0bf7176a9425c69bf4e | sforrester23/SlitherIntoPython | /chapter7/Question3.py | 930 | 4.15625 | 4 | # Write a program that takes a string as input from the user.
# The string will consist of digits and your program should print out the first repdigit.
# A repdigit is a number where all digits in the number are the same.
# Examples of repdigits are 22, 77, 2222, 99999, 444444
# Building upon the previous exercise,
# write a program that takes a string as input from the user and prints the first number encountered
# along with the starting position of the number.
s = input("Please enter a string: ")
output = ""
i = 0
while i < len(s) - 1 and not (s[i].isnumeric() and s[i] == s[i+1]):
i += 1
j = i
if i >= len(s) - 1 or s[i] != s[i+1]:
print("There is no repdigit in that string.")
else:
while j < len(s) - 1 and s[j].isnumeric() and s[j+1] == s[j]:
output += s[j]
j += 1
output += s[j]
print("The first number in that string is: {}, starting at position: {}".format(output, i))
|
b658ee5282565a260e1587236095fce043b8d1c8 | DPDominika/checkio | /elementary/Index Power.py | 276 | 3.84375 | 4 | # https://py.checkio.org/mission/index-power/
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n == 0:
return 1
elif len(array)-1 < n:
return -1
elif len(array)-1 >= n:
return (array[n])**n
|
48fcb99bd4daccc3dc0299c91e1c22e405893d7b | zielman/Codeforces-solutions | /B/B 1331 Limericks.py | 128 | 3.578125 | 4 | # https://codeforces.com/problemset/problem/1331/B
a = int(input())
d = 2
while a % d != 0:
d += 1
print(f"{d}{a//d}") |
aa97b0278459bb51b78691727f28b91e8f7b1fba | xhimanshuz/time-pass | /Python/Data_Structure/linear_search.py | 1,004 | 4.125 | 4 | #!/usr/bin/python3
# LINEAR SEARCH SIMPLE PROGRAM
from sys import argv
class LinearSearch:
def __init__(self, size=None):
self.size = size
self.array = []
self.flag = 0
self.count = 0
def algo(self):
for i in range(self.size):
self.count+=1
print(self.count)
if self.n is self.array[i]:
print("Found at index number {}".format(i))
self.flag = 1
break
if self.flag is 0:
print("Element not Found")
def inp(self):
print("Enter {} Elements in an array: ".format(self.size))
for i in range(self.size):
self.array.append(i)
self.n = int(input("Enter Element to Search its Location: "))
def main():
if (len(argv))>1:
size = int(argv[1])
else:
size = int(input("Enter Size of Array: ") )
ls = LinearSearch(size)
ls.inp()
ls.algo()
if __name__ == '__main__':
main()
|
116c3e03ca403f1aa64d26ae9aea50d969d0b533 | aakashmt97/My-Python-Games | /Guess Number.py | 694 | 4.09375 | 4 | import random
guessTaken = 0
name = input("What is your Name: ")
print("Well, " + name + " I'm thinking of a number between 1 to 20")
number = random.randint(1, 20)
for guessTaken in range(6):
guess = int(input("Guess the number: "))
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
guessTaken = str(guessTaken + 1)
print("Good Job " + name + "!! You guessed the number in " + guessTaken +
" guesses!")
if guess != number:
number = str(number)
print("Sorry " + name + ", the number I was guessing is " + number + ".")
|
9b59538392a8aa730eaf93ae9885b8bd5a56fd5a | feliciaamy/movie-trailer-website_1 | /media.py | 1,029 | 3.84375 | 4 | import webbrowser
class Movie():
"""This class provides a way to store movie related information"""
def __init__(self,title='',storyline='',poster='',youtube='',rating='',rank=''):
self.title = title
self.storyline = storyline
self.poster_image_url = poster
self.trailer_youtube_url = youtube
self.rating = rating
self.rank = rank
def setTitle(self,title):
self.title = title
def setStoryline(self,storyline):
self.storyline = storyline
def setPoster(self,poster):
self.poster_image_url = poster
def setTrailer(self,youtube):
self.trailer_youtube_url = youtube
def setRating(self,rating):
self.rating = rating
def setRank(self,rank):
self.rank = rank
def getTitle(self):
return self.title
def show_trailer(self):
#Open youtube to show the trailer of the movie
webbrowser.open(self.trailer_youtube_url)
|
0bb6244e975f141bd095a7f542055f47711035c9 | govindnayak/CODING | /ARRAYS/kth_largest_after_insertion.py | 594 | 3.65625 | 4 | #Given an input stream of n integers the task is to insert integers to stream and print
#the kth largest element in the stream at each insertion
#Use HEAP instead of an array window!
import heapq
t = int(input())
while(t):
t-=1
k, n = map(int, input().split())
a = list(map(int, input().split()))
s = []
for j in range(k-1):
print(-1, end=" ")
for i in range(k):
heapq.heappush(s, a[i])
print(s[0], end=" ")
for i in range(k, n):
m = s[0]
if a[i]>m:
x = heapq.heappop(s)
heapq.heappush(s, a[i])
print(s[0], end=" ")
else:
print(m, end=" ")
print("")
|
5b7e1d1ca2403112eebbea50b1165def516a4c3a | diningphills/eulerproject | /problems/20~29/25/dy.py | 397 | 3.78125 | 4 | def digitCount(n):
count = 1
while n >= 10:
count += 1
n = n/10
return count
def Fibonacci(F, i):
if i==0 or i==1:
return 0
else:
newValue = F[i-2] + F[i-1]
F.append(newValue)
F = [1, 1]
i=2
while True:
Fibonacci(F, i)
print(F[i], i)
if digitCount(F[i]) >= 1000:
print(i)
break
else:
i += 1 |
62eb75f2ec5595c79abb0453e2c04b5fe0c06bb3 | clprenz/de_sim | /de_sim/examples/random_walk.py | 3,729 | 3.71875 | 4 | """ A simulation of a random walk where a variable is incremented or decremented with equal probability at each event
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2018-02-27
:Copyright: 2018-2020, Karr Lab
:License: MIT
"""
import argparse
import random
import sys
from de_sim.simulation_engine import SimulationEngine
from de_sim.simulation_message import SimulationMessage
from de_sim.simulation_object import ApplicationSimulationObject
class MessageSentToSelf(SimulationMessage):
"A message that's sent to self"
class RandomWalkSimulationObject(ApplicationSimulationObject):
""" The random state variable model
* State: a number
* Event scheduling: schedule events randomly
* Event execution: randomly increment or decrement the state
"""
def __init__(self, name, initial_value, output=True):
self.state = initial_value
self.output = output
super().__init__(name)
def send_initial_events(self):
self.send_event(0, self, MessageSentToSelf())
self.send_event(1, self, MessageSentToSelf())
def handle_simulation_event(self, event):
# print time, state, event queue
if self.output:
print()
print("Time: {}; state: {}".format(self.time, self.state))
eq = self.simulator.event_queue.render(sim_obj=self, as_list=True)
if eq is None:
print("Empty event queue")
else:
times = [ev[1] for ev in eq[1:]]
print("Event queue times: {}".format(times))
self.state += random.choice([-1, 1])
for i in range(random.choice([0, 1, 2])):
self.send_event(random.choice([1, 6]), self, MessageSentToSelf())
event_handlers = [(MessageSentToSelf, handle_simulation_event)]
# register the message types sent
messages_sent = [MessageSentToSelf]
class RunRandomWalkSimulation(object):
@staticmethod
def parse_args(cli_args=None): # pragma: no cover # don't bother testing
""" Parse command line arguments
Args:
cli_args (:obj:`list`, optional): if provided, use to test command line parsing
Returns:
:obj:`argparse.Namespace`: parsed command line arguements
"""
parser = argparse.ArgumentParser(
description="A trivial simulation that increments or decrements a variable at each event")
parser.add_argument('initial_state', type=int, help="Initial state")
parser.add_argument('time_max', type=float, help="End time for the simulation")
parser.add_argument('--no-output', dest='output', action='store_false',
help="Don't write progress to stdout")
if cli_args is not None:
args = parser.parse_args(cli_args)
else: # pragma: no cover # reachable only from command line
args = parser.parse_args()
return args
@staticmethod
def main(args):
# create a simulator
simulator = SimulationEngine()
# create a simulation object and add it to the simulation
simulator.add_object(RandomWalkSimulationObject('random state variable object',
args.initial_state, args.output))
# run the simulation
simulator.initialize()
num_events = simulator.simulate(args.time_max)
sys.stderr.write("Executed {} event(s).\n".format(num_events))
return(num_events)
if __name__ == '__main__': # pragma: no cover # reachable only from command line
try:
args = RunRandomWalkSimulation.parse_args()
RunRandomWalkSimulation.main(args)
except KeyboardInterrupt:
pass
|
3d1412ba02b62065e248aa6dc1b3c95f586d5c67 | tkremer72/Python-Masterclass | /PythonCodingExercises/11.Continue/without_continue.py | 89 | 3.75 | 4 | # Without continue
for x in range(21):
if x % 3 != 0 and x % 5 != 0:
print(x) |
6fe6b4201536b987eb7716d0e7d232f7f15f6bdb | VineethChandha/Cylinder | /Packing&Unpacking.py | 743 | 4.53125 | 5 | #PY.01.14 Introduction to packing and unpacking
L=[1,2,3,4]
P="abc"
print(P)
print(*P)
print(L)
print(1,2,3,4)
print(*L) #* is used in unpacking the data
def add(*numbers): #by using the * in parameter it acts as tuple and can take any number of arguments
total=0
for number in numbers:
total=total+number
print(total)
add(1,2,3,3,4,)
def about(name,age,like):
s="{} is {} years old and likes {}".format(name,age,like)
print(s)
dictionary={"name":"vineeth","age":24,"like":"playing"}
about(**dictionary)
def foo(**kwargs): #for unpacking use ** as parameter
for key,value in kwargs.items():
print("{}:{}".format(key,value))
foo(ram="male",sita="female")
|
41ccf2f9e3694ddf5b6c1658f372aaf4c7a8e721 | dilkas/project-euler | /096.py | 2,200 | 3.640625 | 4 | import copy
def square_range(i):
return range(i - i % 3, i - i % 3 + 3)
def neighbours(I, J):
return ([(I, j) for j in range(9)] + [(i, J) for i in range(9)] +
[(i, j) for i in square_range(I) for j in square_range(J)])
def insert(grid, I, J, value):
grid[I][J] = value
for i, j in neighbours(I, J):
if not isinstance(grid[i][j], set): continue
grid[i][j].discard(value)
if len(grid[i][j]) == 0: return True
return False
def min_set(grid):
min_i = -1
min_j = -1
for i in range(9):
for j in range(9):
if (isinstance(grid[i][j], set) and
(min_i == -1 or len(grid[i][j]) < len(grid[min_i][min_j]))):
min_i = i
min_j = j
return min_i, min_j
def search(grid):
while True:
made_changes = False
found_sets = False
for i in range(9):
for j in range(9):
if isinstance(grid[i][j], set):
found_sets = True
if len(grid[i][j]) == 1:
made_changes = True
if insert(grid, i, j, grid[i][j].pop()): return 0
if not found_sets: return int(''.join(map(str, grid[0][:3])))
if not made_changes: break
i, j = min_set(grid)
for digit in grid[i][j]:
new_grid = copy.deepcopy(grid)
if insert(new_grid, i, j, digit): continue
s = search(new_grid)
if s > 0: return s
return 0
def initialize(grid):
new_grid = copy.deepcopy(grid)
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
new_grid[i][j] = (set(range(1, 10)) -
set(grid[I][J] for I, J in neighbours(i, j)))
return new_grid
def parse_grid(f):
f.readline()
grid = []
for _ in range(9):
line = f.readline()
if line[-1] == '\n': line = line[:-1]
grid.append(map(int, line))
return initialize(grid)
def parse_grids(filename):
f = open(filename)
grids = [parse_grid(f) for _ in range(50)]
f.close()
return grids
print sum(search(grid) for grid in parse_grids('p096_sudoku.txt'))
|
208692b5473d0f038818b135ac992aa17a5df64d | BiniyamMelaku2/alx-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 446 | 3.53125 | 4 | #!/usr/bin/python3
"""
module for island grid perimeter
"""
def island_perimeter(grid):
''' defines island grid method '''
val = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
val += 2
if i > 0 and grid[i - 1][j] == 1:
val -= 1
if j > 0 and grid[i][j - 1] == 1:
val -= 1
return (val * 2)
|
ffc2cb368a442864a7a5e2b2c0b81fccbe8417bb | bvshyam/CUNY-repository | /602 - Python/Assignment 8 - Image Processing/practice/lessons/matplotlib/examples/plot_bar_ex.py | 718 | 4 | 4 | """
Bar plots
==========
An example of bar plots with matplotlib.
"""
import numpy as np
import matplotlib.pyplot as plt
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
fig = plt.figure()
ax = fig.add_axes([0.025, 0.025, 0.95, 0.95])
ax.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
ax.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
for x, y in zip(X, Y1):
ax.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
ax.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
ax.set_xlim(-.5, n)
ax.set_xticks(())
ax.set_ylim(-1.25, 1.25)
ax.set_yticks(())
plt.show()
|
624a83a4fa1395d933e21974247bb7778e105cac | joaocassianox7x/Apostila | /codigos/kuttaprimeiraordemedo.py | 721 | 3.53125 | 4 | y0=5 #valor inicial
t0=0 #ponto inicial
tf=10 #ponto final
n=10**5 #numero de pontos
dt=(tf-t0)/n
y=[]
y.append(y0)
def func(a,b): #a=y e b=t
return(-a+b)
for i in range(n):
t=i*dt #t
#print(t)
k1=func(y[i],t)
k2=func(y[i]+k1*dt/2,t)
k3=func(y[i]+k2*dt/2,t+dt/2)
k4=func(y[i]+k3*dt,t+dt)
y.append(y[i]+(dt/6)*(k1+k4+2*(k2+k3)))
import numpy as np
import matplotlib.pyplot as plt
t=np.linspace(t0,tf,n+1)
plt.plot(t,t-1+3.5*np.exp(-t),'r')
plt.plot(t,y,'b')
plt.legend(["Solução Analítica","Solução por RK4"],loc="upper left")
plt.grid(True)
plt.xlim(t0,tf)
plt.xlabel("t (s)")
plt.savefig("rk4primeiraordem.png") |
57fbd548bb3517b2ca7002a7b96c0fc13a4d7b0e | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/ParticleMan/b.py | 702 | 3.671875 | 4 | #!/usr/bin/env python
def printResult(case, result):
print "Case #{}: {}".format(case, result)
def flip(s, num):
return ''.join([other(x) for x in s[:num][::-1]]) + s[num:]
def other(c):
if c == '+':
return '-'
else:
return '+'
t = int(raw_input())
for i in xrange(1, t + 1):
state, = [s for s in raw_input().split(" ")]
if len(state) == 0:
printResult(i, 0)
c = other(state[0])
index = 0
flips = 0
while True:
index = state.find(c, index)
if index == -1:
break
state = flip(state, index)
flips += 1
c = other(c)
if state[0] == '-':
flips += 1
printResult(i, flips)
|
3db31c0fbad45f2d9132722d1189a156a8e506ad | viirii/CAS_project | /dp/merger.py | 875 | 3.578125 | 4 | import csv
# created by Christine Baek
# November 26, 2016
# merge 2 .csv files into single .csv in criss-cross format
semiglo = []
local = []
def readCSV(filename, destination) :
print(filename)
with open(filename, 'r') as csvfile :
filereader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in filereader :
destination.append(row)
print(destination[0])
def write(first, second) :
with open('merged.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for i in range(len(first)) :
filewriter.writerow(first[i])
filewriter.writerow(second[i]);
filewriter.writerow([]);
lfile = 'Cas_Local_Alignment.csv'
smfile = 'Cas_SemiGlobal_Alignment.csv'
readCSV(smfile, semiglo)
readCSV(lfile, local)
write(semiglo, local)
|
1b8c2a49b2f7968bf806ea5e18e57569af18327c | Etoakor/wuxing | /RedFlag.py | 1,578 | 3.828125 | 4 | import turtle
import time
turtle.setup(width=0.9, height=0.9)
# width, height,输入宽和高为整数时, 表示像素; 为小数时, 表示占据电脑屏幕的比例
turtle.bgcolor("red") # 画布背景颜色
turtle.fillcolor("yellow") # 绘制图形的填充颜色
turtle.color('yellow') # 绘制图形颜色
turtle.speed(10) # 绘制图形的速度
# 主星
turtle.begin_fill()# 准备开始填充图形
turtle.up()
turtle.goto(-600, 220) # 将画笔移动到坐标为-600, 220的位置
turtle.down()
for i in range(5):
turtle.forward(150) # 向当前画笔方向移动150像素长
turtle.right(144)# 顺时针移动 144°
turtle.end_fill() # 填充完成
time.sleep(1)
# 第1颗副星
turtle.begin_fill()
turtle.up()
turtle.goto(-400, 295)
turtle.setheading(305)
turtle.down()
for i in range(5):
turtle.forward(50)
turtle.left(144) # 逆时针移动 144°
turtle.end_fill()
time.sleep(1)
# 第2颗副星
turtle.begin_fill()
turtle.up()
turtle.goto(-350, 212)
turtle.setheading(30)
turtle.down()
for i in range(5):
turtle.forward(50)
turtle.right(144)
turtle.end_fill()
time.sleep(1)
# 第3颗副星
turtle.begin_fill()
turtle.up()
turtle.goto(-350, 145)
turtle.setheading(5)
turtle.down()
for i in range(5):
turtle.forward(50)
turtle.right(144)
turtle.end_fill()
time.sleep(1)
# 第4颗副星
turtle.begin_fill()
turtle.up()
turtle.goto(-400, 90)
turtle.setheading(300)
turtle.down()
for i in range(5):
turtle.forward(50)
turtle.left(144)
turtle.end_fill()
time.sleep(10) |
9b76298a0ee4ab2282a72232c8f12fc3fede1c9a | yesseli/Proyecto | /Buscaminas.py | 13,546 | 3.734375 | 4 | import tkinter, configparser, random, os, tkinter.messagebox, tkinter.simpledialog
#Importamos una la libreria de tkinter, analizador de configuracion, generador de variables random, un modulo os, un modulo caja de mensajes de Tkinter y un modulo de dialogos simples
window = tkinter.Tk()
#agregamos a la variable Window la funcion de tkinter
window.title("Buscaminas")
#Añadimos el titulo de la ventana
filas = 10
columnas = 10
minas = 10
#preparamos los valores de las variables filas, columnas y las minas
field = []
buttons = []
#Agregamos una lista de botones y campos
colores = ['#FFFFFF', '#0000FF', '#008200', '#FF0000', '#000084', '#840000', '#008284', '#840084', '#000000']
#una lista de colores
gameover = False
#Agregamos una variable bool para tomar un valor verdadero o falso
customsizes = []
#Agregamos una lista de perzonalizacion
def createMenu():
menubar = tkinter.Menu(window)
menusize = tkinter.Menu(window, tearoff=0)
menusize.add_command(label="Pequeño (10x10 with 10 mines)", command=lambda: setSize(10, 10, 10))
menusize.add_command(label="Mediano (20x20 with 40 mines)", command=lambda: setSize(20, 20, 40))
menusize.add_command(label="Grande (35x35 with 120 mines)", command=lambda: setSize(35, 35, 120))
menusize.add_command(label="Personalizado", command=setCustomSize)
menusize.add_separator()
for x in range(0, len(customsizes)):
menusize.add_command(label=str(customsizes[x][0])+"x"+str(customsizes[x][1])+" with "+str(customsizes[x][2])+" mines", command=lambda customsizes=customsizes: setSize(customsizes[x][0], customsizes[x][1], customsizes[x][2]))
menubar.add_cascade(label="Tamaño", menu=menusize)
menubar.add_command(label="Exit", command=lambda: window.destroy())
window.config(menu=menubar)
#DEFINIMOS UNA FUNCION LLAMADA MENU, AÑADIMOS LAS VARIBLES menubar y menusize PARA DECLARAR UNA FUNCION DE MENU Y MENUS FLOTANTES DENTRO DE ESTES
#USAMOS menusize.add_command PARA AÑADIR OPCIONES O MENUS PARA ESCOJER EL TAMAÑO DE LA VENTANA O TABLA DE JUEGO
#USAMOS UN for x in range PARA LA PERZONALIZACION DE TAMAÑOS DE LA OCION PERSONALIZADO
#USAMOS menubar.add SACAR UNA ETIQUETA LLAMADO TAMAÑO PARA DARNOS LAS OPCIONES DEL menusize
def setCustomSize():
global customsizes
r = tkinter.simpledialog.askinteger("Personalizar Tamaño", "Ingrese la cantidad de filas")
c = tkinter.simpledialog.askinteger("Personalizar Tamaño", "Ingrese la cantidad de columnas")
m = tkinter.simpledialog.askinteger("Personalizar Tamaño", "Ingrese la cantidad de minas")
while m > r*c:
m = tkinter.simpledialog.askinteger("Personalizar Tamaño", "El máximo de minas para esta dimensión es: " + str(r*c) + "\nIngrese la cantidad de minas")
customsizes.insert(0, (r,c,m))
customsizes = customsizes[0:5]
setSize(r,c,m)
createMenu()
#DEFINIMOS UNA FUNCION LLAMADA customSize , AGREGAMOS LA VARIABLE customsizes EN UNA FUNCION GLOBAL PARA QUE ESTA SE PUEDA ACCEDER DESDE CUALQUIER PARTE DEL PROGRAMA
#DEFINIMOS UNA LA VARIABLE (R) PARA LAS FILAS QUE QUIERA INGRESAR EL USUARIO
#DEFINIMOS UNA LA VARIABLE (C) PARA LAS COLUMNAS QUE QUIERA INGRESAR EL USUARIO
#DEFINIMOS UNA LA VARIABLE (M) PARA LAS MINAS QUE QUIERA INGRESAR EL USUARIO ESTO SIEMPRE CON LOS TERMINOS DE TKINTER DE DIALGOS SIMPRES DE NUESTRA LIBRERIA
#USAMOS UN BUCLE DE WHILE QUE DESCRIBE QUE SI LA CANTIDAD DE MINAS ES MAYOR QUE LA CANTIDAD DE FILAS * COLUMNAS
#NOS MOSTRARA UN DIALOGO DE RESTIRCCION DE COLUMNAS Y NOS PEDIRA INGRESAR DENUEVO UN NUMERO CORRECTO
#establecemos los tamaños para cada fila, columna o mina y las agregamos a una funcion global
def setSize(r,c,m):
global rows, cols, mines
rows = r
cols = c
mines = m
saveConfig()
restartGame()
#....................................................................................................
def saveConfig():
global rows, cols, mines
#Configuracion
config = configparser.SafeConfigParser()
config.add_section("game")
config.set("game", "rows", str(rows))
config.set("game", "cols", str(cols))
config.set("game", "mines", str(mines))
config.add_section("sizes")
config.set("sizes", "amount", str(min(5,len(customsizes))))
for x in range(0,min(5,len(customsizes))):
config.set("sizes", "row"+str(x), str(customsizes[x][0]))
config.set("sizes", "cols"+str(x), str(customsizes[x][1]))
config.set("sizes", "mines"+str(x), str(customsizes[x][2]))
with open("config.ini", "w") as file:
config.write(file)
#DEFINIMOS UNA FUNCION DE savaConfig, Usamos las variables globales rows, cols y mines PARA CONFIGURAR QUE AL MOMENTO DE ABRIR DENUEVO LA APLICACION NOS MUESTRE EL TAMAÑO ANTERIOR AL QUE HABIAMOS ELEJIDO
#PARA ESTO SE ES NECESARIO UTILIZAR EL MODUL DE CONFIGPANSER
def loadConfig():
global rows, cols, mines, customsizes
config = configparser.SafeConfigParser()
config.read("config.ini")
rows = config.getint("game", "rows")
cols = config.getint("game", "cols")
mines = config.getint("game", "mines")
amountofsizes = config.getint("sizes", "amount")
for x in range(0, amountofsizes):
customsizes.append((config.getint("sizes", "row"+str(x)), config.getint("sizes", "cols"+str(x)), config.getint("sizes", "mines"+str(x))))
#...................................................................................................................................
#DEFINIMOS UNA FUNCION LLAMADA loadconfig, PARA CARGAR LA CONFIGURACION GURDADA
#UTILIZAMOS for in range PARA CARGAR Y POSICIONAR LAS MINAS COLUMNAS Y FILAS Y DISTRIBUIR ESTAS POR TODA LA TABLA
def prepareGame():
global rows, cols, mines, field
field = []
for x in range(0, rows):
field.append([])
for y in range(0, cols):
# agregar botón y valor de inicio para el juego
field[x].append(0)
#generar minas
for _ in range(0, mines):
x = random.randint(0, rows-1)
y = random.randint(0, cols-1)
# Evitar que las minas se sobre pongan
while field[x][y] == -1:
x = random.randint(0, rows-1)
y = random.randint(0, cols-1)
field[x][y] = -1
if x != 0:
if y != 0:
if field[x-1][y-1] != -1:
field[x-1][y-1] = int(field[x-1][y-1]) + 1
if field[x-1][y] != -1:
field[x-1][y] = int(field[x-1][y]) + 1
if y != cols-1:
if field[x-1][y+1] != -1:
field[x-1][y+1] = int(field[x-1][y+1]) + 1
if y != 0:
if field[x][y-1] != -1:
field[x][y-1] = int(field[x][y-1]) + 1
if y != cols-1:
if field[x][y+1] != -1:
field[x][y+1] = int(field[x][y+1]) + 1
if x != rows-1:
if y != 0:
if field[x+1][y-1] != -1:
field[x+1][y-1] = int(field[x+1][y-1]) + 1
if field[x+1][y] != -1:
field[x+1][y] = int(field[x+1][y]) + 1
if y != cols-1:
if field[x+1][y+1] != -1:
field[x+1][y+1] = int(field[x+1][y+1]) + 1
#..................................................................................................
#DEFINIMOS UNA FUNCION DE PREPARACION DE JUEGO
#USAMOS EL CAMPO LLAMADO FIELD
#USAMOS fori x in range PARA LAS FILAS
#UTILIZAMOS field.append para agreagar un objeto a la lista
#USAMOS for y in range PARA DAR UN BOTON Y VALOR DE INICIO PARA EL JUEGO EN LAS COLUMNAS
#UTILIZAMOS for _ in range PARA ESTABLECER UN RANGO ENTRE LAS VARIABLES X / Y PARA COLOCAR LAS MINAS ENTRE ESTAS DE FORMA ALEATORA x = random.randint(0, rows-1) , y = random.randint(0, cols-1)
#UTILIZAMOS DENUEVO EL CAMPO DE field Y UN BUCLE DE WHILE PARA EVITAR QUE LAS MINAS PUESTAS ALEATOREAS NO SE SOBREPONGAN UNAS CON OTRAS PARA ELLO UTILIZAMOS LAS CONDICION DE IF
def prepareWindow():
global rows, cols, buttons
tkinter.Button(window, text="Reiniciar", command=restartGame).grid(row=0, column=0, columnspan=cols, sticky=tkinter.N+tkinter.W+tkinter.S+tkinter.E)
buttons = []
for x in range(0, rows):
buttons.append([])
for y in range(0, cols):
b = tkinter.Button(window, text=" ", width=2, command=lambda x=x,y=y: clickOn(x,y))
b.bind("<Button-3>", lambda e, x=x, y=y:onRightClick(x, y))
b.grid(row=x+1, column=y, sticky=tkinter.N+tkinter.W+tkinter.S+tkinter.E)
buttons[x].append(b)
#............................................................................................................
#ACA USAMOS UNA FUNCION PARA LA PREPARACION DE UN BOTON DE REINICIAR USANDO LA LIBRERIA DE TK QUE REINICIARA EL JUEGO DESDE 0 Y RECLOCANDO TANTO COMO FILAS COLUMNAS Y LAS MINAS
def restartGame():
global gameover
gameover = False
for x in window.winfo_children():
if type(x) != tkinter.Menu:
x.destroy()
prepareWindow()
prepareGame()
def onRightClick(x,y):
global buttons
if gameover:
return
if buttons[x][y]["text"] == "?":
buttons[x][y]["text"] = " "
buttons[x][y]["state"] = "normal"
elif buttons[x][y]["text"] == " " and buttons[x][y]["state"] == "normal":
buttons[x][y]["text"] = "?"
buttons[x][y]["state"] = "disabled"
#.......................................................................................................................
#DEFINIMOS UNA FUNCION para el click derecho en x & y USAMOS GLOBAL
#para la lista de BOTONES
#USAMOS if en el bool de gameover: USAMOS if en la lista de Buttons que al
#clickear alguna de las casillas se coloque un texto, si esta se vuelve a clickear
#quitara el texto y lo colocara normal, usamos else if para que al clickear en las
#casillas en blanco colocar el texto y desabilitar la casilla con el texto
def autoClickOn(x,y):
global field, buttons, colores, rows, cols
if buttons[x][y]["state"] == "disabled":
return
if field[x][y] != 0:
buttons[x][y]["text"] = str(field[x][y])
else:
buttons[x][y]["text"] = " "
buttons[x][y].config(disabledforeground=colores[field[x][y]])
buttons[x][y].config(relief=tkinter.SUNKEN)
buttons[x][y]['state'] = 'disabled'
if field[x][y] == 0:
if x != 0 and y != 0:
autoClickOn(x-1,y-1)
if x != 0:
autoClickOn(x-1,y)
if x != 0 and y != cols-1:
autoClickOn(x-1,y+1)
if y != 0:
autoClickOn(x,y-1)
if y != cols-1:
autoClickOn(x,y+1)
if x != rows-1 and y != 0:
autoClickOn(x+1,y-1)
if x != rows-1:
autoClickOn(x+1,y)
if x != rows-1 and y != cols-1:
autoClickOn(x+1,y+1)
def clickOn(x,y):
global field, buttons, colores, gameover, rows, cols
if gameover:
return
buttons[x][y]["text"] = str(field[x][y])
if field[x][y] == -1:
buttons[x][y]["text"] = "?"
buttons[x][y].config(background='green', disabledforeground='black')
gameover = True
tkinter.messagebox.showinfo("Game Over", "Has PERDIDO.")
#ahora mostramos todas las otras minas
for _x in range(0, rows):
for _y in range(cols):
if field[_x][_y] == -1:
buttons[_x][_y]["text"] = "?"
else:
buttons[x][y].config(disabledforeground=colores[field[x][y]])
if field[x][y] == 0:
buttons[x][y]["text"] = " "
#Repite todos los botones que están cerca.
autoClickOn(x,y)
buttons[x][y]['state'] = 'disabled'
buttons[x][y].config(relief=tkinter.SUNKEN)
checkWin()
#.........................................................................................................
#DEFINIMOS UNA FUNCION para los clicks USAMOS LAS VARIABLES
#GLOBALES, Agregamos una condicion de if field DONDE SI EL RESULTADO DE LAS VARIABLES X & Y SON IGUAL A -1 ESTA COLOCARA UN TEXTO LE DARA UN COLOR DE FONDO Y DE FUENTE
#SI EL BOOL DE gameover es verdadero NOS MOSTRARA UNA CAJA DE TEXTO CON IFNORMACION DE QUE EL JUEGO SE ACABO Y HEMOS PERDIDO
#APLICAMOS LA CONDICION DE if field DENUEVO PARA QUE CUANDO CLICKIEMOS UNA CASILLA CORRECTA Y LAS DEMAS ESTEN VACIAS O SU VALOR SEA 0 REPETIRA TODOS LOS BOTONES QUE ESTAN CERCA Y INABILITARA
def checkWin():
global buttons, field, rows, cols
win = True
for x in range(0, rows):
for y in range(0, cols):
if field[x][y] != -1 and buttons[x][y]["state"] == "normal":
win = False
if win:
tkinter.messagebox.showinfo("Gave Over", "HAS GANADO")
if os.path.exists("config.ini"):
loadConfig()
else:
saveConfig()
createMenu()
prepareWindow()
prepareGame()
window.mainloop()
#..........................................................................................................
#DEFINIMOS UNA FUNCION DE checkeo DE VICOTORIA
#USAMOS LAS VARIABLES Y LISTAS GLOBALES
#USAMOS LA VARIABLE WIN como verdadera
#USAMOS for in x / y range para DAR UNA CONDICION QUE AL MOMENTO DE QUE UN BOTON O UNA CASILLA TENGA EL VALOR DE UNA MINA NUESTRA VARIABLE WIN sea falsa
#AGREGAMOS LA CONDICION if win PARA Q CUANDO win sea verdadera NOS MUESTRE UNA CAJA DE TEXTO DE INFORMACION DE QUE EL JUEGO TERMINO Y HEMOS GANADO
#AGREGAMOS OTRA CONDICION DE os para CARGAR UNA CONFIGURACION O DE LO CONTRARIO SALVAR LA CONFIGURACION DE NUESTRO JUEGO
# CERRAMOS LAS FUNCIONES
|
18568cf39642a69a3335d4aaaacb0cc9163beaf4 | buaazyz/battery_detect | /preprocessing/Preprocessing.py | 524 | 3.6875 | 4 | import cv2
#统一输入尺寸
def Resize_Input(img,size = (1040,2000,3)):
"""
输入: 待转换的图片img,目标尺寸size,默认为1040*2000*3
输出:转换好后的图片img_new
"""
if img.shape<=size:
img_new = cv2.copyMakeBorder(img,0,size[0]-img.shape[0],0,size[1]-img.shape[1],cv2.BORDER_CONSTANT,value=[255,255,255])
else:
img_new = img[:size[0],:size[1],:]
#print(img_new.shape)
return img_new
img = Resize_Input( cv2.imread('small.png') )
print(img.shape) |
e9625d0791619322549c19bdfeb60a849eec1ea9 | bhavya20051/codacademy_course_part2 | /codacademy_2/python loops/games loop.py | 351 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 12 17:30:33 2020
@author: bhavy
"""
board_games = ['Settlers of Catan', 'Carcassone', 'Power Grid', 'Agricola', 'Scrabble']
sport_games = ['football', 'football - American', 'hockey', 'baseball', 'cricket']
for game in board_games:
print(game)
for game in sport_games:
print(game) |
b578ce2b8dbd0673d336d3e16e3eb5518b3a6090 | Hacker5preme/pwlist-algorithm | /code/user_inputs.py | 2,573 | 3.6875 | 4 | # Version 0.3
def pw_len_limit():
length_limit = input("PLEASE ENTER THE MAXIMUM LENGTH FOR THE PASSWORDS GETTING GENERATED | FOR NO LIMIT ENTER 0: ")
return length_limit
def user_inp_information():
print("*** INFORMATION SPIDER FOR GENERATING THE PASSWORD-LIST ***")
print("*** ENTER DATES IN THIS FORMAT DD/MM/YYYY ***")
x = 1
standard_info = {}
standard_info["First-Name"] = input("FIRST NAME OF THE TARGET: ")
standard_info["Second-Name"] = input("MIDDLE NAME OF THE TARGET: ")
standard_info["Surname"] = input("SURNAME OF THE TARGET: ")
info1 = int(input("NUMBER OF PETS OWNED BY THE TARGET: "))
while info1 > 0:
standard_info["Pet-" + str(x)] = input("NAME OF PET " + str(x) +": ")
x = x + 1
info1 = info1 - 1
standard_info["Place-of-birth"] = input("PLACE OF BIRTH: ")
standard_info["Birthday"] = input("DATE OF BIRTH: ")
standard_info["Loved"] = input("NAME OF WIFE/GIRLFRIEND | HUSBAND/BOYFRIEND | IF NOT EXISTENT ENTER: none ")
x = 1
if standard_info["Loved"] == "none":
pass
else:
standard_info["Loved-nickname"] = input("NICKNAME OF WIFE/GIRLFRIEND | HUSBAND/Boyfriend | IF NOT EXISTENT ENTER NONE: ")
standard_info["Loved-birthday"] = input("BIRTHDAY OF THE SIGNIFICANT OTHER: ")
info2 = int(input("NUMBER OF CHILDREN: "))
x = 1
while info2 > 0:
standard_info["chilren-name-" + str(x)] = input("NAME OF CHILD " + str(x) + ": ")
standard_info["children-nickname-" + str(x)] = input("NICKNAME OF CHILD " + str(x) + ": ")
standard_info["children-birthday-" + str(x)] = input("CHILD'S " + str(x) + " DATE OF BIRTH: ")
x = x + 1
info2 = info2 -1
standard_info["fav-number"] = input("FAVOURITE NUMBER | IF NOT EXISTENT ENTER: none ")
standard_info["gamertag/nickname"]=input("GAMERTAG OR NICKNAME | IF NOT EXISTENT ENTER: none ")
return standard_info
def user_inp_add_information():
q1 = input("ANY ADDITIONAL INFORMATION TO ADD: Y | N: ")
if q1 == "N":
addi_info = 0
if q1 == "Y":
addi_info = []
print("PLEASE ENTER DATES IN THE FORMAT: DD/MM/YYYY START WITH A HASHTAG #DD/MM/YYYY")
print("DO NOT USE ANY SPECIAL SIGNS EXCEPT THE # ")
print("TO STOP THE QUESTIONS ENTER none")
x = 1
while x != 0:
add = input("INFORMATION " + str(x) + ": ")
if add == "none":
x = 0
else:
addi_info.append(add)
x = x + 1
return addi_info
|
d7393b4ac08c0bfe6ad9205d488adb67501ef128 | iandavidson/SSUCS115 | /Lab11/Lab11c.py | 4,401 | 3.78125 | 4 | """
Program: CS 115 Lab 11c
Author: Ian Davidson
Description: This program will open a file and then search its contents
using linear and binary search.
"""
def readfile(filename):
"""
Reads the entire contents of a file into a single string using
the read() method.
Parameter: the name of the file to read (as a string)
Returns: the text in the file as a large, possibly multi-line, string
"""
infile = open(filename, "r") # open file for reading
# Use Python's file read function to read the file contents
filetext = infile.read().splitlines()
#print('Number of lines in file:', len(filetext))
infile.close() # close the file
return filetext # the text of the file, as a single string
def print_list(list_to_print):
for i in range(len(list_to_print)):
print(i , ":" , list_to_print[i])
def find_index_of_min(list, start):
'''
Finds the minimum value in the list and returns it's index, list can also start at an index and look beyond it
while looking for min.
'''
if len(list) < start:
return None
min_value = list[start]
min_idx = start
for i in range(start, len(list)):
if min_value > list[i]:
min_value = list[i]
min_idx = i
return min_idx
def selection_sort(L):
'''
Use the selection sort algorithm to sort a list.
Parameter: unsorted list
Sorts the original list that was passed to it -- doesn't return anything.
'''
swap_count = 0
for i in range(len(L)-1):
min_unsorted = find_index_of_min(L, i)
place = L[i]
L[i] = L[min_unsorted]
L[min_unsorted] = place
print('Swapped elements', i, "and", min_unsorted, "--", L[i], 'and', L[min_unsorted])
def merge(L, start_index, sublist_size):
"""
Merge two sublists of a list L
Parameters:
L - the list
start_index - the index of the first element to be merged
sublist_size - the size of the chunks to be merged
Left chunk: L[start_index] to L[start_index + sublist_size - 1]
Right chunk: L[start_index + sublist_size] to L[start_index + 2 * sublist_size - 1]
"""
index_left = start_index
left_stop_index = start_index + sublist_size
index_right = start_index + sublist_size
right_stop_index = min(start_index + 2 * sublist_size,
len(L))
print('Merging sublists:', L[index_left:left_stop_index], 'and',
L[index_right:right_stop_index]);
L_tmp = []
while (index_left < left_stop_index and
index_right < right_stop_index):
if L[index_left] < L[index_right]:
L_tmp.append(L[index_left])
index_left += 1
else:
L_tmp.append(L[index_right])
index_right += 1
if index_left < left_stop_index:
L_tmp.extend(L[index_left : left_stop_index])
if index_right < right_stop_index:
L_tmp.extend(L[index_right : right_stop_index])
L[start_index : right_stop_index] = L_tmp
print('Merged sublist:', L_tmp, '\n')
def merge_sort(L):
"""
Sort a list L using the merge sort algorithm.
(Starter code doesn't fully sort the list.)
"""
chunksize = 1 # Start by dividing the list into N sub-lists of 1 element each
while chunksize < len(L):
print("\n*** Sorting sublists of size", chunksize)
# Divide the list into pairs of chunks
left_start_index = 0 # Start of left chunk in each pair
# While we still have chunks to merge
while left_start_index + chunksize < len(L):
merge(L, left_start_index, chunksize)
# Move to next pair of chunks
left_start_index += 2 * chunksize
print('List is now', L)
chunksize = chunksize * 2
def main():
""" Read and print a file's contents. """
user_choice = input('Name of input file: ')
read_file = readfile(user_choice)
user = input("Type S for selection sort and M for merge sort: ")
print("The original list of cities is: ")
print_list(read_file)
print()
user = user.lower()
if user == 's':
print("The new list of cities is: ")
selection_sort(read_file)
print_list(read_file)
if user == 'm':
print("The new list of cities is: ")
merge_sort(read_file)
print_list(read_file)
main() |
868a678621c004fbb01670290e32c3c4b2b2fef8 | kesappagarimohan/python-practice | /factorial.py | 126 | 3.546875 | 4 | def fact(number):
result=1
for i in range(1,number+1):
result=result*i
return result
print(fact(5))
|
2d4633eb90ffab4efdaa84a8490944ca843e7b45 | michal-franc/CodingKatas | /interview-cake/product-of-other-numbers.py | 572 | 4 | 4 | def product_of_other_numbers(list_of_ints):
product_values = [0] * len(list_of_ints)
# calculate product for before i
product_so_far = 1
for i, integer in enumerate(list_of_ints):
product_values[i] = product_so_far
product_so_far *= integer
product_so_far = 1
# calculate product for after i
for i in xrange(len(list_of_ints) - 1, -1, -1):
product_values[i] *= product_so_far
product_so_far *= list_of_ints[i]
return product_values
test_data = [1, 7, 3, 4]
print(product_of_other_numbers(test_data))
|
aaad245345f605b320981baf74fac7c16f181770 | bassemhussein-code/4--Programming-Foundations-Algorithms | /sexth.py | 2,206 | 3.8125 | 4 | import sys
A = [-10, -3, 5, 6]
# def findMaximumProduct(A):
# max_i, max_j = 0, 0
# max_product = -sys.maxsize
# for i in range(len(A)-1):
# for j in range(i+1, len(A)):
# if max_product < A[i] * A[j]:
# max_product = A[i]*A[j]
# (max_i, max_j) = (i, j)
# print('The Pair is ', (A[max_i], A[max_j]))
# def findMaximumProduct(A):
# n = len(A)
# A.sort()
# if (A[0]*A[1]) > (A[n-1]*A[n-2]):
# print('The Pair is ', (A[0], A[1]))
# else:
# print('The Pair is ', (A[n-1], A[n-2]))
# Function to find the maximum product of two integers in a list
def findMaximumProduct(A):
# to store the maximum and second maximum element in a list
max1 = A[0]
max2 = -sys.maxsize
# to store the minimum and second minimum element in a list
min1 = A[0]
min2 = sys.maxsize
for i in range(1, len(A)):
# if the current element is more than the maximum element,
# update the maximum and second maximum element
if A[i] > max1:
max2 = max1
max1 = A[i]
# if the current element is less than the maximum but greater than the
# second maximum element, update the second maximum element
elif A[i] > max2:
max2 = A[i]
# if the current element is more than the minimum element,
# update the minimum and the second minimum
if A[i] < min1:
min2 = min1
min1 = A[i]
# if the current element is less than the minimum but greater than the
# second minimum element, update the second minimum element
elif A[i] < min2:
min2 = A[i]
# otherwise, ignore the element
# choose the maximum of the following:
# 1. Product of the maximum and second maximum element or
# 2. Product of the minimum and second minimum element
if max1 * max2 > min1 * min2:
print("Pair is", (max1, max2))
else:
print("Pair is", (min1, min2))
if __name__ == '__main__':
A = [-10, -3, 5, 6, -2]
findMaximumProduct(A)
|
0f1c366219a8a9ea6ac41db86b74e795ff37c473 | abhishm/cs61a | /set_using_linked_list.py | 4,384 | 3.796875 | 4 | class Link(object):
empty = ()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __repr__(self):
if self.rest:
return "Link({0}, {1})".format(self.first, repr(self.rest))
else:
return "Link({0})".format(self.first)
def __len__(self):
return 1 + len(self.rest)
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i - 1]
@property
def second(self):
return self.rest.first
@second.setter
def second(self, value):
self.rest.first = value
def extend_link(link_1, link_2):
"""
Combine LINK_1 and LINK_2 to a new Linked List
>>> l1 = Link(1, Link(2))
>>> l2 = Link(3, Link(4, Link(5, Link(6))))
>>> extend_link(l1, l2)
Link(1, Link(2, Link(3, Link(4, Link(5, Link(6))))))
"""
if link_1 is Link.empty:
return link_2
else:
return Link(link_1.first, extend_link(link_1.rest, link_2))
def filter_link(f, link):
"""Return a link list for which F is true for all its elements
>>> l1 = Link(1, Link(2, Link(3)))
>>> odd = lambda x: x % 2
>>> filter_link(odd, l1)
Link(1, Link(3))
"""
if link is Link.empty:
return link
else:
if f(link.first):
return Link(link.first, filter_link(f, link.rest))
else:
return filter_link(f, link.rest)
# Sets as unsorted sequences
def empty(s):
return s is Link.empty
def contains(s, v):
""" Return true is set S contains value V
>>> s = Link(1, Link(2, Link(3)))
>>> contains(s, 3)
True
>>> contains(s, 4)
False
"""
if empty(s):
return False
if s.first == v:
return True
else:
return contains(s.rest, v)
def adjoin(s, v):
""" Return a set containing all elements of s and element v
>>> s = Link(1, Link(2, Link(3)))
>>> adjoin(s, 1)
Link(1, Link(2, Link(3)))
>>> adjoin(s, 4)
Link(1, Link(2, Link(3, Link(4))))
"""
if empty(s):
return Link(v)
elif s.first == v:
return s
else:
return Link(s.first, adjoin(s.rest, v))
def intersect(set1, set2):
""" Return the intersections of two sets
>>> s1 = Link(1, Link(2, Link(3)))
>>> s2 = Link(3, Link(4))
>>> s3 = Link(5)
>>> intersect(s1, s2)
Link(3)
>>> intersect(s1, s3)
()
"""
if empty(set1) or empty(set2):
return Link.empty
elif contains(set2, set1.first):
return Link(set1.first, intersect(set1.rest, set2))
else:
return intersect(set1.rest, set2)
def union(set1, set2):
""" Return the union of two sets
>>> s1 = Link(1, Link(2, Link(3)))
>>> s2 = Link(3, Link(4))
>>> s3 = Link(5)
>>> union(s1, s2)
Link(1, Link(2, Link(3, Link(4))))
>>> union(s1, s3)
Link(1, Link(2, Link(3, Link(5))))
"""
if empty(set1):
return set2
elif empty(set2):
return set1
elif contains(set2, set1.first):
return union(set1.rest, set2)
else:
return Link(set1.first, union(set1.rest, set2))
# Return set as a ordered sequence
def contains2(s, v):
"""Return true is S contains v
>>> s = Link(1, Link(2, Link(3)))
>>> contains2(s, 1)
True
>>> contains2(s, 1.5)
False
"""
if empty(s):
return False
elif s.first == v:
return True
elif s.first > v:
return False
else:
return contains2(s.rest, v)
def adjoin2(s, v):
""" Return a new set containing all values of set s and v
>>> s = Link(1, Link(2, Link(3)))
>>> adjoin2(s, 1.5)
Link(1, Link(1.5, Link(2, Link(3))))
"""
if empty(s):
return Link(v)
elif s.first == v:
return s
elif s.first > v:
return Link(v, s)
else:
return Link(s.first, adjoin2(s.rest, v))
def add(s, v):
""" Add v to s and return s
>>> s = Link(1, Link(2))
>>> add(s, 3)
Link(1, Link(2, Link(3)))
>>> add(s, 4)
Link(1, Link(2, Link(3, Link(4))))
"""
assert not empty(s), "Cannot add to an empty set"
if s.first == v:
return s
elif s.first > v:
s.rest = adjoin2(s, s.first)
s.first = v
return s
else:
s.rest = adjoin2(s.rest, v)
return s
|
17273c0faa852864473992b92ac49c8ffacb1d30 | pedrom505/AlbionAnalytics | /Errors.py | 1,156 | 3.546875 | 4 | import logging
class ApplicationError(Exception):
"""
Generic exception class used by every exceptions implemented
"""
def __init__(self, *args):
self.logger = logging.getLogger(__name__)
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
error_message = self.__class__.__name__
if self.message:
error_message += f": {self.message}"
self.logger.error(error_message)
return error_message
class InvalidParameter(ApplicationError):
"""
The InvalidParameter exception is raised when a a invalid parameter is passed to the function
"""
class FileNotFounded(ApplicationError):
"""
The InvalidParameter exception is raised when a a invalid parameter is passed to the function
"""
class InternalError(ApplicationError):
"""
The InternalError exception is raised when a operation error occurs in the application
"""
class ConnectionFailure(ApplicationError):
"""
The ConnectionError exception is raised when a occurs a failure to connect with the specified server
""" |
06f183868101c135652436fc4686c3a82c4de01c | Boot-Camp-Coding-Test/Programmers | /day12/problem4/[노태윤](재도전 성공!)문자열 내 마음대로 정렬하기.py | 2,252 | 3.546875 | 4 | # 테스트 5~7 / 11~12 실패
def sorting(sorted_list,starting_index,ending_index) :
sorted_list[starting_index:ending_index+1] = sorted(sorted_list[starting_index:ending_index+1])
return sorted_list
def solution(strings, n):
answer = []
sorted_list = sorted(strings,key=lambda x : x[n])
starting_index = 0
ending_index = 0
for i in range(1,len(sorted_list)) :
if sorted_list[i][n] == sorted_list[i-1][n] :
ending_index+=1
else :
if ending_index - starting_index == 0 :
starting_index = i
ending_index = i
continue
sorted_list = sorting(sorted_list,starting_index,ending_index)
starting_index = i
ending_index = i
return sorted_list
# ===========================================================================================================
# 재도전
def solution(strings, n):
ordered_strings = sorted(strings) # 전체적인 sorting
answer = sorted(ordered_strings,key=lambda x : x[n]) # 인덱스 별 sorting
return answer
# Key points
# sorted 함수 정렬 과정
# 왼쪽부터 진행
# Ex)
# strings =['sun','bed','car','run','gun','bar','bun']
# sorted(strings,key=lambda x : x[1]) ==> ['car', 'bar', 'bed', 'sun', 'run', 'gun', 'bun']
# 왼쪽부터 1번 index 를 기준으로 오름차순으로 정렬
# 가장 먼저 'a' 가 포함된 'car' --> 'bar'
# 그 다음 'e' 가 포함된 'bed'
# 그 다음 'u' 가 포함된 (왼쪽부터 차례대로 찾기) 'sun' --> 'run' --> 'gun' --> 'bun'
# 이렇게 되버리면 'car', 'bar' 순서가 맞지 않음 (문제 요구 사항 : index 값에 같은 문자면 사전순으로 정렬)
# 뒤에 'sun' , 'run' , 'gun' , 'bun' 도 순서가 맞지 않음
# 처음부터 사전순으로 정렬하면 해결됨
# ordered_strings = sorted(strings) ==> ['bar', 'bed', 'bun', 'car', 'gun', 'run', 'sun']
# sorted(ordered_strings,key=lambda x : x[n]) ==> ['bar', 'car', 'bed', 'bun', 'gun', 'run', 'sun']
# 왼쪽부터 오른쪽으로 순차적으로 검색 후 정렬한다! (key=lambda 쓸때만 그런거 같다)
|
032dfecb448992d92146a9878a72c0e822ff4c84 | Bytamine/ff-olymp | /14 primality test/4.py | 306 | 4.03125 | 4 | #!/usr/bin/env python3
def isPrime(n: int) -> bool:
d = 2
while d * d <= n and n % d != 0:
d += 1
return d * d > n
k = int(input())
if k == 1:
print(2)
else:
count = 1
i = 1
while count != k:
i += 2
if isPrime(i):
count += 1
print(i) |
86fd8bd90a7461362881a18fa1ae7eb8120e8d12 | pedrogomez2019upb/Taller_PracticaProgramacion | /44.py | 496 | 3.921875 | 4 | #Escribe un algoritmo que, dados dos números, verifique si ambos están entre 0 y 5 o retorne false sino es cierto. Por ejemplo 1 y 2 ---> true ; 1 y 8 ---> false
#Primero hay que recibir los valores a analizar
a=int(input("Bienvenido! Por favor ingresa el primer número: "))
b=int(input("Por favor ingresa el segundo valor: "))
#Ponemos condicionales para analizar los valores
if (a<5 and a>0)and(b<5 and b>0):
print("True")
else:
print("False")
#Desarrollado por Pedro Gómez / ID:000396221 |
eb2685d163ef8c8bb59e93063cac5c77a4d55625 | minorl/hackcu | /mlprototype/coroutinetest.py | 339 | 3.515625 | 4 | def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
cr.next()
return cr
return start
@coroutine
def f():
i = 0
yield None
while True:
print "Iterating"
yield i
print "In between"
j = (yield)
print "Got: " + str(j)
i += 1
|
42554afaeffd721b8407f102ddf02644db051259 | gdh756462786/Leetcode_by_python | /BinaryTree/Arranging Coins.py | 1,092 | 4.09375 | 4 | # coding: utf-8
'''
You have a total of n coins that you want to form
in a staircase shape,
where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows
that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form the following rows:
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3.
'''
import math
class Solution2(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(2 * n + 0.25) - 0.5)
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
l, r = 0, n
while l <= r:
m = (l + r) / 2
if m*(m+1)/2 > n:
r = m - 1
else:
l = m + 1
return r
solution = Solution()
print solution.arrangeCoins(5) |
eaeda89fb3847229fc49a71c4f554a83def50c12 | carlos-echeverria/RobotTuples | /generateGroupsSwap.py | 2,443 | 4.15625 | 4 | #!/usr/bin/env python3
# Script that generates 2 groups, each consisting of 24 robot 3-tuples.
# The first group is generated by populating it with random elements from the
# list of all possible combinations of 18 robots in 3-tuples. The second set is
# generated by choosing two random tuples from the first set and swapping its
# elements until two new valid tuples are generated. After a certain number of
# steps we obtain a group which is different enough from the first one.
import robotTuples as rT
import matplotlib.pyplot as plt
from random import seed
from collections import Counter
n = 18 # number of robots
k = 3 # tuple size
groupSize = 24 # number of tuples per group
# creates list of robots:
robots = list(range(1,n+1))
# generates all the possible tuples with the above given parameters:
totalTuples = rT.possibleTuples(robots,k)
totalCombis = len(totalTuples) # number of available tuples to choose from
print(f"\nWith {n} robots, there are {totalCombis} posible combinations of {k}-tuples.\n\nWe will construct {2} groups of {k}-tuples, each consisting of {groupSize} elements.\n\nEvery robot should appear {4} times in both groups.")
# generates first group by taking random tuples from list of all possible ones:
Group1 = rT.generateGroup(totalTuples, groupSize)
#
CurrentGroup = set(Group1)
print(f"Is the first solution a complete group?: {rT.isGroupComplete(CurrentGroup, n, 4)}")
shuffleTimes = 100
for itr in range(shuffleTimes):
if (itr%10==0):
print(f'--{itr}--')
CurrentGroup = rT.shufflePairOfElements(CurrentGroup, totalTuples)
###print('----')
if itr == shuffleTimes-1:
#print(f"There were {cntr} shuffles made.")
print(f"The next found solution is:\n {sorted(CurrentGroup)}.")
print(f"Is the next found solution a complete group?: {rT.isGroupComplete(CurrentGroup, n, 4)}")
Total = Group1
for x in CurrentGroup:
Total.append(x)
count = Counter(Total)
print(f"We have seen {len(count)} tuples from the possible {totalCombis}")
# x axis: one point per key in the Counter (=unique tuple)
x=range(len(count))
# y axis: count for each tuple, sorted by tuple value
y=[count[key] for key in sorted(count)]
# labels for x axis: tuple as strings
xlabels=[str(t) for t in sorted(count)]
# plot
plt.bar(x,y,width=0.6)
# set the labels at the middle of the bars
plt.xticks([x+0.5 for x in x],xlabels, rotation = 'vertical')
# show plot
plt.show()
|
b04d75103e187087eee02b2bc897d741ac5fea9d | wolfecameron/structural_RNN | /vis_structs.py | 5,205 | 4.28125 | 4 | """Creates visualizations of structures created by the circle RNN
using matplotlib"""
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
def vis_spring(all_pts):
"""takes in a list of tuples containing r and theta
values and creates a polar plot of these coordinates
with matplotlib
"""
# create a polar matplotlib axis
axis = plt.subplot(111, projection="polar")
# set title and graph the points
plt.title("Polar Graph of Torsional Spring")
plt.plot([np.pi*(t[1] % 2.0) for t in all_pts], [t[0] for t in all_pts])
plt.show()
def vis_spring_with_thickness(all_pts):
"""takes in a list of tuples containing r, theta, and thickness
and uses matplotlib to create a polar graph of the torsional
spring including the thicknesses at each point
"""
# create polar axis for matplotlib
axis = plt.subplot(111, projection='polar')
# title the plot
plt.title("Polar Graph of Torsional Spring")
# go through each pair of adjacent points and add that
# line for the two points into the graph
for prev, nxt in zip(all_pts[:], all_pts[1:]):
thetas = [np.pi*(prev[1] % 2.0), np.pi*(nxt[1] % 2.0)]
radius = [prev[0], nxt[0]]
plt.plot(thetas, radius, linewidth=2.0, color='black')
# show the plot after all lines are added
plt.show()
def vis_cartesian_output(all_pts):
"""creates a visualization of an RNNs outputs in the cartesian
space - these outputs are used to create the geometry for the
tooth of a gear"""
# create an axis to plot on
axis = plt.subplot(111)
# title the graph
plt.title("Graph of Gear Tooth Geometry")
# set equal limits of the axis
plt.xlim(-.5, .5)
plt.ylim(0.0, 1.0)
# go through each pair of points in the geometry and graph them one by one
for prev, nxt in zip(all_pts[:], all_pts[1:]):
x_vals = [prev[0], nxt[0]]
y_vals = [prev[1], nxt[1]]
plt.plot(x_vals, y_vals, linewidth=2.0, color='black')
plt.show()
def vis_gear_mechanism(outputs, pos_thresholds):
"""takes all values from gear mechanism output of rnn and uses them
to generate a visualization of the gear system with matplotlib, the
pitch diameter of the gears is graphed
each element of outputs is of form (radius, gear_pos, stop)
pos_thresholds contains the two threshold values to interpret value of gear_pos
if lower than two values, it is to left, if in middle it is attached to back, and
if greater it is to right of the previous gear
"""
# create matplotlib axis to plot circles on
fig, ax = plt.subplots()
# instantiate variables to be used in plotting
position = (0, 0)
radius = outputs[0][0]
circles = []
all_pos = [0] # keep this so you know the maximum location
# create circle object for first gear and add into list
circles.append(plt.Circle(position, radius, alpha=.4))
# go through all other outputs to create each gear
for out_ind in range(1, len(outputs)):
radius = outputs[out_ind][0]
# direction dictates if gear placed to left, right, or attached to back
# determined by gear_pos value in relation to position thresholds
direction = 1
if(outputs[out_ind][1] < pos_thresholds[0]):
direction = -1
elif(outputs[out_ind][1] >= pos_thresholds[0] and outputs[out_ind][1] <= pos_thresholds[1]):
direction = 0
# add up radius of current and previous gear to find change in x location for them to mesh
pos_delta = outputs[out_ind][0] + outputs[out_ind - 1][0]
position = (position[0] + direction*pos_delta, 0)
all_pos.append(position[0])
# create and append circle object for current gear
circles.append(plt.Circle(position, radius, alpha=.4))
# plot all the circles on the matplotlib axis
for c in circles:
ax.add_artist(c)
# set max/default window size of matplotlib
x_max = max(all_pos)
x_min = min(all_pos)
all_rad = [x[0] for x in outputs]
max_rad = 1.25*max(all_rad) # scale max radius up slightly so window not too tight
ax.set_ylim((-max_rad, max_rad))
ax.set_xlim((x_min - max_rad, x_max + max_rad))
plt.show()
def vis_gears_nonlinear(mechanism, c_dict):
"""takes in a list gear objects and outputs a matplotlib visualization
of the gear system - where the gears may be placed at angles instead of
always in a straight line"""
# create matplotlib axis for the visualization
fig, ax = plt.subplots()
# create a circle object for each gear
circles = []
for gear in mechanism:
#print(gear)
circles.append(plt.Circle((gear.pos[0], gear.pos[1]), gear.radius, \
alpha=.25, color=c_dict[gear.pos[2]]))
# plot all circles onto the matplotlib axis
for c in circles:
ax.add_artist(c)
# find bounds for creating the window of the visualization
padding = 5.0
max_radius = max([x.radius for x in mechanism])
max_x = max([abs(x.pos[0]) for x in mechanism])
x_lim = (max_radius + max_x) # scale up a bit to give extra space
y_lim_lower = (mechanism[0].radius - max_radius) - padding
y_lim_upper = (mechanism[0].radius + max_radius) + padding
ax.set_xlim((-padding, x_lim + padding))
ax.set_ylim((y_lim_lower, y_lim_upper))
plt.show()
if __name__ == '__main__':
"""main loop used for simple testing"""
output = [((0,0), 1.0), ((5, 2), 3.0), ((-5, -2), 1.5)]
vis_gears_nonlinear(output)
|
074e633c2b8d07b14286880121d723cd871f434b | JGproyectos/Laboratorios-de-Algoritmos-2 | /Algoritmos II/ProyectoII.py | 11,071 | 3.5625 | 4 | """
Nombres: Gaspar Hermán Sandoval, Jesús Marcano carnets:13-10637, 12-10359
Descripción: Proyecto II
paja
El misterio del robo de DACE
"""
# Importando algunos modulos
import sys
import random
# Definiendo algunas funciones
def borrar_espacios(x): # Funcion que carga una lista en un arreglo y quita el "\n"
y = [] # lista vacia donde se almacenará todo
# Se carga un archivo de texto que contenga la información necesaria de los productos
with open(x,'r') as f:
datos = f.readlines() # Almacenamos todos los datos del archivo aquí
for line in datos: # Colocamos cada línea del archivo dentro del arreglo
y.append(line)
# Eliminamos el "\n" de cada elemento del arreglo
for i in range(len(y)):
y[i] = y[i].replace("\n","")
if y[i].isnumeric(): # En caso de tener un número tratado como texto se convierte en un número
y[i] = int(y[i])
# Invariante
assert(all(y[i] == y[i].replace("\n","")) for i in range(len(y)))
return y
def CrearTabla(n): # Crea una tabla vacía de tamaño 2n
tabla = [None] * 2 * n
return tabla
def FuncionHash1(a,k,b,p,n): # Función para calcular posiciones de una tabla de hash
habk = (a * k) + b # a,b son números aleatorios < p y k es la clave a guardar
habk = habk % p # p es un número primo > n a
habk = habk % n # n es el tamaño del arreglo
# Postcondicion
assert(habk <= n) # El número calculado debe estar dentro de la tabla
return habk
def FuncionHash2(k,n):
return k % n
def ASCII(palabra):
temporal = 0 # Aquí se guardara el ASCII del numero
for i in range(len(palabra)):
contadorASCII = ord(palabra[i])
temporal = temporal + contadorASCII
temporal = temporal // len(palabra)
return temporal
class Persona():
def __init__(self,nombre,documento):
self.nombre = nombre
self.documento = [documento]
self.ASCII = 0 # Se guarda el ASCII aquí
self.clave1 = 0 # Aquí se guardara una funcion de hash con su valor
self.clave2 = 0 # Aquí se guardará otra función de hash
self.size = 0 # Aquí se guarda el tamaño del arreglo
def agregar(self,elemento):
if self.size < 20:
self.documento.append(elemento) # Agregamos el elemento aquí
self.size = self.size + 1 # Sumamos 1 a la cantidad de elementos que hay
else:
print("ERROR: memoria llena ")
class Tabla():
def __init__(self,n):
self.tabla = CrearTabla(n) # Creamos la tabla
self.size = n # Sacamos su tamaño (util para las funciones de hash)
self.primo = 123455681 # Número primo lo suficientemente grande
self.a = random.randrange(1,self.primo) # Se crea para la funcion de hash y se elige justo al crear la tabla
self.b = random.randrange(0,self.primo) # Igual que a y no cambia nunca
self.personas = [] # Lista donde se almacenan las personas
def buscar(self,nombre):
myAscii = ASCII(nombre)
posicion1 = FuncionHash1(self.a,myAscii,self.b,self.primo,self.size)
posicion2 = FuncionHash2(myAscii,self.size)
return ((self.tabla[posicion1] is not None) and (self.tabla[posicion1].nombre == nombre)) or \
((self.tabla[posicion2] is not None) and (self.tabla[posicion2].nombre == nombre))
def redimensionar(self):
"""
Esta función se llama sólo cuando es necesario cambiar el tamaño de la tabla actual
además de que tendrá que volver a calcular varios de sus atributos y volver a colocar
los mismos elementos que ya estaban en la tabla, en esta nueva tabla. Pero eso se hizo
en base a una función de hash que dependía de las dimensiones de la tabla vieja.
Se recomienda crear una tabla el doble de grande que antes.
"""
self.tabla = CrearTabla(2 * self.size) # Nueva tabla de tamaño doble al anterior
self.size = len(self.tabla)
for i in range(len(self.personas)):
self.insertar(self.personas[i]) # Se pasa un False para ahorrar calculos, las llamadas recursivas pasan False
def insertar(self,persona): # Persona es un objeto
if not self.buscar(persona.nombre): # Condicion para agregar a la lista sólo una vez
self.personas.append(persona) # Agregamos aquí la persona
contador = 0 # Como se transforma en un ASCII se guarda aquí
for i in range(len(persona.nombre)):
temporal = ord(persona.nombre[i]) # Se saca el ASCII de cada letra
contador = contador + temporal # Se almacena aquí
contador = contador // len(persona.nombre) # Sacamos la division
persona.ASCII = contador # Se guarda aquí
posicion1 = FuncionHash1(self.a,persona.ASCII,self.b,self.primo,self.size)
posicion2 = FuncionHash2(persona.ASCII,self.size)
persona.clave1 = posicion1 # Se guarda aquí este valor de la función de Hash
persona.clave2 = posicion2 # Se guarda aquí otro valor de la función de Hash
for i in range(self.size): # Inserción del cuco
if self.tabla[posicion1] is None: # Si la posición está vacía lo insertamos
self.tabla[posicion1] = persona
condicion = False # Esta condicion se usa en caso de tener que redimensionar
return True # Salimos del bucle
else: # En caso de que la posición principal donde se quiera insertar esté vacío
condicion = True # Si se está aquí al terminar de iterar, habrá que redimensionar
persona, self.tabla[posicion1] = self.tabla[posicion1],persona # Intercambiamos
if posicion1 == persona.clave1:
posicion1 = persona.clave2
else:
posicion1 = persona.clave1
if condicion: # Entonces hay que redimensionar la tabla
self.redimensionar()
self.insertar(persona) # En llamadas recursivas se pasa un False de argumento para ahorrar calculos
return True
else:
return False
"""
documento = Tabla(4)
print(documento.tabla)
arreglo = [["Gaspar","hola"],["Jose",5],["María",True],["María iguana",[1,2,3,4]]]
for i in range(len(arreglo)):
arreglo[i] = Persona(arreglo[i][0],arreglo[i][1])
for i in range(len(arreglo)):
documento.insertar(arreglo[i],True)
#print(documento.personas)
for i in range(len(documento.tabla)):
if documento.tabla[i] is not None:
print(documento.tabla[i].nombre,"\n",documento.tabla[i].clave1)
print(documento.tabla[i].clave2)
print("\n")
for i in range(len(documento.tabla)):
if documento.tabla[i] is not None:
print(documento.tabla[i].nombre,end = ",")
else:
print(None,end = ",")
print("\n")
"""
# Lectura de datos
prueba = borrar_espacios("entrada1.txt")
# Separamos en los elementos
for i in range(1,len(prueba)): # No se inicia en 0 ya que ese sólo es el número de pistas
prueba[i] = prueba[i].split()
# Creamos las tablas
documentos = Tabla(len(prueba))
pagos = Tabla(len(prueba))
pistas = ""
# Se procede a la inserción de los elementos en sus respectivas tablas de hash
for i in range(1,len(prueba)): # Se empieza en 1 ya que el 0 es sólo un entero
if prueba[i][0] == "doc":
elASCII = ASCII(prueba[i][1]) # Se convierte en su elemento de la tabla
otro2 = FuncionHash1(documentos.a,elASCII,documentos.b,documentos.primo,documentos.size)
otro3 = FuncionHash2(elASCII,documentos.size)
if documentos.tabla[otro2] != None: # En caso de que la tabla no está vacía
if documentos.tabla[otro2].nombre == prueba[i][1]: # En caso de que esté en la primera posición de Hash
documentos.tabla[otro2].agregar(prueba[i][2])
for j in range(len(documentos.personas)): # En este caso hay que agregar a esta lista
if documentos.personas[j].nombre == prueba[i][1]:
documentos.personas[j].agregar(prueba[i][2])
break
if documentos.tabla[otro3] != None:
if documentos.tabla[otro3].nombre == prueba[i][1]: # En caso de que no esté en la primera posicion y si en la segunda
documentos.tabla[otro3].agregar(prueba[i][2])
for j in range(len(documentos.personas)): # En este caso hay que agregar a esta lista
if documentos.personas[j].nombre == prueba[i][1]:
documentos.personas[j].agregar(prueba[i][2])
break
else: # En caso de que no lo haya encontrado
temporal = Persona(prueba[i][1],prueba[i][2]) # Lo convertimos en el objeto a agregar
documentos.insertar(temporal)
elif prueba[i][0] == "pag":
elASCII = ASCII(prueba[i][1]) # Se convierte en su elemento de la tabla
otro2 = FuncionHash1(pagos.a,elASCII,pagos.b,pagos.primo,pagos.size)
otro3 = FuncionHash2(elASCII,pagos.size)
if pagos.tabla[otro2] != None:
if pagos.tabla[otro2].nombre == prueba[i][1]: # En caso de que esté en la primera posición de Hash
pagos.tabla[otro2].agregar(prueba[i][2])
for j in range(len(pagos.personas)): # En este caso hay que agregar a esta lista
if pagos.personas[j].nombre == prueba[i][1]:
pagos.personas[j].agregar(prueba[i][2])
break
if pagos.tabla[otro3] != None:
if pagos.tabla[otro3].nombre == prueba[i][1]: # En caso de que no esté en la primera posicion y si en la segunda
pagos.tabla[otro3].agregar(prueba[i][2])
for j in range(len(pagos.personas)): # En este caso hay que agregar a esta lista
if pagos.personas[j].nombre == prueba[i][1]:
pagos.personas[j].agregar(prueba[i][2])
break
else: # En caso de que no lo haya encontrado
temporal = Persona(prueba[i][1],prueba[i][2]) # Lo convertimos en el objeto a agregar
pagos.insertar(temporal)
else:
pistas = pistas + prueba[i][2]
print(pistas)
print(documentos.size)
for i in range(len(documentos.tabla)):
if documentos.tabla[i] is not None:
print(documentos.tabla[i].nombre,"\n",documentos.tabla[i].clave1)
print(documentos.tabla[i].clave2)
print("\n")
print(documentos.a," a")
print(documentos.b," b")
print("\n")
for i in range(len(documentos.tabla)):
if documentos.tabla[i] is not None:
print(documentos.tabla[i].nombre,end = ",")
else:
print(None,end = ",")
print("\n")
|
d4f94c7d783e5efb3a25f695e6e218b5e79d8285 | jianghaoyuan2007/algorithm | /Week_03/id_38/LeetCode_429_38.py | 499 | 3.65625 | 4 | from collections import deque
class Solution:
def levelOrder(self, root):
result = []
if not root:
return result
queue = deque()
queue.append(root)
while queue:
items = []
for _ in range(len(queue)):
node = queue.popleft()
items.append(node.val)
for item in node.children:
queue.append(item)
result.append(items)
return result
|
c220881e3b25f203c94ddbd47842f951b4db3669 | RinuElisabath/Competitive-programming- | /basics/nonRepeatingCharacters.py | 133 | 4.21875 | 4 | #find non repeating characters in a string
str1=input("enter string:")
for i in str1:
if str1.count(i)==1:
print(i) |
1774c4b5e15bbbace71f9f65690cdf8578f41f91 | vvalotto/Patrones_Disenio_Python | /patrones_gof/Strategy/graznido.py | 405 | 3.65625 | 4 | from abc import ABCMeta, abstractmethod
class Graznido(metaclass=ABCMeta):
@abstractmethod
def graznar(self):
pass
class GraznidoSilencioso(Graznido):
def graznar(self):
print('<< Silencio >>')
class GraznidoFuerte(Graznido):
def graznar(self):
print("Graznido Fuerte")
class GraznidoChirrido(Graznido):
def graznar(self):
print("Chirrido")
|
c709f087f021f3ae2034bd1a55a791eb9e83772f | tuhiniris/Python-ShortCodes-Applications | /list/Remove the Duplicate Items from a List.py | 909 | 4.40625 | 4 | """
Problem Description
The program takes a lists and removes the duplicate items from the list.
Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements of the list.
4. Use an if statement to check if the element is already there in the list and if it is not there, append it to another list.
5. Print the non-duplicate items of the list.
6. Exit.
"""
a=[]
n=int(input("Enter size of the list: "))
for i in range(n):
data=int(input(f"Enter elements of array at position {i}: "))
a.append(data)
print("elements in the list: ",end=" ")
for i in range(n):
print(a[i],end=" ")
print()
b=set()
unique=[]
for i in a:
if i not in b:
unique.append(i)
b.add(i)
print(f"List without duplicate elements are: {unique}") |
da6b7e88da8fcb5b4efb999bb42e64b4b790cfe8 | Gramotei-vlad/Task | /Without_LSP.py | 961 | 4.125 | 4 | class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def perimeter(self):
return (self.width + self.height) * 2
def area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self):
super().__init__()
def setWidth(self, width):
self.width = width
self.height = width
def setHeight(self, height):
self.height = height
self.width = height
def test(rectangle):
assert rectangle.perimeter() == 30
assert rectangle.area() == 56
return 'OK'
rectangle_1 = Rectangle()
rectangle_1.setWidth(7)
rectangle_1.setHeight(8)
square_1 = Square()
square_1.setWidth(7)
square_1.setHeight(8)
print(test(rectangle_1))
print(test(square_1)) # Тут не пройдет assert => нарушение lsp
|
d3c868c77af1d1d280f4faede570901799f08518 | fanzijian/leet-code-practice | /src/code/code_m_0107.py | 638 | 3.875 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
题目链接:https://leetcode-cn.com/problems/rotate-matrix-lcci/
Authors: fanzijian
Date: 2020-04-06 11:23:56
"""
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n//2):
for j in range((n+1)//2):
matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1], matrix[n-j-1][i] = matrix[n-j-1][i], matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1]
return matrix
|
6caba9bea554aada682c536b2528dd6b0720b41b | Raj-kar/PyRaj-codes | /dobble_game.py | 1,022 | 4.03125 | 4 | from random import choice, shuffle
words = ['goon', 'loser', 'criminal', 'carbon', 'collection',
'helpless', 'crisis', 'adventure', 'bloodsport', 'mouse']
def get_random_word():
# choose a random word from list of words
rand_word = choice(words)
# remove the word, for stop repetation
words.remove(rand_word)
return rand_word
def create_list_of_words():
return [get_random_word() for _ in range(4)]
# Create two list of words (each has 4 words)
first_list = create_list_of_words()
second_list = create_list_of_words()
# Select a random word
same_word = get_random_word()
# Append the same word both in list
first_list.append(same_word)
second_list.append(same_word)
# Shuffle the list
shuffle(first_list)
shuffle(second_list)
print("\n-------------------------- FIND THE SIMILARITY --------------------------")
print(first_list, second_list)
if input("Find Similar word -- \n").lower() == same_word:
print("Correct !!")
else:
print(f"The correct word is {same_word}") |
c714bf4fb145df2c8e37c646104cfd09d8dbbe91 | liuya2360/H2-Computing | /Python/Pop quizes/Pop quiz 3/bonus2.py | 824 | 3.59375 | 4 | def get_dist(x1,y1,x2,y2):
dist = ((x1-x2)**2+(y1-y2)**2)**0.5
return dist
def check_rectangle(a):
n = len(a)#number of points
cnt_rec = 0
for i in range(len(a)-3):
for j in range(i+1, len(a)-2):
for k in range(j+1, len(a)-1):
for l in range(k+1, len(a)):
dis_i_j = get_dist(a[i][0],a[i][1],a[j][0],a[j][1])
dis_k_l = get_dist(a[k][0],a[k][1],a[l][0],a[l][1])
dis_i_k = get_dist(a[i][0],a[i][1],a[k][0],a[k][1])
dis_j_l = get_dist(a[j][0],a[j][1],a[l][0],a[l][1])
dis_i_l = get_dist(a[i][0],a[i][1],a[l][0],a[l][1])
dis_j_k = get_dist(a[j][0],a[j][1],a[k][0],a[k][1])
if dis_i_j == dis_k_l and dis_i_k == dis_j_l and dis_i_l == dis_j_k:
cnt_rec += 1
#print("!",i,j,k,l)
return cnt_rec
n = [(0,1), (1,0), (1,1), (1,2), (2,1), (2,2)]
print(check_rectangle(n)) |
66a2eee8a2bfeada035f14a73660c5193399b2e5 | teuntjepeeters/Voorbeeldcode_OWE1a_1920 | /exception_handling_valueerror.py | 399 | 3.609375 | 4 | def invoer():
"""Voer uw leeftijd in
Return:
getal - str, leeftijd
"""
getal = input("Voer uw leeftijd in (jaren): ")
return getal
def main():
try:
jaren = int(invoer())
print("U bent "+ str(jaren) + " jaren oud")
print("Dat is "+ str(jaren*12) + " maanden")
except ValueError:
print("U heeft geen leeftijd ingevoerd")
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.