blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
1bb1c0e327300b98526b91d88217cd75360260bf | jfernand196/Ejercicios-Python | /concatenar_lista.py | 319 | 3.53125 | 4 | # simular la funcion join
numeros = [2,4,5,77]
#opcion 1
#print('juan'.join([str(n) for n in numeros]))
#print('juan'.join(numeros))
#opcion 2
def concatenar_listas(lista):
resultado= ''
for i in lista:
resultado +=str(i)
return resultado
numeros = [2,4,5,77]
print(concatenar_listas(numeros))
|
30163909aeaaa4efaa8d27365f4631b18390aab4 | jfernand196/Ejercicios-Python | /operador_not.py | 382 | 3.53125 | 4 | #Operador logico de negacion de verdad: NOT
print('Operador logico de negacion de verdad : NOT')
llueve = True
print('contenido de la variable llueve:', llueve)
llueve = not llueve
print('contenido de la variable llueve:', llueve)
print()
edad = 17
resultado = not edad < 18
print('Resultado', resultado)
edad = 19
resultado = not edad < 18
print('Resultado', resultado) |
7b884b25dd4b1f427e61c8259d7673e9f49706cb | jfernand196/Ejercicios-Python | /makeitreal03.py | 390 | 3.953125 | 4 | # Duplica cada elemento
# Escribe una función llamada duplicar que reciba un arreglo de números como parámetro y retorne un
# nuevo arreglo con cada elemento duplicado (multiplicado por dos).
# duplicar([3, 12, 45, 7]) # retorna [6, 24, 90, 14]
# duplicar([8, 5]) # retorna [16, 10]
def duplicar(x):
return [i*2 for i in x]
print(duplicar([3, 12, 45, 7]))
print(duplicar([8, 5])) |
42d3e9a30261a005a547a0957c4e53d2a19d5911 | jfernand196/Ejercicios-Python | /examen_makeitreal.py | 610 | 4.21875 | 4 | # Temperaturas
# Escribe una función llamada `temperaturas` que reciba un arreglo (que representan temperaturas) y
# retorne `true` si todas las temperaturas están en el rango normal (entre 18 y 30 grados) o `false` de
# lo contrario.
# temperaturas([30, 19, 21, 18]) -> true
# temperaturas([28, 45, 17, 21, 17, 70]) -> false
def temperaturas(x):
r= []
for i in x:
o=0
if i>= 18 and i<=30:
r.append(i)
return r
print(temperaturas([30, 19, 21, 18])) #-> true
print(temperaturas([28, 45, 17, 21, 17, 70])) #-> false
|
661cafb9861064d8006a56dceaf4177a0131bf31 | jfernand196/Ejercicios-Python | /gen_num_primos.py | 652 | 3.578125 | 4 | ## Generar n cantidad de numeros primos consecutivos
# 2, 3, 5, 7, 11 ...
def generar_primo():
numero = 2
yield numero
while True:
temp = numero
while True:
temp += 1
contador = 1
contador_divisores = 0
while contador <= temp:
if temp % contador == 0:
contador_divisores +=1
if contador_divisores > 2:
break
contador += 1
if contador_divisores == 2:
yield temp
g = generar_primo()
primos = [next(g) for _ in range(20)]
print(primos)
|
38b85a7e4050e345f3b1eedadb288fcec5dad51a | jfernand196/Ejercicios-Python | /letcode_1678.py | 855 | 4.09375 | 4 | # You own a Goal Parser that can interpret a string command. The command consists of an alphabet
# of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G",
# "()" as the string "o", and "(al)" as the string "al". The interpreted strings are
# then concatenated in the original order.
# Given the string command, return the Goal Parser's interpretation of command.
# Example 1:
# Input: command = "G()(al)"
# Output: "Goal"
# Explanation: The Goal Parser interprets the command as follows:
# G -> G
# () -> o
# (al) -> al
# The final concatenated result is "Goal".
# Example 2:
# Input: command = "G()()()()(al)"
# Output: "Gooooal"
# Example 3:
# Input: command = "(al)G(al)()()G"
# Output: "alGalooG"
command = "G()()()()(al)"
output = command.replace('()', 'o').replace('(al)', 'al')
print(output)
|
342bd4524146685a04fb5bbc20fe03f51d4baedd | jfernand196/Ejercicios-Python | /try_except_else_finally.py | 435 | 3.921875 | 4 | # Programa que le pide al usuario la edad (edad entero) y comprueba
#si ese usuario es mayor de edad (18 años)
try:
numero = int(input('introduce tu edad: '))
except ValueError:
print('no has introduciod un nuemero entero')
else:
if numero >= 18:
print('eres mayo de edad')
else:
print('no eres mayor de edad')
finally:
print('el codigo ha terminado') ## finally se ejecuta siempre
|
d13db4be9d30a72dbe1edb5af5178d3b897fbf4d | jfernand196/Ejercicios-Python | /area_triangulo.py | 466 | 3.859375 | 4 | ## Calcular el area de un triangulo
base = None
altura = None
while True:
try:
base = float(input('escriba la base del triangulo: '))
break
except:
print('Debe de escribir un numero.')
while True:
try:
altura = float(input('escriba la altura del triangulo: '))
break
except:
print('Debe de escribir un numero.')
area = base * altura / 2
print("el area del triangulo es igual a {}".format(area))
|
2b8f6de2b9ac1a87bbc8a2e27df982fb72bef80f | ChetanVDhawan/PythonDataStructures | /LinkedList.py | 2,290 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.start = None
def add(self, data):
node = Node(data)
if self.start is None:
self.start = node
return
temp = self.start
while temp.next is not None:
temp = temp.next
temp.next = node
def pop(self):
if self.start is None or self.start.next is None:
self.start = None
print("[]")
return
temp = self.start
while temp.next.next is not None:
temp = temp.next
temp.next = None
def delete(self,data):
if self.start is None:
print("Nothing to delete")
if self.start.data == data:
self.start = self.start.next
temp = self.start
while temp.next is not None:
if temp.next.data == data:
temp.next = temp.next.next
return
temp =temp.next
print("Data isnt in list")
def length(self):
count = 0
temp = self.start
while temp is not None:
count=count+1
temp = temp.next
print(f"count is {count}")
return count
def insert(self,position,data):
count = 0
node = Node(data)
if position == 0:
self.start,self.start.next = node,self.start
return
temp = self.start
while temp is not None:
if position > 0 and position <= self.length():
if count == position -1:
temp.next, temp.next.next = node, temp.next
else:
print("Index out of bounds")
return
temp = temp.next
count = count + 1
def print(self):
temp = self.start
while temp is not None:
print(temp.data)
temp = temp.next
if __name__ == "__main__":
l1 = LinkedList()
l1.add("Chetan")
l1.add("Dhawan")
l1.add("Prasad")
l1.add("yui")
l1.add("Raj")
l1.delete("hasdhs")
l1.print()
print("=============")
l1.length()
l1.insert(5,"DID")
l1.print()
print("=============")
|
59b2ff13da21c4d38f95749450ba726579c69209 | piranna/asi-iesenlaces | /0708/listas/ej234.py | 568 | 3.96875 | 4 | # -*- coding: cp1252 -*-
#$Id$
"""
Disea un programa que elimine de una lista todos los elementos de
valor par y muestre por pantalla el resultado.
(Ejemplo: si trabaja con la lista [1, -2, 1, -5, 0, 3] sta pasar
a ser [1, 1, -5, 3].)
"""
# mtodo 1: con while
lista = [1, -2, 1, -5, 0, 3]
i = 0
while i < len(lista):
if lista[i] % 2 == 0:
del lista[i]
else:
i += 1
print lista
# mtodo 2: usar remove
lista = [1, -2, 1, -5, 0, 3]
for el in lista:
if el%2 == 0:
lista.remove(el)
print lista
|
bae04ed2f85dc7b04153764d391fedf3f3148106 | piranna/asi-iesenlaces | /0708/examenes/27feb/1234.py | 3,292 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def listadoAlumnos(listaAlumnos, curso, grupo=0):
"""
Entrada: una lista de alumnos como la indicada anteriormente, el nombre de un curso y opcionalmente el número de un grupo.
Devuelve una lista con los datos de los alumnos del curso y grupo indicados. Si no se indica grupo, devolverá todos los alumnos del curso indicado.
"""
resultado = []
for alumno in listaAlumnos:
if grupo:
if alumno[1] == curso and alumno[2]==grupo:
resultado.append(alumno)
else:
if alumno[1] == curso:
resultado.append(alumno)
return resultado
def media(notas):
return sum(notas)/len(notas)
def alumnoMedia(listaAlumnos):
"""
Entrada: una lista de alumnos como la indicada anteriormente.
Devuelve una lista de parejas: nombre de alumno, media de las notas.
"""
resultado = []
for al in listaAlumnos:
resultado.append([al[0], media(al[-1])])
return resultado
def listadoDeAlumnosAprobados(rutaFichero, listaAlumnos, curso, grupo=0):
"""
Entrada: una lista de alumnos como la indicada anteriormente, la ruta de un fichero, el nombre de un curso y opcionalmente el número de un grupo.
Salida: crea un fichero con los datos de los alumnos del curso que aprueban. Si no se especifica grupo, se refiere a todo el curso. Los datos se grabarán con la siguiente estructura:
nombre del alumno; media de las asignaturas
nombre del alumno; media de las asignaturas
nombre del alumno; media de las asignaturas
"""
f = open(rutaFichero, 'w')
alumnos = listadoAlumnos(listaAlumnos, curso, grupo)
medias = alumnoMedia(alumnos)
for al in medias:
if al[1] >= 5:
f.write("%s;%d\n" % (al[0], al[1]))
f.close()
def mejorNota(rutaFichero):
"""
Entrada: una ruta de un fichero que tiene la estructura creada anteriormente.
Salida: imprime en pantalla el alumno (o alumnos) que tienen la mejor nota con el siguiente formato: Nombre de alumno: nota.
"""
f = open(rutaFichero)
mejores = []
mejor = -1 # inicializado con dato no válido
for linea in f:
nombre, nota = linea.split(';')
nota = int(nota)
if nota == mejor:
mejores.append([nombre, nota])
if nota > mejor:
mejor = nota
mejores = [[nombre, nota]]
for nombre, nota in mejores:
print nombre,'-->', nota
if __name__ == '__main__':
# datos de test
lista_alumnos = [
["Pérez, Juan", "ASI", 1, [4, 5, 8, 3] ],
["Alvarez, Maria", "ESI", 2, [8,6,5,9,4]],
["Rivas, Ana", "ASI", 1, [3,4,5]],
["Marcos, Carlos", "ASI", 2, [9,9,9]],
["Vera, Carmen", "ASI", 2, [8,9,10]]
]
# funciones de test
# alumnos de ASI
print listadoAlumnos(lista_alumnos, "ASI")
print
# alumnos de 1º de ASI
print listadoAlumnos(lista_alumnos, "ASI",1)
print
# media de todos los alumnos
print alumnoMedia(lista_alumnos)
print
# media de los de ASI
print alumnoMedia(listadoAlumnos(lista_alumnos, "ASI"))
print
# listado aprobados
listadoDeAlumnosAprobados('aprueban_Asi.txt', lista_alumnos, 'ASI')
mejorNota('aprueban_Asi.txt')
|
4733fe243f4582efe2705f4181188a2920f3f846 | piranna/asi-iesenlaces | /0708/repeticiones/ej118.py | 989 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
$Id$
Realiza un programa que proporcione el desglose en billetes y monedas de
una cantidad entera de euros. Recuerda que hay billetes de 500, 200, 100,
50, 20, 10 y 5 € y monedas de 2 y 1 €.
Debes recorrer los valores de billete y moneda disponibles con uno o más
bucles for-in.
"""
# Presentación
print "*" * 50
print "Desglose de billetes"
print "*" * 50
# Petición de la cantidad
cantidad = int(raw_input("Introduzca un número positivo "))
# Variable para evitar tantas repeticiones
billetes = [500, 200, 100, 50, 20, 10, 5]
for billete in billetes:
parcial = cantidad / billete # división entera: x billetes de billete
if parcial:
print parcial, "billetes de", billete, "euros"
cantidad = cantidad % billete # actualizamos la cantidad que queda por repartir
parcial = cantidad / 2
if parcial:
print parcial, "monedas de 2 euros"
cantidad = cantidad % 2
if cantidad:
print cantidad, "monedas de 1 euro"
|
42bb3d5df47e7eb91425f7a92e19872ed16e3483 | piranna/asi-iesenlaces | /0708/repeticiones/ej109.py | 861 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
$Id$
Calcula el factorial de un número entero positivo que pedimos por teclado
Si tienes dudas de lo que es el factorial, consulta http://es.wikipedia.org/wiki/Factorial
"""
# Presentación
print "*" * 50
print "Programa que calcula el factorial de un número"
print "*" * 50
# Petición del número positivo
numero = int(raw_input("Introduzca un número positivo "))
while numero < 0: # Aseguramos que el número es positivo
numero = int(raw_input("Introduzca un número positivo "))
# Por defecto: factorial de 0 es 1
factorial = 1
for n in range(1, numero + 1): # +1 porque si no range llegaría sólo hasta numero-1
# n va tomando los valores desde 1 hasta numero
factorial = factorial * n
print "El factorial del número", numero, "es", factorial
# Sugerencia: programa el bucle con un while y compara
|
ba9b41a053ff6e6ea6df38fae9807cb3ecd49220 | piranna/asi-iesenlaces | /0708/examenes/23nov/exa10.py | 1,744 | 4.09375 | 4 | # -*- encoding: utf-8 -*-
# $Id$
"""
Escribe una función que reciba una lista de nombres y que imprima la
lista ordenada. La lista tendrá la siguiente estructura:
[ “Ana, Martínez, Blasco”, “Nombre,Apellido1, Apellido2”, ...].
La ordenación se hará según el siguiente criterio:
Apellido1 – apellido2 – Nombre. Es decir, se ordena por el primer
apellido, si coincide, se ordena por el segundo apellido y si coincide
también, se ordena por el nombre. El listado se hará de forma tabulada
dejando 15 espacios para cada elemento.
"""
def esMayor(nombre1, nombre2):
"""
nombre tiene la estructura "Nombre, Apellido1, Apellido2" por eso
hacemos un split(',') para separar la información
Un nombre es mayor, cuando el primer apellido es mayor. Si no se compara
el segundo apellido y en última instancia el nombre
"""
nom1, ape1_1, ape1_2 = nombre1.split(',')
nom2, ape2_1, ape2_2 = nombre2.split(',')
if ape1_1 > ape2_1:
return True
elif ape1_1 == ape2_1:
if ape1_2 > ape2_2:
return True
elif ape1_2 == ape2_2:
if nom1 > nom2:
return True
return False
def ordenaListaNombres(lNombres):
"""
compara apellido1, apellido2 y nombre
"""
for x in range(1, len(lNombres)):
for y in range(len(lNombres)-x):
if esMayor(lNombres[y], lNombres[y+1]):
lNombres[y], lNombres[y+1] = lNombres[y+1], lNombres[y]
lista = ["Ana, Marco, Perez", "Pablo, Marco, Jimenez","Ana, Marco, Jimenez"]
ordenaListaNombres(lista)
print lista |
597e97399626f74acfdadf7a75811a102fa19ff4 | piranna/asi-iesenlaces | /0708/repeticiones/ej129.py | 930 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
$Id$
Haz un programa que calcule el máximo comun divisor (mcd)
de dos enteros positivos.
El mcd es el número más grande que divide exactamente a ambos numeros.
Documentación: http://es.wikipedia.org/wiki/M%C3%A1ximo_com%C3%BAn_divisor
"""
# Presentación
print "*" * 50
print "Programa máximo común divisor"
print "*" * 50
# AVISO: falta validar que so positivos
numero1 = int(raw_input("Introduce el primer número: "))
numero2 = int(raw_input("Introduce el segundo número: "))
# prueba a sustituir esto por una sentencia con if
mayor = max(numero1, numero2)
menor = min(numero1, numero2)
candidato = 1
for valor in range(2, menor + 1):
if mayor % valor == 0 and menor % valor == 0:
candidato = valor
print "El mcd de %d y %d es %d" % (numero1, numero2, candidato)
"""
Propuesta: implementar el algoritmo de euclides:
http://es.wikipedia.org/wiki/Algoritmo_de_Euclides
"""
|
4c4716e3d4b6710d9452f20af531be6c2cd5a9f5 | piranna/asi-iesenlaces | /0708/repeticiones/mayormenor.py | 756 | 3.84375 | 4 | # -*- coding: cp1252 -*-
"""
$Id$
Trabajos con series de nmeros
Mayor, menor, media ...
Cuidado con los valores no vlidos al procesar una serie
"""
num = int(raw_input("Introduce un num positivo: "))
mayor = num # candidato el primero
menor = num
total = 0
veces = 0
while num >=0:
if num > mayor: # Sustituir el que habamos guardado antes
mayor = num
if num < menor: # Sustituir el que habamos guardado antes
menor = num
veces += 1
total += num
num = int(raw_input("Introduce un num positivo: "))
print "El mayor es", mayor
print "El menor es", menor
print "Suma de los nmeros", total
print "Media de los nmeros", total / float(veces)
|
54582356e4fb4257a8066bdcca0f4612837deca9 | piranna/asi-iesenlaces | /0708/repeticiones/esprimo.py | 564 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
$Id$
Calcula si un número es primo. Ej. pág 118.
Hay que mejorar el algoritmo.
"""
num = int(raw_input("Introduzca un número: "))
creo_que_es_primo = True
for divisor in range (2, num ):
if num % divisor == 0:
creo_que_es_primo = False
# Esta parte necesita una mejora. Prueba con un número muy grande
# creo_que_es_primo ya es un booleano.
# No es necesario compararlo creo_que_es_primo == True
if creo_que_es_primo:
print 'El número', num ,'es primo'
else:
print 'El número', num ,'no es primo'
|
3c55d755d5a00cab0e2ef1847d1c90672d6ac23a | zllu2/iMSA_577 | /lessons/Module2/notebooks/helper_code/mlplots.py | 1,071 | 3.734375 | 4 | import pandas as pd
import numpy as np
import seaborn as sns
# Convenience function to plot confusion matrix
# This method produces a colored heatmap that displays the relationship
# between predicted and actual types from a machine learning method.
def confusion(test, predict, labels, title='Confusion Matrix'):
'''
test: true label of test data, must be one dimensional
predict: predicted label of test data, must be one dimensional
labels: list of label names, ie: ['positive', 'negative']
title: plot title
'''
bins = len(labels)
# Make a 2D histogram from the test and result arrays
pts, xe, ye = np.histogram2d(test, predict, bins)
# For simplicity we create a new DataFrame
pd_pts = pd.DataFrame(pts.astype(int), index=labels, columns=labels )
# Display heatmap and add decorations
hm = sns.heatmap(pd_pts, annot=True, fmt="d")
hm.axes.set_title(title, fontsize=20)
hm.axes.set_xlabel('Predicted', fontsize=18)
hm.axes.set_ylabel('Actual', fontsize=18)
return None |
44a036e4b3d596c701892a3905bb27e369f93018 | seanx92/hotel_retrieval | /hotels/search.py | 6,175 | 3.53125 | 4 | import shelve
import time
import heapq
from tokenization import tokenize
def search(name, address, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]):
''' This function is used for finding the conjunctive result by searching by "address" and "name".
'''
address_search_result = searchByAddress(address)
name_search_result = searchByName(name)
if len(address_search_result) == 0 and len(name_search_result) == 0:
return getDefaultData()
elif len(address_search_result) == 0:#if no search resuls for address search return, final result is the result of name search
result = name_search_result
elif len(name_search_result) == 0:#if no search result for name search retuan, final result is the result of address search
result = address_search_result
else:#if both of the address and name search have results, intersect the result
if len(address_search_result) > len(name_search_result):
result = intersect_two(name_search_result, address_search_result)
else:
result = intersect_two(address_search_result, name_search_result)
# if len(result) == 0:#if no result after intersection, use the result of address search as final result
# print "I'm in the no intersected result part"
# result = address_search_result
# print "time before ranking is:", time.time() - start
# print result
return rankResult(result, onlyOverall, tags)
def rankResult(result_ids, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]):
'''This function is used for rank the results by overall rating or tags.
'''
hotel_score = shelve.open('hotels/static/data/hotel_score.db')
result = []
for id in result_ids:
result.append((id, hotel_score[str(id)]))
if onlyOverall:
result = rankByOverall(result)
else:
result = rankByTags(result, tags)
hotel_score.close()
mid3 = time.time()
hotels = shelve.open('hotels/static/data/hotels.db')
for i in range(len(result)):
result[i] = (str(result[i]),hotels[str(result[i])])
hotels.close()
print "read hotel data from db time is:", time.time() - mid3
return result
def rankByOverall(hotel_list):
'''This function rank the input hotel_list with the average overall rating.
'''
temp = []
for hotel_tuple in hotel_list:
temp.append((float(hotel_tuple[1]["overall"]), hotel_tuple[0]))
result = getTopResults(temp)
return result#sorted(hotel_list, key=lambda x: x[1]["average_scores"]["overall"], reverse=True)
def rankByTags(hotel_list, tags):
'''This function rank the input hotel_list with the weighted averaged rating for the given tag list.
'''
length = len(tags)
temp = []
result = []
for hotel_tuple in hotel_list:
score = 0
for tag in tags:
score += hotel_tuple[1][tag]
score /= length
temp.append((score, hotel_tuple[0]))
result = getTopResults(temp)
return result
def getTopResults(hotel_scores):
h = []
result = []
count = 30#how many results need to be return
for h_s in hotel_scores:
if count > 0:
heapq.heappush(h, h_s)
count = count - 1
elif h_s[0] > h[0]:
heap.heappushpop(h, h_s)
h.sort(key=lambda x: x[0], reverse=True)
for hotel_scores in h:
result.append(hotel_scores[1])
return result
def searchByName(name):
'''This function is used for searching by name.
'''
name_hotel = shelve.open('hotels/static/data/index_nameHotel.db')
query_list = tokenize(name)
keys = name_hotel.keys()
result = []
for term in query_list:
if term in keys:
result.append(name_hotel[term])
if len(result) > 1:
result = intersect(result)
elif len(result) == 1:
result = result[0]
name_hotel.close()
return result
def searchByAddress(address):
'''This function is used for searching by address.
'''
address_hotel = shelve.open('hotels/static/data/index_addressToHotel.db')
query_list = tokenize(address)
result = []
keys = address_hotel.keys()
for term in query_list:
if term in keys:
result.append(address_hotel[term])
if len(result) > 1:
result = intersect(result)
elif len(result) == 1:
result = result[0]
address_hotel.close()
return result
def intersect(resultLists):
'''This function is used for intersecting given lists.
'''
resultLists.sort(key=lambda x: len(x))
result = resultLists[0]
i = 1
while i < len(resultLists):
result = intersect_two(result, resultLists[i])
i += 1
return result
def intersect_two(resultList1, resultList2):
'''This function is used for intersecting two given lists.
It is useful for intersect() function and when intersect the search result getting from name searching and address searching.
'''
result = []
i = 0
j = 0
while i < len(resultList1) and j < len(resultList2):
if int(resultList1[i]) == int(resultList2[j]):
result.append(resultList1[i])
i = i + 1
j = j + 1
elif int(resultList1[i]) < int(resultList2[j]):
i = i + 1
else:
j = j + 1
return result
def getDefaultData():
hotels = shelve.open('hotels/static/data/hotels.db')
result = []
i = 30
j = 0
while i > 0:
if str(j) in hotels:
result.append((str(j), hotels[str(j)]))
i = i - 1
j = j + 1
hotels.close()
return result
# start = time.time()
# result = search('hilton', 'new york', False, ["service", "sleep_quality","cleanliness", "location"])
# # result = search('continental','')
# print "uses time:", time.time() - start
# print "there are", len(result), "hits"
# #print result
# for item in result:
# #print item["name"]
# print item[0], item[1]["name"], item[1]["hotel_id"]#, item["address"]
# #print search('', 'hotel', False, ["cleanliness"])'''
|
c10d96e43b1b728b1f42250686fcae0d9aae2b69 | jcguy/AdventOfCode2017 | /problem4.py | 827 | 3.703125 | 4 | #!/usr/bin/env python3
# Advent of Code, Problem 4
# James Corder Guy
def main():
# Part 1
num_valid = 0
with open("problem4.txt") as f:
for line in f:
phrase = line.replace("\n", "").split(" ")
if sorted(phrase) == sorted(list(set(phrase))):
num_valid += 1
print("Part 1: {}".format(num_valid))
# Part 2
num_valid = 0
with open("problem4.txt") as f:
for line in f:
phrase = line.replace("\n", "").split(" ")
new_phrase = []
for word in phrase:
new_phrase.append("".join(sorted(word)))
phrase = new_phrase
if sorted(phrase) == sorted(list(set(phrase))):
num_valid += 1
print("Part 2: {}".format(num_valid))
if __name__ == "__main__":
main()
|
795f82845050e500086eea28a79bdfc9654ed8b7 | anwenliucityu/atomman | /mep/integrator/rungekutta.py | 820 | 3.5 | 4 | # coding: utf-8
def rungekutta(ratefxn, coord, timestep, **kwargs):
"""
Performs Runge-Kutta ODE integration for a timestep.
Parameters
----------
ratefxn : function
The rate function to use.
coord : array-like object
The coordinate(s) of the last timestep.
timestep : float
The timestep value to use.
**kwargs : any
Any extra keyword parameters to pass on to ratefxn.
Returns
-------
array-like object
The coordinate(s) moved forward by timestep.
"""
k1 = timestep * ratefxn(coord, **kwargs)
k2 = timestep * ratefxn(coord - 0.5 * k1, **kwargs)
k3 = timestep * ratefxn(coord - 0.5 * k2, **kwargs)
k4 = timestep * ratefxn(coord - k3, **kwargs)
return coord + k1 / 6 + k2 / 3 + k3 / 3 + k4 / 6 |
f9e60194c6a8df0e7755f45703ca36915db08388 | maisha815/Solitaire_Cypher | /cipher.py | 2,513 | 4.03125 | 4 | import c_functions
import os.path
def validate_file_name(message):
""" (str) -> str
Prompt user the message to type the name of a file. Keep re-prompting
until a valid filename that exists in the same directory as the current
code file is supplied.
Return the name of the file.
"""
file_name = input(message)
while not os.path.exists(file_name):
print("Invalid filename! Please try again.")
file_name = input(message)
return file_name
def choose_encrypt_decrypt():
""" () -> str
Prompt user to enter if they choose the encryption or decryption process.
Keep re-prompting until a valid process is given.
Return the process chosen.
"""
message = 'Shall we encrypt %s or decrypt %s? ' %(
c_functions.ENCRYPT, c_functions.DECRYPT)
process = input(message)
while not (process == c_functions.ENCRYPT or
process == c_functions.DECRYPT):
print('Invalid process! I will ask again...')
process = input(message)
if process == c_functions.ENCRYPT:
print("Okay! Let's Encrypt this message into absolute gibberish!")
elif process == c_functions.DECRYPT:
print("Let's Decrypt this puzzle and see what secret lies ahead!")
return process
def main_operation():
""" () -> NoneType
Perform the chosen process using a deck supplied and a message supplied.
If the process is 'e', encrypt; if 'd', decrypt.
Stop the process if a valid card is not supplied.
"""
prompt_user = 'Enter the filename of the card deck: '
access_deck_file = open(validate_file_name(prompt_user), 'r')
deck_to_use = c_functions.read_deck(access_deck_file)
access_deck_file.close()
if not (c_functions.validate_deck(deck_to_use)):
print('This is not a valid card deck.')
print('Stopping the process.')
return
prompt = 'Enter the filename of the message: '
access_message_file = open(validate_file_name(prompt), 'r')
messages = c_functions.read_message(access_message_file)
access_message_file.close()
# validating a message file is not needed as anything will be
# encrypted or decrypted if it is an alphabet, numerals will be ignored.
process = choose_encrypt_decrypt()
for message in c_functions.process_message(deck_to_use, messages, process):
print(message)
if __name__ == "__main__":
main_operation()
|
a7248417ac7f1924cd5db4323c8b3903bdda1047 | grimsley217/608-mod1 | /range.py | 175 | 4.25 | 4 | #range.py
"""This prints the range of values from the integers provided."""
x=min(47, 95, 88, 73, 88, 84)
y=max(47, 95, 88, 73, 88, 84)
print('The range is', x, '-', y, '.')
|
da79c29a1fa65206d5446bf374974aaef57b09e2 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /lista4_ex_8.py | 265 | 3.640625 | 4 | from random import randint
s1 = str(input("Digite o 1º texto: ").replace("",""))
s2 = str(input("Digite o 2º texto: ").replace("",""))
len_s1 = len(s1)
len_s2 = len(s2)
print(len_s1)
menor = len_s1
if(len_s2<menor):
menor = len_s2
r = randint(0,menor)
print(r)
|
9a28fbd169078b2133058156d9f7c3c8f86d38ae | luiz-vinicius/IP-UFRPE-EXERCICIOS | /aula_lista_ex_2.py | 157 | 4.09375 | 4 | lista = []
for x in range(10):
v = float(input("Digite um valor: "))
lista.append(v)
lista.reverse()
for i,p in enumerate(lista):
print(i+1,"º = ",p)
|
3323f4d0504f59a298ff413e4e79de25f23f79b0 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /lista3_ex_8.py | 291 | 3.75 | 4 | nome = str(input("Digite o nome do funcionário: "))
sal = float(input("Digite o salário bruto do funcionário: "))
des = sal *5/100
sal_liq = sal - des
print("Nome do funcionário: {} \nSalário Bruto {:.2f} \nDesconto: {:.2f} \nSalário Líquido: {:.2f}".format(nome, sal, des, sal_liq))
|
03fc80b0a61c1c6a16672f55488287f969f0a0e3 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /if_ex_9.py | 471 | 3.953125 | 4 | peso = float(input("Digite seu peso: "))
altura = float(input("Digite sua altura: "))
imc = peso/(altura*2)
if(imc<20):
print("Abaixo do peso")
elif(imc>20 and imc<=25):
print("Peso ideal")
elif(imc>25 and imc<=30):
print("Sobrepeso")
elif(imc>30 and imc<=35):
print("Obesidade Moderada")
elif(imc>35 and imc<=40):
print("Obesidade Severa")
elif(imc>40 and imc<=50):
print("Obesidade Mórbida")
else:
print("Super Obesidade") |
91e92a5aaf939ad7a970b43c0e9ac2984d8c3c80 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /lista4_ex_3.py | 109 | 3.796875 | 4 | nome = str(input("Digite o seu nome completo:"))
espaço = nome.split(" ")
print(espaço[-1],",",espaço[0])
|
e7c8dc1d1cf897ec181b2ddf648f0cda2b25af14 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /while_ex_1.py | 523 | 3.796875 | 4 | qnt_alunos = 0
qnt_altura = 0
while True:
idade = int(input("Digite a idade: "))
if(idade<=100 and idade>0):
altura = float(input("Digite a altura: "))
if(altura==0):
break
if(idade>=13):
qnt_alunos +=1
if(altura>=1.5):
qnt_altura +=1
else:
print("Digite uma idade valida!")
print("Quantidade de alunos com mais de 13 anos: {} \nE maiores de que 1.50m: {}".format(qnt_alunos, qnt_altura))
|
1cab19115488ffde362ca1a725cf79bce4d17030 | luiz-vinicius/IP-UFRPE-EXERCICIOS | /if_ex_7.py | 247 | 4.0625 | 4 | v = input("Digite \nM-Matutino \nV-Vespertino \nN-Noturno \n: ")
if(v=='M'or v=='m'):
print("Bom dia!")
elif(v=='V' or v=='v'):
print("Boa Tarde!")
elif(v=='N' or v=='n'):
print("Boa Noite!")
else:
print("Valor Inválido!") |
56aa08c0b985d4c08aba410e2c6f82ce2908be0a | luiz-vinicius/IP-UFRPE-EXERCICIOS | /for_ex_1.py | 596 | 3.59375 | 4 | c = 0
for i in range(10):
qnt = int(input("Digite a quantidade itens vendidos pelo vendedor: "))
if(qnt>0 and qnt<=19):
c = qnt*0.10
print("A comissão do {}º vendedor será de: {}%".format(i+1,c))
elif(qnt>=20 and qnt<50):
c = qnt*0.15
print("A comissão do {}º vendedor será de {}%".format(i+1,c))
elif(qnt>=50 and qnt<75):
c = qnt*0.20
print("A comissão do {}º vendedor será de {}%".format(i+1,c))
else:
c = qnt*0.25
print("A comissão do {}º vendedor será de {}%".format(i+1,c))
|
de9ed90bb6c7ea52a2e457dfcddbe8014ff15f23 | JoelsonSartoriJr/study-astronomy | /Nbody/main.py | 2,983 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from acceleration import acceleration
from energy import energy
def main():
""" Init simulation N-body parameters"""
N = 100 # Number of particles
t = 0 # Time of the simulation
tEnd = 10.0 # time at which simulation ends
dt = 0.01 # timestep
softening = 0.01 # softening length
G = 1.0 # Newtons Gravitational Constant
plotRealTime = True # plotting as the simulation goes along
np.random.seed(42)
mass = 20.0*np.ones((N, 1))/N # total mass of particles is 20
pos = np.random.randn(N, 3)
vel = np.random.randn(N, 3)
# Convert to Center of Mass frame
vel -= np.mean(mass*vel, 0) / np.mean(mass)
# Calculate init gravitational accelerations
acc = acceleration(pos, mass, G, softening)
# Calculate initial energy of system
KE, PE = energy(pos, vel, mass, G)
# Number of timesteps
Nt = int(np.ceil(tEnd/dt))
# Save energies, particles orbits for plotting trails
pos_save = np.zeros((N, 3, Nt+1))
pos_save[:, :, 0] = pos
KE_save = np.zeros(Nt+1)
KE_save[0] = KE
PE_save = np.zeros(Nt+1)
PE_save[0] = PE
t_all = np.arange(Nt+1)*dt
# pre figure
fig = plt.figure(figsize=(4, 5), dpi=80)
grid = plt.GridSpec(3, 1, wspace=0.0, hspace=0.3)
ax1 = plt.subplot(grid[0:2,0])
ax2 = plt.subplot(grid[2, 0])
#simulation Main loop
for i in range(Nt):
vel += acc*dt/2.0
pos += vel*dt
acc = acceleration(pos, mass, G, softening)
vel += acc*dt/2.0
t += dt
KE, PE = energy(pos, vel, mass, G)
# Save energies
pos_save[:, :, i+1] = pos
KE_save[i+1] = KE
PE_save[i+1] = PE
# Plot in real time
if plotRealTime or (i == Nt -1):
plt.sca(ax1)
plt.cla()
xx = pos_save[:,0,max(i-50,0):i+1]
yy = pos_save[:,1,max(i-50,0):i+1]
plt.scatter(xx,yy,s=1,color=[.7,.7,1])
plt.scatter(pos[:,0],pos[:,1],s=10,color='blue')
ax1.set(xlim=(-2, 2), ylim=(-2, 2))
ax1.set_aspect('equal', 'box')
ax1.set_xticks([-2,-1,0,1,2])
ax1.set_yticks([-2,-1,0,1,2])
plt.sca(ax2)
plt.cla()
plt.scatter(t_all,KE_save,color='red',s=1,label='KE' if i == Nt-1 else "")
plt.scatter(t_all,PE_save,color='blue',s=1,label='PE' if i == Nt-1 else "")
plt.scatter(t_all,KE_save+PE_save,color='black',s=1,label='Etot' if i == Nt-1 else "")
ax2.set(xlim=(0, tEnd), ylim=(-300, 300))
ax2.set_aspect(0.007)
plt.pause(0.001)
plt.sca(ax2)
plt.xlabel('time')
plt.ylabel('Energy')
ax2.legend(loc='nbody.png', dpi=240)
return 0
if __name__=="__main__":
main() |
efc673e72bf226503ca35988255ae723ce7b9071 | keerthanachinna/first | /vowel1.py | 176 | 4.125 | 4 | c=input("enter the character")
if(c=='a' or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u'or=='U'):
print (c+,"vowel")
else:
print(c+,"consoant")
|
a7e7e5f0d0d6ea259a65432cfb51d99778ec1aa4 | kaviyakaviyarasan98/practice | /factorial.py | 86 | 3.671875 | 4 | num=int(input())
i=1
fact=1
while(i<=5):
fact=fact*i
i=i+1
print(fact)
|
c4f579fb11e9282776556fe875783bdc04344f59 | kanwar101/Python_Review | /src/Chapter07/parrot.py | 265 | 3.921875 | 4 | prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
active = True
while active:
message = input ("Do you want to Quit? ")
if message != 'quit':
print (message)
else:
active=False
|
7a932affcbd170fa57dcb114ac972460b47e3b54 | kanwar101/Python_Review | /src/Chapter08/pizza.py | 242 | 4.09375 | 4 | def make_pizza(size, *toppings):
"""Print dynamic list of toppings"""
print (f"You ordered {size} pizza with following toppings:")
for topping in toppings:
print (topping)
#make_pizza( size='thin crust','olives', 'peppers','onion')
|
daacca98ea87613f501c1db9e060948ff3e7d018 | kanwar101/Python_Review | /src/Chapter06/aliens.py | 436 | 3.953125 | 4 | aliens_0 = {'color':'green', 'point':5}
alient_1 = {'color':'blue', 'point':7}
alient_2 = {'color':'white', 'point':10}
aliens =[aliens_0,alient_1, alient_2]
for alien in aliens:
print(alien)
print("next item in the list")
empty_aliens = []
for value in range(0,10):
new_alien = {'color':'Orange', 'points':value*2}
empty_aliens.append (new_alien)
print (empty_aliens)
print ("Only first 5 element")
print (empty_aliens[:5]) |
d2ab2cc50739a52b7a3fcfac1af26f54a621bb07 | kanwar101/Python_Review | /src/Chapter11/test_name_function.py | 351 | 3.5 | 4 |
import unittest
from name_function import get_formatted_name
class NameTestCase (unittest.TestCase):
"""Test for the name funtion"""
def test_first_last_name (self):
"""testing formatted names"""
formatted_name = get_formatted_name('Bob', 'Crow')
self.assertEqual ('Bob Crow', formatted_name)
if __name__ == '__main__':
unittest.main()
|
98379659dbbd937bfc5db774006c392ce352f08d | kanwar101/Python_Review | /src/Chapter06/alien.py | 739 | 3.5625 | 4 | alien_0={'key1':'value1', 'key2':'value2','key3':'value3'}
print (alien_0['key1'])
alien_0['key4'] = 'value4'
print (alien_0)
empty_dict={}
empty_dict['system'] = 'HP'
empty_dict['OS'] = 'Chrome'
empty_dict['processor']='intel'
print (empty_dict)
empty_dict['system']='Dell'
print (empty_dict)
# if loop with dictionaries
alien_0={'x_position':0, 'y_position':25, 'speed':'fast'}
print (f"Original Position {alien_0['x_position']}")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment =2
else:
x_increment = 3
alien_0 ['x_position'] = alien_0 ['x_position'] + x_increment
print (alien_0)
# remove value pair from dictionary
del alien_0['speed']
print (alien_0)
# dictionary usage
|
ded6b6fb5db245ede155d1ceb4f9a67a4c68e0b9 | kanwar101/Python_Review | /src/Chapter11/name_function.py | 164 | 3.84375 | 4 |
def get_formatted_name (first, last, middle =''):
"""Print formatted name"""
if middle:
return f"{first} {middle} {last}"
else:
return f"{first} {last}"
|
2790f8ae5a5e897fa6d95dfafd5008c8169f0b53 | kanwar101/Python_Review | /src/Chapter04/slice_list.py | 151 | 3.5 | 4 | players = ['bob','dan','steve','reddy']
print (players[1:3])
print (players[-1:])
print (players[-2:])
for player in players[2:4]:
print (player)
|
b976f86e302748c97bcd5033499a0f2a928bcbdc | taddes/python-blockchain | /data_structures_assignment.py | 1,053 | 4.40625 | 4 | # 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want.
person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']},
{'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']},
{'name': 'Pepper', 'age': 5, 'hobbies': ['hunting', 'eating plants', 'napping']}]
# 2) Use a list comprehension to convert this list of persons into a list of names (of the persons).
name_list = [name['name'] for name in person ]
print(name_list)
# 3) Use a list comprehension to check whether all persons are older than 20.
age_check = all([age['age'] > 20 for age in person ])
print(age_check)
# 4) Copy the person list such that you can safely edit the name of the first person (without changing the original list).
copied_person = person[:]
print(copied_person)
print(person)
# 5) Unpack the persons of the original list into different variables and output these variables.
name, age, hobbies = person
print(name)
print(age)
|
8820ec93b9d0c2cffea06dca6d832ac02b53996b | marboh1126/homework | /hw-3.py | 326 | 3.71875 | 4 | class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bow(self):
print('bowbowbow')
def sayName(self):
print('Name: ' + self.name)
def sayAge(self):
print('Age: ' + str(self.age))
dog = Dog('Masato', 24)
dog.bow()
dog.sayName()
dog.sayAge()
|
866b64d7ad1da8e45faed0f702565fa0544e12c1 | changfenxia/gb-python | /lesson_1/ex_4.py | 558 | 3.9375 | 4 | '''
4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.
'''
number = input("Введите целое положительное число: ")
max = int(number[0])
x = 0
while x < len(number):
if (int(number[x]) > max):
max = int(number[x])
x += 1
print(f"Самое большая цифра в числе {number}: {max}") |
0eea84be3a43149c15164ee857b647d8fc7fd08b | changfenxia/gb-python | /lesson_5/ex_6.py | 1,395 | 3.5 | 4 | '''
6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета и общее количество занятий по нему. Вывести словарь на экран.
Примеры строк файла:
Информатика: 100(л) 50(пр) 20(лаб).
Физика: 30(л) — 10(лаб)
Физкультура: — 30(пр) —
Пример словаря:
{“Информатика”: 170, “Физика”: 40, “Физкультура”: 30}
'''
# helper function to strip non-digits from string
def string_to_int(x):
return int(''.join(filter(str.isdigit, x)))
classes_dict = {}
with open('classes.txt') as my_file:
lines = my_file.read().split('\n')
for line in lines:
subject_name, hours = line.split(':')
hours = [string_to_int(x) for x in hours.split() if len(x) > 1]
classes_dict[subject_name] = sum(hours)
print(classes_dict) |
e1ddd1d2897462bc6d6831993acdd9b9257554b2 | changfenxia/gb-python | /lesson_1/ex_2.py | 503 | 4.3125 | 4 | '''
2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
'''
time_seconds = int(input("Enter time in seconds: "))
hours = time_seconds // 3600
minutes = (time_seconds % 3600) // 60
seconds = time_seconds - (hours * 3600) - (minutes * 60)
print(f"{hours:02d}:{minutes:02d}:{seconds:02d}") |
672968de994d9c62f0edb21db7e9339c8bb2a2dd | felipedelta0/URIOnlineJudge | /1010 - URI Online Judge - Solved.py | 1,202 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago.
Entrada
O arquivo de entrada contém duas linhas de dados. Em cada linha haverá 3 valores, respectivamente dois inteiros e um valor com 2 casas decimais.
Saída
A saída deverá ser uma mensagem conforme o exemplo fornecido abaixo, lembrando de deixar um espaço após os dois pontos e um espaço após o "R$". O valor deverá ser apresentado com 2 casas após o ponto.
Exemplos de Entrada Exemplos de Saída
12 1 5.30 VALOR A PAGAR: R$ 15.50
16 2 5.10
13 2 15.30 VALOR A PAGAR: R$ 51.40
161 4 5.20
1 1 15.10 VALOR A PAGAR: R$ 30.20
2 1 15.10
'''
entrada = input()
entrada2 = input()
numerosStr = entrada.split(" ")
numerosStr2 = entrada2.split(" ")
numeros = [float(num) for num in numerosStr]
numeros2 = [float(num) for num in numerosStr2]
cod, qtd, val = numeros
cod1, qtd1, val1 = numeros2
valf = (qtd * val) + (qtd1 * val1)
print ("VALOR A PAGAR: R$ {:.2f}".format(valf))
|
edd4db95c5ca029c1378e16677318becafac984f | Artamamo/hwsys | /hw.py | 1,778 | 3.75 | 4 | import sys
str = sys.argv
n=0
uppercase = False
EnglishCheck = False
NumberCheck = False
fail = False
Check = False
try:
n=len(str[1])
except:
print("請輸入字串")
if n<8:
print("長度小於8")
sys.exit(0)
elif n>16:
print("長度大於16")
sys.exit(0)
list1 =list(str[1])
for i in range(0,n):
if 65 <= ord(list1[i]) <= 90:
uppercase = True
EnglishCheck = True
if 97 <= ord(list1[i]) <=122:
EnglishCheck = True
if 48 <= ord(list1[i]) <=57:
NumberCheck = True
if (65 <= ord(list1[i]) <= 90) == False and (97 <= ord(list1[i]) <=122) == False and (48 <= ord(list1[i]) <=57) == False:
Check = True
if EnglishCheck == False:
print("缺少英文")
sys.exit(0)
elif uppercase == False:
print("請輸入至少一個大寫英文")
sys.exit(0)
elif NumberCheck == False:
print("缺少數字")
sys.exit(0)
elif Check == False:
print("缺少符號")
sys.exit(0)
temp = list1[0]
for i in range(1,n):
if ord(temp)+1 == ord(list1[i]) and ord(temp)!=64 and ord(temp)!=47 and ord(temp)!=96 :
continuous = True
if 65 <= ord(list1[i]) <=90:
print("大寫英文不可連續")
fail = True
elif 97 <= ord(list1[i]) <=122:
print("小寫英文不可連續")
fail = True
elif 48 <= ord(list1[i]) <=57:
print("數字不可連續")
fail = True
else:
continuous = False
temp = list1[i]
if fail == True:
sys.exit(0)
if continuous == False and uppercase == True and EnglishCheck == True and NumberCheck == True:
print("success")
|
95cbcc07243fb919699df576b9bb1458637ddd49 | sroy8091/daily_coding_problem | /find_missing_positive.py | 1,039 | 3.859375 | 4 | """
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3
"""
def swap_positions(list, pos1, pos2):
get = list[pos1], list[pos2]
list[pos2], list[pos1] = get
return list
def segregate(arr):
j = 0
for i in range(len(arr)):
if arr[i] <= 0:
swap_positions(arr, i ,j)
j += 1
return j
def find_missing(arr):
j = segregate(arr)
for i in range(j, len(arr)):
if arr[i] - 1 < len(arr)-1 and arr[arr[i]-1] > 0:
arr[arr[i]-1] = -arr[arr[i]-1]
for i in range(len(arr)):
if arr[i] > 0:
return i + 1
def main():
arr = [3, 4, -1, 1]
print(find_missing(arr))
if __name__=="__main__":
main() |
4d22bc86b5997a8b622aebd80dc81a956863a926 | RDH06/Python | /28-07-2018classprogram/Some_Process.py | 598 | 3.546875 | 4 | import os
def File_to_Listwrds(fname):
if not os.path.isfile(fname):
return[]
wordlst = []
with open(fname,'r') as fob:
wordlst = []
for walk in fob:
flst = walk.strip("\n").split()
wordlst.extend(flst)
return wordlst
def search_word(wlst,word):
rlst=[]
for walk in wlst:
if word in walk:
rlst.append(walk)
return rlst
def word_count(wlst,word):
count = 0
for walk in wlst:
if walk == word:
count +=1
return count
|
f4b1f6480bbe645be84bbfc89b23b224bc87435c | kishannerella/CSE537 | /P3/submit.py | 4,025 | 3.625 | 4 | #do not modify the function names
#You are given L and M as input
#Each of your functions should return the minimum possible L value
#Or return -1 if no solution exists for the given L
#Your backtracking function implementation
import time
def isSafe(assignments,marker):
assignments[marker] = 1
keys = assignments.keys()
dist = []
for i in range(0,len(keys)-1):
for j in range(i+1,len(keys)):
if assignments[i] == 1 and assignments[j] == 1:
if (j-i) in dist:
assignments[marker] = 0
return False
dist.append(j - i)
assignments[marker] = 0
return True
def isSafefinal(assignments):
keys = assignments.keys()
dist = []
for i in range(0,len(keys)-1):
for j in range(i+1,len(keys)):
if assignments[i] == 1 and assignments[j] == 1:
if (keys[j] - keys[i]) in dist:
return False
dist.append(keys[j] - keys[i])
#print sorted(dist)
return True
def print_ans(assignments):
keys = assignments.keys()
ans = []
for key in keys:
if(assignments[key]==1):
ans.append(key)
print ans
print "\n"
def BTUtil(L,M,assignments,start):
counter = M
if counter == 0:
#print assignments
if isSafefinal(assignments):
print_ans(assignments)
return False
return False
for i in range(start,L+1):
if(isSafe(assignments,i)):
assignments[i] = 1
counter = counter - 1
x = BTUtil(L,counter,assignments,i+1)
if x == False:
counter = counter + 1
assignments[i] = 0
else:
return True
return False
#print assignments
def BT(L, M):
"*** YOUR CODE HERE ***"
counter = M
assignments = {}
return BTUtil(L,M,assignments,0)
return -1
def FCassigmnets(assignments,counter,marker):
assignments[marker] = 1
keys = assignments.keys()
#print assignments
dist = []
for i in range(0,len(keys)-1):
for j in range(i+1,len(keys)):
if assignments[i] == 1 and assignments[j] == 1:
if (j-i) in dist:
assignments[marker] = 0
return False
dist.append(j - i)
remaining = [key for key,val in assignments.items() if val==0 and key>marker]
count = len(remaining)
for item in remaining:
for key in keys:
if assignments[key] == 1 and (item - key) in dist:
count = count - 1
break
assignments[marker] = 0
if count >= counter:
return True
return False
def FCUtil(L,M,assignments,start):
counter = M
if counter == 0:
#print assignments
if isSafefinal(assignments):
print_ans(assignments)
return False
return False
for i in range(start,L+1):
if(FCassigmnets(assignments,counter-1,i)):
assignments[i] = 1
counter = counter - 1
x = FCUtil(L,counter,assignments,i+1)
if x == False:
counter = counter + 1
assignments[i] = 0
else:
return True
return False
#Your backtracking+Forward checking function implementation
def FC(L, M):
"*** YOUR CODE HERE ***"
counter = M
assignments = {}
remaining = range(0,L+1)
for item in remaining:
assignments[item] = 0
#print remaining
return FCUtil(L,M,assignments,0)
return -1
#Bonus: backtracking + constraint propagation
def CP(L, M):
"*** YOUR CODE HERE ***"
return -1
print time.time()
BT(34,8)
print time.time()
FC(34,8)
print time.time() |
920f126b9081a52fd2882375de6a026e29470590 | teamroke/tessas_first_program | /Tessa.py | 378 | 3.609375 | 4 | import random
def get_name(weather):
nickname = input('What is your nickname? ')
print(f'That is funny, hello {nickname}')
print(f'It is {weather} outside!')
return nickname
for i in range(1,5):
print(f'You rolled a: {random.randint(1,20)}')
print('argh!')
name = input('What is your name? ')
print(f'Hello, {name}!')
nick = get_name('sunny')
print(nick)
|
255f6298f6215d04542086661c9fb3c8121d7f76 | lhotse-speech/lhotse | /lhotse/parallel.py | 2,663 | 3.71875 | 4 | import queue
import threading
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from typing import Callable, Generator, Iterable
def parallel_map(
fn: Callable,
*iterables: Iterable,
num_jobs: int = 1,
queue_size: int = 5000,
threads: bool = False,
) -> Generator:
"""
Works like Python's ``map``, but parallelizes the execution of ``fn`` over ``num_jobs``
subprocesses or threads.
Under the hood, it spawns ``num_jobs`` producer jobs that put their results on a queue.
The current thread becomes a consumer thread and this generator yields items from the queue
to the caller, as they become available.
Example::
>>> for root in parallel_map(math.sqrt, range(1000), num_jobs=4):
... print(root)
:param fn: function/callable to execute on each element.
:param iterables: one of more iterables (one for each parameter of ``fn``).
:param num_jobs: the number of parallel jobs.
:param queue_size: max number of result items stored in memory.
Decreasing this number might save more memory when the downstream processing is slower than
the producer jobs.
:param threads: whether to use threads instead of processes for producers (false by default).
:return: a generator over results from ``fn`` applied to each item of ``iterables``.
"""
thread = SubmitterThread(
fn, *iterables, num_jobs=num_jobs, queue_size=queue_size, threads=threads
)
thread.start()
q = thread.queue
while thread.is_alive() or not q.empty():
try:
yield q.get(block=True, timeout=0.1).result()
except queue.Empty:
# Hit the timeout but thread is still running, try again.
# This is needed to avoid hanging at the end when nothing else
# shows up in the queue, but the thread didn't shutdown yet.
continue
thread.join()
class SubmitterThread(threading.Thread):
def __init__(
self,
fn: Callable,
*iterables,
num_jobs: int = 1,
queue_size: int = 10000,
threads: bool = False,
) -> None:
super().__init__()
self.fn = fn
self.num_jobs = num_jobs
self.iterables = iterables
self.queue = queue.Queue(maxsize=queue_size)
self.use_threads = threads
def run(self) -> None:
executor = ThreadPoolExecutor if self.use_threads else ProcessPoolExecutor
with executor(self.num_jobs) as ex:
for args in zip(*self.iterables):
future = ex.submit(self.fn, *args)
self.queue.put(future, block=True)
|
56aeca5ce7c3654160344be4329f5a8b821c16f8 | shadowleaves/deep_learning | /cnn/tflayer_text_cnn.py | 5,843 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple example using convolutional neural network to classify IMDB
sentiment dataset.
References:
- Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng,
and Christopher Potts. (2011). Learning Word Vectors for Sentiment
Analysis. The 49th Annual Meeting of the Association for Computational
Linguistics (ACL 2011).
- Kim Y. Convolutional Neural Networks for Sentence Classification[C].
Empirical Methods in Natural Language Processing, 2014.
Links:
- http://ai.stanford.edu/~amaas/data/sentiment/
- http://emnlp2014.org/papers/pdf/EMNLP2014181.pdf
"""
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import tensorlayer as tl
import numpy as np
# from tensorlayer.prepro import pad_sequences
# import tflearn
# from tflearn.layers.core import input_data, dropout, fully_connected
# from tflearn.layers.conv import conv_1d, global_max_pool
# from tflearn.layers.merge_ops import merge
# from tflearn.layers.estimator import regression
from tflearn.data_utils import to_categorical, pad_sequences
from tflearn.datasets import imdb
# IMDB Dataset loading
train, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000,
valid_portion=0.1)
X_train, y_train = train
X_val, y_val = test
# Data preprocessing
# Sequence padding
X_train = pad_sequences(X_train, maxlen=100, value=0.)
X_val = pad_sequences(X_val, maxlen=100, value=0.)
y_train = np.array(y_train, dtype='int32')
y_val = np.array(y_val, dtype='int32')
# Converting labels to binary vectors
# y_train = to_categorical(y_train, nb_classes=2)
# Y_val = to_categorical(Y_val, nb_classes=2)
# Building convolutional network
# embedding
sess = tf.InteractiveSession()
embd_dims = 128
nbf = 128 # doesn't have to be equal to embedding dims
x = tf.placeholder(tf.int32, shape=[None, 100], name='x')
y_ = tf.placeholder(tf.int64, shape=[None, ], name='y_')
# network = tl.layers.InputLayer(x, name='input')
network = tl.layers.EmbeddingInputlayer(inputs=x,
vocabulary_size=10000,
embedding_size=embd_dims,
name='embedding_layer')
branch1 = tl.layers.Conv1dLayer(network,
act=tf.nn.relu,
shape=[3, nbf, nbf],
stride=1,
padding='VALID',
name='branch1',
)
branch2 = tl.layers.Conv1dLayer(network,
act=tf.nn.relu,
shape=[4, nbf, nbf],
stride=1,
padding='VALID',
name='branch2',
)
branch3 = tl.layers.Conv1dLayer(network,
act=tf.nn.relu,
shape=[5, nbf, nbf],
stride=1,
padding='VALID',
name='branch3',
)
# reg1 = tf.contrib.layers.l2_regularizer(0.01)(branch1.all_layers[-1])
# reg2 = tf.contrib.layers.l2_regularizer(0.01)(branch2.all_layers[-1])
# reg3 = tf.contrib.layers.l2_regularizer(0.01)(branch3.all_layers[-1])
network = tl.layers.ConcatLayer([branch1, branch2, branch3],
concat_dim=1, name='concat_layer')
network = tl.layers.ExpandDimsLayer(network, axis=3, name='expand_dims')
shape = [z.value if z.value else -1 for z in
network.all_layers[-1].shape.dims[:-1]]
network = tl.layers.ReshapeLayer(network, shape=shape)
# network = tl.layers.ExpandDimsLayer(network, axis=3, name='expand_dims')
k = network.all_layers[-1].shape[1].value
network = tl.layers.MaxPool1d(network,
# filter_size=[k, 1],
filter_size=k,
strides=1,
# padding='valid',
)
network = tl.layers.FlattenLayer(network)
network = tl.layers.DropoutLayer(network, keep=0.5)
network = tl.layers.DenseLayer(network, n_units=2, act=tf.identity)
network.print_layers()
# define cost function and metric.
y = network.outputs
# y_ = tf.reshape(y_, [32, 2])
# y = tf.reshape(y, [32, 2])
# y_op = tf.argmax(tf.nn.softmax(y), 1)
cost = tl.cost.cross_entropy(y, y_, 'cost') # + reg1 + reg2 + reg3
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
y_op = tf.argmax(tf.nn.softmax(y), 1)
# define the optimizer
train_params = network.all_params
train_op = tf.train.AdamOptimizer(
learning_rate=0.001, beta1=0.9, beta2=0.999,
epsilon=1e-08,
use_locking=False,
).minimize(cost, var_list=train_params)
# initialize all variables in the session
tl.layers.initialize_global_variables(sess)
# print network information
network.print_params()
network.print_layers()
# train the network
tl.utils.fit(sess, network, train_op, cost, X_train, y_train, x, y_,
acc=acc,
batch_size=32, n_epoch=5, print_freq=1,
X_val=X_val, y_val=y_val,
eval_train=False)
sess.close()
# import pdb
# pdb.set_trace()
# y = network.outpu
# y = network.outputs
# cost = tl.cost.cross_entropy(y, y_, 'cost')
# import pdb
# pdb.set_trace()
# # import pdb
# # pdb.set_trace()
# network = regression(network, optimizer='adam', learning_rate=0.001,
# loss='categorical_crossentropy', name='target')
# # Training
# model = tflearn.DNN(network, tensorboard_verbose=0)
# model.fit(X_train, y_train, n_epoch=5, shuffle=True, validation_set=(
# X_val, Y_val), show_metric=True, batch_size=32)
|
edf5c327f33d0adac1a3638e4f67ab810ad40c7d | shadowleaves/deep_learning | /mxnet/mxnet_binary.py | 8,507 | 3.515625 | 4 | #!/usr/bin/env python
import mxnet as mx
import numpy as np
from rnn import rnn_unroll, DataIter
# from minpy_binary import create_dataset, printSample
def create_dataset(nb_samples, sequence_len):
"""Create a dataset for binary addition and return as input, targets."""
max_int = 2**(sequence_len - 1) # Maximum integer that can be added
# Transform integer in binary format
format_str = '{:0' + str(sequence_len) + 'b}'
nb_inputs = 2 # Add 2 binary numbers
nb_outputs = 1 # Result is 1 binary number
X = np.zeros((nb_samples, sequence_len, nb_inputs)) # Input samples
T = np.zeros((nb_samples, sequence_len, nb_outputs)) # Target samples
# Fill up the input and target matrix
for i in xrange(nb_samples):
# Generate random numbers to add
nb1 = np.random.randint(0, max_int)
nb2 = np.random.randint(0, max_int)
# Fill current input and target row.
# Note that binary numbers are added from right to left,
# but our RNN reads from left to right, so reverse the sequence.
X[i, :, 0] = list(reversed([int(b) for b in format_str.format(nb1)]))
X[i, :, 1] = list(reversed([int(b) for b in format_str.format(nb2)]))
T[i, :, 0] = list(reversed([int(b)
for b in format_str.format(nb1 + nb2)]))
return X, T
# Show an example input and target
def printSample(x1, x2, t, y=None):
"""Print a sample in a more visual way."""
x1 = ''.join([str(int(d)) for d in x1])
x2 = ''.join([str(int(d)) for d in x2])
t = ''.join([str(int(d[0])) for d in t])
if y is not None:
y = ''.join([str(int(d[0])) for d in y])
print('x1: {:s} {:2d}'.format(x1, int(''.join(reversed(x1)), 2)))
print('x2: + {:s} {:2d} '.format(x2, int(''.join(reversed(x2)), 2)))
print(' ------- --')
print('t: = {:s} {:2d}'.format(t, int(''.join(reversed(t)), 2)))
if y is not None:
print('y: = {:s} {:2d}'.format(y, int(''.join(reversed(y)), 2)))
print '\n'
def xavier(shape, coef=1.0):
n_in, n_out = shape
a = np.sqrt(6.0 / (n_in + n_out)) * coef
res = mx.random.uniform(low=-a, high=a, shape=shape)
return res
def loss_func(label, pred, ep=1e-10):
loss = -np.sum(np.multiply(label, np.log(pred + ep)) +
np.multiply((1 - label), np.log(1 - pred + ep))) \
/ (pred.shape[0] * pred.shape[1])
return loss
# class RMSProp(mx.optimizer.Optimizer):
# def __init__(self, decay=0.95, momentum=0.9, **kwargs):
# super(RMSProp, self).__init__(**kwargs)
# self.decay = decay
# self.momentum = momentum
# def create_state(self, index, weight):
# """Create additional optimizer state: mean, variance
# Parameters
# ----------
# weight : NDArray
# The weight data
# """
# return (mx.nd.zeros(weight.shape, weight.context), # cache
# # mx.nd.zeros(weight.shape, weight.context), # g
# mx.nd.zeros(weight.shape, weight.context)) # delta
# def update(self, index, weight, grad, state, ep=1e-6):
# """Update the parameters.
# Parameters
# ----------
# index : int
# An unique integer key used to index the parameters
# weight : NDArray
# weight ndarray
# grad : NDArray
# grad ndarray
# state : NDArray or other objects returned by init_state
# The auxiliary state used in optimization.
# """
# assert(isinstance(weight, mx.nd.NDArray))
# assert(isinstance(grad, mx.nd.NDArray))
# lr = self._get_lr(index)
# # wd = self._get_wd(index)
# self._update_count(index)
# cache, delta = state
# # grad = grad * self.rescale_grad
# # if self.clip_gradient is not None:
# # grad = clip(grad, -self.clip_gradient, self.clip_gradient)
# cache[:] = (1 - self.decay) * (grad * grad) + self.decay * cache
# # g[:] = (1 - self.decay) * grad + self.decay * g
# grad_norm = grad / mx.nd.sqrt(cache + ep) # + wd * weight
# delta[:] = (self.momentum) * delta - lr * grad_norm
# weight[:] += delta
# # import pdb
# # pdb.set_trace()
if __name__ == '__main__':
# Create dataset
nb_train = 2000 # Number of training samples
nb_test = 100
num_hidden = 3
n_inputs = 2
n_labels = 1
# Addition of 2 n-bit numbers can result in a n+1 bit number
seq_len = 7 # Length of the binary sequence
batch_size = 100
# Create training samples
seed = 2
np.random.seed(seed)
mx.random.seed(seed)
init_states = [
('init_h', (batch_size, num_hidden)),
# ('wx', (num_hidden, n_inputs)), # , num_hidden)),
# ('wh', (num_hidden, num_hidden)),
# ('b', (num_hidden, )),
# ('wa', (n_labels, num_hidden)),
# ('ba', (n_labels, )),
]
# X, T = create_dataset(nb_train, seq_len)
data_train = DataIter(nb_train, batch_size, seq_len, n_inputs,
n_labels, init_states,
create_dataset=create_dataset)
# data_eval = DataIter(500, batch_size, n_inputs, init_states)
wx = mx.sym.Variable('wx')
wh = mx.sym.Variable('wh')
b = mx.sym.Variable('b')
wa = mx.sym.Variable('wa')
ba = mx.sym.Variable('ba')
sym = rnn_unroll(wx, wh, b, wa, ba,
seq_len=seq_len,
n_inputs=2,
num_hidden=3,
n_labels=1,
batch_size=batch_size)
# mod = mx.mod.Module(sym)
# from sys import platform
# ctx = mx.context.gpu(0) if platform == 'darwin' else mx.context.cpu(0)
arg_params = {
'init_h': mx.nd.zeros((batch_size, num_hidden)),
'wx': xavier((num_hidden, n_inputs)),
'wh': xavier((num_hidden, num_hidden)),
'b': mx.nd.zeros((num_hidden, )),
'wa': xavier((n_labels, num_hidden)),
'ba': mx.nd.zeros((n_labels, )),
}
from utils.timedate import timing
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
opt_params = {'learning_rate': 0.01,
'gamma1': 0.5,
'gamma2': 0.8,
# decay=0.5, # decay, gamma1
# momentum=0.8, # momentum, gamma2
}
# optimizer = mx.optimizer.RMSProp(**opt_params)
eval_metric = mx.metric.create(loss_func)
n_epochs = 20
t0 = timing()
if False:
model = mx.model.FeedForward(
# ctx=ctx,
symbol=sym,
num_epoch=n_epochs,
optimizer='RMSProp',
# optimizer_params=opt_params,
# eval_metric=eval_metric,
arg_params=arg_params,
**opt_params
)
model.fit(X=data_train,
eval_metric=eval_metric,
batch_end_callback=mx.callback.Speedometer(batch_size, 20),
)
else:
module = mx.mod.Module(sym,
data_names=('data',),
label_names=('label',),
)
module.bind(data_shapes=data_train.provide_data,
label_shapes=data_train.provide_label,
for_training=True, # default
)
module.init_params(arg_params=arg_params)
if False:
module.fit(data_train,
optimizer='RMSProp', # mx.optimizer.RMSProp,
optimizer_params=opt_params,
num_epoch=n_epochs,
eval_metric=eval_metric,
)
else:
module.init_optimizer(kvstore='local',
optimizer='RMSProp',
optimizer_params=opt_params)
for epoch in xrange(n_epochs):
for idx, batch in enumerate(data_train):
module.forward(batch, is_train=True)
module.backward()
module.update()
module.update_metric(eval_metric=eval_metric,
labels=batch.label)
res = module.score(data_train, eval_metric)
print res[0]
timing(t0, 'mxnet', 's')
|
3bc0d6c4c609c1b412a9f4cc8d0855519079178a | guispecian/FATEC-MECATRONICA-1600792021024-Guilherme | /LTP1-2020-2/Pratica06/programa09.py | 216 | 3.796875 | 4 | #Repetição Infinita (Cuidado, pois se a variavel somatorio for = 1; o programa nunca acaba)
somatoria = 0
while True:
print(somatoria)
somatoria = somatoria + 10
if somatoria == 100:
break
print("Fim")
|
67878144c8ee495452dbd731515c0858a040c586 | guispecian/FATEC-MECATRONICA-1600792021024-Guilherme | /LTP1-2020-2/Pratica11/programa01.py | 478 | 4.0625 | 4 | #Calculo da area do triangulo
#Função para calculo do semiperimetro
def semiperimetro(a,b,c):
return (a+b+c)/2
#Função para calculo da area
def area(a,b,c):
s = semiperimetro(a,b,c)
return (s*(s-a)*(s-b)*(s-c)) ** 0.5
#Programação Principal
#Informe os lados A, B e c
a = int(input('Informe o valor do lado A:'))
b = int(input('Informe o valor do lado B:'))
c = int(input('Informe o valor do lado C:'))
#Calculo da area
print('O valor da area é:', area(a,b,c))
|
70c81e53b62d9adcedb92dbec0e4d7a2eb4b46e0 | anhtu96/algorithms | /sorting/counting_sort.py | 586 | 3.5 | 4 | def counting_sort_1(arr):
maxval = max(arr)
sorted_arr = []
L = [None] * (maxval + 1)
for i in arr:
if L[i]:
L[i].append(i)
else:
L[i] = [i]
for i in L:
sorted_arr.extend(i)
return sorted_arr
def counting_sort_2(arr):
maxval = max(arr)
sorted_arr = [None] * len(arr)
C = [0] * (maxval + 1)
for i in arr:
C[i] += 1
for i in range(len(C)):
if i > 0:
C[i] += C[i-1]
for i in reversed(arr):
sorted_arr[C[i] - 1] = i
C[i] -= 1
return sorted_arr |
b699ab088ff08f3c0c5c9f6cbb4d2a1564acd528 | anhtu96/algorithms | /graph_algorithms/bfs.py | 652 | 3.9375 | 4 | from collections import deque
class BFSResult(object):
def __init__(self):
self.level = {}
self.parent = {}
def bfs(g, s):
""" Queue-based implementation of BFS.
Args:
- g: a graph with adjacency list adj s.t g.adj[u] is a list of u's neighbors.
- s: source vertex.
"""
r = BFSResult()
r.parent = {s: None}
r.level = {s: 0}
queue = deque()
queue.append(s)
while queue:
u = queue.popleft()
for n in g.neighbors(u):
if n not in r.level:
r.parent[n] = u
r.level[n] = r.level[u] + 1
queue.append(n)
return r |
b5ea314bac79c17cc8ff66f43b999cc6a02ac2fb | EliasKassapis/Deep-Learning | /assignment_1/code/mlp_numpy.py | 3,136 | 4.125 | 4 | """
This module implements a multi-layer perceptron (MLP) in NumPy.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from modules import *
class MLP(object):
"""
This class implements a Multi-layer Perceptron in NumPy.
It handles the different layers and parameters of the model.
Once initialized an MLP object can perform forward and backward.
"""
def __init__(self, n_inputs, n_hidden, n_classes):
"""
Initializes MLP object.
Args:
n_inputs: number of inputs.
n_hidden: list of ints, specifies the number of units
in each linear layer. If the list is empty, the MLP
will not have any linear layers, and the model
will simply perform a multinomial logistic regression.
n_classes: number of classes of the classification problem.
This number is required in order to specify the
output dimensions of the MLP
TODO:
Implement initialization of the network.
"""
########################
# PUT YOUR CODE HERE #
#######################
self.n_hidden = n_hidden
#initialize input layer
a_0 = LinearModule(n_inputs,n_hidden[0])
z_0 = ReLUModule()
self.layers = [a_0]
self.layer_out = [z_0]
#initialize hidden_layers
for l in range(len(n_hidden)-1):
current_a = LinearModule(n_hidden[l],n_hidden[l + 1])
current_z = ReLUModule()
self.layers.append(current_a)
self.layer_out.append(current_z)
#initialize last layer
a_N = LinearModule(n_hidden[-1],n_classes)
z_N = SoftMaxModule()
self.layers.append(a_N)
self.layer_out.append(z_N)
# raise NotImplementedError
########################
# END OF YOUR CODE #
#######################
def forward(self, x):
"""
Performs forward pass of the input. Here an input tensor x is transformed through
several layer transformations.
Args:
x: input to the network
Returns:
out: outputs of the network
TODO:
Implement forward pass of the network.
"""
########################
# PUT YOUR CODE HERE #
#######################
#forward pass
for i in range(len(self.n_hidden)+1):
x = self.layers[i].forward(x)
x = self.layer_out[i].forward(x)
# raise NotImplementedError
########################
# END OF YOUR CODE #
#######################
return x
def backward(self, dout):
"""
Performs backward pass given the gradients of the loss.
Args:
dout: gradients of the loss
TODO:
Implement backward pass of the network.
"""
########################
# PUT YOUR CODE HERE #
#######################
for i in range(len(self.n_hidden), -1, -1):
dout = self.layer_out[i].backward(dout)
dout = self.layers[i].backward(dout)
# raise NotImplementedError
########################
# END OF YOUR CODE #
#######################
return
|
b0a0ec721c9f7571a4f294c1b05aa07b3b82c2eb | marcozpina/DevNet | /AgendaTelefonica.py | 1,362 | 4.09375 | 4 | agenda_telefonica = {}
while True:
print ()
print ("-------- .: Menu :. --------\n")
print ("1.- Ingresar nuevo contacto\n")
print ("2.- Eliminar contacto\n")
print ("3.- Consultar contactos\n")
print ("4.- Salir del programa\n")
select = int (input("Selecciona una opcion: "))
print ()
if select == 1:
name = str (input("Nombre: "))
#last = str (input("Apellido: "))
phone = input ("Telefono: ")
print ()
if name not in agenda_telefonica:
agenda_telefonica [name] = phone
print (" -- Contacto agregado correctamente --\n")
elif select == 2:
name = input ("Selecciona el nombre que quieres eliminar: ")
if name in agenda_telefonica:
del (agenda_telefonica [name])
print ("Contacto eliminado correctamente\n")
else:
print ("Este contacto no existe")
elif select == 3:
if name in agenda_telefonica:
for name,phone in agenda_telefonica.items():
print ("Estos son todos los contactos: \n")
print (f"Nombre: {name}, Telefono: {phone}")
else:
print ("No hay contactos aún")
elif select == 4:
print (" .: Hasta pronto :. \n")
break
else:
print ("Opcion inválida")
|
0ef332e089b580d4c64f222ea88a6c8c0fb6d52e | arinanda/huffman-code-implementation-webapps | /storage/compressor/huffman/adaptive_huffman/adaptive_huffman.py | 1,600 | 3.625 | 4 | from common.util import Node
def insert_node(null, char):
char_node = Node(char, 1)
empty_node = Node(parent=null.parent, left=null, right=char_node)
char_node.parent = empty_node
if null.parent:
if null is null.parent.left:
null.parent.left = empty_node
else:
null.parent.right = empty_node
null.parent = empty_node
return char_node
def get_code(node):
code = str()
while node.parent is not None:
if node.parent.left is node:
code = '0' + code
else:
code = '1' + code
node = node.parent
return '0' + code
def swap(a, b):
if a and b:
if a.value > b.value:
if a.parent.left is a:
a.parent.left = b
else:
a.parent.right = b
if b.parent.left is b:
b.parent.left = a
else:
b.parent.right = a
a.parent, b.parent = b.parent, a.parent
def update_tree(root):
while root:
if root.parent:
sibling = root.parent.right if root.parent.left is root else root.parent.left
swap(root.left, sibling)
swap(root.right, sibling)
swap(root.left, root.right)
if root.left and root.right:
root.value = root.left.value + root.right.value
root = root.parent
def print_tree(root, space=0):
if space == 0:
print('\n\n')
if root:
print('%s%s' % (' ' * space, str(root)))
print_tree(root.left, space+2)
print_tree(root.right, space+2)
|
30da36f468a59b34608639ecf55725b37457a0a1 | daniel-paul/Farm-Simulation | /Agent.py | 8,522 | 3.65625 | 4 | import math
import copy
import random
import time
from Simulator import Simulator
# Main Agent class
class Agent:
def __init__(self, size, timeLimit):
self.simulator = Simulator(size) # Simulator instance of the farm
self.monteCarlo = MonteCarloTreeSearch(size) # Instance of the MonteCarloTreeSearch
self.timeLimit = timeLimit # Limit of time for action (in seconds)
self.totalFood = 0 # Total food harvested by the agent
def run(self):
while not self.simulator.complete:
nextMove = self.monteCarlo.findNextMove(self.simulator, self.timeLimit) # Decide next action
self.totalFood += makeMove(self.simulator, nextMove) # Execute it
print(nextMove.actionName) # Print action completed
print("Total food units: " + str(self.totalFood))
# Helper function that applies the action contained in move to the simulator instance
def makeMove(simulator, move):
if move.action == 0:
return simulator.plantBean(move.actionX, move.actionY)
elif move.action == 1:
return simulator.plantCorn(move.actionX, move.actionY)
elif move.action == 2:
return simulator.harvest(move.actionX, move.actionY)
else:
return simulator.simulateDay()
# Class that implements the MonteCarloTreeSearch
class MonteCarloTreeSearch:
def __init__(self, size):
self.size = size
self.tree = Tree(size)
self.maxScore = 15 * size * size # this is an approximation of the max score possible,
# to have the scores in a range from 0 to 1
def findNextMove(self, simulator, timeLimit):
start_time = time.time()
while time.time() - start_time < timeLimit:
# Creates a copy of the simulator, all the moves will be applied in this copy
tempSimulator = copy.deepcopy(simulator)
# Select a Leaf Node from the tree and applies all the moves to the simulator
leaf = self.selectLeafNode(self.tree.root, tempSimulator)
if not tempSimulator.complete:
# If the node is not terminal expands it
self.expandNode(leaf)
nodeToExplore = leaf
if len(leaf.children) > 0:
# Selects a random Child from the Leaf and applies that action to the simulator
nodeToExplore = leaf.getRandomChild(tempSimulator)
# Applies random movements to the last node and gets the final score
simulationResult = self.simulateRandomPlay(nodeToExplore, tempSimulator)
# Applies the score to the all the explored nodes involved
self.backPropagation(nodeToExplore, simulationResult)
# Selects the best child
bestChild = self.tree.root.getBestChild()
self.tree.root = bestChild
bestChild.parent = False
# Return the action
return bestChild.action
# Selects the best child now using UCB score until reach a leaf Node, if one of the actions is not possible,
# removes it from the children and selects another
def selectLeafNode(self, node, simulator):
while len(node.children) > 0:
success = -1
while success == -1:
best = None
bestScore = -1
for child in node.children:
score = child.getUCBscore()
if score > bestScore:
best = child
bestScore = score
success = makeMove(simulator, best.action)
if success == -1:
node.children.remove(best)
best.food = node.food + success
node = best
return node
# Expand the node, creating a new child for each possible Move
def expandNode(self, node):
possibleMoves = node.getPossibleMoves()
for action in possibleMoves:
newNode = Node(self.size, action)
newNode.parent = node
node.children.append(newNode)
# Simulate 'random' plays from the simulator and returns the efficiency of the farm
def simulateRandomPlay(self, node, simulator):
food = node.food
while not simulator.complete:
food += self.randomMove(simulator)
return food / self.maxScore
# Applies the score to all the nodes until reach the root
def backPropagation(self, node, score):
while node:
node.score += score
node.visitCount += 1
node = node.parent
# Generate a 'random' move, it will only call simulateDay() if there is not any other option
def randomMove(self, simulator):
possibleMoves = self.size * self.size * 3
move = random.randint(0, possibleMoves - 1)
success = -1
count = 0
while count < possibleMoves and success == -1:
opt = move % 3
posX = int(move / 3) % self.size
posY = int(int(move / 3) / self.size)
if opt == 0:
success = simulator.plantBean(posX, posY)
elif opt == 1:
success = simulator.plantCorn(posX, posY)
else:
success = simulator.harvest(posX, posY)
count += 1
move = (move + 1) % possibleMoves
if success == -1:
success = simulator.simulateDay()
return success
# Tree class used by the MonteCarlo Tree Search
class Tree:
def __init__(self, size):
action = Action(-1, 0, 0)
self.root = Node(size, action)
# Node class
class Node:
def __init__(self, size, action):
self.size = size
self.action = action # Information about the last action performed to reach the node
self.parent = None # Parent of the Node
self.children = [] # List of child nodes
self.visitCount = 0.0 # Number of visits to this node
self.score = 0.0 # Sum of all the scores obtained by this node
self.c = 1.41
self.food = 0 # Food harvested until this node
# Returns the UCB score of the node
def getUCBscore(self):
if self.visitCount == 0.0:
return 1000000
else:
return self.score / self.visitCount + self.c * math.sqrt(math.log(self.parent.visitCount) / self.visitCount)
# Returns the child with best average score
def getBestChild(self):
best = None
bestScore = -1
for child in self.children:
score = child.score / child.visitCount if child.visitCount > 0 else 0
if score > bestScore:
bestScore = score
best = child
return best
# Returns a random child node and applies the action contained by it to the simulator,
# if the action is not valid it chooses a different child and remove the previous from the list
def getRandomChild(self, simulator):
success = -1
while success == -1:
childNumber = random.randint(0, len(self.children) - 1)
success = makeMove(simulator, self.children[childNumber].action)
if success == -1:
self.children.remove(self.children[childNumber])
self.children[childNumber].food = self.food + success
return self.children[childNumber]
# Generate an array containing all the possible actions
def getPossibleMoves(self):
possibleMoves = []
action = Action(3, 0, 0)
action.actionName = "Next day"
possibleMoves.append(action)
for i in range(self.size):
for j in range(self.size):
action = Action(0, i, j)
action.actionName = "Plant beans in: " + str(i) + "," + str(j)
possibleMoves.append(action)
action = Action(1, i, j)
action.actionName = "Plant corn in: " + str(i) + "," + str(j)
possibleMoves.append(action)
action = Action(2, i, j)
action.actionName = "Harvest: " + str(i) + "," + str(j)
possibleMoves.append(action)
return possibleMoves
# Indicates an action performed by the agent
class Action:
def __init__(self, action, x, y):
self.actionName = None # Description of the action
self.action = action # 0 plant beans, 1 plant corn, 2 harvest, 3 next day
self.actionX = x # coordinate x of the action (for plant or harvest)
self.actionY = y # coordinate y of the action (for plant or harvest)
|
a098d9405d28447a47f63db41a3500732cd21cb0 | roshna1924/Python | /ICP4/sourcecode/naivebayes.py | 962 | 3.75 | 4 | #----------- Importing dataset -----------#
import pandas as pd
glass=pd.read_csv("glass.csv")
#Preprocessing data
X = glass.drop('Type',axis=1)
Y = glass['Type']
#----------Splitting Data-----------#
# Import train_test_split function
from sklearn import model_selection
# Split dataset into training set and test set
X_train,X_test,Y_train,Y_test=model_selection.train_test_split(X,Y,test_size=0.2)
#-----------Model Generation ----------#
#Import Gaussian Naive Bayes model
from sklearn.naive_bayes import GaussianNB
#Create a Gaussian Classifier
model=GaussianNB()
#Train the model using the training sets
model.fit(X_train,Y_train)
#Predict the response for test dataset
Y_pred=model.predict(X_test)
#----------Evaluating the model -------------#
from sklearn import metrics
# Model Accuracy, how often is the classifier correct?
print("accuracy score:",metrics.accuracy_score(Y_test,Y_pred))
print(metrics.classification_report(Y_test, Y_pred))
|
7cdaebe77cfb044dfc16e01576311244caae283f | roshna1924/Python | /ICP1/Source Code/operations.py | 590 | 4.125 | 4 | num1 = int(input("Enter first number: "))
num2 = int(input("Enter Second number: "))
operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n"))
def arithmeticOperations(op):
switcher = {
1: "Result of addition : " + str(num1 + num2),
2: "Result of Subtraction : " + str(abs(num1 - num2)),
3: "Result of multiplication : " + str(num1 * num2),
4: "Result of division : " + str(num1 / num2)
}
print(switcher.get(op, "invalid operation\n"))
arithmeticOperations(operation) |
bf98bd690471b14034136df54ebe676bb2e5b920 | ryanpjbyrne/coffeecode2 | /hello.py | 90 | 3.71875 | 4 | print("hello world")
fruits= ["apple", "pear", "oranges"]
for i in fruits:
print(i) |
0909e53fa788ef88debd3a3bceb5226b7e371332 | vincentGuerlais/matCutPy | /matCutPy.py | 2,116 | 3.546875 | 4 | #! /usr/bin/env python
import os
import sys
####################
### Get Help
####################
# print the help and exit the programm
def getHelp() :
print """matCutPy help
Usage : python matCutPy.py input_file cutoff
matCutPy generate a list of IDs with a total of estimated RNA-Seq
fragment counts above a specified cutoff.
The output file is named 'input_file'.cut
"""
sys.exit()
# Is the first argument a call for help ? or is there the amount of required arguments ?
if len(sys.argv)!=3 :
getHelp()
####################
### Variables
####################
#input file name
inFileName = sys.argv[1]
#output file name
outFileName = inFileName + '.cut'
#cutoff value
cutoff_var = int(sys.argv[2])
#Do the files exist ?
if not os.path.isfile(inFileName) :
print inFileName, " can't be found \n"
getHelp()
####################
### Functions
####################
def readMatrix(matrixFile, outFileName, cutoff) :
readFile = open(matrixFile, 'r')
outFile = open(outFileName, 'w')
readFile.readline()
for line in readFile :
cols = line.split()
if keepID(cols,cutoff) :
outFile.write(cols[0]+'\n')
readFile.close()
outFile.close()
def keepID(colList,cutoff):
#Returns True if 1/4 of the values are above the cutoff
keep = False
supColNb = 0
cols = colList[1:]
#number of col needed to be true
minColNb = len(cols)/4
if len(cols)%4 != 0 :
minColNb += 1
for col in cols :
if float(col) > cutoff :
supColNb += 1
if supColNb >= minColNb :
keep = True
return keep
####################
### Main
####################
#printing a line to know that the programm is running. to be removed ?
print "running matCutPy"
readMatrix(inFileName, outFileName, cutoff_var)
#programm is over
print "done matCutPy"
|
8d7937fd6aa3583e7c7937587f550f7809ac5f7a | aghyadalbalkhi-ASAC/Game_of_Greed | /game_of_greed/game_logic.py | 2,593 | 3.5625 | 4 | from abc import abstractmethod, ABC
from collections import Counter
import random
class GameLogic(ABC):
def __init__(self):
pass
@staticmethod
def calculate_score(tupleInt):
rules={
1:{1:100,2:200,3:1000,4:2000,5:3000,6:4000},
2:{1:0,2:0,3:200,4:400,5:600,6:800},
3:{1:0,2:0,3:300,4:600,5:900,6:1200},
4:{1:0,2:0,3:400,4:800,5:1200,6:1600},
5:{1:50,2:100,3:500,4:1000,5:1500,6:2000},
6:{1:0,2:0,3:600,4:1200,5:1800,6:2400},
7:1500, #stight
8:1500 #three pairs
} #input -> tuple(integers)
counter = Counter(tupleInt)
result= counter.most_common() # output -> integer depend on the rules
score=0
if len(tupleInt) == 0:
return 0
if counter.most_common(1)[0][1] == 1 and len(tupleInt) == 6:
return rules[7]
if len(tupleInt) == 6 and len(result)==3 and result[0][1] == 2:
return rules[8]
for i in result:
score+=rules[i[0]][i[1]]
return score
#implement the rules
@staticmethod
def roll_dice(dice_result=6):
'''#input - > integer (1-6) //randint for the dice number in the round
#output -> tuples of the values of theses dices
'''
rand = [random.randint(1,6) for i in range(dice_result)]
return tuple(rand)
class Banker(ABC):
def __init__(self):
self.balance=0
self.shelved=0
def shelf(self,amount): # input -> amount of point
self.shelved+=amount # shelf should temporarily store unbanked points.
def bank(self): # The Total Points
self.balance+=self.shelved
self.clear_shelf() # add the amount of shelf to the bank and clear shelf
# output -> the total of Point
def clear_shelf(self): #remove all unbanked points //Falkel
self.shelved=0
if __name__ == "__main__":
greed = GameLogic()
tuple2 = (5,)
print(GameLogic.roll_dice())
print(GameLogic.roll_dice(2))
print(GameLogic.roll_dice(5))
print(GameLogic.roll_dice(6))
print(dir(Banker)) |
b314f7dbe6ddf2741b5f782b4abecdb9c6fbc5e9 | ColinPLambe/MediumWebScraper | /mediumScraper.py | 2,567 | 3.53125 | 4 | from bs4 import BeautifulSoup
import requests
import sys
import os.path
"""
Colin Lambe
A Webscraper to get the number of words, number of claps, and article text from articles on Medium.com
Uses BeatifulSoup4 and Requests
"""
class MediumScraper:
def scrape(self, url, minWords, minClaps):
#gets the article source code from the url
source = requests.get(url).text
page = BeautifulSoup(source, "lxml")
#the article itself still with html context
article = page.find('article')
#the name of the article
name = article.find('h1').text
#if file already exists don't save again
stripped_name = name.replace(" ", "")
if os.path.isfile(f"./{stripped_name}.txt") :
print("File has already been processed")
else:
#gather the html free text of the article from the paragraph tags
text = []
for par in article.find_all('p'):
text = text + par.text.split(" ")
#finds the claps button and determines the number of claps
for button in page.find_all('button'):
if "claps" in button.text:
num_claps = button.text
num_claps = num_claps.split(" ")[0]
if "K" in num_claps:
num_claps = int(float(num_claps.replace("K", "")) * 1000)
elif "M" in num_claps:
num_claps = int(float(num_claps.replace("M", "")) * 1000000)
else:
num_claps = int(num_claps)
if text.__len__() > minWords:
if num_claps > minClaps:
MediumScraper.save_contents(self, url, name, text.__len__(), num_claps, " ".join(text))
else:
print("Not Enough Claps")
else:
print("Not Enough Words")
""" Saves the article to a file
file name is the name of the article with white space removed and .txt extension
file format follows:
name
url
number of words
number of claps
article text
"""
def save_contents(self,url, name, words, claps, text):
stripped_name = name.replace(" ", '')
file = open(f"{stripped_name}.txt", "w")
file.write(f"""Article Name: {name}
Article Url: {url}
Number of Words: {words}
Number of Claps: {claps}
{text}""")
if __name__ == "__main__":
MediumScraper.scrape(MediumScraper, sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
b749422d017a275cf98d99062a852942d7bd6178 | Mara-d/Prototype-sorting-algorithms-with-numbers | /Prototype-Sorting Algorithms/Sorting Algorithms Proto.py | 7,294 | 3.96875 | 4 | import time
import random
import tkinter as tk
from tkinter import *
import threading
# This is a prototype, seeing numbers getting sorted in real time helps me visualize the algorithms better,
# This program is by far finished, this is just a concept
# I plan to have an OOP approach in the future
window = tk.Tk(className="Sorting Algorithms with NUMBERS")
window.geometry("1200x800")
window['bg'] = 'grey'
a_list = [i for i in range(20)]
def bubble_sort(nums):
random.shuffle(nums)
swapped = True
while swapped:
swapped = False
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
time.sleep(2)
for output in range(1):
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, nums)
blank.configure(state=DISABLED)
swapped = True
def selection_sort(nums):
random.shuffle(nums)
for i in range(len(nums)):
lowest_value_index = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[lowest_value_index]:
lowest_value_index = j
nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i]
time.sleep(2)
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, nums)
blank.configure(state=DISABLED)
def insertion_sort(nums):
random.shuffle(nums)
for i in range(1, len(nums)):
item_to_insert = nums[i]
j = i - 1
while j >= 0 and nums[j] > item_to_insert:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = item_to_insert
time.sleep(2)
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, nums)
blank.configure(state=DISABLED)
def heapify(nums, heap_size, root_index):
largest = root_index
left_child = (2 * root_index) + 1
right_child = (2 * root_index) + 2
if left_child < heap_size and nums[left_child] > nums[largest]:
largest = left_child
if right_child < heap_size and nums[right_child] > nums[largest]:
largest = right_child
if largest != root_index:
nums[root_index], nums[largest] = nums[largest], nums[root_index]
heapify(nums, heap_size, largest)
def heap_sort(nums):
random.shuffle(nums)
n = len(nums)
for i in range(n, -1, -1):
heapify(nums, n, i)
for i in range(n - 1, 0, -1):
nums[i], nums[0] = nums[0], nums[i]
heapify(nums, i, 0)
time.sleep(2)
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, nums)
blank.configure(state=DISABLED)
def merge(left_list, right_list):
sorted_list = []
left_list_index = right_list_index = 0
left_list_length, right_list_length = len(left_list), len(right_list)
for _ in range(left_list_length + right_list_length):
if left_list_index < left_list_length and right_list_index < right_list_length:
if left_list[left_list_index] <= right_list[right_list_index]:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
else:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif left_list_index == left_list_length:
sorted_list.append(right_list[right_list_index])
right_list_index += 1
elif right_list_index == right_list_length:
sorted_list.append(left_list[left_list_index])
left_list_index += 1
time.sleep(2)
for output in range(1):
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, sorted_list)
blank.configure(state=DISABLED)
return sorted_list
def merge_sort(nums):
random.shuffle(nums)
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left_list = merge_sort(nums[:mid])
right_list = merge_sort(nums[mid:])
return merge(left_list, right_list)
def partition(nums, low, high):
pivot = nums[(low + high) // 2]
i = low - 1
j = high + 1
while True:
i += 1
while nums[i] < pivot:
i += 1
j -= 1
while nums[j] > pivot:
j -= 1
if i >= j:
return j
time.sleep(2)
frame = Frame(window, width=150, height=5, padx=20, pady=5)
frame.grid(row=2, column=0, columnspan=7)
blank = Text(frame, wrap=WORD)
blank.pack()
blank.insert(END, nums)
blank.configure(state=DISABLED)
nums[i], nums[j] = nums[j], nums[i]
def quick_sort(nums):
random.shuffle(nums)
def _quick_sort(items, low, high):
if low < high:
split_index = partition(items, low, high)
_quick_sort(items, low, split_index)
_quick_sort(items, split_index + 1, high)
_quick_sort(nums, 0, len(nums) - 1)
t1 = threading.Thread(target=lambda: bubble_sort(a_list))
t1.setDaemon(True)
t2 = threading.Thread(target=lambda: selection_sort(a_list))
t2.setDaemon(True)
t3 = threading.Thread(target=lambda: insertion_sort(a_list))
t3.setDaemon(True)
t4 = threading.Thread(target=lambda: heap_sort(a_list))
t4.setDaemon(True)
t5 = threading.Thread(target=lambda: merge_sort(a_list))
t5.setDaemon(True)
t6 = threading.Thread(target=lambda: quick_sort(a_list))
t6.setDaemon(True)
quit_button = tk.Button(window, text="Quit", command=window.destroy).grid(row=0, column=1, pady=10, padx=40)
merge_button = tk.Button(window, text="Merge Sort", command=lambda: t5.start()).grid(row=0, column=2, pady=10, padx=40)
bubble_button = tk.Button(window, text="Bubble Sort", command=lambda: t1.start()).grid(row=0, column=3,
pady=10, padx=40)
quick_button = tk.Button(window, text="Quick Sort", command=lambda: t6.start()).grid(row=0, column=4, pady=10, padx=40)
selection_button = tk.Button(window, text="Selection Sort", command=lambda: t2.start()).grid(row=0, column=5,
pady=10, padx=40)
insertion_button = tk.Button(window, text="Insertion Sort", command=lambda: t3.start()).grid(row=0, column=6,
pady=10, padx=40)
heap_button = tk.Button(window, text="Heap Sort", command=lambda: t4.start()).grid(row=0, column=7, pady=10, padx=40)
if __name__ == "__main__":
window.mainloop()
|
416b79accfdae13f2df358b5b9636403e75b6f62 | CxrlosKenobi/cs50 | /pset6/Sentimental/readability.py | 694 | 4.0625 | 4 | from cs50 import get_string
letters = 0
words = 1
sentences = 0
text = get_string("Text: ")
# Here we count the letters in the string
for i in range(len(text)):
if (text[i] >= 'a' and text[i] <= 'z') or (text[i] >= 'A' and text[i] <= 'Z'):
letters += 1
# Here we count the words in the string
if text[i] == ' ':
words += 1
# Here we count the sentences in the string
if text[i] == '.' or text[i] == '!' or text[i] == '?':
sentences += 1
# Finnally calculate the index
L = letters / words * 100
S = sentences / words * 100
index = round(0.0588 * L - 0.296 * S - 15.8)
if index < 1:
print("Before Grade 1")
elif index >= 16:
print("Grade 16+")
else:
print(f"Grade {index}")
|
3c839f5ce1fc572fc78255520368ea3ef6952a48 | vimleshtech/python_sep2 | /oops2.py | 389 | 3.53125 | 4 | class emp:
#first argument will take add of object
#at least one argument need to recieve
def newEmp(self):
print(self)
self.sid =input('etner data :')
self.name =input('enter name :')
def show(a):
print(a)
print(a.sid)
print(a.name)
o = emp()
print(o)
o.newEmp()
o.show()
|
4626384e435e06e14c4c69eecd3f760a7c03278f | ivapanic/natprog-2019-2020 | /Prijemni/KFC.py | 1,280 | 3.640625 | 4 | import sys
def main():
m_meat, s_soy, h_bread = map(float, input().split())
pm_kn, ps_kn = map(float, input().split())
if h_bread == 0:
max_earnings = 0
print(max_earnings)
elif m_meat == 0 and s_soy == 0:
max_earnings = 0
print(max_earnings)
else:
is_there_any_meat = m_meat > 0
is_there_any_soy = s_soy > 0
if not is_there_any_meat:
pm_kn = 0
elif not is_there_any_soy:
ps_kn = 0
more_expensive = m_meat if not is_there_any_soy or pm_kn > ps_kn else s_soy
better_price = pm_kn if more_expensive == m_meat else ps_kn
cheaper = s_soy if more_expensive == m_meat else m_meat
worse_price = ps_kn if more_expensive == m_meat else pm_kn
is_there_enough_bread = h_bread >= m_meat + s_soy
if is_there_enough_bread:
max_earnings = more_expensive*better_price + cheaper*worse_price
elif h_bread <= more_expensive:
max_earnings = h_bread*better_price
else:
max_earnings = more_expensive*better_price + (h_bread-more_expensive)*worse_price
print(int(max_earnings) if float(max_earnings).is_integer() else max_earnings)
if __name__ == "__main__":
main()
|
7aa71ae51a60ec0437058f1dbe26e9c8d070764f | BorisBelovA/Python-Labs | /7.1.py | 711 | 3.796875 | 4 | def makeSurnameDict():
my_file = open("students.csv", encoding='utf8')
i = 0
dict = {}
while True:
line = my_file.readline()
if(len(line) != 0):
#print(line.split(';'))
dict[i] = line.split(';')
i+=1
else:
break
dict.pop(0)
for i in range(1,len(dict)):
dict[i][3] = dict[i][3].replace('\n','')
#print(dict)
return dict
def SortBySurname(i):
return i[1]
def sortSurname(dict):
n = 1
dict = dict
surnamArr = []
for i in range(1,len(dict)+1):
surnamArr.append(dict[i])
return sorted(surnamArr,key=lambda i: i[n])
dict = makeSurnameDict()
print(sortSurname(dict)) |
bfed59521e007e81c2d062b67feed94de0807a3c | BorisBelovA/Python-Labs | /5.2.py | 442 | 3.8125 | 4 | def makeSurnameArray():
my_file = open("students.csv", encoding='utf8')
arr = []
for line in my_file:
arr.append(line.split(';'))
arr = arr[1::1]
for elem in arr:
elem[3] = elem[3].replace('\n','')
return arr
def sortSurname(arr):
surnamArr = []
i = 0
while(i<len(arr)):
surnamArr.append(arr[i][1])
i+=1
return sorted(surnamArr)
print(sortSurname(makeSurnameArray())) |
800b7e087ff43e689a00fc75a9bf4a0eb76a490c | BorisBelovA/Python-Labs | /4.2.py | 162 | 3.609375 | 4 | import random
i = 0
list = []
while (i<10):
list.append(random.randint(0,20))
i+=1
print(list)
list = list[2::1]
list.append(1)
list.append(2)
print(list) |
cf7b22bbb77b7a208a8573982d2f78e05a01f3a8 | arpancodes/100DaysOfCode__Python | /day-9/blind-auction.py | 899 | 3.734375 | 4 | from os import system, name
from art import logo
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
print(logo)
print("Welcome to the silent auction for 'The best painting'")
all_bids = []
def init():
name = input("What is your name? ")
bid = int(input("What is your bid? Rs."))
all_bids.append({
"name": name,
"bid": bid
})
def calculate_highest_bid():
max_bid = {"name": "", "bid": 0}
for x in all_bids:
if x["bid"] > max_bid["bid"]:
max_bid = x
print(f'The maximum bid was Rs.{(max_bid["bid"])} by {max_bid["name"]}')
while True:
init()
should_continue = input("Are there more bidders? Type \"yes\" or \"no\": ")
if should_continue == "yes":
clear()
elif should_continue == "no":
clear()
calculate_highest_bid()
break
|
1a50d400abbf33d7692ee73d847c7b90b317ab5d | Mahesh-5/Python | /Tic_Tac_Toe.py | 3,959 | 3.90625 | 4 | import random
from itertools import combinations
class Board(object):
def __init__(self):
self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}
def display(self):
"""
Displays tic tac toe board
"""
d_board = '\nTIC TAC TOE:\n'
for pos, obj in self.board.items():
if obj == None:
d_board += ' _ '
elif obj == ' X ':
d_board += ' X '
elif obj == ' O ':
d_board += ' O '
if pos%3 == 0:
d_board += '\n'
print(d_board)
def getAvailable(self):
"""
Returns available positions
"""
available = []
for pos, obj in self.board.items():
if obj == None:
available.append(pos)
return available
class Tic_Tac_Toe(Board):
pieces = [' O ', ' X ']
def __init__(self):
super().__init__()
self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
self.cp_piece = Tic_Tac_Toe.pieces[0]
def user_setPiece(self, position):
"""
Position parameter denoted by a number on the keypad (1-9)
"""
self.board[position] = self.piece
def user_getPiece(self):
return self.piece
def cp_setPiece(self):
self.board[random.choice(self.getAvailable())] = self.cp_piece
def cp_getPiece(self):
return self.cp_piece
def checkWin(self, player):
"""
Checks if move by either the user or computer results in a win
"""
def at_least_one(A, B):
for i in A:
for j in B:
if i == j:
return True
return False
win_patterns = [(1,2,3),(4,5,6),(7,8,9),
(1,4,7),(2,5,8),(3,6,9),
(3,5,7),(1,5,9)]
spots = [k for k, v in self.board.items() if v == player]
spots.sort()
player_combinations = list(combinations(spots,3))
if at_least_one(player_combinations, win_patterns) == True:
return True
return False
def checkFullBoard(self):
if None not in self.board.values():
self.display()
print('Draw! Game board full!')
return True
return False
#---------
def main():
# Setup game
game = Tic_Tac_Toe()
input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')
if game.user_getPiece() == 'X':
print('You are X. You are going first.')
else:
print('You are O. You are going second.')
game.cp_setPiece()
# Main game loop
while True:
game.display()
position = input('Use the number pad on the lefthand side of your keyboard\nto select your position (1-9):')
try:
position = int(position)
if position in range(1,10):
if position in game.getAvailable():
game.user_setPiece(position)
else:
print('----Please input an available position.')
continue
else:
print('----Please input a number between 1 and 9.')
except ValueError:
print('----Please input a number.')
continue
# FOR USER
# Check for win
if game.checkWin(game.user_getPiece()) == True:
game.display()
print('Congratulations! You win!')
break
# Check for full board
if game.checkFullBoard() == True:
break
# FOR COMPUTER
game.cp_setPiece()
# Check for win
if game.checkWin(game.cp_getPiece()) == True:
game.display()
print('Sorry. You lost.')
break
# Check for full board
if game.checkFullBoard() == True:
break
if __name__ == '__main__':
main()
|
6cae3ccc0e4287a1ff3225051c788e8a8733ebc0 | MaryLivingston21/IndividualProject | /Animal.py | 598 | 3.71875 | 4 | class ANIMAL:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
def to_string(self):
return self.name + ": a " + str(self.age) + " year old " + self.breed + '\n'
def get_name(self):
return self.name
def get_breed(self):
return self.breed
def get_age(self):
return self.age
def __eq__(self, other):
return self.name == other.name and self.breed == other.breed and self.age == other.age
def __hash__(self):
return hash((self.name, self.breed, self.age))
|
6fe0f6441a3135f71e16c2b276a12c957858ccb5 | RyanPeking/tkinter | /贪吃蛇.py | 5,763 | 3.5625 | 4 | import queue
import random
import threading
import time
from tkinter import Tk, Button, Canvas
class Food():
def __init__(self, queue):
self.queue = queue
self.new_food()
def new_food(self):
'''
功能:产生一个食物
产生一个食物的过程就是随机产生一个食物坐标的过程
:return:
'''
# 注意横纵坐标产生的范围
x = random.randrange(5, 480, 10)
y = random.randrange(5, 480, 10)
self.position = x,y # position存放食物的位置
self.exppos = x-5, y-5, x+5, y+5
# 队列,就是一个不能够随意访问内部元素,只能从头弹出一个元素
# 并只能从队尾追加元素的list
# 把一个食物产生的消息放入队列
# 消息的格式,自己定义
# 我的定义是:消息是一个dict,k代表消息类型,v代表此类型的数据
self.queue.put({"food": self.exppos})
class Snake(threading.Thread):
'''
蛇的功能:
1. 蛇能动,由我们的上下左右按键控制
2. 蛇每次动,都需要重新计算蛇头的位置
3. 检测是否游戏完事的功能
'''
def __init__(self, world, queue):
threading.Thread.__init__(self)
self.world = world
self.queue = queue
self.points_earned = 0
self.food = Food(queue)
self.snake_points = [(495, 55), (485, 55), (465, 55), (455, 55)]
self.start()
self.direction = 'Left'
def run(self):
if self.world.is_game_over:
self._delete()
while not self.world.is_game_over:
self.queue.put({"move": self.snake_points})
time.sleep(0.5)
self.move()
def move(self):
'''
负责蛇的移动
1. 重新计算蛇头的坐标
2. 当蛇头跟食物相遇,则加分,重新生成食物,通知world,加分
3. 否则,蛇需要动
:return:
'''
new_snake_point = self.cal_new_pos()#重新计算蛇头位置
# 蛇头位置跟食物位置相同
if self.food.position == new_snake_point:
self.points_earned += 1#得分加1
self.queue.put({"points_earned": self.points_earned})
self.food.new_food()
else:
# 需要注意蛇的信息的保存方式
self.snake_points.pop(0)
# 判断程序是否退出,因为新的蛇可能撞墙
self.check_game_over(new_snake_point)
self.snake_points.append(new_snake_point)
def cal_new_pos(self):
last_x, last_y = self.snake_points[-1]
if self.direction == "Up":
new_snake_point = last_x, last_y - 10# 每次移动10个像素
elif self.direction == "Down":
new_snake_point = last_x, last_y + 10
elif self.direction == "Right":
new_snake_point = last_x + 10, last_y
elif self.direction == "Left":
new_snake_point = last_x - 10, last_y
return new_snake_point
def key_pressed(self, e):
# keysym是按键名称
self.direction = e.keysym
def check_game_over(self, snake_point):
'''
判断依据是蛇头是否和墙相撞
:param snake_point:
:return:
'''
x, y = snake_point[0], snake_point[1]
if not -5 < x < 505 or not -5 < y < 315 or snake_point in self.snake_points:
self.queue.put({'game_over':True})
class World(Tk):
def __init__(self, queue):
Tk.__init__(self)
self.queue = queue
self.is_game_over = False
# 定义画板
self.canvas = Canvas(self, width=500, height=300, bg='gray')
self.canvas.pack()
self.snake = self.canvas.create_line((0,0), (0,0), fill="black",width=10)
self.food = self.canvas.create_rectangle(0,0,0,0,fill='#FFCC4C', outline='#FFCC4C')
self.points_earned = self.canvas.create_text(450, 20, fill='white', text='score:0')
self.queue_handler()
def queue_handler(self):
try:
while True:
task = self.queue.get(block=False)
if task.get("game_over"):
self.game_over()
if task.get("move"):
points = [x for point in task['move'] for x in point]
# 重新绘制蛇
self.canvas.coords(self.snake, *points)
# 同样道理,还需要处理食物,得分
if task.get("food"):
self.canvas.coords(self.food, *task['food'])
elif task.get("points_earned"):
self.canvas.itemconfigure(self.points_earned, text='SCORE:{}'.format(task['points_earned']))
except queue.Empty:
if not self.is_game_over:
self.canvas.after(100, self.queue_handler)
def game_over(self):
'''
游戏结束,清理现场
:return:
'''
self.is_game_over = True
self.canvas.create_text(200, 150, fill='white', text="Game Over")
qb = Button(self,text="Quit", command=self.destroy)
# rb = Button(self, text="Again", command=lambda:self.__init__(self.queue))
self.canvas.create_window(200, 180, anchor='nw', window=qb)
# self.canvas.create_window(200, 220, anchor='nw', window=rb)
if __name__ == '__main__':
q = queue.Queue()
world = World(q)
snake = Snake(world, q)
world.bind('<Key-Left>', snake.key_pressed)
world.bind('<Key-Right>', snake.key_pressed)
world.bind('<Key-Down>', snake.key_pressed)
world.bind('<Key-Up>', snake.key_pressed)
world.mainloop() |
fb56b8ce1d1987049f9cc36b48efaf0a445d7ecf | seblogapps/coursera_python | /Part 2 - Week 1/MemoryCardGame.py | 3,403 | 3.625 | 4 | # "Memory Card Game" mini-project
# Sebastiano Tognacci
import simplegui
import random
# Define constants (can resize canvas if needed)
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 100
CARD_WIDTH = CANVAS_WIDTH / 16.0
CARD_HEIGHT = CANVAS_HEIGHT
FONT_SIZE = CARD_WIDTH
LINE_WIDTH = CARD_WIDTH - 1
# Define global variables
deck1 = range(8)
deck2 = range(8)
# Concatenate the two deck of cards
deck = deck1 + deck2
# List to store the last two selected cards
selected_card = [None] * 2
# List to store the last two selected cards indexes
selected_card_idx = [None] * 2
# helper function to initialize globals
def new_game():
global deck, game_state, turn, exposed
# Shuffle deck
random.shuffle(deck)
# Card exposed list (True/False), initialize all to face down
exposed = [False]*len(deck)
# Game state (0 = no card flipped,1 = one card flipped ,2 = two cards flipped)
game_state = 0
# Initial turn count
turn = 0
# define event handlers
def mouseclick(pos):
global game_state, selected_cards, selected_cards_idx, turn
# Translate pos to index in the deck:
pos_index = pos[0] // CARD_WIDTH
# First click, flip one card face up
if game_state == 0:
exposed[pos_index] = True
selected_card[0] = deck[pos_index]
selected_card_idx[0] = pos_index
game_state = 1
# Second click, flip second card face up
elif game_state == 1:
if not exposed[pos_index]:
exposed[pos_index] = True
selected_card[1] = deck[pos_index]
selected_card_idx[1] = pos_index
game_state = 2
turn += 1
# Third click, check if cards paired, flip one card
else:
# Flip one card,
if not exposed[pos_index]:
# If previously two selected cards are not paired, flip them face down
if selected_card[0] is not selected_card[1]:
exposed[selected_card_idx[0]] = exposed[selected_card_idx[1]] = False
# Flip card, store his value and index
exposed[pos_index] = True
selected_card[0] = deck[pos_index]
selected_card_idx[0] = pos_index
game_state = 1
# cards are logically 50x100 pixels in size
def draw(canvas):
# Update current turn text
label.set_text('Turns = '+str(turn))
# First position where to draw first card and first box (made with a thick line)
card_x_pos = CARD_WIDTH // 5 #10
box_x_pos = CARD_WIDTH // 2 #25
for card_index in range(len(deck)):
#Draw card face up or face down based on exposed list
if exposed[card_index]:
canvas.draw_text(str(deck[card_index]), (card_x_pos,CARD_HEIGHT * 0.7), FONT_SIZE, 'White')
else: # Flip card down (draw green rectangle)
canvas.draw_line((box_x_pos, 0), (box_x_pos, CARD_HEIGHT), LINE_WIDTH, 'Green')
# Move positions of elements 50 pixel on the right of last position
card_x_pos+=CARD_WIDTH
box_x_pos+=CARD_WIDTH
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", CANVAS_WIDTH, CANVAS_HEIGHT)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start() |
a9bc7c1de42cf3bc67125581a6c8d402faa70ea9 | rfolk/Project-Euler | /problem92.py | 1,523 | 3.8125 | 4 | #! /usr/bin/env python3.3
# Russell Folk
# July 9, 2013
# Project Euler #92
# A number chain is created by continuously adding the square of the digits in
# a number to form a new number until it has been seen before.
#
# For example,
# 44 → 32 → 13 → 10 → 1 → 1
# 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
# Therefore any chain that arrives at 1 or 89 will become stuck in an endless
# loop. What is most amazing is that EVERY starting number will eventually
# arrive at 1 or 89.
#
# How many starting numbers below ten million will arrive at 89?
import time
squares = []
numbers = []
start = time.perf_counter()
for i in range ( 10 ) :
squares.append ( i * i )
for i in range ( 568 ) :
numbers.append ( 0 )
numbers [ 1 ] = -1
numbers [ 89 ] = 1
def squareOfDigits ( n ) :
sumOfSquares = 0
while n >= 1 :
sumOfSquares += squares[ n % 10 ]
n = int ( n / 10 )
return sumOfSquares
def chainDigits ( n ) :
if numbers [ n ] == -1 :
return False
if numbers [ n ] == 1 :
return True
#print ( n )
if chainDigits ( squareOfDigits ( n ) ) :
numbers [ n ] = 1
return True
else :
numbers [ n ] = -1
return False
success = 0
for i in range ( 2, 10000001 ) :
n = i
if i > 567 :
n = squareOfDigits ( i )
if chainDigits ( n ) :
success += 1
elapsed = ( time.perf_counter() - start )
print ( "The number of chains that end in 89 is " + str ( success ) )
print ( "Calculated in: " + str ( elapsed ) + " seconds." )
|
e773f8fe3492f330395e0d2c44900b9b96f75b63 | rfolk/Project-Euler | /problem65.py | 1,050 | 3.796875 | 4 | #! /usr/bin/env python3.3
# Russell Folk
# December 3, 2012
# Project Euler #65
# http://projecteuler.net/problem=65
import time
limit = 100
def digitSum ( n ) :
"""
Adds the sum of the digits in a given number 'n'
"""
return sum ( map ( int , str ( n ) ) )
def calceNumerator ( term , numeratorN1 , numeratorN2 ) :
"""
Calculates the numerator of e to the required term
"""
if term == limit :
if term % 3 == 0 :
return ( 2 * int ( term / 3 ) * numeratorN1 ) + numeratorN2
return numeratorN1 + numeratorN2
multiplier = 1
if term % 3 == 0 :
multiplier = 2 * int ( term / 3 )
numerator = multiplier * numeratorN1 + numeratorN2
return calceNumerator ( term + 1 , numerator , numeratorN1 )
start = time.perf_counter()
number = calceNumerator ( 2 , 2 , 1 )
total = digitSum ( number )
elapsed = ( time.perf_counter() - start )
print ( "The digit sum of the numerator of the 100th convergent of e is: " +
str ( total ) + "." )
print ( "Calculated in: " + str ( elapsed ) + " seconds." )
|
7994be2f3282be98f6ff2ad6f63a8e18f39a5833 | siukwan/python-programming | /network/chapter1/1_13a_echo_server.py | 1,111 | 3.671875 | 4 | import socket
import sys
import argparse
host = 'localhost'
data_payload = 2048
backlog = 5
def echo_server(port):
"""A simple echo server """
#Create a TCP socket
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Enable reuse address/port
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
#Bind the socket to the port
server_address = (host,port)
print "Starting up echo server on %s port %s" %server_address
sock.bind(server_address)
#Listen to clients, backlog argument specifies the max no. of queued connections
sock.listen(backlog)
while True:
print "Waiting to receive message from client"
client, address = sock.accept()
data = client.recv(data_payload)
if data:
print "Data: %s" %data
client.send(data)
print "sent %s bytes back to %s" % (data,address)
#end connection
client.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port',action="store",dest = "port",type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_server(port)
|
49893875d1c65cf248f45912a31f9552042b0bd3 | sudhasr/Competitive_Coding_2 | /TwoSum.py | 401 | 3.625 | 4 | #One pass solution. Accepted on Leetcode
#Time complexity - O(n)
#space complexity - O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict1 = {}
for i in range(0,len(nums)):
if (target - nums[i]) in dict1:
return [i,dict1[target-nums[i]]]
else:
dict1[nums[i]] = i
return [] |
989514af8deb8d7d68c51f0a1a0983cf04629656 | cwormsl2-zz/2PlayerPongGame | /cwormsl2Pong.py | 4,268 | 3.625 | 4 | from Ball import Ball
from Paddle import Paddle
from graphics import *
from time import sleep
"""
Caitlin Wormsley 12/14/12
This prgorams runs the game Pong while calling a Ball class and a Paddle class.
Along with the minimum requirements, this game has a background and is a two player version.
"""
class Pong:
def __init__(self):
#creates the window, the ball, the two paddles, and draws the background and the scoreboard.
self.win = GraphWin("Pong", 800, 400)
self.background = Image(Point(400,200),"pingpong.gif")
self.background.draw(self.win)
self.ball=Ball(self.win)
self.paddle = Paddle(self.win,740,150,750,250,"red")
self.paddle1 = Paddle(self.win, 60, 150,70,250,"blue")
self.radius = self.ball.getRadius()
self.scoreboard = Text(Point(400, 50), "")
self.scoreboard.setSize(12)
self.scoreboard.setTextColor("white")
self.scoreboard.draw(self.win)
y = 200
self.middle = self.paddle.move(self.win, y)
self.middle1 = self.paddle1.move(self.win,y)
def checkContact(self):
#gets the values for the top and bottom of the paddles
self.top = self.paddle.getMiddle()- (self.paddle.getHeight()/2)
self.bot = self.paddle.getMiddle() +(self.paddle.getHeight()/2)
self.top1 = self.paddle1.getMiddle() - (self.paddle1.getHeight()/2)
self.bot1 = self.paddle1.getMiddle() + (self.paddle1.getHeight()/2)
#gets the values of the left and right edges of the ball
right = self.ball.getCenter().getX()+self.radius
left = self.ball.getCenter().getX()-self.radius
ballHeight = self.ball.getCenter().getY()
touch = right - self.frontedge
touch1 = self.frontedge1 - left
#if the ball touches either paddle it returns true
if (0 <= touch <= 10) or (0<= touch1 <= 10):
if(self.top < ballHeight <self.bot) and self.ball.moveRight():
return True
elif (self.top1 < ballHeight < self.bot1) and self.ball.moveLeft():
return True
else:
return False
def gameOver(self):
self.frontedge = self.paddle.getEdge()
self.frontedge1 = self.paddle1.getEdge()
ballWidth = self.ball.getCenter().getX()
#returns true if the ball passes either of the paddles
if (ballWidth > self.frontedge):
return True
elif(ballWidth < self.frontedge1):
return True
else:
return False
def play(self):
click = self.win.getMouse()
y = click.getY()
end = self.gameOver()
contact = self.checkContact()
self.hits = 0
self.level = 1
while not end:
#moves the paddles based on the user's click point
#if the ball is moving right the right paddle moves
#if the ball is moving left the left paddle moves
click = self.win.checkMouse()
if click != None and self.ball.moveRight():
y = click.getY()
self.paddle.move(self.win, y)
elif click != None and self.ball.moveLeft():
y = click.getY()
self.paddle1.move(self.win, y)
#moves the ball and reverses the X direction of the ball
self.ball.move(self.win)
sleep(0.025)
contact = self.checkContact()
if contact == True :
self.ball.reverseX()
self.hits = self.hits+1
#increases ball speed after every 5 hits
if self.hits%5==0:
self.ball.goFaster()
self.level=self.level+1
self.scoreboard.setText(("Hits:",self.hits, "Level:", self.level))
end = self.gameOver()
self.scoreboard = Text(Point(400, 100),"You Lost")
self.scoreboard.setSize(12)
self.scoreboard.setTextColor("white")
self.scoreboard.draw(self.win)
self.win.getMouse()
self.win.close()
def main():
p =Pong()
p.play()
main()
|
7b4c2a9f79f8876ab091a03d83e10918d7cf358a | chinaglia-rafa/sorting | /classes/QuickSort.py | 906 | 3.578125 | 4 | from Sorter import *
from random import randint
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in range(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = (start + end)//2
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
class QuickSort(Sorter):
def __init__(self, entrada):
super().__init__("QuickSort", entrada)
def sort(self):
entrada = self.getEntrada()[:]
quick_sort(entrada, 0, len(entrada) - 1)
self.setSaida(entrada)
return entrada
|
b2427bd9bf568696217c5e0dd1db531d8472cb5e | kamadforge/ranking | /algorithms/breadth_first_search.py | 441 | 3.9375 | 4 | BFS(v):
Q = Queue()
Q.add(v)
visited = set()
visted.add(v) #Include v in the set of elements already visited
while (not IsEmpty(Q)):
w = Q.dequeue() #Remove a single element from Q and store it in w
for u in w.vertices(): #Go through every node w is adjacent to.
if (not u in visited): #Only do something if u hasn't already been visited
visited.add(u)
Q.add(u) |
26cf949e46bd2bb958eca1241fe25beef76bbb1d | kamadforge/ranking | /algorithms/binary_tree.py | 1,273 | 4.25 | 4 | class Tree:
def __init__(self):
self.root=None
def insert(self, data):
if not self.root:
self.root=Node(data)
else:
self.root.insert(data)
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
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
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Use the insert method to add nodes
# root = Node(12)
# root.insert(6)
# root.insert(14)
# root.insert(3)
# root.PrintTree()
#second way
tree=Tree()
tree.insert(3)
tree.insert(10)
tree.insert(12)
tree.insert(5)
tree.insert(6)
tree.insert(11)
tree.root.PrintTree()
|
a64c513cd683163b5596310bf0c15c39b83e2e3d | remnestal/eppu | /keyboard.py | 1,007 | 4.09375 | 4 | import curses
class Keyboard(object):
""" Simple keyboard handler """
__key_literals = ['q', 'w', 'e', 'f', 'j', 'i', 'o', 'p']
__panic_button = ' '
def __init__(self, stdscr):
self.stdscr = stdscr
def next_ascii(self):
""" Returns the next ascii code submitted by the user """
sequence = self._next_sequence()
return chr(sum(2**i for i, bit in enumerate(sequence) if bit))
def _next_sequence(self):
""" Get the next key sequence entered by the user """
key_sequence = [False] * len(self.__key_literals)
while True:
try:
key = self.stdscr.getkey()
if key == self.__panic_button:
# submit sequence when the panic button is pressed
return key_sequence
else:
index = self.__key_literals.index(key)
key_sequence[index] = not key_sequence[index];
except:
pass
|
2185999943f7891d33a7519159d3d08feba8e14d | tim-jackson/euler-python | /Problem1/multiples.py | 356 | 4.125 | 4 | """multiples.py: Exercise 1 of project Euler.
Calculates the sum of the multiples of 3 or 5, below 1000. """
if __name__ == "__main__":
TOTAL = 0
for num in xrange(0, 1000):
if num % 5 == 0 or num % 3 == 0:
TOTAL += num
print "The sum of the multiples between 3 and 5, " \
"below 1000 is: " + str(TOTAL)
|
7588f35f10bea6d457e9058d21b41d8fff329fe9 | karthik137/tensorflow | /housing_prices_byprice.py | 787 | 3.75 | 4 | import tensorflow as tensor
import numpy as np
from tensorflow import keras
'''
Housing Price Condition
One house cost --> 50K + 50K per bedroom
2 bedroom cost --> 50K + 50 * 2 = 150K
3 bedroom cost --> 50K + 50 * 3 = 200K
.
.
.
7 bedroom cost --> 50K + 50 * 4 = 400K
'''
'''
Training set to be given
xs = [100,150,200,250,300,350]
ys = [1,2,3,4,5,6]
'''
# Create model
model = tensor.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
xs = np.array([1.0,2.0,3.0,4.0,5.0,6.0],dtype=float)
ys = np.array([100.0,150.0,200.0,250.0,300.0,350.0],dtype=float)
# Train the neural network
model.fit(xs, ys, epochs=1000)
print("Predicting for house with number of bedrooms = 7")
print(model.predict([7.0]))
|
ac4244195cf8ecf1330621bd31773f3b211f4d5c | HaNuNa42/pythonDersleri | /python dersleri/tipDonusumleri.py | 1,286 | 4.1875 | 4 | #string to int
x = input("1.sayı: ")
y = input("2 sayı: ")
print(type(x))
print(type(y))
toplam = x + y
print(toplam) # ekrana yazdirirken string ifade olarak algiladigindan dolayı sayilari toplamadi yanyana yazdi bu yuzden sonuc yanlis oldu. bu durumu duzeltmek için string'ten int' veri tipine donusturmemiz gerek
print("doğrusu şöyle olmalı")
toplam = int(x) + int(y)
print(toplam)
print("---------------")
a = 10
b = 4.1
isim = "hatice"
ogrenciMi = True
print(type(a))
print(type(b))
print(type(isim))
print(type(ogrenciMi))
print("---------------")
#int to float
a = float(a) # int olan a degiskeni floata donusturduk
print(a)
print(type(a)) # donusup donusmedigini kontrol edelim
print("---------------")
#float to int
a = int(b) # float olan a degiskeni inte donusturduk
print(b)
print(type(b))
print("---------------")
# bool to string
ogrenciMi = str(ogrenciMi) # bool olan a degiskeni stringe donusturduk
print(ogrenciMi)
print(type(ogrenciMi))
print("---------------")
#bool to int
ogrenciMi = int(ogrenciMi) # bool olan a degiskeni inte donusturduk
print(ogrenciMi)
print(type(ogrenciMi)) |
74d037e74d7f602d96e5c07931ac5f561eab0359 | mehoil1/Lesson-10 | /News_json.py | 726 | 3.5625 | 4 | import json
def ten_popular_words():
from collections import Counter
with open('newsafr.json', encoding='utf-8') as f:
data = json.load(f)
words = data['rss']['channel']['items']
descriptions = []
for i in words:
descriptions.append(i['description'].split())
format_description = []
for word in sum(descriptions, []):
if len(word) > 6:
format_description.append(word.lower())
Counter = Counter(format_description)
words = Counter.most_common(10)
for word in words:
print(f'Слово: "{word[0]}" встречается: {word[1]} раз')
ten_popular_words()
|
c62c8cac3dd6d0f918755eea1d4a28c025a4afac | masterfabela/Estudios | /FRMCode/DI/Exame Python/romaymendezfrancisco/MetodosDB.py | 2,337 | 3.53125 | 4 | import sqlite3
try:
"""datos conexion"""
bbdd = 'frm'
conex = sqlite3.connect(bbdd)
cur = conex.cursor()
print("Base de datos conectada.")
except sqlite3.OperationalError as e:
print(e)
def pechar_conexion():
try:
conex.close()
print("Pechando conexion coa BD.")
except sqlite3.OperationalError as e:
print(e)
def consultar_pacientes():
try:
cur.execute("select * from paciente")
listado = cur.fetchall()
conex.commit()
print("Pacientes")
return listado
except sqlite3.Error as e:
print("Erro na recuperacion dos pacientes")
print(e)
conex.rollback()
def consultar_medidas():
try:
cur.execute("select * from medida")
listado = cur.fetchall()
conex.commit()
print("Medidas")
return listado
except sqlite3.Error as e:
print("Erro na recuperacion das medidas")
print(e)
conex.rollback()
def insert_paciente(fila,lblavisos):
try:
cur.execute("insert into paciente(dni,nome,sexo) values (?,?,?)", fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[0] + ' engadida.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def insert_medida(fila,lblavisos):
try:
cur.execute("insert into medida (dni,peso,talla,imc,fecha,clasificacion) values (?,?,?,?,?,?)", fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[0] + ' engadida.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def update_paciente(fila, lblavisos):
try:
cur.execute("update paciente set nome = ?, sexo = ? where dni = ? ;",fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[2] + ' modificada.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def delete_paciente(fila,lblavisos):
try:
cur.execute('delete from paciente where dni = ? and nome = ? and sexo = ?;',fila)
conex.commit
lblavisos.show()
lblavisos.set_text('Fila '+fila[0]+' eliminada.')
except sqlite3.OperationalError as e:
print(e);
conex.rollback() |
2afdae0bc871c7651934dedb5a6a72e696fef54f | liuyzGIt/python_datastructure_algorithms | /data_structure_algorithms/code/queue_prio_list.py | 1,157 | 3.8125 | 4 | class PrioQueueError(ValueError):
pass
class PrioQueue:
"""小的元素优先"""
def __init__(self, elems):
self.elems = list(elems)
self.elems.sort(reverse=True)
def is_empty(self):
return not self.elems
def enqueue(self, item):
i = len(self.elems) -1
while i >= 0:
if self.elems[i] <= item:
i -= 1
else:
break
self.elems.insert(i+1, item)
def dequeue(self):
if self.is_empty():
raise PrioQueueError(' Empty in dequeue')
return self.elems.pop()
def peek(self):
if self.is_empty():
raise PrioQueueError(' Empty in dequeue')
return self.elems[-1]
def show(self):
print(self.elems)
if __name__ == "__main__":
pq = PrioQueue([1,54,8])
pq.show()
print(pq.dequeue())
pq.enqueue(100)
pq.show()
pq.enqueue(2)
pq.show()
pq.dequeue()
pq.show()
pq.peek()
pq.show()
pq.dequeue()
pq.dequeue()
pq.dequeue()
pq.dequeue()
|
68372dfabb4a768815176fd77acbab0dca4cfd68 | AngelLiang/python3-stduy-notes-book-one | /ch02/memory.py | 635 | 4.28125 | 4 | """内存
对于常用的小数字,解释器会在初始化时进行预缓存。
以Python36为例,其预缓存范围是[-5,256]。
>>> a = -5
>>> b = -5
>>> a is b
True
>>> a = 256
>>> b = 256
>>> a is b
True
# 如果超出缓存范围,那么每次都要新建对象。
>>> a = -6
>>> b = -6
>>> a is b
False
>>> a = 257
>>> b = 257
>>> a is b
False
>>> import psutil
>>> def res():
... m = psutil.Process().memory_info()
... print(m.rss >> 20, 'MB')
...
>>> res()
17 MB
>>> x = list(range(10000000))
>>> res()
403 MB
>>> del x
>>> res()
17 MB
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
|
b83d307111992d4dae35a3769afa7e3a26e7d6a4 | Man-lu/100DaysOfCodingMorseCode | /MorseCode/main.py | 2,110 | 3.515625 | 4 | from colorama import Fore
from data import morse_dict
continue_to_encode_or_decode = True
print(f"{Fore.MAGENTA}############## MORSE CODE | ENCODE AND DECODE MESSAGES ##############{Fore.MAGENTA}")
def encode_message():
""""Encodes Normal Text, Numbers and Some Punctuation into Morse Code"""
message = input(f"****** TYPE IN THE MESSAGE TO ENCODE :\n{Fore.RESET}")
message = message.replace(" ", "|").upper()
encoded_message = []
for char in message:
try:
encoded_message.append(morse_dict[char])
except KeyError:
print(f"{Fore.LIGHTRED_EX}******I Cannot Recognize One or More of Your Letters: ******{Fore.RESET}")
encoded_message.append(" ")
print(f"{Fore.MAGENTA}******Your Encoded Message is as follows: ******{Fore.RESET}")
print(f"{Fore.CYAN}<START> {Fore.RESET} {''.join(encoded_message)} {Fore.CYAN} <END>")
def decode_message():
""""Decodes the Morse Code into a Normal Text"""
message = input(f"****** TYPE IN THE MORSE CODE TO DECODE "
f"{Fore.RED}**USE 'SPACE' TO SEPARATE MORSE CODE REPRESENTING A LETTER AND '|' "
f"TO SEPARATE WORDS :\n{Fore.RESET}\n").split(" ")
decoded_message = []
for char in message:
for key,value in morse_dict.items():
if value == char:
decoded_message.append(key)
decoded_message = "".join(decoded_message).replace("|", " ").title()
print(f"{Fore.MAGENTA}******Your Decoded Message is as follows: ******{Fore.RESET}")
print(f"{Fore.CYAN}<START> {Fore.RESET} {decoded_message} {Fore.CYAN} <END>")
while continue_to_encode_or_decode:
encode_decode = input(f"{Fore.LIGHTGREEN_EX}############## Type 'E' to Encode and 'D' to Decode"
f" and 'any key' to Quit ##############\n{Fore.RESET}").lower()
if encode_decode == 'e':
encode_message()
elif encode_decode == 'd':
decode_message()
else:
print(f"{Fore.RED}******You Have Quit Encoding or Decoding: ******{Fore.RESET}")
continue_to_encode_or_decode = False
|
56dd440b18d46fb27786c94f6ba663d8fd29f284 | tomjay1/auth | /authcontproject.py | 2,546 | 4.09375 | 4 | #register
#-first name, last name, password, email
#-generate useraccount
#login
#-account number and password
#bank operation
#initialization process
import random
database = {} #dictonary
def init():
print ('welcome to bankphp')
haveaccount = int(input('do you have an account with us: 1 (yes) 2 (no) \n'))
if (haveaccount == 1):
isValidOptionSelected = True
login()
elif(haveaccount == 2):
isValidOptionSelected = True
#register()
print(register())
else:
print('you have selected invalid option')
init()
def login():
print ('*******login********')
accountnumberfromuser =int(input('insert your account number \n'))
password = input('input your password \n')
for accountnumber,userdetails in database.items():
if(accountnumber == accountnumberfromuser):
if(userdetails[3] == password):
bankoperation(userdetails)
print("invalid account number")
login()
def register():
print('***Register***')
email = input('what is your email address? \n')
first_name = input('what is your first name? \n')
last_name = input('what is your last name? \n')
password= input('create a password for yourself \n')
accountnumber = generationaccountnumber()
database[accountnumber] = [ first_name, last_name, email, password ]
print('Your account has been created')
print ('your account number is: %d' % accountnumber)
print ('make sure to keep it safe')
print ('======== ========= =========== ======')
#return database
login()
def bankoperation(user):
print('welcome %s %s '% (user[0], user[1]))
selectedoption = int(input('select an option (1)deposit (2)withdrawal (3) logout (4)exit \n'))
if(selectedoption == 1):
depositoperation()
elif(selectedoption == 2):
withdrawaloperation()
elif(selectedoption ==3):
logout()
elif(selectedoption ==4):
exit()
else:
print('invalid option selected')
bankoperation(user)
def withdrawaloperation():
print('withdrawal')
def depositoperation():
print('deposit operation')
def generationaccountnumber():
print('generating account number')
return random.randrange(1111111111,9999999999)
print(generationaccountnumber())
def logout():
login()
### actual banking system ###
init()
|
2334036ddc243ed0d3befd33a69d030a0d82c215 | klq/euler_project | /euler26.py | 1,124 | 3.84375 | 4 | def euler26():
"""
Reciprocal cycles:
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
"""
max_length = 0
for i in range(2,1000):
cycle = unit_fraction(i)
if cycle > max_length:
d = i
max_length = cycle
print d, max_length
def unit_fraction(n):
# Key to solve: just need to store a list of remainders
current_digit = 1
temp_r = []
while True:
m,r = divmod(current_digit * 10, n)
if r == 0:
return 0 # no recurring cycle
if r not in temp_r: # not recurring yet
temp_r.append(r)
current_digit = r
else:
recurring_cycle = len(temp_r) - temp_r.index(r)
return recurring_cycle
#print unit_fraction(81)
euler26() # 983 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.