blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
cd52872bb60cc623d2fcff85f2bf10a0fd7315fc | ngocvuu/vuubaongoc-fundamental-c4e16 | /session05/homework/bacteria.py | 291 | 4 | 4 | howmany = int(input("How many B bacterias are there? "))
howmuch = int(input("How much time in mins will we wait? "))
#check lại công thức
final = howmany * 2 ** (howmuch - 1)
sum = howmany * (1 - 2 ** howmuch) / (1 - 2)
print("After",howmuch, "minutes, we would have",sum,"bacterias")
|
e61730efef371632a91a0ac2b33654c1bcb003f5 | leoflorov/python1 | /lesson_2_hw_easy.py | 1,992 | 4.21875 | 4 | # Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
newList = ["яблоко", "банан", "киви", "арбуз"]
i = 0
while len(newList) > i:
print(i + 1, newList[i])
i += 1
newList = ["яблоко", "банан", "киви", "арбуз"]
print('1.', newList[0])
print('2.', newList[1])
print('3.', newList[2])
print('4.', newList[3])
newList = ["яблоко", "банан", "киви", "арбуз"]
listLength = len(newList)
for i in range(listLength):
print(str(i + 1) + '. ' + '{}'.format(newList[i]))
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке.
spisok_1 = {1, 33, 45, "привет", 15.4, "мир"}
spisok_2 = {45, "мир", "осталось", 12, 33, 1}
spisok_3 = spisok_2 - spisok_1
print(list(spisok_3))
# Задача-3:
# Дан произвольный список из целых чисел.
# Получите НОВЫЙ список из элементов исходного, выполнив следующие условия:
# если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два.
lessonList = [1, 22, 13, 14, 95, 11, 78, 15, 64]
newList = []
lessonVar = len(lessonList)
for i in range(lessonVar):
if lessonList[i] % 2 == 0:
newList.append(lessonList[i] / 4)
else:
newList.append(lessonList[i] * 2)
print(newList)
|
87bd984142adcc63f0d6705a0885a6dea6ee2320 | Walrusbane524/Basic-python-projects | /Mathematical Scripts/SimpleWordCounter.py | 1,194 | 4.25 | 4 | ## Recebe uma frase de um usuário, identifica a palavra mais frequente, imprime ela e as vezes que ela foi usada.
# Receives a phrase from the user, identifies the most frequently used word, prints it and how many times it was used.
c = 0
itemIndex = 0
rep = 0
lista = []
## Recebe a frase do usuário e a divide nas vírgulas.
# Receives the phrase from the user and divides it on commas.
frase = input('Insira uma frase: ')
listaTemp = frase.split(',')
## Divide a list nos espaços.
# Divides the remaining sections of the phrase into words.
for i in range (0, (len(listaTemp))):
lista.extend(listaTemp[i].split(' '))
## Organiza as palavras da lista em ordem alfabética.
# Organizes the words from the list in alphabetical order.
lista.sort()
## Pega o índice da palavra mais usada e a quantidade de vezes que ela foi usada.
# Acquires the index of the most used word and how many times it was used.
while c <= len(lista) - 1:
if (lista.count(lista[c])) > rep:
rep = (lista.count(lista[c]))
itemIndex = c
c += 1
## Imprime o resultado.
# Prints the result.
print('A palavra mais frequente é', lista[itemIndex], 'e foi usada', rep, 'vezes.') |
6bbe2a6d5a548998c6c7d517300faab63bd137d9 | Leon201/praticingpython | /algorithmForDummies/Ch09reconnectingTheDots/depthFirstTraverse.py | 760 | 3.71875 | 4 | graph = {
'A': ['B', 'C']
, 'B': ['A', 'C', 'D']
, 'C': ['A', 'B', 'D', 'E']
, 'D': ['B', 'C', 'E', 'F']
, 'E': ['C', 'D', 'F']
, 'F': ['D', 'E']
}
def dfs(graph, start):
stack = [start]
parents = {start: start}
path = list()
while stack:
print ('Stack is : %s' % stack)
vertex = stack.pop(-1)
print ('Processing %s' % vertex)
for candidate in graph[vertex]:
if candidate not in parents:
parents[candidate] = vertex
stack.append(candidate)
print ('Adding %s to the stack'
% candidate)
path.append(parents[vertex] + '>' + vertex)
return path[1:]
steps = dfs(graph, 'A')
print('\nDFS:', steps) |
934913ea4b0753b8df0e211270f113853fc5464a | Othmanbdg/Frigo | /test_knnnn.py | 4,466 | 3.578125 | 4 | import random
from tkinter import *
ingredient=['sauces','yaourts','fruits','legumes','viandes','eau','soda','glace','fromage','lait']
temoin=['sauces','yaourts','fruits']
prsn=[]
path=r"C:/Users/Vil/Desktop/"
def gens(num):
var = 1
secu=[]
prsn.clear()
for i in range(num):
a = random.randint(0,len(ingredient)-1)
while a == 0:
a = random.randint(0,len(ingredient)-1)
b=frigo(a)
if b in secu:
b=frigo(a)
b.append(var)
var = var +1
prsn.append(b)
secu.append(b)
def frigo(num):
L=[]
cuse=[]
for i in range (num):
a=random.randint(0,len(ingredient)-1)
b=ingredient[a]
if b in L:
a=random.randint(0,len(ingredient)-1)
b=ingredient[a]
else:
L.append(b)
return L
def knn(temoin):
vide=[]
for elt in temoin:
for i in range (len(prsn) - 1):
a = prsn[i]
for elts in a:
if elt == elts:
if a not in vide:
vide.append(a)
c=len(vide)
dede=''
for i in range(c):
d=vide[i]
x=d[-1]
dede=dede+str(x)+","
if len(dede) == 2:
print("le frigo similaire est le numero: "+dede)
if len(dede) > 2:
print('les frigos similaires ont le numero:'+dede)
if vide==[]:
print('aucun frigo similaire')
return vide
def autre(prsn,vide):
zzz= []
for item in prsn:
if item not in vide:
zzz.append(item)
return zzz
def voisin(vide,K):
if K > len(vide):
print("vous avez dépassé le nombre d'element de la liste")
if K == 1:
print('Le voisin le plus proche est la liste numéros'+" "+str(vide[0][-1]))
if K<len(vide) and K<1:
T=vide[:K]
beto=''
for elt in T:
q = elt[-1]
beto = beto + str(q) + ','
print("les "+ " " + str(K)+" "+" plus proches voisins sont les numeros " + beto)
if K==len(vide):
print(vide)
gens(3)
vide = knn(temoin)
sss = autre(prsn,vide)
vide.extend(sss)
app = Tk()
app.title("KNN")
screen_x=int(app.winfo_screenwidth())
screen_y=int(app.winfo_screenheight())
window_x=1024
window_y=768
posX= ( screen_x // 2) - (window_x // 2)
posY= ( screen_y // 2) - (window_y // 2)
geo="{}x{}+{}+{}".format(window_x,window_y,posX,posY)
app.geometry(geo)
app.configure(bg="#8c7ae6")
image= PhotoImage(file=path+"frigo.png")
btn = Button(app,image=image)
btn.pack()
btn.place(x=400,y=100)
X=[100,400,700,1000,1300,100,400,700,1000,1300]
Y=[100,100,100,100,100,600,600,600,600,600]
def affiche(o):
for i in range (o):
btn = Button(app,image=image)
btn.pack()
btn.place(x=X[i],y=Y[i])
affiche(len(vide))
#légumes sauces soda steak et yaourt
legumex=[140,440,740]
legumey=[280,280,280]
saucex=[250,550,850]
saucey=[290,290,290]
sodax=[200,500,800]
soday=[290,290,290]
steakx=[135,435,735]
steaky=[330,330,330]
yaourtx=[230,530,830]
yaourty=[330,330,330]
legume=PhotoImage(file=path+"legumes.png")
sauces=PhotoImage(file=path+"sauces.png")
soda=PhotoImage(file=path+"soda.png")
steak= PhotoImage(file=path+"steak.png")
yaourt= PhotoImage(file=path+"yaourt.png")
def test(vide):
for i in range(vide[-1][-1]):
for item in vide[i]:
o=0
if item=='legumes':
leg= Button(app,image=legume)
leg.pack()
leg.place(x=legumex[i],y=legumey[o])
if item=='sauces':
sauc= Button(app,image=sauces)
sauc.pack()
sauc.place(x=saucex[i],y=saucey[o])
if item=='viandes':
stak=Button(app,image=steak)
stak.pack()
stak.place(x=steakx[i],y=steaky[o])
if item=='yaourts':
yaa = Button(app,image=yaourt)
yaa.pack()
yaa.place(x=yaourtx[i],y=yaourty[o])
if item=='soda':
sod= Button(app,image=soda)
sod.pack()
sod.place(x=sodax[i],y=soday[o])
o=o+1
test(vide)
app.mainloop()
|
85303a958e191e19fa32c26b5e58b86a4de15f73 | hsmith851/Python-Projects | /LatticePath.py | 561 | 3.609375 | 4 | import math
def LatticePath(down, right):
#Euler Problem Lattice Path
if (down == 0 or right == 0):
return 1
else:
return LatticePath (down - 1, rigLatticePathht) + LatticePath (down, right - 1)
#Recursive counting of Lattice Path of NxM Grid
#LatticePath_v2 uses binomial coefficient of the NxN grid to solve for the number of LatticePath
def LatticePath_v2(down, right):
numPaths = 0
return math.factorial (down + right) / (math.factorial (down) ** 2)
print( LatticePath (3, 3))
print (LatticePath_v2 (20, 20))
|
b411ef4bf33cdc46da458f5e092aaa09e25cb3f5 | latinos/HWWAnalysis | /CutBasedAnalyzer/scripts/dumpSelected.py | 2,750 | 3.515625 | 4 | #!/usr/bin/env python
import optparse
import sys
import ROOT
import array
import os.path
import HWWAnalysis.Misc.ROOTAndUtils as utils
#---------------------------------------------------------
import locale
locale.setlocale(locale.LC_NUMERIC, "")
def format_num(num):
"""Format a number according to given places.
Adds commas, etc. Will truncate floats into ints!"""
if isinstance(num,int):
return '%d' % num
elif isinstance(num,float):
return '%.2f' % num
else:
return str(num)
def get_max_width(table, index):
"""Get the maximum width of the given column index"""
return max([len(format_num(row[index])) for row in table])
def pprint_table(out, table):
"""Prints out a table of data, padded for alignment
@param out: Output stream (file-like object)
@param table: The table to print. A list of lists.
Each row must have the same number of columns. """
col_paddings = []
for i in range(len(table[0])):
col_paddings.append(get_max_width(table, i))
for row in table:
# left col
# print >> out, row[0].ljust(col_paddings[0] + 1),
# rest of the cols
for i in range(1, len(row)):
col = format_num(row[i]).rjust(col_paddings[i] + 2)
print >> out, col,
print >> out
#---------------------------------------------------------
treeName='hwwAnalysis'
def dumpSelected( path ):
f = ROOT.TFile.Open(path)
if not f.__nonzero__() or not f.IsOpen():
raise NameError('File '+path+' not open')
hwwTree = f.Get(treeName)
if not hwwTree.__nonzero__():
raise NameError('Tree '+treeName+' doesn\'t exist in '+path)
types = {}
types['ee'] = '00'
types['em'] = '01'
types['me'] = '10'
types['mm'] = '11'
# cut = types['ll']
hwwTree.Draw('>>counters','nt.selected==1','entrylist')
eList = ROOT.gDirectory.Get('counters')
n = ROOT.HWWNtuple()
hwwTree.SetBranchAddress('nt',ROOT.AddressOf(n))
hwwTree.SetEntryList(eList)
table = []
for i in xrange(eList.GetN()):
j = eList.GetEntry(i)
hwwTree.GetEntry(j)
table.append([j,n.run,n.lumiSection,n.event,n.type,n.mll,n.pA.Pt(),n.pB.Pt(),n.dPhi])
table = sorted(table, key=lambda nt: nt[1])
table.insert(0,['entry','run','lumi','event','type','mll','ptLead','ptTrail','dphi'])
pprint_table(sys.stdout,table)
if __name__ == '__main__':
usage = 'usage: %prog [options]'
parser = optparse.OptionParser(usage)
(opt, args) = parser.parse_args()
sys.argv.append( '-b' )
ROOT.gROOT.SetBatch()
ROOT.gSystem.Load('libFWCoreFWLite')
ROOT.AutoLibraryLoader.enable()
dumpSelected( args[0])
|
e2e2c2401953feeba59a95db21b8844edd14e988 | namnamgit/pythonProjects | /bonus.py | 159 | 3.734375 | 4 | anos = int(input("Anos de servico: "))
valor_por_ano = float(input("Valor por ano: "))
bonus = anos * valor_por_ano
print("Bônus de R$%5.2f" %bonus)
input()
|
411a765cd54ceaff36b818e3f5afab7df79d55cd | iasminqmoura/algoritmos | /Lista - Repetição/Exercicio28.py | 1,008 | 3.5625 | 4 | a = 0
c = 0
maior = -9999
soma_salarios = 0
soma_filhos = 0
media = 0
salario_menor_q = 0
while a != 'a':
c = c + 1
salario = float(input(f'{c} salario:'))
numero_de_filhos = int(input(f'{c} filhos:'))
if salario >= 0:
soma_salarios = soma_salarios + salario
soma_filhos = soma_filhos + numero_de_filhos
if salario > maior:
maior = salario
if salario <= 150:
salario_menor_q = salario_menor_q + 1
else:
media_salarios = soma_salarios / (c - 1)
print(f'R${media_salarios :.2f} e a media dos salarios')
media_filhos = soma_filhos / (c - 1)
print(f'{media_filhos :.0f} e a media de filhos')
print(f'R${maior} e o maior salario')
porcentagem_salario_menor_q = (salario_menor_q * 100) / (c - 1)
print(f'{porcentagem_salario_menor_q :.2f}% da populacao recebe menos de R$150 por mes') |
0fabb182524fd2f3a1af51e2d60f7f174ef8b88b | TryNeo/practica-python | /ejerccios/ejercicio-125.py | 899 | 4.34375 | 4 | #!/usr/bin/python3
"""
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
"""
def expanded_form(num):
try:
expanded_list = [1]+[10**power for power in range (1,100)]
nums_list = [int(str(num)[i]) for i in range(0,len(str(num)))][::-1]
return " + ".join([str(nums_list[i]*expanded_list[i]) for i in range(0,len(nums_list)) if nums_list[i]!=0][::-1])
except:
pass
if __name__ == "__main__":
print(expanded_form(12))
"""
test.assert_equals(expanded_form(12), '10 + 2');
test.assert_equals(expanded_form(42), '40 + 2');
test.assert_equals(expanded_form(70304), '70000 + 300 + 4');
"""
|
f072d87cc8a2c892861471c9cd16a81e555415b5 | Jaikelly/CursoPython | /Turtle/Turtle.py | 483 | 3.5625 | 4 | import turtle;
#creamos un objeto(pantalla)
s = turtle.Screen();
#la pluma
t = turtle.Turtle();
'''
#hace una linea de xxx pixeles, se mueve a la izquierda
t.backward(100);
#se mueve hacia la derecha(se voltea la pluma)
t.right(90);
#hace una linea hacia abajo
t.forward(100);
#se mueve a la izquierda(la pluma)
t.left(90);
t.forward(100);
'''
#abreviado
t.fd(100);
t.rt(90);
t.fd(100);
t.lt(90);
t.bk(100);
#hara queda pantalla se quede fija, que no se cierre
turtle.done(); |
eff27306cc2e0cc7b31c4510e97a6ec5090b823a | GuidoTorres/codigo8 | /Seman4/Dia1/02-clasesconconstructor.py | 1,497 | 4.125 | 4 | # class Persona:
# #Este es el constructor de la clase
# #Se usa self para instaciar todos los atributos de la clase, se crean
# #con el constructor y se pueden utilizar en todos los metodos
# def __init__(self, nombre, edad):
# self.nombre = nombre
# self.edad = edad
# def saludar(self):
# print("Hola, me llamo {} y tengo {} años".format(self.nombre, self.edad))
# persona1 = Persona("Guido", 25)
# print(persona1.nombre
# persona1.saludar()
#CRear una clase persona que tenga de atributos sus datos personales y su experencia laboral,
#que se ingrese por un menu la opc1 para ingresr nueva experiencia laboral,
# que la opcion 2 la muestre
#la opc 3 la elimine
# y opc 4 salga del programa
class Persona:
def __init__(self, nombre, apellido, edad, explaboral):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
self.explaboral = []
persona1 = Persona("Guido", "Torres" , 25, "AAAA")
opcion = +input("""======MENU========
1. Ingresar experiencia laboral
2. Mostrar
3. Eliminar
4. Salir""")
elif (opcion == 1):
exp = input("Ingrese nueva experiencia laboral: ")
explaboral.append(exp)
elif (opcion == 2):
print(persona1.explaboral)
elif (opcion == 3):
explaboral1.remove(exp)
elif (opcion == 4):
|
9c1abe3be9d10087be84725e6d42bdd20d5b4070 | abhiprd-219/sand-clock-pattern- | /.py | 433 | 3.71875 | 4 | def printLine(nums):
print(space, end='')
for i in nums:
print(i,end='', sep='')
print()
MAX = int(input())
space = ""
num = [i for i in range(1,MAX)] + [i for i in range(MAX, 0, -1)]
for i in range(2*MAX):
if i < MAX:
printLine(num[i:2*MAX-i-1])
space += " "
elif i==MAX:
space = space[1:]
elif i> MAX:
space = space[1:]
printLine(num[2*MAX-i-1:i])
|
041e186966d84c714fd1af9e6047dd896fb8447f | codecampNick/bots | /utilities.py | 656 | 3.578125 | 4 | import csv
class CsvFunctions:
def createCsv(self,filePath, fileMode, job):
with open('testFile.csv',mode='w') as testFile:
writer = csv.DictWriter(testFile, fieldnames=list(job.__dict__))
writer.writeheader()
print('Headers Created!!')
def addCsvRows(self, fileMode, job):
props = []
for key, value in job.__dict__.items():
props.append(value)
with open('testFile.csv',mode='a') as testFile:
writer = csv.writer(testFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(props)
print('Adding rows!')
|
2bd309408bb0aa2d406be49cc978a47194f1f462 | hongyilinux/python | /basic/dic/2ex.py | 404 | 3.84375 | 4 | str = "hello python"
l1 = list(str)
print('将字符串转换成列表')
print(l1)
tu1 = tuple(str)
print('将字符串转换成元组')
print(tu1)
set1 = set(str)
print('将字符串转换成集合:集合是没有次序的,会删除重复元素')
print(set1)
list2 = [('a',1),('b',2),('c',3),('d',4)]
dic1 = dict(list2)
print('把带有键值对的元组列表转换成字典')
print(dic1)
|
6eafa1625ea71b0734eb0b54222350b8e61ed590 | bhatnitish1998/aps-2020 | /check_prime.py | 283 | 4.125 | 4 | # check if a given number is prime or not
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True |
d292cd3f513e1def295cbd60e74cc997fa1ccc41 | CrazyClown41/PythonProjects | /src/personal-projects/CheckPrime.py | 508 | 4 | 4 | def getNum():
num = int(input("Enter number to see if it is prime: "))
return num
def check(num):
listRange = list(range(1,num+1))
divisorList = []
for number in listRange:
if num % number == 0:
divisorList.append(number)
if divisorList[0] == 1 and divisorList[1] == num:
print("Number is prime!")
else:
print("Number is not prime.")
print("And these are the divisors of", num, ":", divisorList)
check(getNum()) |
fc970e3e39a64a94b7c2c078c534563123885967 | Wilson1211/LeetCode | /Manacher_Algorithm.py | 1,505 | 3.5625 | 4 | class Solution:
def longestPalindrome(self, s: str) -> str:
string_size = len(s)
if string_size < 3:
if s==s[::-1]:
return s
else:
return s[0]
manacher_str = "#"
for index in range(len(s)):
manacher_str += s[index]
manacher_str += "#"
LPS_table = [0]*len(manacher_str)
center = 1
max_right = 2
max_length = 0
LPS_center = 0
total_size = len(manacher_str)
for index in range(1, len(manacher_str)):
if index < max_right:
LPS_table[index] = min(LPS_table[2*center-index], max_right-index) # center - (index-center)
else:
LPS_table[index] = 0
# when calculating LPS value, self position (index) is not included
while (index-LPS_table[index]-1 >= 0 and
index+LPS_table[index]+1 < total_size and
manacher_str[index-LPS_table[index]-1] == manacher_str[index+LPS_table[index]+1]):
LPS_table[index] += 1
if LPS_table[index] > max_length:
max_length = LPS_table[index]
LPS_center = index
if LPS_table[index]+index-1 > max_right:
max_right = LPS_table[index]+index-1
center = index
start = int((LPS_center-max_length)/2)
return s[start: start+max_length] |
02a39c17d27e6895eee4acd35c9ea933723cd7fe | Chidalu567/computervision | /Open cv project/Opencv2/Drawing Function in opencv.py | 1,237 | 4.125 | 4 | '''We use the cv2.(line,rectangle,circle,ellipse,putText,polylines) functions to draw things in opencv2'''
import cv2
import numpy
img=numpy.zeros((512,512,3),numpy.uint8); #create a black background
#===>Drawing line in opencv
cv2.line(img,(0,0),(450,450),(255,255,0),3); #create a line in cv2
#===Drawing Rectangle in opencv
cv2.rectangle(img,(150,50),(400,20),(255,255,0),2); #create a rectangle
#===>Drawing circle
cv2.circle(img,(400,200),35,(255,255,0),2); #create a circle
#===>Drawing ellipse
cv2.ellipse(img,(300,200),(100,300),360,20,180,(255,255,0),2); #create an ellipse
#==>Putting Text
cv2.putText(img,'OPEN CV ',(100,200),cv2.FONT_HERSHEY_SIMPLEX,2,(225,225,0),2); #puttext in opencv
#Drawing of polylines
Vertices=numpy.array([[100,300],[50,200],[100,100],[200,100],[300,200],[200,300]],numpy.int32); #cretae an array
points=Vertices.reshape((-1,1,2)); #reshape array
cv2.polylines(img,[points],True,(255,255,0),4); #create a polyline
cv2.namedWindow('Draw Function',cv2.WINDOW_NORMAL); #create a named window
cv2.imshow('Draw Function',img); #show image
cv2.imwrite('Drawn by opencv.png', img); #write image
if cv2.waitKey(0)&0xFF==ord('q'):
cv2.destroyWindow(); #destroy window
|
b5e466b531f0afafee881658b96d1babaaa587b0 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEU2-Algorithms-gp/src/challenge.py | 1,960 | 3.84375 | 4 | # Work out the time complexity of these solutions
"""
Formally:
1. Compute the Big-O for each line in isolation
2. if something is in a loop, multiply it's Big-O by the loop for the total.
3. If two things happen sequentially, add the Big-Os.
4. Drop leading multiplicative constants from each of the Big-Os.
5. From all of the Big-Os that are added, drop all but the biggest, dominating one.
"""
import math
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# 1
def baz(n):
s = 0
<<<<<<< HEAD
for i in range(n): # O(n)
for j in range(int(math.sqrt(n))): # O(sqrt(n)) n * sqrt n
s += i * j # O(1)
return s # O(1)
=======
for i in range(n): # O(n)
for j in range(int(math.sqrt(n))): # O(sqrt(n)) n * sqrt n
s += i * j # O(1)
return s # O(1)
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# O(n sqrt(n))
# 2
def frotz(n):
<<<<<<< HEAD
s = 0 # O(1)
for i in range(n): # O(n)
for j in range(2 * n): # O(2n) => O(n) => O(n^2)
s += i * j # O(1)
return s # O(1)
=======
s = 0 # O(1)
for i in range(n): # O(n)
for j in range(2 * n): # O(2n) => O(n) => O(n^2)
s += i * j # O(1)
return s # O(1)
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# O(2 n^2) => O(n^2)
# 3
def bar(x):
<<<<<<< HEAD
sum = 0 # O(1)
for i in range(0, 1463): # O(1436) => O(1)
i += sum # O(1)
for _ in range(0, x): # O(x)
for _ in range(x, x + 15): # O(15) => O(1)
sum += 1 # O(1) * O(x) * O(1) => O(1 * X * 1) => O(x)
# O(n) linear
=======
sum = 0 # O(1)
for i in range(0, 1463): # O(1436) => O(1)
i += sum # O(1)
for _ in range(0, x): # O(x)
for _ in range(x, x + 15): # O(15) => O(1)
sum += 1 # O(1) * O(x) * O(1) => O(1 * X * 1) => O(x)
# O(n) linear
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
|
3dc922ef17a09cd6c13f81f4a092f42c46b15e1e | Sushmi-pal/pythonassignment2 | /Q18.py | 469 | 3.59375 | 4 | import json
info={"about_me":[{"name":"Sushmita Palikhe",
"age":22}]}
# File representation of json data
with open("info.json",'w') as f:
json.dump(info,f,indent=2)
# String representation of json data
serialize_info=json.dumps(info,indent=2)
print('Serializing')
print(serialize_info)
print('Deserializing')
json_file = open('info.json' )
data = json.load(json_file)
print(data)
json_file.close()
deserialize_info=json.loads(serialize_info)
print(deserialize_info) |
e7ce968ade37234d00d4f9e30537137742c740e9 | shevonwang/Python-Logistic-Regression | /main.py | 3,666 | 3.5625 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn.metrics import confusion_matrix # 导入混淆矩阵函数
from numpy import *
import pandas as pd
from sklearn.metrics import roc_curve #导入ROC曲线函数
import matplotlib.pyplot as plt
# calculate the sigmoid function
def sigmoid(z):
return 1.0 / (1 + exp(-z))
# m denotes the number of examples here, not the number of features
def gradientDescent(train_x, train_y, theta, alpha, m, num_n, num_iterations):
x_trans =train_x.transpose()
for i in range(0, num_iterations):
hypothesis = sigmoid(dot(train_x, theta))
error = hypothesis - train_y
gradient = dot(x_trans, error) / m
# update
theta = theta - alpha * gradient
return theta
def cleanData(original_data_file, output_file):
original_df = pd.read_excel(original_data_file, header=0)
original_num_samples, original_num_features = shape(original_df)
original_df.columns = range(original_num_features)
for i in range(original_num_features):
for j in range(original_num_samples):
original_df[i][j] = (original_df[i][j] - original_df[i].mean()) / original_df[i].std()
original_df.to_excel(output_file)
def getFinalData(final_data_file, p):
df = pd.read_excel(final_data_file, header=0)
df = df.as_matrix()
num_m, num_n = shape(df)
x_0 = ones(num_m) # 初始化 x_0
df = insert(df, 0, x_0, axis=1) # 插入x0 = 1
# 划分训练集与测试集
train_x = df[0:int(len(df)*p), range(num_n)]
train_y = df[0:int(len(df)*p), [num_n]] #注意啦,这里一定要两个中括号,返回值类型为 'DataFrame',不然的话,返回的 train_y 就是 'Series'
test_x = df[int(len(df)*p):, range(num_n)]
test_y = df[int(len(df)*p):, [num_n]]
num_samples, num_features = shape(train_x)
alpha = 0.01
num_iterations = 1000
theta = ones((num_features, 1))
theta = gradientDescent(train_x, train_y, theta, alpha, num_samples, num_features, num_iterations)
return theta, test_x, test_y
def testLogRegres(theta, test_x, test_y):
num_samples, num_features = shape(test_x)
theta_trans = theta.transpose()
scores = []
for i in range(num_samples):
z = dot(theta_trans, test_x[i])
predict = sigmoid(z)
if predict >= 0.5:
predict = 1
else:
predict = 0
scores.append(predict)
print(scores)
#用 ROC 曲线评估模型
fpr, tpr, thresholds = roc_curve(test_y, scores, pos_label=1)
plt.plot(fpr, tpr, linewidth=2, label='ROC of CART', color='green') # 作出ROC曲线
plt.xlabel('False Positive Rate') # 坐标轴标签
plt.ylabel('True Positive Rate') # 坐标轴标签
plt.ylim(0, 1.05) # 边界范围
plt.xlim(0, 1.05) # 边界范围
plt.legend(loc=4) # 图例
plt.show() # 显示作图结果a
cm = confusion_matrix(test_y, scores) # 混淆矩阵
plt.matshow(cm, cmap=plt.cm.Greens) # 画混淆矩阵图
plt.colorbar() # 颜色标签
for x in range(len(cm)): # 数据标签
for y in range(len(cm)):
plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center')
plt.ylabel('True label') # 坐标轴标签
plt.xlabel('Predicted label') # 坐标轴标签
plt.show()
if __name__ == '__main__':
original_data_file = '../data/original-data.xls'
final_data_file = '../data/finaldata.xls'
cleanData(original_data_file, final_data_file)
p = 0.8 #训练集所占的比例
theta, test_x, test_y = getFinalData(final_data_file, p)
testLogRegres(theta, test_x, test_y)
|
df41dd31b7a3a37a714bb0cbd698a31996967551 | caojcarlos/ProjetosPython | /adivinhacao.py | 638 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 07:12:03 2020
@author: Jose Carlos Nunes
Objetivo: Programa Basico para jogo de Adivinhacao
"""
import random
sorteado = random.randrange(1,100)
jogador = int(input('Digite um numero entre [1, 100]: '))
erro = 0
while (jogador != sorteado):
if (jogador < sorteado):
print('O numero é maior')
elif (jogador > sorteado):
print('O numero e menor')
else:
break
erro += 1
jogador = int(input('Tente novamente, digite um numero entre [1, 100]: '))
print ('Parabens voce acertou em {} tentativas'. format(str(erro + 1)))
|
df39801e5d068a99ffcf6bd85caf590864b9ee28 | btRooke/smart-home | /controller/password_hashing.py | 335 | 3.5625 | 4 | import hashlib
import random
import string
def generate_salt(length=16):
"""
random salt of 16 characters
"""
return "".join([random.choice(string.ascii_letters + string.digits) for i in range(length)])
def hash_string(string_to_hash):
h = hashlib.sha256(string_to_hash.encode("utf-8"))
return h.hexdigest()
|
4894e18e1a23c3e899e0fdddfe1cad49709cdf8c | leeinae/algorithm-python | /Programmers/12899.py | 299 | 3.53125 | 4 | def solution(n):
num = ['1', '2', '4']
answer = ''
while n > 0:
remainder = n % 3 if n % 3 != 0 else 3
answer = num[remainder - 1] + answer
n = (n - 1) // 3
return answer
solution(3)
solution(18)
solution(16)
solution(8)
solution(10)
solution(500000000)
|
a18e167f77e38de3bf44bf278c41643cf662a33b | KatherineCG/TargetOffer | /8-旋转数组的最小数字.py | 1,133 | 3.515625 | 4 | class Solution():
def Min(self, list):
length = len(list)
index1 = 0
index2 = length - 1
indexMid = index1
while list[index1] >= list[index2]:
if index2 - index1 == 1:
indexMid = index2
break
indexMid = (index2 + index1) / 2
if list[index2] == list[index1] and list[indexMid] == list[index1]:
return self.MinInOrder(list, index1, index2)
if list[indexMid] >= list[index1]:
index1 = indexMid
elif list[indexMid] <= list[index2]:
index2 = indexMid
result = list[indexMid]
return result
def MinInOrder(self, list, index1, index2):
result = list[index1]
for index1 in range(1, index2):
if list[index1] < result:
result = list[index1]
return result
if __name__ == '__main__':
test = Solution()
list1 = [1,0,1,1,1]
list2 = [1,2,3,4,5]
list3 = [3,4,5,1,2]
print test.Min(list1)
print test.Min(list2)
print test.Min(list3) |
1d9bf325002b36143e4820464e7e4e99ec2d3e9e | CesarGlezR/EVA1 | /python/EVA1_12_Pendiente.py | 247 | 3.9375 | 4 | print("Introduce y1")
y1 = float(input())
print("Introduce y2")
y2 = int(input())
print("Introduce x1")
x1 = float(input())
print("introduce x2")
x2 = float(input())
p = (y1 - y2) / (x1 - x2)
print("La pendiente es ", end='', flush=True)
print(p)
|
95441465172155a3a245d011f8866310cf559add | aco1731/snippets | /snippets/factorial_asyncio.py | 783 | 3.59375 | 4 | import asyncio
import time
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(0.01)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def print_time(x):
for _ in range(x):
print(f"TIME NOW: {time.strftime('%X')}")
await asyncio.sleep(1)
async def main():
# Schedule three calls *concurrently*:
task5 = asyncio.create_task(print_time(5))
print(f"started at {time.strftime('%X')}")
await asyncio.gather(
task5,
factorial("A", 1000),
factorial("B", 10),
factorial("C", 100),
)
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
|
986d87f329ba154fe9a121d7972b4ac9c243894f | thalita89/ChallengePython | /challenge02 | 993 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 14:34:51 2020
@author: thalitaramires
"""
#Challenge02
#----------------------------------------------------------------
#Digital root is the recursive sum of all the digits in a number.
#Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
#Examples
# 16 --> 1 + 6 = 7
# 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
#132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
#493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
#-----------------------------------------------------------------
def digitalRoot(arg):
a = arg
res = 0
b = str(a)
for i in range(len(b)):
res += int(b[i])
while res >= 10:
return digitalRoot(res)
else:
return res
x = digitalRoot(493193)
print('Resultado: ', x)
|
b9306df1eef5e353d89626ab1112eadb68db7207 | t4d-classes/python_03012021 | /app.py | 574 | 4.3125 | 4 | result = 0
command = input("Please enter a command: ")
print(command)
while command:
if command == "clear":
result = 0
else:
num = int(input("Please enter an operand: "))
if command == "add":
result = result + num
elif command == "subtract":
result = result - num
elif command == "multiply":
result = result * num
elif command == "divide":
result = result / num
print(f"Result: {result}")
command = input("Please enter a command: ")
print(command)
|
51d17769fb6aabf35bf590e073c4364b3d564985 | natalyazhiltsova/Zhiltsova-Natalya | /Lecture02/Lecture02.py | 2,271 | 4.125 | 4 | #1 Спросить пользователя и получить строку в ответ
s = input("Please, enter the number: ")
s = s.strip()
#2 Проверить корректность ввода
if not (1 <= len(s) <= 2):
print("Invalid input")
exit(1)
# Завершает программу если ввод некорректный
if not s.isdigits():
print("Invalid input")
exit(1)
digits = "0123456789"
if s[0] not in digits:
print("Invalid input")
exit(1)
if len(s) > 1 and s[1] not in digits:
print("Invalid input")
exit(1)
#3 Преобразование строки в число
n = int(s)
#4 Проверка диапазона
if not(0 <= n <= 99):
print("Invalid input")
exit(1)
#5 Формирование ответа
answer = ""
if n // 10 == 2:
answer += "двадцать "
elif n // 10 == 3:
answer += "тридцать "
elif n // 10 == 4:
answer += "тридцать "
elif n // 10 == 5:
answer += "тридцать "
elif n // 10 == 6:
answer += "тридцать "
elif n // 10 == 7:
answer += "тридцать "
elif n // 10 == 8:
answer += "тридцать "
elif n // 10 == 9:
answer += "тридцать "
if n == 0 and n:
answer = answer + "нуль"
elif n % 10 == 1:
answer += "один"
elif n % 10 == 2:
answer += "два"
elif n % 10 == 3:
answer += "три"
elif n % 10 == 4:
answer += "четыре"
elif n % 10 == 5:
answer += "пять"
elif n % 10 == 6:
answer += "шесть"
elif n % 10 == 7:
answer += "семь"
elif n % 10 == 8:
answer += "восемь"
elif n % 10 == 9:
answer += "девять"
elif n == 10:
answer += "десять"
elif n == 11:
answer += "одиннадцать"
elif n == 12:
answer += "двенадцать"
elif n == 13:
answer += "тринадцать"
elif n == 14:
answer += "четырнадцать"
elif n == 15:
answer += "пятнадцать"
elif n == 16:
answer += "шестнадцать"
elif n == 17:
answer += "семнадцать"
elif n == 18:
answer += "восемнадцать"
elif n == 19:
answer += "девятнадцать"
answer = answer.rstrip()
print(f"Result: {answer}")
|
c7c785e0fe2c104c360bc61c91b45285d0a18f1b | Sergey-Laznenko/Stepik | /Generation Python - A Beginner's Course/9_String_data_type/9.4.str_methods_v2/8.py | 349 | 4.03125 | 4 | """
На вход программе подается строка текста, состоящая из слов, разделенных ровно одним пробелом.
Напишите программу, которая подсчитывает количество слов в ней.
"""
text = input()
a = text.count(' ')
print(a + 1)
|
6a3643776752f9d9cec9f3137f282cb538e9f1e6 | JuniorDugue/002-tip-calculator | /fstrings.py | 699 | 4.4375 | 4 | print(8/3) # returns 2.6666666666666665 a floating point number
print(int(8/3)) # returns 2 as an integer
print(round(8/3)) # will return 3 rounding to a whole number
print(round(8 / 3, 2)) # to specifify a decial placement e.g. 2 decimal places
print( 8 // 3) # floored divisions that'll return 2
# if you wanted to continue an operation, you can store equation to a variable and
# you can use shorthands e.g. if you're trying to keep score of a sports score
answer = 4 / 2
answer /= 2
print(answer)
# f-string
# make sure to write f in front of your strings
score = 0
height = 1.8
isWinning = True
print(f"your score is {score}, your height is {height}, you are wnning is {isWinning}") |
c372b22474cfa7434ab7bc61edd54f24fa8105b0 | HaidiChen/Coding | /python/recursion/hanoi.py | 210 | 3.96875 | 4 | def hanoi(n, p1, p2, p3):
if n == 1:
move(p1, p2)
return
hanoi(n - 1, p1, p3, p2)
move(p1, p2)
hanoi(n - 1, p3, p2, p1)
def move(x, y):
print('from {} to {}'.format(x, y))
|
7810134033b10fb730cafa531b546237c159ae4d | bennosski/elph | /imagaxis/convolution.py | 7,548 | 3.9375 | 4 | from numpy import *
import fourier
def basic_conv(a, b, indices_list, axes, circular_list, izeros, op='...,...'):
'''
a and b must be the same size
the length of each axis must be even
indices_list specifies the way in which to convovle for the corresponding axes in 'axes'
the repeated index is summed over
the single index is the remaining index after convolution
for example, indices = ['x,y-x'] will perform the sum over x of a(x)*b(y-x)
options for each entry of indices_list is one of four forms (you can change the letter names):
'x,y-x' or 'x,x+y' or 'y-x,x' or 'x+y,x'
every convolution can be put into one of these forms by relabeling the index which is summed over
note that 'x,x-y' is not in one of these forms but after the relabeling x->x+y it becomes 'x+y,x'
axes specify the axes over which convolutions occur
circular_list (True or False) specifies whether to do a circular or a regular convolution
op specifies the tensor operation which to perform to the intermediate ffts
it is a string which becomes the first argument to numpy.einsum
by default it is elementwise multiplication
izero is the index of x=0 in the arrays a and b
'''
a_ = a[:]
b_ = b[:]
dims = array([min(d1,d2) for d1,d2 in zip(shape(a), shape(b))])
#maxdims = array([max(d1,d2) for d1,d2 in zip(shape(a), shape(b))])
for indices, axis, circular in zip(indices_list, axes, circular_list):
if circular: continue
comma = indices.index(',')
a_ = concatenate((a_, zeros(2*dims-array(shape(a)))), axis=axis)
b_ = concatenate((b_, zeros(2*dims-array(shape(b)))), axis=axis)
for axis, izero in zip(axes, izeros):
a_ = roll(a_, -izero, axis=axis)
b_ = roll(b_, -izero, axis=axis)
a_ = fft.fftn(a_, axes=axes)
b_ = fft.fftn(b_, axes=axes)
for indices, axis in zip(indices_list, axes):
if '+' in indices:
comma = indices.index(',')
if comma==1:
a_ = roll(flip(a_, axis=axis), 1, axis=axis)
elif comma==3:
b_ = roll(flip(b_, axis=axis), 1, axis=axis)
else: raise ValueError
x = fft.ifftn(einsum(op, a_, b_), axes=axes)
for axis, izero in zip(axes, izeros):
x = roll(x, izero, axis=axis)
return x
def basic_conv0(a, b, indices_list, axes, circular_list, op='...,...'):
'''
todo: write optional zeros argument
- if x is the repeated index, then yz-xz=0 and xz=0 and yz=0
a and b must be the same size
the length of each axis must be even
indices_list specifies the way in which to convovle for the corresponding axes in 'axes'
the repeated index is summed over
the single index is the remaining index after convolution
for example, indices = ['x,y-x'] will perform the sum over x of a(x)*b(y-x)
options for each entry of indices_list is one of four forms (you can change the letter names):
'x,y-x' or 'x,x+y' or 'y-x,x' or 'x+y,x'
every convolution can be put into one of these forms by relabeling the index which is summed over
note that 'x,x-y' is not in one of these forms but after the relabeling x->x+y it becomes 'x+y,x'
axes specify the axes over which convolutions occur
circular_list (True or False) specifies whether to do a circular or a regular convolution
op specifies the tensor operation which to perform to the intermediate ffts
it is a string which becomes the first argument to numpy.einsum
by default it is elementwise multiplication
'''
a_ = a[:]
b_ = b[:]
dims = array([min(d1,d2) for d1,d2 in zip(shape(a), shape(b))])
#maxdims = array([max(d1,d2) for d1,d2 in zip(shape(a), shape(b))])
for indices, axis, circular in zip(indices_list, axes, circular_list):
if circular: continue
comma = indices.index(',')
a_ = concatenate((a_, zeros(2*dims-array(shape(a)))), axis=axis)
b_ = concatenate((b_, zeros(2*dims-array(shape(b)))), axis=axis)
for axis in axes:
a_ = roll(a_, shape(a)[axis]//2, axis=axis)
b_ = roll(b_, shape(b)[axis]//2, axis=axis)
a_ = fft.fftn(a_, axes=axes)
b_ = fft.fftn(b_, axes=axes)
for indices, axis in zip(indices_list, axes):
if '+' in indices:
comma = indices.index(',')
if comma==1:
a_ = roll(flip(a_, axis=axis), 1, axis=axis)
elif comma==3:
b_ = roll(flip(b_, axis=axis), 1, axis=axis)
else: raise ValueError
x = fft.ifftn(einsum(op, a_, b_), axes=axes)
for axis in axes:
x = roll(x, shape(a)[axis]//2, axis=axis)
return x
def conv(a, b, indices_list, axes, circular_list, beta=None, kinds=(None,None,None), op='...,...', jumps=(None,None)):
'''
todo: write optional zeros argument
- if x is the repeated index, then yz-xz=0 and xz=0 and yz=0
a and b must be the same size
the length of each axis must be even
indices_list specifies the way in which to convovle for the corresponding axes in 'axes'
the repeated index is summed over
the single index is the remaining index after convolution
for example, indices = ['x,y-x'] will perform the sum over x of a(x)*b(y-x)
options for each entry of indices_list is one of four forms (you can change the letter names):
'x,y-x' or 'x,x+y' or 'y-x,x' or 'x+y,x'
every convolution can be put into one of these forms by relabeling the index which is summed over
note that 'x,x-y' is not in one of these forms but after the relabeling x->x+y it becomes 'x+y,x'
axes specify the axes over which convolutions occur
circular_list specifies whether to do a circular or a regular convolution for each axis
kinds = (kind of a, kind of b, kind of out). Either 'fermion' or 'boson'
op specifies the tensor operation which to perform to the ffts
it is a string which becomes the first argument to numpy.einsum
by default it is elementwise multiplication
'''
for indices, axis, circular in zip(indices_list, axes, circular_list):
if circular:
a = fft.fft(a, axis=axis)
b = fft.fft(b, axis=axis)
else:
a = fourier.w2t(a, beta, axis, kind=kinds[0], jump=jumps[0])
b = fourier.w2t(b, beta, axis, kind=kinds[1], jump=jumps[1])
comma = indices.index(',')
if '+' in indices:
if comma==1:
a = flip(a, axis=axis)
if not circular and kinds[0]=='fermion': a *= -1.0
if circular: a = roll(a, 1, axis=axis)
elif comma==3:
b = flip(b, axis=axis)
if not circular and kinds[1]=='fermion': b *= -1.0
if circular: b = roll(b, 1, axis=axis)
else:
raise ValueError
x = einsum(op, a, b)
for axis, circular in zip(axes, circular_list):
if circular:
x = fft.ifft(x, axis=axis)
else:
x = fourier.t2w(x, beta, axis, kind=kinds[2])[0]
for axis, circular in zip(axes, circular_list):
if circular:
x = roll(x, shape(a)[axis]//2, axis=axis)
return x
|
1e20bd47ebf020bad0e2f40a16ca38c969bf1eaf | liguoyu666/chuji_suanfa | /04.存在重复元素.py | 1,396 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/4 下午2:23
# @Author : liguoyu
# @FileName: 04.存在重复元素.py
# @Software: PyCharm
# 给定一个整数数组,判断是否存在重复元素。
# 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
#
# 输入: [1,2,3,1]
# 输出: true
#
# 输入: [1,2,3,4]
# 输出: false
#
# 输入: [1,1,1,3,3,4,3,2,4,2]
# 输出: true
def containsDuplicate_1(nums):
"""
:type nums: List[int]
:rtype: bool
"""
return False if len(nums) == len(set(nums)) else True
def containsDuplicate_2(nums):
"""
:type nums: List[int]
:rtype: bool
"""
numsdic = {}
for i in nums:
if i not in numsdic:
numsdic[i] = True
else:
return True
return False
def containsDuplicate_3(nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
if __name__ == '__main__':
nums_1 = [1,2,3,4]
nums_2 = [1,2,3,2,4]
y1 = containsDuplicate_1(nums_1)
y2 = containsDuplicate_1(nums_2)
y3 = containsDuplicate_2(nums_1)
y4 = containsDuplicate_2(nums_2)
y5 = containsDuplicate_3(nums_1)
y6 = containsDuplicate_3(nums_2)
print(y1,y2,y3,y4,y5,y6) |
98afc5982cfef6ef0d70bdfbb79c8d51456b048d | DyuldinKS/stepik.algorithms | /4.2.huffman-codes/heap.py | 1,870 | 3.6875 | 4 | class Heap:
def __init__(self, iterable=None):
if not iterable:
return
for item in iterable:
self.insert(item)
def _swap(self, i, j):
self.list[i], self.list[j] = self.list[j], self.list[i]
def _get_parent_index(self, index):
return (index - 1) >> 1 if index > 0 else None
def _get_min_child_index(self, parent_index):
left = parent_index * 2 + 1
right = left + 1
length = len(self.list)
if left < length:
if right < length:
return left if self.list[left] <= self.list[right] else right
else:
return left
else:
return None
def insert(self, elem):
elem_index = len(self.list)
self.list.append(elem)
parent_index = self._get_parent_index(elem_index)
while (parent_index is not None and
self.list[parent_index] > self.list[elem_index]):
self._swap(parent_index, elem_index)
elem_index = parent_index
parent_index = self._get_parent_index(elem_index)
def extract_min(self):
if len(self.list) == 1:
return self.list.pop()
parent_index = 0
min_elem = self.list[parent_index]
self.list[parent_index] = self.list.pop()
child_index = self._get_min_child_index(parent_index)
while (child_index is not None and
self.list[parent_index] > self.list[child_index]):
self._swap(parent_index, child_index)
parent_index = child_index
child_index = self._get_min_child_index(parent_index)
return min_elem
def __len__(self):
return len(self.list)
def is_empty(self):
return len(self.list) == 0
def __str__(self):
return str(self.list)
list = []
|
6e21458cfb0bfb9d76e72293085cd3b8cf262126 | Rustofaer/GeekUniversity-Python | /lesson-4/task1.py | 865 | 3.859375 | 4 | # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете
# необходимо использовать формулу: (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных
# значений необходимо запускать скрипт с параметрами.
from sys import argv
try:
script_name, hours, wage, bonus = argv
hours = float(hours)
wage = float(wage)
bonus = float(bonus)
if hours < 0 or wage <= 0 or bonus < 0:
raise ValueError
except ValueError:
print("Ошибка ввода")
else:
print("Заработная плата =", hours * wage + bonus)
|
ed769537d5841025208f669c8cf814e6f39a34c2 | Nurmatov-07/PythonTasks | /На GitHub/Tuples_in_python.py | 489 | 3.953125 | 4 |
def max_min():
new_tuple = (23.4, 54.123, -5.4344, -99.1, 4.1, 0.999, 78.78, 98.123, 12.21, 1.11)
i = 0
max = 0
min = 0
for j in range(0, len(new_tuple)):
for i in range(0, len(new_tuple)):
if new_tuple[i] > max:
max = new_tuple[i]
if new_tuple[i] < min:
min = new_tuple[i]
print(new_tuple)
print('Maximum value: {0}, \n Minimum value: {1}'.format(max, min))
max_min() |
7868ee5e7fe380d0760e9fefd7b1cfa36905dbbc | HOZH/leetCode | /leetCodePython2020/2373.largest-local-values-in-a-matrix.py | 847 | 3.515625 | 4 | #
# @lc app=leetcode id=2373 lang=python3
#
# [2373] Largest Local Values in a Matrix
#
# @lc code=start
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
ans = []
for i in range(n - 2):
res = []
for j in range(n - 2):
k = []
k.append(grid[i][j])
k.append(grid[i][j + 1])
k.append(grid[i][j + 2])
k.append(grid[i + 1][j])
k.append(grid[i + 1][j + 1])
k.append(grid[i + 1][j + 2])
k.append(grid[i + 2][j])
k.append(grid[i + 2][j + 1])
k.append(grid[i + 2][j + 2])
m = max(k)
res.append(m)
ans.append(res)
return ans
# @lc code=end
|
7ed40abe4cc67b18dbed5fa0f6854df320486850 | surya-lights/Python_Cracks | /Tuple.py | 254 | 4.09375 | 4 | # Tuple items - data types
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
# A Tuple with multiple data types
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
|
f01db7fea13aa2b5b796bb214eb634cd673fd7df | habpygo/DeltaPlotting | /3-Dplot.py | 564 | 3.6875 | 4 | from numpy import *
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
# u and va are parametric variables.
# u is an array from 0 to 2*pi, with 100 elements
u=r_[0:2*pi:100j]
# v is an array from 0 to 2*pi, with 100 elements
v=r_[0:pi:100j]
# x, y, and z are the coordinates of the points for plotting
# each is arranged in a 100x100 array
x=10*outer(cos(u),sin(v))
y=10*outer(sin(u),sin(v))
z=10*outer(ones(size(u)),cos(v))
fig=p.figure()
ax = p3.Axes3D(fig)
ax.plot_wireframe(x,y,z)
ax.set_xlabel('X')
ax.set_xlabel('y')
ax.set_xlabel('Z')
p.show()
|
a5bb95bde84a8fa2f865bad5d4a30e09188d6647 | nathanlct/cp | /project_euler/27.py | 830 | 3.65625 | 4 | """
P(n) = n^2 + an + b
|a|, |b| < 1000
Find a, b st N is maximal: for n < N, P(n) is prime
Return ab
"""
"""
P(0) = b has to be prime
P(1) = a+b+1 has to be prime
"""
def _is_prime(n):
if n < 2: return False
if n % 2 == 0: return (n == 2)
for k in range(3, n, 2):
if n % k == 0: return False
return True
memoiz = {}
def is_prime(n):
if n not in memoiz:
ans = _is_prime(n)
memoiz[n] = ans
return memoiz[n]
max_n = 0
argmax_n = (0, 0)
for a in range(-999, 1000):
for b in range(-999, 1000):
n = 0
while True:
p = n*n + a*n + b
if not is_prime(p):
if n > max_n:
max_n = n
argmax_n = a, b
break
n += 1
print(max_n, argmax_n, argmax_n[0] * argmax_n[1]) |
20c73e8dc19eb3224516519d285414b36b442005 | khoabangnguyen/JSON-Handlers | /json_to_csv/JsonConverter.py | 2,905 | 3.859375 | 4 | import json
import csv
import os
# Program to convert nested JSON files into flat CSV files
# Helper function to help flatten nested JSON values
def flatten_json(nested_json):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '.')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '.')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out
# Function to convert all JSON files in a directory into a single CSV file
def convert_dir(directory, file_name):
csv_writer = csv.writer(open(file_name, "w", newline=''))
for file_name in os.listdir(directory):
csv_writer.writerow([file_name])
print(file_name)
file_path = directory + file_name
json_in = open(file_path, encoding="utf8")
json_data = json.load(json_in)
flat_json = flatten_json(json_data)
for key, value in flat_json.items():
key_list = [" ",key]
val_list = [value]
key_list.extend(val_list)
print(key_list)
csv_writer.writerow(key_list)
# Function to convert a single file in a directory
def convert_file(file_path, file_name):
csv_writer = csv.writer(open('C:/Users/user/PycharmProjects/jsonConverter/csv_en/' + file_name + ".csv", "w",
newline=''))
json_in = open(file_path, encoding="utf8")
json_data = json.load(json_in)
flat_json = flatten_json(json_data)
for key, value in flat_json.items():
key_list = [key]
val_list = [value]
key_list.extend(val_list)
# print(value) # only for converting Tamil json back
csv_writer.writerow(key_list)
# Function to convert all JSON files in directory to separate CSV Files
def convert_dir_separate(directory):
for file_name in os.listdir(directory):
print(file_name)
file_path = directory + file_name
csv_name = file_name[:-5]
convert_file(file_path, csv_name)
# Niche function to print out translated values with special characters
def get_special_text(file_path):
json_in = open(file_path, encoding="utf-8")
json_data = json.load(json_in)
flat_json = flatten_json(json_data)
for key, value in flat_json.items():
print(value)
# Use functions
# current_path = 'C:/Users/user/PycharmProjects/jsonConverter/en/'
# convert_dir_separate(current_path)
# get_special_text('C:/Users/user/PycharmProjects/jsonConverter/tm/cms_index.json')
convert_dir('C:/Users/user/PycharmProjects/jsonConverter/cms_en/', 'landingCMS.csv')
# convert_file('C:/Users/user/PycharmProjects/jsonConverter/en/occupations.json', 'occupations')
|
2995d9d0ba2a04c3695bf2da89596e0e73538597 | alecmori/project_euler_answers | /answers/problem_33/run_problem.py | 1,848 | 3.890625 | 4 | # -*- coding: utf-8 -*-
import fractions
def run_problem(n=2):
max_num = 10**n
min_num = 10**(n-1)
total_frac = fractions.Fraction(1, 1)
for denom in range(min_num + 1 , max_num):
for numer in range(min_num, denom):
first_digit_numer = int(numer / 10)
second_digit_numer = numer % 10
first_digit_denom = int(denom / 10)
second_digit_denom = denom % 10
if (
first_digit_numer == 0 or
second_digit_numer == 0 or
first_digit_denom == 0 or
second_digit_denom == 0
):
continue
new_frac = None
if first_digit_numer == first_digit_denom:
new_frac = fractions.Fraction(
second_digit_numer,
second_digit_denom,
)
elif first_digit_numer == second_digit_denom:
new_frac = fractions.Fraction(
second_digit_numer,
first_digit_denom,
)
elif second_digit_numer == first_digit_denom:
new_frac = fractions.Fraction(
first_digit_numer,
second_digit_denom,
)
elif second_digit_numer == second_digit_denom:
new_frac = fractions.Fraction(
first_digit_numer,
first_digit_denom,
)
if not new_frac:
continue
orig_frac = fractions.Fraction(numer, denom)
if new_frac == orig_frac:
total_frac *= orig_frac
return total_frac.denominator
if __name__ == '__main__':
answer = run_problem()
if answer == 100:
print('Correct!')
else:
print('Incorrect!')
|
d713d69c7ca2a058981722f24b74ae10934364c9 | petercollingridge/code-for-blog | /language/analyse_frequency.py | 2,667 | 3.671875 | 4 | from utils import get_word_counts, show_in_order, convert_counts_to_percentages
from collections import defaultdict
def get_most_common_words(word_counts, num=10):
common_word_counts = []
for i, (word, count) in enumerate(sorted(word_counts.items(), key=lambda word: -word[1])):
common_word_counts.append((word, count))
if (i == num - 1):
break
return common_word_counts
def get_length_distribution(word_counts):
length_distribution = defaultdict(int)
for word, count in word_counts.items():
length_distribution[len(word)] += count
return length_distribution
def get_letter_counts(word_counts):
letter_counts = defaultdict(int)
for word, count in word_counts.items():
for letter in word:
letter_counts[letter] += count
return letter_counts
def get_starting_letter_counts(word_counts):
first_letters = defaultdict(int)
last_letters = defaultdict(int)
for word, count in word_counts.items():
first_letters[word[0]] += count
last_letters[word[-1]] += count
return first_letters, last_letters
def convert_to_percentage(counts):
total = sum(counts.values())
percentages = dict()
for item, count in counts.items():
percentages[item] = 100 * count / total
return percentages
def find_median_word_length(word_lengths):
middle_word_count = sum(word_lengths.values()) / 2
for word_length, count in sorted(word_lengths.items(), key=lambda item: item[0]):
middle_word_count -= count
if middle_word_count <= 0:
print(word_length)
break
if __name__ == '__main__':
import os
word_counts = get_word_counts(os.path.join('word_lists', 'filtered_word_counts.txt'))
total_word_count = sum(word_counts.values())
# common_word_counts = get_most_common_words(word_counts)
# length_distribution = get_length_distribution(word_counts)
# Mean word count
# print(sum(word * count for word, count in length_distribution.items()) / total_word_count)
# find_median_word_length(length_distribution)
#letter_counts = get_letter_counts(word_counts)
#show_in_order(letter_counts)
first_letters, last_letters = get_starting_letter_counts(word_counts)
percentages = convert_counts_to_percentages(first_letters)
percentages = convert_counts_to_percentages(last_letters)
start_to_end_ratio = {letter: count / (count + last_letters.get(letter, 0)) for letter, count in first_letters.items()}
show_in_order(start_to_end_ratio)
print(list((word, count) for word, count in word_counts.items() if word[-1] == 'x'))
|
7b96af8aef0e4760c93fd819d286691f9ffc0b17 | HitenSidapara/Python3-Bootcamp | /DebuggingAndErrorHandling/Handle.py | 325 | 3.734375 | 4 | # Handle the error
# name
# Gives us the name error
# now handle this error
#
# try:
# name
# except NameError as err:
# print(err);
# Another Example :
def get(d,key):
try:
return d[key]
except KeyError:
return None
d = {"name":"Hiten"}
print(get(d,"name"));
print(get(d,"city"));
|
db96cda3d915c74fd3dc0a3290d95b221aae2b0f | lishulongVI/leetcode | /python3/106.Construct Binary Tree from Inorder and Postorder Traversal(从中序与后序遍历序列构造二叉树).py | 1,447 | 4.03125 | 4 | """
<p>Given inorder and postorder traversal of a tree, construct the binary tree.</p>
<p><strong>Note:</strong><br />
You may assume that duplicates do not exist in the tree.</p>
<p>For example, given</p>
<pre>
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]</pre>
<p>Return the following binary tree:</p>
<pre>
3
/ \
9 20
/ \
15 7
</pre>
<p>根据一棵树的中序遍历与后序遍历构造二叉树。</p>
<p><strong>注意:</strong><br>
你可以假设树中没有重复的元素。</p>
<p>例如,给出</p>
<pre>中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]</pre>
<p>返回如下的二叉树:</p>
<pre> 3
/ \
9 20
/ \
15 7
</pre>
<p>根据一棵树的中序遍历与后序遍历构造二叉树。</p>
<p><strong>注意:</strong><br>
你可以假设树中没有重复的元素。</p>
<p>例如,给出</p>
<pre>中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]</pre>
<p>返回如下的二叉树:</p>
<pre> 3
/ \
9 20
/ \
15 7
</pre>
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
|
4a6513ef15c9d949f432ccadf3fabc08af4fa8ec | xbaysal11/Python | /Encryption/decryptStory.py | 1,284 | 3.875 | 4 | #daniyarovbaysal
def decryptStory():
"""
Using the methods you created in this problem set,
decrypt the story given by the function getStoryString().
Once you decrypt the message, be sure to include as a comment
your decryption of the story.
returns: string - story in plain text
"""
def decryptStory():
"""
Using the methods you created in this problem set,
decrypt the story given by the function getStoryString().
Use the functions getStoryString and loadWords to get the
raw data you need.
returns: string - story in plain text
"""
text = getStoryString()
best = findBestShift(loadWords(), text)
return applyShift(text, best)
# Build data structures used for entire session and run encryption
#
if __name__ == '__main__':
# To test findBestShift:
wordList = loadWords()
#s = applyShift('Hello, world!', 8)
#best = findBestShift(wordList, s)
#assert applyShift(s, best) == 'Hello, world!'
# To test decryptStory, comment the above four lines and uncomment this line:
try:
text = 'Lmlqclqc umpbq: qgknjc pygj gqjylb dyrrcl qmjsrgml'
print applyShift(text,findBestShift(wordList, text))
print decryptStory()
except:
print "All is ok"
|
98db346a5f98ad75d3333dbe3aff0153aef4052c | socio-culturalBrainLab/social_network | /mc/load.py | 3,305 | 3.53125 | 4 | import pandas as pd
import numpy as np
import os
def list_files(path):
"""
MC 14/06/21
Inputs:
path : path of the folder were the focals are stored
Outputs:
list of all the paths to all the files
"""
fichiers = []
for (_,_,files) in os.walk(path): #look at all the files in the folder given by the path
for file in files:
if file.endswith(".xls"):
fichiers.append(os.path.join(path,file)) #add the path of each file in a list
return fichiers
def infos(path):
"""
MC 14/06/21
Inputs:
path : path of the excel file were the infos are stored
Outputs:
table of the infos about the individuals
"""
infos = pd.read_excel(path, index_col='Individuals', sheet_name = 'Infos') #read the sheet named Infos in the excel given by the path
return infos
def kinship(path):
"""
MC 15/06/21
Inputs:
path : path of the excel file were the infos about kinship are stored
Outputs:
matrix of kinship
"""
matrix = pd.read_excel(path, sheet_name='Kinship', index_col=0) #read the kinship sheet of the excel given by the path
#matrix = pd.DataFrame.to_numpy(matrix) #transform the pd DataFrame to a numpy matrix
return matrix
def reorder_files(fichiers, save = False, name=None, path=None):
"""
MC/BK 29/04/21
Inputs:
fichiers : list of the paths to the files to reorder
save : if you want to save the reorder into a new .csv, by default = False
name : name of the new .csv, by default = None
path : where to save the file, by default = None
Outputs:
DataFrame of the files reordered, and a new .csv if save=True
"""
data = pd.read_excel(fichiers[0], encoding="latin-1") #read the first file of the list to get the column names
data_complete = pd.DataFrame(columns=data.columns) #create an empty dataframe with only the columns, where all reordered files will be concatenated
data_tmp = pd.DataFrame(columns=data.columns) #initialisation of the temporary dataframe
for fichier in fichiers: #for each file in the list of files
data = pd.read_excel(fichier, encoding="latin-1") #Read the file
data_reordered = pd.DataFrame(columns=data.columns) #create a new empty dataframe with the same columns as the file to reorder
for i in np.unique(data['Observation date']): #for each different date of observation (if there are several)
data_day = data[data['Observation date']==i] #takes only the data from this date of observation
for j in np.unique(data_day['Subject']): #for each subject followed during this day
data_day_subject = data_day[data_day['Subject']==j] #takes only the data from this subject followed
order = np.argsort(data_day_subject['Start (s)']) #sort the rows of this data depending on their starting times
data_tmp = pd.concat([data_tmp,data_day_subject.iloc[order]]) #concatenate the data following the order of the starting times
data_complete = pd.concat([data_complete, data_tmp]) #concatenate the reordered files in one big dataframe
if save:
data_complete.to_csv(path + name, sep=';', encoding="latin-1")
return data_complete |
93656adccf3266a1b7b5e1b39637108f7a2124ae | Crissky/python_IA | /Perceptron.py | 2,153 | 3.59375 | 4 | class Perceptron:
def __init__(self, dataset, labels, threshold=0.2, learning_rate=0.01, epoches=100):
self.dataset = dataset
self.labels = labels
self.threshold = threshold
self.learning_rate = learning_rate
self.epoches = epoches
self.weights = [0]*len(dataset[0])
def __str__(self):
space = '\n';
text = 'Informações do Perceptron' + space;
text += "Limiar: " + str(self.threshold) + space;
text += "Taxa de aprendizado: " + str(self.learning_rate) + space;
text += "Entradas: " + str(self.dataset) + space;
text += "Pesos: " + str(self.weights) + space;
return text;
def predict(self, inputs):
product_vector = [x * y for x, y in zip(inputs, self.weights)]
sumation = sum(product_vector)
return self.toBinary(sumation)
def toBinary(self, value):
if(value >= self.threshold):
activation = 1
else:
activation = 0
return activation
def fit(self):
print("Iniciando Treinamento com {} épocas...".format(self.epoches))
for epoch in range(self.epoches):
for inputs, label in zip(self.dataset, labels):
output = self.predict(inputs)
delta_weight = list(map(lambda xi: self.learning_rate * (label - output) * xi, inputs))
self.weights = [x + y for x, y in zip(self.weights, delta_weight)]
print("Treinamento Concluído")
if(__name__ == '__main__'):
training_inputs = [(0,0), (0,1), (1,0), (1,1)];
labels = [0, 0, 0, 1]; #AND
#labels = [0, 1, 1, 0]; #XOR
threshold = 0.2;
learning_rate = 0.01;
perceptron = Perceptron(training_inputs, labels, threshold, learning_rate);
print(perceptron)
perceptron.fit()
print("predict [0,0]:", perceptron.predict([0,0]));
print("predict [0,0]:", perceptron.predict([0,1]));
print("predict [0,0]:", perceptron.predict([1,0]));
print("predict [1,1]:", perceptron.predict([1,1]));
print();
print(perceptron);
|
50fb9ca05833e71c30328517097bb0267fe66fb3 | zpoint/Reading-Exercises-Notes | /core_python_programming/8/8-7.py | 338 | 3.75 | 4 | def getfactors(num):
alist = []
for i in range(1,num):
if num % i == 0:
alist.append(i)
return alist
def isperfect(num):
if sum(getfactors(num)) == num:
print 1
else:
print 0
isperfect(int(raw_input('Please enter a number to determine whether it\'s Perfect Number'))) |
97342f0b6bc30b3eed4b5f636e445ba8c5d6a9c2 | chithien0909/Competitive-Programming | /Leetcode/Leetcode - Bitwise AND of Numbers Range.py | 773 | 3.625 | 4 | """
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
"""
import math
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
if m* n == 0: return 0
strM = "{0:b}".format(m)
strN = "{0:b}".format(n)
if len(strM) < len(strN): strM = "0" * (len(strN) - len(strM)) + strM
if len(strN) < len(strM): strN = "0" * (len(strM) - len(strN)) + strN
ans = ["0"] * max(len(strM), len(strN))
for i in range(len(ans)):
if strM[i] != strN[i]: break
else: ans[i] = strM[i]
return int(''.join(ans), 2)
s = Solution()
print(s.rangeBitwiseAnd(1,2)) |
66cb276a6a31a1298a474f8fa582023276f9526d | kckoh/python_tutorial | /python_101/part1/function.py | 335 | 4 | 4 | def factorial (num):
if num is 1:
return 1
else:
return num * factorial(num -1 )
# print factorial(3)
def rgb(r,g,b):
if isinstance(r, int) and isinstance(g, int) and isinstance(b, int) :
print "#%x%x%x" % (r,g,b)
else:
print "r,g,b has to be integer"
rgb(100,10.5,300) |
d72b032aac0f2d0a245dc4b9d086c81565df937b | dq-code/leetcode | /101-SymmetricTree.py | 729 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, n1, n2):
if n1 == None and n2 == None: return True
if n1 and n2 and n1.val == n2.val: return self.isSameTree(n1.left, n2.right) and self.isSameTree(n1.right,
n2.left)
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None: return True
return self.isSameTree(root.left, root.right)
|
59a20f8dce60d54b83fc5a8d4a6aa46e27ec76e4 | priyanshi-mittal/Python-Lab | /Prime.py | 158 | 3.96875 | 4 | x=int(input("Enter a number"))
c=0
for i in range(1,x+1):
if x%i==0:
c+=1
if c==2:
print("prime no.")
else:
print("not prime")
|
0f54d9796fe1f78bff2a44fea034b9f86d31d11e | ssj234/PythonStudy | /sklearn/tu_c2_9.pca.train.py | 1,100 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
matplot = True
# Python机器学习及实践的第二章中的例子,
# 使用手写数字,先对其将维,再训练
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# 导入数据,每条数据65个, 最后一个是结果
digits_train=pd.read_csv('data/optdigits.tra',header=None)
digits_test=pd.read_csv('data/optdigits.tes',header=None)
x_digits=digits_train[np.arange(64)]
y_digits=digits_train[64]
# 导入PCA
from sklearn.decomposition import PCA
estimator=PCA(n_components=2) # 将64维压缩到2维
x_pca=estimator.fit_transform(x_digits)
from matplotlib import pyplot as plt
def plot_pca_scatter():
colors=['black','blue','purple','yellow','white','red','lime','cyan','orange','gray']
for i in range(len(colors)):
px=x_pca[:,0][y_digits.as_matrix() == i]
py=x_pca[:,1][y_digits.as_matrix() == i]
plt.scatter(px,py,c=colors[i])
plt.legend(np.arange(0,10).astype(str))
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.show()
if matplot == True:
plot_pca_scatter()
|
a6c2402662c9c30682f8b87932d9df545286c46e | danilo-montes-code/Playlist-Updator | /UpdatePlaylist.py | 5,670 | 3.8125 | 4 | # Updates a playlist in reference to other playlists
# Pulls data from other playlists and removes songs that are no longer in said playlists
# Basically a playlist merger
# https://spotipy.readthedocs.io/en/latest
# developer.spotify.com
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
# Makes sure that the answer to a posed question is an integer value, repeating the prompt if not
def make_sure_is_a_number(question):
try:
print()
text = input(question).lower()
num = int(text)
except ValueError:
print('Please enter a integer value.')
else:
return num
# adds the ids of the tracks in the given playlist to a list
def add_tracks_to_list(tracks, playlist):
for item in tracks['items']:
playlist.append(item['track']['id'])
while tracks['next']:
tracks = sp.next(tracks)
add_tracks_to_list(tracks, playlist)
return playlist
# Gets the main playlist
def get_main_playlist(playlists):
main_playlist = 'monarchy' # input('What is the name of the main playlist?: ').lower()
for playlist in playlists['items']:
# if you own the playlist and the name of the playlist is the playlist name given by the user, return playlist
if playlist['owner']['id'] == username and playlist['name'].lower() == main_playlist:
return playlist
print('Playlist name does not match any of the public playlists that you own')
get_main_playlist(playlists)
# Gets the playlists that songs are being pulled from
def get_sub_playlists(playlists):
sub_playlist_amount = 2 # make_sure_is_a_number('How many playlists do you want to pull data from?: ')
# while type(sub_playlist_amount) is not int:
# sub_playlist_amount = make_sure_is_a_number('How many playlists do you want to pull data from?: ')
sub_playlist_names = ['monarch v', 'monarch vi'] # []
# for i in range(0, sub_playlist_amount):
# sub_playlist_names.append(input(f'What is the name of playlist #{i+1}?: ').lower())
sub_playlists = []
for playlist in playlists['items']:
if playlist['owner']['id'] == username:
playlist_name_placeholder = playlist['name'].lower()
for sub_playlist in sub_playlist_names:
if sub_playlist == playlist_name_placeholder:
sub_playlists.append(playlist)
return sub_playlists
# Gets the missing tracks
def get_tracks(main_playlist, sub_playlists):
# gets the ids of the songs already in the main playlist
main_playlist_tracks = []
results = sp.user_playlist(username, main_playlist['id'], fields="tracks,next")
tracks = results['tracks']
main_playlist_tracks = add_tracks_to_list(tracks, main_playlist_tracks)
# gets the ids of the songs in the sub playlists
sub_playlist_tracks = []
for playlist in sub_playlists:
results = sp.user_playlist(username, playlist['id'], fields="tracks,next")
tracks = results['tracks']
sub_playlist_tracks = add_tracks_to_list(tracks, sub_playlist_tracks)
# removes duplicate tracks from across the sub playlists
sub_playlist_tracks = list(dict.fromkeys(sub_playlist_tracks))
# returns a list of ids for the missing tracks
return get_missing_tracks(main_playlist_tracks, sub_playlist_tracks)
# Returns the tracks missing from the main playlist that are present in the sub playlists
def get_missing_tracks(main_playlist_songs, sub_playlist_songs):
missing_tracks = []
if len(main_playlist_songs) != 0:
for song in main_playlist_songs:
for sub_song in sub_playlist_songs:
if song != sub_song and not song_is_in_main_playlist(main_playlist_songs, sub_song):
missing_tracks.append(sub_song) # Puts song in the missing songs list
main_playlist_songs.append(sub_song) # Puts in it the main playlist list to not check again
return missing_tracks
else:
return sub_playlist_songs
# returns true if the given song is in the main playlist already
def song_is_in_main_playlist(main_playlist_songs, song):
in_list = False
for track in main_playlist_songs:
if track == song:
in_list = True
break
return in_list
# Removes songs that are not in the sub playlists but is in the main playlist
def remove_songs():
pass
def main():
# gets the playlists from the user
playlists = sp.user_playlists(username)
# sets the main playlist
main_playlist = get_main_playlist(playlists)
# sets the sub playlists
sub_playlists = get_sub_playlists(playlists)
# list of the ids of the missing tracks
tracks = get_tracks(main_playlist, sub_playlists)
for track in tracks:
print(track)
# adds the missing tracks to the main playlist
# scope = 'playlist-modify-public'
# util.prompt_for_user_token(username, scope, 'id',
# 'secret', 'http://localhost:8888/')
# sp.trace = False
# results = sp.user_playlist_add_tracks(username, main_playlist['id'], tracks)
# print(results)
# sp.user_playlist_add_tracks(username, main_playlist['id'], tracks)
if __name__ == '__main__':
# sets up the credentials for the spotipy object
client_credentials_manager = SpotifyClientCredentials(client_id='',
client_secret='')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# the username of the user, taken from spotify uri
username = '22kl7y3a4dhdzvca75vnxxmky'
main()
|
837826234e845fcb720051e740ef4484fe4d0852 | Sreelekshmi-60/Programming-lab | /1.3-7colordiff.py | 210 | 3.796875 | 4 | list1=set(['red','blue','green','white','black'])
list2=set(['green','orange','violet','black','yellow'])
colorlist=list1.difference(list2)
print("Set of colors from list1 not contained in list2 = ",colorlist)
|
79dad1a5e25b039a5182f844d94ed2c06d065c12 | shettysahab/Networks | /Computer-Networks-1/examples/sample.py | 2,876 | 3.65625 | 4 | from socket import *
import ssl
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = "smtp.gmail.com"
port = 587
# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM)
ssl_clientSocket = ssl.wrap_socket(clientSocket,
ca_certs = '/etc/ssl/certs/ca.pem',
cert_reqs = ssl.CERT_REQUIRED,ssl_version=ssl.PROTOCOL_SSLv23)
ssl_clientSocket.connect((mailserver, port))
###################################################################
print "got to here 1"
###############################################################
recv = ssl_clientSocket.recv(1024)
print
print recv
# If the first three numbers of what we receive from the SMTP server are not
# '220', we have a problem
if recv[:3] != '220':
print '220 reply not received from server.'
# Send HELO command and print server response.
heloCommand = 'EHLO \r\n'
ssl_clientSocket.send(heloCommand)
recv1 = ssl_clientSocket.recv(1024)
print recv1
######################################################################
print "Got to here 2"
#####################################################################
# If the first three numbers of the response from the server are not
# '250', we have a problem
if recv1[:3] != '250':
print '250 reply not received from server.'
# Send MAIL FROM command and print server response.
mailFromCommand = 'MAIL From: [email protected]\r\n'
ssl_clientSocket.send(mailFromCommand)
recv2 = ssl_clientSocket.recv(1024)
print recv2
# If the first three numbers of the response from the server are not
# '250', we have a problem
if recv2[:3] != '250':
print '250 reply not received from server.'
# Send RCPT TO command and print server response.
rcptToCommand = 'RCPT To: [email protected]\r\n'
ssl_clientSocket.send(rcptToCommand)
recv3 = ssl_clientSocket.recv(1024)
print recv3
# If the first three numbers of the response from the server are not
# '250', we have a problem
if recv3[:3] != '250':
print '250 reply not received from server.'
# Send DATA command and print server response.
dataCommand = 'DATA\r\n'
ssl_clientSocket.send(dataCommand)
recv4 = ssl_clientSocket.recv(1024)
print recv4
# If the first three numbers of the response from the server are not
# '250', we have a problem
if recv4[:3] != '250':
print '250 reply not received from server.'
# Send message data.
ssl_clientSocket.send(msg)
# Message ends with a single period.
ssl_clientSocket.send(endmsg)
# Send QUIT command and get server response.
quitCommand = 'QUIT\r\n'
ssl_clientSocket.send(quitCommand)
recv5 = ssl_clientSocket.recv(I1024)
print recv5
# If the first three numbers of the response from the server are not
# '250', we have a problem
if recv5[:3] != '221':
print '221 reply not received from server.'
|
c939f22c85e1665432bce018b093d50c7e45a205 | 4dv3ntur3r/Python | /100-Days-of-Code/day-18/main.py | 1,600 | 3.796875 | 4 | import random
import turtle
from random import choice
timmy = turtle.Turtle()
screen = turtle.Screen()
turtle_colors = ["lime green", "cyan", "crimson", "magenta", "deep pink", "dark violet", "dark blue",]
turtle.colormode(255)
#timmy.shape("turtle")
# for _ in range(4):
# timmy.forward(100)
# timmy.right(90)
# for _ in range(15):
# timmy.forward(10)
# timmy.penup()
# timmy.forward(10)
# timmy.pendown()
# def draw_gon(sides):
# angle = 360/sides
# for _ in range(sides):
# timmy.forward(100)
# timmy.right(angle)
#
# for no_of_sides in range(3, 11):
# timmy.color(choice(turtle_colors))
# draw_gon(no_of_sides)
# def art_turtle():
# timmy.pensize(15)
# timmy.speed(0)#fastest
# directions = [0, 90, 180, 360]
# for _ in range(200):
# timmy.color(choice(turtle_colors))
# timmy.forward(30)
# timmy.setheading(choice(directions))
#
# art_turtle()
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return ((r, g, b))
#
# timmy.pensize(15)
# timmy.speed(0)#fastest
# directions = [0, 90, 180, 360]
# for _ in range(200):
# timmy.color(random_color())
# timmy.forward(30)
# timmy.setheading(choice(directions))
timmy.speed(0)
def draw_the_circle_thingy(size_of_gap):
for _ in range(int(360 / size_of_gap)):
timmy.color(random_color())
timmy.circle(100)
timmy.right(size_of_gap) # or can use timmy.setheading(timmy.heading() + size_of_gap)
draw_the_circle_thingy(5)
screen.exitonclick()
|
a340adc9136e662cc23b0cb72d6760d346750482 | mrblack10/tamrin | /jadi/azmon4_3.py | 390 | 3.9375 | 4 | def find_longest_word(input_string):
input_string = input_string.split()
#print(input_string)
maxs = None
maxlen = 0
for s in input_string :
#print ('s:',s)
if len(s)>= maxlen :
maxlen = len(s)
maxs = s
#print (maxlen,maxs,'\n************')
return maxs
input_string = 'armin azarakhsh dos dre toro'
print (find_longest_word(input_string))
|
2be6f72d84d3b86afdf839a5520aa7dce99102df | thecodearrow/LeetCode-Python-Solutions | /Merge Sorted Array.py | 850 | 3.6875 | 4 | #https://leetcode.com/problems/merge-sorted-array/submissions/
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
n=len(nums1)
l2=len(nums2)
if(n==0):
return
if(l2==0):
return
p1=n-l2-1
p2=l2-1
currentIndex=n-1
while p1>=0 and p2>=0:
if(nums1[p1]>=nums2[p2]):
nums1[currentIndex]=nums1[p1]
p1-=1
currentIndex-=1
else:
nums1[currentIndex]=nums2[p2]
p2-=1
currentIndex-=1
while p2>=0:
#left over elements
nums1[currentIndex]=nums2[p2]
p2-=1
currentIndex-=1
|
3dbbbb4a0fcd3c7010dfb705a876afd4baf77940 | simyy/leetcode | /combination-sum.py | 1,947 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/combination-sum/
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target),
find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
"""
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
# Sort candidates to avoid duplicate recurse
sort_candidates = sorted(candidates)
result = []
# Recurse
self.recurse(sort_candidates, target, [], result)
return result
def recurse(self, candidates, target, tmp_nums, result):
# If target is 0, then tmp_nums[] is a valid combination.
if target == 0:
result.append(tmp_nums[:])
return
# If candidates is empty, then return.
if not candidates:
return
# Traverse in candidates
for i in range(len(candidates)):
# Jump the same candidates to avoid duplicate recurse
if i > 0 and candidates[i] == candidates[i - 1]:
continue
if candidates[i] <= target:
# The candidates[i + 1:] is next candidates
self.recurse(candidates[i:], target - candidates[i], tmp_nums + [candidates[i]], result)
else:
break
if __name__ == '__main__':
s = Solution()
print s.combinationSum([2,3,6,7], 7) |
a704862041b009effedab157ec42cacd5695957d | DmitryVlaznev/leetcode | /1551-minimum-operations-to-make-array-equal.py | 1,434 | 3.875 | 4 | # 1551. Minimum Operations to Make Array Equal
# Medium
# You have an array arr of length n where arr[i] = (2 * i) + 1 for all
# valid values of i (i.e. 0 <= i < n).
# In one operation, you can select two indices x and y where 0 <= x, y <
# n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x]
# -=1 and arr[y] += 1). The goal is to make all the elements of the
# array equal. It is guaranteed that all the elements of the array can
# be made equal using some operations.
# Given an integer n, the length of the array. Return the minimum number
# of operations needed to make all the elements of arr equal.
# Example 1:
# Input: n = 3
# Output: 2
# Explanation: arr = [1, 3, 5]
# First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
# In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
# Example 2:
# Input: n = 6
# Output: 9
# Constraints:
# 1 <= n <= 10^4
from utils import checkValue
class Solution:
def minOperations(self, n: int) -> int:
mid, odd = n // 2, n % 2
t = 2 * mid + odd
l = mid - 2 + odd
return l * (t - l - 2) + t - odd
t = Solution()
checkValue(0, t.minOperations(1))
checkValue(1, t.minOperations(2))
checkValue(2, t.minOperations(3))
checkValue(4, t.minOperations(4))
checkValue(6, t.minOperations(5))
checkValue(9, t.minOperations(6))
checkValue(12, t.minOperations(7))
checkValue(16, t.minOperations(8))
|
9ba276d2521de23841146af5a03138d6671167c0 | imarkofu/PythonDemo | /Demo/day07.py | 3,199 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from collections import Iterable
from collections import Iterator
# import builtins
from functools import reduce
print(isinstance([], Iterable))
print(isinstance({}, Iterable))
print(isinstance('abc', Iterable))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance(100, Iterable))
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterator))
print(isinstance({}, Iterator))
print(isinstance('abc', Iterator))
# list、dict、str虽然是Iterable,却不是Iterator
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数
print(isinstance(iter([]), Iterator))
print(isinstance(iter('abc'), Iterator))
# 为什么list、dict、str等数据类型不是Iterator?
# Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据
# Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
# 高阶函数
# 变量可以指向函数
print(abs(-10))
print(abs)
f = abs
print(f)
# 结论:函数本身也可以赋值给变量,即:变量可以指向函数。
print(f(-10))
# 函数名也变量
# abs = 10
# print(abs(-1))
# 把abs指向10后,就无法通过abs(-10)调用该函数了!
# builtins.abs = 10
# 传入函数
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs))
# map/reduce
# map()函数接收两个参数,一个是函数,一个是Iterable
# map将传入的函数依次作用到序列的每个元素
# 并把结果作为新的Iterator返回。
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上
# 这个函数必须接收两个参数
# reduce把结果继续和序列的下一个元素做累积计算
# reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
def add(x, y):
return x + y
print(reduce(add, [1, 3, 5, 7, 9]))
def fn(x, y):
return x * 10 + y
print(reduce(fn, [1, 3, 5, 7, 9]))
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
print(reduce(fn, map(char2num, '13579')))
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def normalize(name):
return name[0].upper() + name[1:].lower()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
def prod(L):
def mul(a, b):
return a * b
return reduce(mul, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
def str2float(s):
i = s.index('.')
return reduce(fn, map(char2num, s[:i])) + reduce(fn, map(char2num, s[i+1:])) * (0.1**len(s[i+1:]))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
|
d2de1248daa9522382bfa206d89cf4caf1de88e5 | naman-32/Python_Snippets | /BASIC/v3.py | 1,088 | 3.8125 | 4 |
courses = ['History' , 'Math', 'Physics', 'CompSci']
print(len(courses))
print(courses[1:3])
print(courses[0])
print(courses[1])
print(courses[:3])
print(courses[1:3])
courses_a = ['art','maths']
#courses.extend(courses_a)
#courses.append(courses_a)
courses.insert(1,courses_a)
print(courses)
courses.remove(courses_a)
print(courses)
courses.remove('History')
print(courses)
courses.sort()
print(courses)
num= [122123,51321,1312231,45454]
num.sort()
print(max(num))
print(min(num))
print(sum(num))
for item in courses:
print(item)
for index,courses2 in enumerate(courses ,start=20):
print(index,courses2)
for i,num2 in enumerate(num,start = 200):
print(i,num2)
courses.reverse()
courses.sort(reverse = True)#T
dc = courses.pop()
print(dc)
print(courses)
num3= [122123,80000000,1312231,45454]
n = sorted(num3)
print(n)
print (courses.index('Math'))
print('Math' in courses)#truefalse
course_join = ' - '.join(courses)
print(course_join)
course_split = course_join.split('-')
print(course_split)
|
db2749b26991284a3f3995e986dafd0f97159286 | ambrocio-gv/PythonConsoleApps | /2c.py | 457 | 3.984375 | 4 | #In
#The program accepts any number of integers, one on one on each line, ranging -100 to 100
#inclusive. Input is terminated by any value that is outside the acceptable range.
#Out
#On a single line, print the sum of all the numbers from the input
x = int(input("x:"))
total = 0
while True:
if (x >= -100 and x <= 100):
total = total + x
x = int(input("x:"))
else:
print(total)
break
|
a132a794d5a97777d88f9eeb571bfd84b4be3483 | lucashsouza/Desafios-Python | /CursoEmVideo/Aula07/ex009.py | 588 | 3.890625 | 4 | num = int(input('Digite um numero e veja sua tabuada: '))
t1 = num * 1
t2 = num * 2
t3 = num * 3
t4 = num * 4
t5 = num * 5
t6 = num * 6
t7 = num * 7
t8 = num * 8
t9 = num * 9
t10 = num * 10
print('A tabuada é: ')
print('{}x1 = {}'.format(num, t1))
print('{}x2 = {}'.format(num, t2))
print('{}x3 = {}'.format(num, t3))
print('{}x4 = {}'.format(num, t4))
print('{}x5 = {}'.format(num, t5))
print('{}x6 = {}'.format(num, t6))
print('{}x7 = {}'.format(num, t7))
print('{}x8 = {}'.format(num, t8))
print('{}x9 = {}'.format(num, t9))
print('{}x10 = {}'.format(num, t10))
|
2de82a7035e6686e412a118504025d50f6ac2844 | JARVVVIS/ds_algo_practice | /hackerrank/6FibTillN.py | 243 | 3.953125 | 4 | ## Print all fibonacci numbers <=n
def main():
n = int(input())
vals = [0,1]
while vals[-1]<=n:
num = sum(vals[-2:])
vals.append(num)
[print(x,end=' ') for x in vals[:-1]]
if __name__ == '__main__':
main() |
d03755090035d43d2109e04fe0f75d7b4a9fc013 | kercheval/Fun_ProjectEuler | /Problem 4/problem4.py | 1,560 | 3.875 | 4 | def is_palindromic(candidate: int):
check_string = str(candidate)
first_index = 0
last_index = -1
while first_index < check_string.__len__():
if check_string[first_index] != check_string[last_index]:
return False
first_index += 1
last_index -= 1
return True
def get_max_palindromic(number_min, number_max) -> int:
max_palindromic = number_max # initial condition
tuple_1 = number_max
tuple_2 = number_max
min_tuple_1 = number_min
min_tuple_2 = number_min
while tuple_1 > min_tuple_2 and tuple_1 > min_tuple_1:
test_product = tuple_1 * tuple_2
# Mod 11 checks added based on analysis described in solution discussion and reduced runtime by 65%
if (tuple_1 % 11 == 0 or tuple_2 % 11 == 0) and is_palindromic(test_product):
print(str(test_product) + " using " + str(tuple_1) + "*" + str(tuple_2))
if (test_product > max_palindromic):
max_palindromic = test_product
min_tuple_2 = tuple_2
tuple_2 = tuple_1 - 1
tuple_1 -= 1
elif tuple_2 <= min_tuple_2:
tuple_2 = tuple_1 - 1
tuple_1 -= 1
else:
tuple_2 -= 1
return max_palindromic
NUMBER_MAX = 999
NUMBER_MIN = 100
# 580085 using 995*583
# 906609 using 993*913
# 886688 using 968*916
# 888888 using 962*924
# 861168 using 932*924
# Max palindromic for 999 is 906609
print("Max palindromic for " + str(NUMBER_MAX) + " is " + str(get_max_palindromic(NUMBER_MIN, NUMBER_MAX)))
|
6a2db4c3b82c6a06385ce51b9670f4bd377a5a33 | mzahn571/PYTHON | /archive/cisco-web-gui-02.py | 977 | 3.53125 | 4 | import requests
import json
import xlsxwriter
# Define variable for RESTful Call
hostname = 'localhost'
url = "http://%s:5000/json/cisco/routes"% hostname
username = 'student'
password = 'student'
# Making RESTful call via python to attain JSON data
data = requests.get(url, auth=(username, password))
format_data = data.content
json_output = json.loads(format_data)
# Create a workbook and add a worksheet.
count = 0
workbook = xlsxwriter.Workbook('/home/student/Desktop/routes.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 2, 24)
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0
for route in json_output['items']:
dest_net = route['destination-network']
dest_int = route['outgoing-interface']
protocol = route['routing-protocol']
worksheet.write(col + count, row, protocol)
worksheet.write(col + count, row + 1, dest_net)
worksheet.write(col + count, row + 2, protocol)
count = count + 1
workbook.close()
|
3c3f6e1d026d692765bb85325471adfb1704d4f7 | moinsoft/Programming-Essential-Python-3 | /exercise_6_2a.py | 110 | 3.890625 | 4 | moin = [3,5,9,6,7,4,1,2]
min = moin[0]
for x in moin[1:]:
if x < min:
min = x
print("Minimum = ",min) |
69039b212084ce581fbf238d60aeb8f56c57c8e8 | n4tm/stem-games | /mypong/natanael.lucena/mypong.py | 4,913 | 4.34375 | 4 | # Jucimar Jr 2019
# Adaptado por Natanael Lucena de Medeiros
# pong em turtle python https://docs.python.org/3.3/library/turtle.html
# baseado em http://christianthompson.com/node/51
# fonte Press Start 2P https://www.fontspace.com/codeman38/press-start-2p
# som pontuação https://freesound.org/people/Kodack/sounds/258020/
import functools
import turtle
import winsound
from random import choice
from pathlib import Path
# import os
# desenhar tela
screen = turtle.Screen()
screen.delay(0)
screen.tracer(0)
screen.title("My Pong")
screen.bgcolor("black")
screen.setup(width=800, height=600)
def general_constructor(a):
a.speed('fastest')
a.shape("square")
a.color("white")
a.penup()
def paddle_draw(p, aux):
general_constructor(p)
p.shapesize(stretch_wid=5, stretch_len=1)
p.penup()
p.goto(-350 * aux, 0)
# desenhar raquetes
paddle_1 = turtle.Turtle()
paddle_2 = turtle.Turtle()
paddle_draw(paddle_1, 1)
paddle_draw(paddle_2, -1)
# desenhar bola
ball = turtle.Turtle()
general_constructor(ball)
ball.goto(0, 0)
ball.dx = 1
ball.dy = 1
# pontuação
score_1 = 0
score_2 = 0
# contorno da tela
space = turtle.Turtle()
space.color("white")
space.penup()
space.goto(400, 300)
space.pendown()
space.pensize(4)
for i in range(8):
if i % 2 != 0:
if i != 3 and i != 7:
space.fd(600)
else:
space.fd(800)
else:
space.rt(90)
space.hideturtle()
# head-up display da pontuação
hud = turtle.Turtle()
general_constructor(hud)
hud.hideturtle()
hud.goto(0, 260)
hud.write("0 : 0", align="center", font=("Press Start 2P", 24, "normal"))
#Menu inicial piscando
eraseable = turtle.Turtle()
eraseable.color("white")
eraseable.hideturtle()
eraseable.up()
eraseable.setposition(0, 0)
ball.hideturtle()
def blink_on():
if not start:
eraseable.write("Press Enter to start", align="center", font=("Press Start 2P", 20, "normal"))
screen.ontimer(blink_off, 300)
else:
eraseable.undo()
def blink_off():
eraseable.undo()
if not start:
screen.ontimer(blink_on, 450)
screen.ontimer(blink_on, 1)
#vincular tecla para iniciar
start = False
def start_pressed():
global start
start = True
turtle.listen()
turtle.onkeypress(start_pressed, "Return")
while not start:
screen.update()
ball.showturtle()
def paddle_up(n1):
if n1 == 1:
p = paddle_1
else:
p = paddle_2
y = p.ycor()
if y < 250:
y += 30
else:
y = 250
p.sety(y)
def paddle_down(n1):
if n1 == 1:
p = paddle_1
else:
p = paddle_2
y = p.ycor()
if y > -250:
y += -30
else:
y = -250
p.sety(y)
# mapeando as teclas
screen.listen()
screen.onkeypress(functools.partial(paddle_up, 1), "w")
screen.onkeypress(functools.partial(paddle_down, 1), "s")
screen.onkeypress(functools.partial(paddle_up, 2), "Up")
screen.onkeypress(functools.partial(paddle_down, 2), "Down")
#path do arquivo de som
s1path = str(Path().absolute()) + "\\arcade-bleep-sound"
s2path = str(Path().absolute()) + "\\bounce.wav"
def collision_treatment_x():
hud.clear()
hud.write("{} : {}".format(score_1, score_2), align="center", font=("Press Start 2P", 24, "normal"))
# os.system("afplay arcade-bleep-sound.wav&")
winsound.PlaySound(s1path, winsound.SND_ASYNC)
ball.goto(0, 0)
# aleatoriedade na direção da bola
n = choice([-1, -1.5, -2, 1, 1.5, 2])
ball.dx *= -1
ball.dy = n
def collision_treatment_y():
winsound.PlaySound(s2path, winsound.SND_ASYNC)
if ball.ycor() < -280:
ball.sety(-280)
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
def paddle_collision_treatment():
ball.dx *= -1
# os.system("afplay bounce.wav&")
winsound.PlaySound(s2path, winsound.SND_ASYNC)
def move_ball():
global score_1, score_2
screen.update()
point = False
# movimentação da bola
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# colisão com paredes inferior e superior
if ball.ycor() > 290 or ball.ycor() < -290:
collision_treatment_y()
# colisão com parede esquerda
if ball.xcor() < -390:
point = True
score_2 += 1
collision_treatment_x()
# colisão com parede direita
if ball.xcor() > 390:
point = True
score_1 += 1
collision_treatment_x()
# colisão com raquetes
if not point:
if ball.xcor() > 330 and paddle_2.ycor() + 50 > ball.ycor() > paddle_2.ycor() - 50:
ball.setx(330)
paddle_collision_treatment()
elif ball.xcor() < -330 and paddle_1.ycor() + 50 > ball.ycor() > paddle_1.ycor() - 50:
ball.setx(-330)
paddle_collision_treatment()
#sincronização de tempo de desenho e movimento
screen.ontimer(move_ball, 1)
move_ball()
#loop da tela para dinâmica de movimento
screen.mainloop() |
4d527669d921bc0be49b8d75a003551ff76f6f8e | bil-bal/cs50-submissions | /Python/Readability/readability.py | 376 | 3.671875 | 4 | from cs50 import get_string
import re
s = get_string("Text: ")
regex = re.compile('[^a-zA-Z]')
L = len(regex.sub("", s))
W = len(re.split(" ", s))
S = len(re.split("! |\. |\? ", s))
index = round(0.0588 * ((L / W) * 100) - 0.296 * ((S / W) * 100) - 15.8)
if index < 1:
print("Before Grade 1")
elif index > 16:
print("Grade 16+")
else:
print(f"Grade {index}") |
ecd40f515408178c70a5426f4607e75bd3188852 | sreenivr/Sudoku | /sudoku.py | 2,700 | 4.125 | 4 | board = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 4, 0, 0, 2, 0, 7, 0],
[0, 0, 0, 0, 1, 3, 2, 8, 0],
[8, 0, 0, 9, 0, 6, 0, 4, 0],
[7, 0, 1, 0, 0, 0, 0, 2, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 8, 0, 0, 0, 0, 5, 3, 7],
[0, 0, 0, 5, 6, 0, 0, 0, 4],
[0, 0, 7, 0, 0, 0, 0, 0, 0],
]
# print the sudoku board
def print_board():
for i in range(len(board)):
if ((i % 3) == 0) and (i != 0):
print("- - - - - - - - - -")
for j in range(len(board[i])):
if ((j % 3) == 0) and (j != 0):
print("|", end="")
print (board[i][j], "", end='')
print()
# Check if the given number is valid at the location specified at the row(r), col(c) on the board(b)
def is_allowed(r, c, num):
if num > 9 or num < 1 or r > 9 or r < 0 or c > 9 or c < 0:
raise Exception("check_valid(): only numbers 1-9 are allowed.")
return False
# Check if the the given num in col
for i in range(9):
if(board[i][c] == num):
return False
# Check if the the given num in row
for i in range(9):
if(board[r][i] == num):
return False
# Check if the num in 3x3 grid
gr = r // 3
gc = c // 3
for i in range(gr*3, gr*3 + 3):
for j in range(gc*3, gc*3 + 3):
#print(i, j, board[i][j])
if board[i][j] == num:
return False
return True
# Check if all the 9x9 locations are filled
def is_empty():
for row in range(9):
for col in range(9):
if board[row][col] == 0:
return True
return False
# Recursive function to solve the Sudoku
def solve():
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
allowed = is_allowed(row, col, num)
if allowed:
board[row][col] = num
solve()
if (is_empty() is False): return
board[row][col] = 0
return
def run(b):
global board
board = b
solve()
if __name__ == '__main__':
# Example board
b = [
[0, 0, 0, 2, 6, 0, 7, 0, 1],
[6, 8, 0, 0, 7, 0, 0, 9, 0],
[1, 9, 0, 0, 0, 4, 5, 0, 0],
[8, 2, 0, 1, 0, 0, 0, 4, 0],
[0, 0, 4, 6, 0, 2, 9, 0, 0],
[0, 5, 0, 0, 0, 3, 0, 2, 8],
[0, 0, 9, 3, 0, 0, 0, 7, 4],
[0, 4, 0, 0, 5, 0, 0, 3, 6],
[7, 0, 3, 0, 1, 8, 0, 0, 0]
]
run(b)
print_board()
|
be601f01069a264ea285dcb5453804432cb693cf | Srini-py/Python | /Sci-Kit/ip_transforms.py | 2,965 | 4 | 4 | '''
In machine learning (especially in graph neural networks), we need to convert the IP addresses into integers starting from 0.
So we need a transformation that converts ips into integers and vice versa. Please note that an ip address should be mapped to the same integer,
whether it is a source ip (src_ip) or a destination ip (dst_ip).
To implement this transformation, we use Transformations from sklearn.preprocessing. Please complete the code in the 4 methods - __init__, fit, transform
and inverse_trasnform
The test cases in the end will verify if the transformation is giving the expected output.
'''
import pandas as pd
from sklearn.base import TransformerMixin
# define a dataframe with source and destination ips
df = pd.DataFrame({
'src_ip': ['1.1.1.1','2.2.2.2','3.3.3.3','1.1.1.1'],
'dst_ip': ['5.5.5.5', '1.1.1.1','6.6.6.6','8.8.8.8']
})
# output expected after the forward transformation
df_transformed_expected = pd.DataFrame({
'src_ip': [0, 1, 2, 0],
'dst_ip': [3, 0, 4, 5]
})
class IpTransform(TransformerMixin):
def __init__(self):
#Call TransformerMixin init
super().__init__()
self.stack = [] #define a list to store all ip addresses for indexing
self.src = [] #source ip list
self.dest = [] #destinataion ip list
def fit(self, df):
df2 = df[:] #create a duplicate
self.src = df2['src_ip'].tolist() #initialize source ip list
self.dest = df2['dst_ip'].tolist() #initialize destination ip list
#create unique list of ip addresses for both source and destination
for ip in self.src:
if ip not in self.stack:
self.stack.append(ip)
for ip in self.dest:
if ip not in self.stack:
self.stack.append(ip)
return self
def transform(self, df):
df2 = df[:] #create a duplicate
for i in range(len(self.src)):
#create fitting values from the model
self.src[i] = self.stack.index(self.src[i])
self.dest[i] = self.stack.index(self.dest[i])
#Transform the text data
df2.src_ip = self.src
df2.dst_ip = self.dest
return df2
def inverse_transform(self, df):
df2 = df[:]
inv_src = [self.stack[self.src[i]] for i in range(len(self.src))]
inv_dest = [self.stack[self.dest[i]] for i in range(len(self.dest))]
#inverse the test data
df2.src_ip = inv_src
df2.dst_ip = inv_dest
return df2
# Define the transformation
ip_transform = IpTransform()
# do the forward transform
df_transformed_output = ip_transform.fit_transform(df)
# do the reverse transform
df_inverse_transformed = ip_transform.inverse_transform(df_transformed_output)
# Run these test cases to verify that the outputs of forward and reverse transform
from pandas.testing import assert_frame_equal
assert_frame_equal(df_transformed_output, df_transformed_expected)
assert_frame_equal(df_inverse_transformed, df)
|
f851ba5a7c9a463f7d0c3cedab7ed992ef207607 | brpadilha/PythonPractice | /aManOrABoy.py | 154 | 3.78125 | 4 | def check (a):
if a > 18:
print ('You are a man')
else:
print ('You are a boy')
age = int(input('How old are you? '))
check(age) |
bbade80c726055ae90d98ca67092cd834587b9ca | manhcuongpbc/tranmanhcuong-lab-c4e18 | /Lab03/homework/ex9.py | 192 | 3.953125 | 4 | def get_even_list(l):
even_list = []
for i in l:
if i % 2 == 0:
even_list.append(i)
return(even_list)
even_list = get_even_list([-1,2,1,3,4,6])
print(even_list) |
3d45724ec562cd03e98bdc875407005e1c642e78 | aaruel/advent-of-code-2017 | /Day 11/day11.py | 901 | 3.734375 | 4 | # Help from here
# https://www.redblobgames.com/grids/hexagons/#coordinates
import functools
path = input().split(",")
distance = lambda x, y: (abs(x) + abs(y) + abs(x+y))/2
move = {
"n": lambda p: {"x": p["x"], "y": p["y"]+1},
"ne": lambda p: {"x": p["x"]+1, "y": p["y"]},
"se": lambda p: {"x": p["x"]+1, "y": p["y"]-1},
"s": lambda p: {"x": p["x"], "y": p["y"]-1},
"sw": lambda p: {"x": p["x"]-1, "y": p["y"]},
"nw": lambda p: {"x": p["x"]-1, "y": p["y"]+1},
}
def part2(key, value):
newpos = move[key](value)
x = value["x"]
y = value["y"]
nx = newpos["x"]
ny = newpos["y"]
ndist = distance(nx, ny)
odist = value["hdist"]
if ndist > odist:
return {"x": nx, "y": ny, "hdist": ndist}
else:
return {"x": nx, "y": ny, "hdist": odist}
xy = functools.reduce(lambda x, y: part2(y, x), path, {"x": 0, "y": 0, "hdist": 0})
print(distance(xy["x"], xy["y"]))
print(xy) |
394565498fe9fb77bb9f8354cd8b7edcb1db343d | egor909/algrtm | /деревья/23.py | 1,593 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def printTree(self):
if self.left:
self.left.printTree()
print(self.data)
if self.right:
self.right.printTree()
def search(self, find):
if find < self.data:
if self.left is None:
return str(find) + " не найдено"
return self.left.search(find)
elif find > self.data:
if self.right is None:
return str(find) + " не найдено"
return self.right.search(find)
else:
return str(self.data) + ' найдено'
root = Node(int(input("введите корень= ")))
arr = input("введите ветви = ").split()
for i in range(len(arr)):
root.insert(int(arr[i]))
print("двоичное дерево= ")
root.printTree()
a = int(input("введите иск. число= "))
print(root.search(a))
while (a != ""):
a = input("введите иск. число = ")
if (a != ""):
print(root.search(int(a)))
|
a874f0cc33df74bb95d0ace9027c31302754628b | EvangelineRebello/Programs | /ass6.py | 2,184 | 3.828125 | 4 | import math
def accept_array(A):
n=int(input("Enter the total number of students"))
print("Input percentage of the students")
for i in range(n):
per=float(input("Enter percentage %d : "%(i+1)))
A.append(per)
print("Student percentage accepted successfully\n\n")
return n
def display_array(A,n):
if(n==0):
print("\nNo records in the database ")
else:
print("Students percentage list : ")
for i in range(n):
print("\t Percentage",i+1,":",A[i],"%")
print("\n")
def InsertionSort(A,n):
for i in range(1,n):
element=A[i]
j=i
while j>0 and A[j-1]>element:
A[j]=A[j-1]
j=j-1
A[j]=element
def ShellSort(A,n):
gap=int(n/2)
while gap>0:
for i in range(gap,n):
temp=A[i]
j=i
while j>=gap and A[j-gap]>temp:
A[j]=A[j-gap]
j-=gap
A[j]=temp
gap=int(gap/2)
def Top(A,n):
ShellSort(A,n)
print("Top 5 scores are : ")
count=0
for i in range(n-1,-1,-1):
count+=1;
print("\t Rank",count,":",A[i],"%")
def Main():
A=[]
while True:
print("\t1 : Accept & Display Students info ")
print("\t2 : Insertion Sort")
print("\t3 : Shell Sort")
print("\t4 : Display top 5 scores")
print("\t5 : exit")
ch = int(input("Enter your choice "))
if(ch==5):
print("End of Program")
quit()
elif(ch==1):
A=[]
n= accept_array(A)
display_array(A,n)
elif(ch==2):
print("Sorting the array in ascending order using Bubble Sort")
InsertionSort(A,n)
display_array(A,n)
elif(ch==3):
print("Sorting the array in ascending order using Selection Sort")
ShellSort(A,n)
display_array(A,n)
elif(ch==4):
print("Top five scores are : ")
Top(A,n)
else:
print("Wrong choice entered!! Try again")
Main()
|
a397c10c0bc6bde27de8eba3eb89c234d58c0f3e | nphucnguyen/python_cc1 | /Algorithm/lab13.py | 3,645 | 3.796875 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(set)
def __str__(self):
return str(dict(self.graph))
def addEdge(self,u,v = None):
if v is None:
self.graph[u]
return
self.graph[u].add(v)
self.graph[v].add(u)
def BFS(self,s):
# mark all the vertices as not visited
visited = set()
queue = []
queue.append(s)
visited.add(s)
while queue:
s = queue.pop(0)
for adjvertice in self.graph[s]:
if adjvertice not in visited:
visited.add(adjvertice)
queue.append(adjvertice)
return visited
def shortestPath_BFS(self,start,goal):
visited = set()
# graph in the BFS
queue = []
queue.append(start)
visited.add(start)
# if the desired node is reached
if start == goal:
print('Same Node')
return -1
count =0
count = self._shortestPath(visited,queue,goal,count)
if goal not in visited:
return -1
return count
def _shortestPath(self,visited,queue,goal,count):
if queue == []:
return count
temp_queue = queue.copy()
for vertex in temp_queue:
queue.pop(0)
for adjvertex in self.graph[vertex]:
if adjvertex == goal:
visited.add(adjvertex)
count +=1
return count
if adjvertex not in visited:
visited.add(adjvertex)
queue.append(adjvertex)
count +=1
return self._shortestPath(visited,queue,goal,count)
# while queue:
# start = queue.pop()
# for adjvertice in self.graph[start]:
# if adjvertice not in visited:
# visited.add(adjvertice)
# queue.append(adjvertice)
g = Graph()
g.addEdge(1,4)
g.addEdge(1,3)
g.addEdge(2,5)
print(g.shortestPath_BFS(3,5))
#lab13.2
# class Graph():
# def __init__(self, V):
# self.V = V
# self.graph = [[0 for column in range(V)] for row in range(V)]
# def isBipartite(self, src):
# # array contain separate bipart: 1 and 0 if it's fill
# colorArr = [-1] * self.V
# # Assign first color to source
# colorArr[src] = 1
# queue = []
# queue.append(src)
# # Run while there are vertices in queue
# while queue:
# u = queue.pop()
# # Return false if there is a self-loop
# if self.graph[u][u] == 1:
# return False
# for v in range(self.V):
# # v is not colored
# if self.graph[u][v] == 1 and colorArr[v] == -1:
# # Assign alternate color to this
# # adjacent v of u
# colorArr[v] = 1 - colorArr[u]
# queue.append(v)
# # An edge from u to v exists and destination
# # v is colored with same color as u
# elif self.graph[u][v] == 1 and colorArr[v] == colorArr[u]:
# return False
# # If we reach here, then all adjacent
# return True
# g = Graph(4)
# g.graph = [[0, 1, 0, 1],
# [1, 0, 1, 0],
# [0, 1, 0, 1],
# [1, 0, 1, 0]
# ]
# print (1 if g.isBipartite(0) else 0)
|
9818a6c2a541296f85e9fe4db4c1c49516287452 | ManuelsPonce/ACC_ProgrammingClasses | /COSC1336-IntroToProgramming/Test/Test 2/John_Fonseca_Test2_LoopFile.py | 3,075 | 3.75 | 4 | import os
#Defining Main
def main():
#Accumulator
total = 0
finalTotal = 0
#Create File to write data to
numFile = open("numbers.txt", 'w')
#Loop 10 times and write each iteration to the file
for count in range(1, 11):
numFile.write(str(count) + '\n')
#Close File
numFile.close()
#Open File
readFile = open("numbers.txt", 'r')
#Read line
line = readFile.readline()
print("**********Numbers.txt**********")
#Read File
while line !='':
#Convert string to number
line = int(line)
#Calculate Total for numbers read
total += line
print("Number Read: ", line)
line = readFile.readline()
#Close the file read
readFile.close()
#Display Calculated Total
print("Calculated Total for Numbers Read: ", total)
#Remove 16, 17 and 18 from file
#Create File to write data to
numFile = open("numbers.txt", 'a')
#Loop 10 times and write each iteration to the file
for count in range(11, 21):
numFile.write(str(count) + '\n')
#Close File
numFile.close()
#Create temp file
tempFile = open("temp.txt", 'w')
#Open File
readFile = open("numbers.txt", 'r')
#Read line
line = readFile.readline()
#Delete numbers 16, 17 and 18 from file
while line != '':
#Convert string to number
line = int(line)
if line != 16 and line != 17 and line != 18:
tempFile.write(str(line) + '\n')
else:
#Value not written to file
print()
#Read next line
line = readFile.readline()
#Close File
tempFile.close()
#Close the file read
readFile.close()
#Change the number 10 to 50
#Create temp file
temp2File = open("temp2.txt", 'w')
#Open File
readFile = open("temp.txt", 'r')
#Read line
line = readFile.readline()
#Change number 10 to 50
while line != '':
#Convert string to number
line = int(line)
if line != 10:
temp2File.write(str(line) + '\n')
else:
temp2File.write("50" + '\n')
#Read next line
line = readFile.readline()
#Close File
temp2File.close()
#Close the file read
readFile.close()
#Remove and Rename Files
os.remove("temp.txt")
os.remove("numbers.txt")
os.rename("temp2.txt", "numbers.txt")
#Display Final Result
#Open File
readFile = open("numbers.txt", 'r')
#Read line
line = readFile.readline()
print("**********Numbers.txt Final Result**********")
#Read File
while line !='':
#Convert string to number
line = int(line)
#Calculate Total for numbers read
finalTotal += line
print("Number Read: ", line)
line = readFile.readline()
#Close the file read
readFile.close()
#Display Calculated Total
print("Calculated Total for Numbers Read: ", finalTotal)
#Calling Main Function
main()
|
5b5f80595a53c01050d4da241f7bfb61c6682b6b | Lnan95/project-Euler | /project Euler 1.py | 685 | 4.34375 | 4 | '''
1.If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
'''
def f(number):
s = 0
for i in range(number):
if (i // 3) * 3 == i or (i // 5) * 5 == i:
s += i
return s
def f2(number):
s = 0
for j in range(number):
if j % 3 == 0 or j % 5 == 0:
s += j
return s
import cProfile
def test(fun,arg,time=10000):
for i in range(time):
fun(arg)
cProfile.run('test(f,1000)') # total time : 1.619
cProfile.run('test(f2,1000)') # total time : 1.062
# %求余的方法值得学习 |
b47565c024fbfa162a0f12dce7e9ce7423c17bb3 | viniciuslopes13/sistemas_inteligentes | /busca em profundidade limitada.py | 710 | 3.5 | 4 | class State:
def __init__(self,n, depth):
self.n = n
self.depth = depth
def initialState():
return State(1,0)
def stackIsEmpty():
return len(stack) == 0
def showState(s):
print(s.n)
def expand(s):
if s.n >= 4:
return []
ret = []
ret.append(State(2*s.n + 1,s.depth+1))
ret.append(State(2*s.n, s.depth+1))
return ret
stack = []
def push(s):
stack.append(s)
def pop():
return stack.pop()
depthLimit = 1
s = initialState()
push(s)
while not stackIsEmpty():
current = pop()
showState(current)
if (current.depth>=depthLimit):
continue
children = expand(current)
for child in children:
push(child)
|
f8cd684a457ca4850903e5fabef63dab68f12fe1 | nurl8n/PP2 | /pygame/drafts4/main.py | 2,812 | 3.53125 | 4 | import pygame
import random
# initialization
pygame.init()
# screen size
screen = pygame.display.set_mode((800, 600))
# downloading an image
backImage = pygame.image.load("bg.png")
# ("./images/bg.png") we can do, ./ means that the same folder, but another path
# name of game
pygame.display.set_caption("GALAXY GAME")
fonts = pygame.font.SysFont('Times new roman', 40)
isDone = False
isBul = False
# downloading other images
bulletImage = pygame.image.load("bullet.png")
enemyImage = pygame.image.load("enemy.png")
playerImage = pygame.image.load("player.png")
score = 0
# starting position
bul_x, bul_y = 220, 460
# changing the position
bul_dx, bul_dy = 0, 0
# starting position
player_x, player_y = 200, 500
last_x = 0
# enemy position, randomly in x,y positions
enemy_x = random.randint(100, 700)
enemy_y = random.randint(20, 50)
# changing the position of enemy
enemy_dx, enemy_dy = 5, 60
def show_player(x, y):
screen.blit(playerImage, (x, y))
def show_enemy(x, y):
screen.blit(enemyImage, (x, y))
def show_bullet(x, y):
screen.blit(bulletImage, (x, y))
# collision of enemy with enemy
def isCollision(enemy_x, enemy_y, bul_x, bul_y):
if bul_x in range(enemy_x, enemy_x + 70) and bul_x in range(enemy_y, enemy_y + 70):
return True
return False
def show_score(x, y):
sc = fonts.render("Score:" + str(score), True, (50, 100, 150))
screen.blit(sc, (x, y))
while not isDone:
for event in pygame.event.get():
if event.type == pygame.QUIT:
isDone = True
# getting the pressed button
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
player_x -= 5
bul_x -= 5
if pressed[pygame.K_RIGHT]:
player_x += 5
bul_x += 5
if (player_x < 0 or player_x > 735) and (bul_x < 0 or bul_x > 735):
player_x = player_x % 735
bul_x = bul_x % 735
enemy_x += enemy_dx
# when enemy hits the wall, it goes another side
if enemy_x < 0 or enemy_x > 735:
enemy_dx = -enemy_dx
enemy_y += enemy_y
screen.blit(backImage, (0, 0))
if bul_x == player_x + 20 and bul_y ==460:
last_x = player_x
if pressed[pygame.K_SPACE]:
isBul = True
if isBul:
bul_y -= 5
bul_x = last_x + 20
if bul_y == 0:
isBul = False
bul_x = player_x + 20
bul_y = 460
isCol = isCollision(enemy_x, enemy_y, bul_x, bul_y)
if isCol and bul_y < 460:
enemy_x = random.randint(100, 700)
enemy_y = random.randint(20, 50)
bul_x = player_x + 20
bul_y = 460
score += 1
isBul = False
# showing the functions
show_player(player_x, player_y)
show_enemy(enemy_x, enemy_y)
show_bullet(bul_x, bul_y)
show_score(650, 60)
pygame.display.update()
|
c847f11c77a52271e194b71ab29dba3136da2c49 | yastil01/two_pointers | /LC_259_three_sum_smallest.py | 556 | 3.65625 | 4 | class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
if len(nums) < 3:
return 0
nums.sort()
count = 0
n = len(nums)
for first in range(n):
second = first + 1
third = n - 1
while second < third:
if nums[first] + nums[second] + nums[third] < target:
count += third-second
second += 1
else:
third -= 1
return count
|
17db071fa3bcb3809f736aa12ee9f3957ef4c35e | ratedRA/python | /Algo/DP/stairs.py | 137 | 3.703125 | 4 | def ways(n):
if n==1:
return 1
if n==2:
return 2
return ways(n-1)+ways(n-2)
n = int(input())
countWays = ways(n)
print(countWays) |
151bbbd0b691acd494d84f4f5c5968a4699b3ed1 | mahimrocky/NumerialMathMetics | /runge_kutta_fourth_order.py | 515 | 3.734375 | 4 | import math
import parser
formula = str(input("Enter the equation:\n"))
code = parser.expr(formula).compile()
def f(x,y):
return eval(code)
print("Enter the value of x0:\n")
x0=float(input())
print("Enter the value of yo:\n")
y0=float(input())
print("Enter the value of h:\n")
h=float(input())
k1=round(float(h*(f(x0,y0))),5)
k2=round(float(h*(f(x0+h/2,y0+k1/2))),5)
k3=round(float(h*(f(x0+h/2,y0+k2/2))),5)
k4=round(float(h*(f(x0+h,y0+k3))),5)
del_y=(k1+(2*k2)+(2*k3)+k4)/6
y=round(y0+del_y,5)
print(y)
|
5c4f2b4dcaa9e94dec00889706cd9d6b6525ed3b | jpspm/PLC | /python/caracteristicas.py | 629 | 3.640625 | 4 | countFLV = 0
person = 0
maxAge = 0
while(1):
age = int(input())
if age != -1:
caracteristicas = list(input().split())
if caracteristicas[0] == 'f' and caracteristicas[1]=='l' and caracteristicas[2] == 'v' and age >= 18 and age <=35:
countFLV+=1
if age > maxAge:
maxAge = age
person+=1
else:
break
print("Mais velho:", maxAge)
if person != 0:
percent = float((countFLV*100)/person)
print("Mulheres com olhos verdes, loiras com 18 a 35 anos: {:.2f}".format(percent)+"%")
else:
print("Mulheres com olhos verdes, loiras com 18 a 35 anos: -nan%") |
a7468e942d30f58de3e6206dfb6e8d402a3e91e4 | peipei1109/P_05_Books | /python_core_programing/18threads/mtsleep5.py | 981 | 3.53125 | 4 | # -*- encoding: utf-8 -*-
'''
Created on 2016年5月14日
@author: LuoPei
'''
import threading
from time import ctime,sleep
loops = [ 4, 2 ]
class MyThread(threading.Thread):
def __init__(self,func,args,name=''):
threading.Thread.__init__(self)
self.name=name
self.func=func
self.args=args
def run(self):
apply(self.func,self.args)
def loop(nloop,nsec):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
print 'starting at:', ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
t=MyThread(loop,(i,loops[i]),loop.__name__)
threads.append(t)
for i in nloops: #start all threads
threads[i].start()
for i in nloops: #wait for completion
threads[i].join()
print 'all DONE at:', ctime()
if __name__=="__main__":
main() |
b450667f8653100dd4ff1acf170f9e343170eb0a | Devoid33/CSC310Project1JacobW | /CSC310Project1JacobWilliams.py | 6,497 | 4.21875 | 4 | """Basic example of an adapter class to provide a stack interface to Python's list."""
# from ..exceptions import Empty
class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty stack."""
self._data = [] # nonpublic list instance
def __len__(self):
"""Return the number of elements in the stack."""
return len(self._data)
def is_empty(self):
"""Return True if the stack is empty."""
return len(self._data) == 0
def push(self, e):
"""Add element e to the top of the stack."""
self._data.append(e) # new item stored at end of list
def top(self):
"""Return (but do not remove) the element at the top of the stack.
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Exception('Stack is empty')
return self._data[-1] # the last item in the list
def pop(self):
"""Remove and return the element from the top of the stack (i.e., LIFO).
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Exception('Stack is empty')
return self._data.pop() # remove last item from list
class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying storage."""
DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
def __init__(self):
"""Create an empty queue."""
self._data = [None] * ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
def is_empty(self):
"""Return True if the queue is empty."""
return self._size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue.
Raise Empty exception if the queue is empty.
"""
if self.is_empty():
raise Exception('Queue is empty')
return self._data[self._front]
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO).
Raise Empty exception if the queue is empty.
"""
if self.is_empty():
raise Exception('Queue is empty')
answer = self._data[self._front]
self._data[self._front] = None # help garbage collection
self._front = (self._front + 1) % len(self._data)
self._size -= 1
return answer
def enqueue(self, e):
"""Add an element to the back of queue."""
if self._size == len(self._data):
self._resize(2 * len(self.data)) # double the array size
avail = (self._front + self._size) % len(self._data)
self._data[avail] = e
self._size += 1
def _resize(self, cap): # we assume cap >= len(self)
"""Resize to a new list of capacity >= len(self)."""
old = self._data # keep track of existing list
self._data = [None] * cap # allocate list with new capacity
walk = self._front
for k in range(self._size): # only consider existing elements
self._data[k] = old[walk] # intentionally shift indices
walk = (1 + walk) % len(old) # use old size as modulus
self._front = 0 # front has been realigned
def radixSort(a):
# Creates several buckets in which to store the values while being sorted at each digit
arrOfQs = [ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(),
ArrayQueue(), ArrayQueue(), ArrayQueue()]
max = a[0]; # Finds the max value of array
for i in range(1, len(a)):
if (a[i] > max):
max = a[i];
count = 0 # Finds the highes amount of digits (10^i) of the max number in array
while max > 0:
if max == 0:
count += 1
count += 1
# Integer divide by ten in order to "count" each digit
max = max // 10
# For each value from zero to the amount of digits of our highest value
for i in range(1, count + 1):
cnt = 0; # -Keeps track of how many are currently in "buckets"
# For each item in array
for j in range(len(a)):
# Set the bucket whose index is equal to the value of the digit in question to the value of item in the array
arrOfQs[a[j] % (10 ** i) // 10 ** (i - 1)].enqueue(a[j])
# For each bucket
for j in range(len(arrOfQs)):
# While there are values in the bucket
while (not arrOfQs[j].is_empty()):
# Cycle pur each value back into the array
a[cnt] = arrOfQs[j].dequeue()
# Note which value we are examining
cnt += 1;
def postFixConvert(e):
numStack = ArrayStack();
for i in range(len(e)): # For every char in the string
if e[i] in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: # If the char in question is a number
numStack.push(int(e[i])) # Add it to the stack
else: # Otherwise (if the value is an operator)
val1 = numStack.pop() # Remove the digits it from the stack and store them
val2 = numStack.pop() # (This is also so we can subtract and divide with out worrying about the order)
if e[i] == "+": # If the operator is 'Add'
numStack.push(val2 + val1) # Push the sum of the two values to the stack
if e[i] == "−": # If the operator is 'Subtract'
numStack.push(val2 - val1) # Push the difference to the stack
if (e[i] == "∗"): # If the operator is 'Multiply'
numStack.push(val2 * val1) # Push the product to the stack
if e[i] == "/": # If the operator is 'Divide'
numStack.push(val2 / val1) # Push the 'Quotient' to the stack
# This ensures that every two values before an operator condensed into one, ensuring we will only have one value at the end
return numStack.pop() # return only value in the stack
if __name__ == '__main__':
Q = [35, 53, 55, 33, 52, 32, 25] # Makes array
print(Q)
radixSort(Q);
print(Q)
print(postFixConvert("52+83−∗4/"))
|
18a60ca4fa6b42b3e20d7db58866940bacc078da | bgnori/online-judge | /project-euler/0019/run.py | 1,797 | 3.828125 | 4 |
"""
1900 Jan 1 is 1st day. 0th day is 1899 Dec 31.
define "day1900" as follows:
1900 Jan 1 is 1
1900 Jan 31 is 31
1900 Feb 1 is 32
1900 Feb 28 is 59
1901 Jan 1 is 366
mod 7 == 1 <=> Monday
"""
def month2days(month, isleap):
# - 1 2 3 4 5 6 7 8 9 10 11 12
usual = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if isleap:
return leap[month]
return usual[month]
def leaptest(year):
"""
>>> leaptest(1900)
False
>>> leaptest(2000)
True
>>> leaptest(1904)
True
>>> leaptest(1903)
False
"""
if year % 4:
return False
elif year % 100 == 0:
if year % 400:
return False
else:
return True
else:
return True
assert False
def day1900(year, month, day):
"""
>>> day1900(1900, 1, 1)
1
>>> day1900(1900, 2, 28)
59
>>> day1900(1900, 3, 1)
60
>>> day1900(1901, 1, 1)
366
>>> day1900(1904, 1, 1) == 365 *4 + 1
True
>>> day1900(1904, 2, 1) == 365 *4 + 31 + 1
True
>>> day1900(1904, 2, 28) == 365 *4 + 31 + 28
True
>>> day1900(1904, 2, 29) == 365 *4 + 31 + 29
True
>>> day1900(1904, 3, 1) == 365 *4 + 31 + 29 + 1
True
>>> day1900(1908, 3, 1) == 365 *8 + 1 + 31 + 29 + 1
True
"""
ys = 0
for y in range(1900, year):
if leaptest(y):
ys += 366
else:
ys += 365
leapy = leaptest(year)
ms = sum([month2days(m, leapy) for m in range(1, month)])
return ys + ms + day
count = 0
for y in range(1901, 2001):
for m in range(1, 13):
if(day1900(y, m, 1) % 7 == 0):
count += 1
print count
|
65455e7dc5f6df7bcbff9ccfbd27220908ad6dfb | ptoche/GDLC | /GDLC/future/skip_split.py | 2,274 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Not thoroughly tested: edge cases probably fail
def skip_split(string, separator=' ', start=None, end=None):
"""
Split a string between two occurrences of the same separator.
Returns:
(head, body, tail)
Modules:
string (separator)
"""
# initialize counters:
a, b, i, j = 0, len(string), 0, 0
if not start:
start = 0
if not end:
end = b
if start >= end:
return ''
print(' start = ', start)
print(' end = ', end)
print(' a = ', a)
print(' b = ', b)
# save the step size:
k = len(separator)
# get the index of the first occurrence:
j = string.find(separator)
if j == -1:
return ''
# search forward every k steps:
while j >= 0 and i <= end:
print(' s[j:j+(k+1)]', s[j:j+(k+1)])
print(' i = ', i)
print(' j = ', j)
if i == start:
a = j
if i == end:
b = j
j = string.find(separator, j+k)
i = i + 1
print(' a = ', a)
print(' b = ', b)
if a >= b:
return ''
return (string[0:a], string[a:b], string[b::])
s = '''<body><div>a</div><div>b</div><div>c</div><div>d</div><div>e</div><div>f</div><div>g</div><div>h</div><div>i</div><div>j</div><div>k</div><div>l</div></body>'''
skip_split(string=s, separator='<div>', start=2, end=3)
skip_split(string=s, separator='<div>', start=0)
skip_split(string=s, separator='<div>', end=2)
# minimal version of the above:
def skip_split(string, separator=' ', start=None, end=None):
"""
Split a string between two occurrences of the same separator.
Returns: (head, body, tail)
"""
# initialize counters:
a, b, i, j = 0, len(string), 0, 0
# save the step size:
k = len(separator)
# get the index of the first occurrence:
j = string.find(separator)
if j == -1:
return ''
# search forward every k steps:
while j >= 0 and i <= end:
if i == start:
a = j
if i == end:
b = j
j = string.find(separator, j+k)
i = i + 1
return (string[0:a], string[a:b], string[b::])
skip_split(string=s, separator='<div>', start=2, end=3)
|
ac464afdde83cc84892e56e463e049f659f98771 | pharick/python-coursera | /week7/8-guess-number-2.py | 335 | 3.671875 | 4 | n = int(input())
numbers = set(range(1, n + 1))
line = input()
while line != "HELP":
question = set(map(int, line.split()))
if len(numbers & question) > len(numbers) / 2:
print("YES")
numbers &= question
else:
print("NO")
numbers -= question
line = input()
print(*sorted(numbers))
|
e4abd0e0cb8020d72062ac83580bd60bb1bf441a | xxrom/5_part_grokaem | /0_simple_multi-input_gradient_decant.py | 1,679 | 3.78125 | 4 | # Neural network
weights = [.1, .2, -.1]
# learn Info
toes = [8.5, 9.5, 9.9, 9.0]
wlrec = [0.65, 0.8, 0.8, 0.9]
nfans = [1.2, 1.3, 0.5, 1]
# ans info
win_or_lose_binary = [1, 1, 0, 1]
# Sum two vectors
def w_sum(a, b):
assert (len(a) == len(b))
output = 0
for i in range(len(a)):
output += a[i] * b[i]
return output
# ele_mul
def vector_multiplier(multiplierNumber, vector):
output = [0, 0, 0]
assert (len(output) == len(vector))
for i in range(len(vector)):
output[i] = multiplierNumber * vector[i]
return output
def neural_network(input, weights):
pred = w_sum(input, weights)
return pred
# Input data
alpha = 0.3 # good choice = 0.01
# with alpha 0.1 - it will be discrapency(расхождение) in weight[0]
# it increases each iteration
true = win_or_lose_binary[0]
input = [toes[0], wlrec[0], nfans[0]]
print('INIT weights: ' + str(weights))
print('-------------')
for index in range(3):
# Prediction and error calculation
pred = neural_network(input, weights)
error = (pred - true)**2
delta = pred - true
print('Iteration: %d' % index)
print('Pred: %.04f' % pred)
print('CubeError: %.04f' % error)
print('Delta: %.04f' % delta)
# Calc change delta (change weights)
weight_deltas = vector_multiplier(delta, input)
# frize changing for first weight
weight_deltas[0] = 0
# IT is important, than NN can learn and get error = 0
# without! changin weight[0] ! overLearning!
# Learning (main change in weights)
for i in range(len(weights)):
weights[i] -= alpha * weight_deltas[i]
print('weights: ' + str(weights))
print('weights deltas: ' + str(weight_deltas))
print('-------------')
|
adfe67028140b151fe3105555d9f5225fbe24c51 | medapalli/Python_UNH | /Homework8/HW8_Prog1.py | 3,569 | 4 | 4 | class Animal():
def __init__(self, name):
self.name=name
def guess_who_am_i(self):
print("I will give you 3 hints, guess what animal I am\n")
while True:
if (self.name=="Elephant"):
print("I have exceptional memory")
str1=input("Who am I?:")
if (str1=="Elephant" or str1=="elephant"):
print("You got it! I am elephant\n")
break
else:
print("Nope, try again!\n")
print("I am the largest land-living mammal in the world\n")
str1=input("Who am I?:")
if (str1=="Elephant" or str1=="elephant"):
print("You got it! I am elephant\n")
break
else:
print("Nope, try again!\n")
print("I Big Trunk")
str1=input("Who am I?:")
if (str1=="Elephant" or str1=="elephant"):
print("You got it! I am elephant\n")
else:
print("I'm out of hints! The answer is: Elephant\n")
break
elif (self.name=="Tiger"):
print("I am the biggest cat")
str1=input("Who am I?:")
if (str1=="Tiger" or str1=="tiger"):
print("You got it! I am tiger\n")
break
else:
print("Nope, try again!\n")
print("I come in black and white or orange and black\n")
str1=input("Who am I?:")
if (str1=="Tiger" or str1=="tiger"):
print("You got it! I am tiger\n")
break
else:
print("Nope, try again!\n")
print("I am wild Animal ")
str1=input("Who am I?:")
if (str1=="Tiger" or str1=="tiger"):
print("You got it! I am tiger\n")
else:
print("I'm out of hints! The answer is: Tiger\n")
break
elif (self.name=="Bat"):
print("I use echo-location")
str1=input("Who am I?:")
if (str1=="Bat" or str1=="bat"):
print("You got it! I am Bat\n")
break
else:
print("Nope, try again!\n")
print("I can fly")
str1=input("Who am I?:")
if (str1=="Bat" or str1=="bat"):
print("You got it! I am Bat\n")
break
else:
print("Nope, try again!\n")
print("I see well in dark")
str1=input("Who am I?:")
if (str1=="Bat" or str1=="bat"):
print("You got it! I am Bat\n")
else:
print("I'm out of hints! The answer is: Bat")
break
e = Animal("Elephant")
t = Animal("Tiger")
b = Animal("Bat")
e.guess_who_am_i()
t.guess_who_am_i()
b.guess_who_am_i()
|
3f9a742dbfe45ddd6157bc4097f1d78f0de0e2e8 | sankeerthankam/Code | /Coderbat/2. Warmup - 2/6. Array Count9.py | 113 | 3.5 | 4 | # Given an array of ints, return the number of 9's in the array.
def array_count9(nums):
return nums.count(9)
|
4a94ad08ce821e198b51c9d10b0075927dcb5f0f | eckelsjd-rose-old/csse120 | /Final Exam/src/problem4.py | 5,219 | 4.03125 | 4 | """
Final exam, problem 4.
Authors: David Mutchler, Dave Fisher, Matt Boutell, their colleagues,
and Joshua Eckels.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import time
def main():
""" Calls the TEST functions in this module. """
run_test_problem4()
def is_prime(n):
"""
What comes in: An integer n >= 2.
What goes out: True if the given integer is prime, else False.
Side effects: None.
Examples:
-- is_prime(11) returns True
-- is_prime(12) returns False
-- is_prime(2) returns True
Note: The algorithm used here is simple and clear but slow.
"""
if n < 2:
return False # Integers less than 2 are treated as NOT prime
for k in range(2, (n // 2) + 1):
if n % k == 0:
return False
return True
# -------------------------------------------------------------------------
# Students:
# Do NOT touch the above is_prime function - it has no TO-DO.
# Do NOT copy code from this function.
#
# Instead, ** CALL ** this function as needed in the problems below.
# -------------------------------------------------------------------------
def run_test_problem4():
""" Tests the problem4 function. """
# Test 1
print('Test 1')
print('-------------')
first_list = [0, 7, 2, 3, 4, 5]
expected_list = [0, -1, -1, -1, 4, -1]
expected_index = 1
actual_index = problem4(first_list)
actual_new_list = first_list
print('Expected index:', expected_index)
print('Actual index:', actual_index)
print()
print('Original List:', [0, 7, 2, 3, 4, 5])
print('Expected new list:', expected_list)
print('Actual new list:', actual_new_list)
print()
# Test 2
print('Test 2')
print('-------------')
first_list = [55, 4, 4, 20]
expected_list = [55, 4, 4, 20]
expected_index = -99
actual_index = problem4(first_list)
actual_new_list = first_list
print('Expected index:', expected_index)
print('Actual index:', actual_index)
print()
print('Original List:', [55, 4, 4, 20])
print('Expected new list:', expected_list)
print('Actual new list:', actual_new_list)
print()
# Test 3
print('Test 3')
print('-------------')
first_list = [55, 55, 7, 31, 4, 2]
expected_list = [55, 55, -1, -1, 4, -1]
expected_index = 2
actual_index = problem4(first_list)
actual_new_list = first_list
print('Expected index:', expected_index)
print('Actual index:', actual_index)
print()
print('Original List:', [55, 55, 7, 31, 4, 2])
print('Expected new list:', expected_list)
print('Actual new list:', actual_new_list)
print()
# -------------------------------------------------------------------------
# DONE: 2. Implement at least THREE tests here.
#
# ** Do NOT use the simpleTestCase form in this problem. **
#
# Instead, use any form you like that clearly demonstrates
# whether the test passed or failed.
#
# Make sure you test different cases, for example, some that return -1
# -------------------------------------------------------------------------
def problem4(integers):
# -------------------------------------------------------------------------
# NOTE: there is an is_prime function near the top of this file.
# -------------------------------------------------------------------------
"""
What comes in:
-- A list of integers.
Side effects:
-- MUTATES the given list of integers so that each prime number in the
list is replaced by -1.
What goes out:
-- Returns the index of the first prime number in the original list
(i.e., the first number that was replaced by -1),
or -99 if the list contained no prime numbers.
Example #1:
integers = [55, 13, 30, 31, 4, 4, 20]
print(integers)
value = problem4(integers)
print(integers)
print(value)
should print:
[55, 13, 30, 31, 4, 4, 20]
[55, -1, 30, -1, 4, 4, 20]
2
Example #2:
integers = [55, 4, 4, 20]
print(integers)
value = problem4(integers)
print(integers)
print(value)
should print:
[55, 4, 4, 20]
[55, 4, 4, 20]
-99
Type hints:
:type integers: list of int
:rtype: int
"""
count = 0
value = -99
for k in range(len(integers)):
number = integers[k]
if is_prime(number):
integers[k] = -1
count += 1
time.sleep(.1)
if count == 1:
value = k
return value
# -------------------------------------------------------------------------
# TODO: 3. Implement and test this function.
# -------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.