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 |
|---|---|---|---|---|---|---|
c47f21ccf47585759700aec437968bbff11c0ae2 | Rodo2005/condicionales_python | /ejercicios_practica.py | 14,030 | 4.1875 | 4 | #!/usr/bin/env python
'''
Condicionales [Python]
Ejercicios de práctica
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__version__ = "1.1"
def ej1():
# Ejercicios de práctica con números
'''
Realice un programa que solicite por consola 2 números
Calcule la diferencia entre ellos e informe por pantalla
si el resultado es positivo, negativo o cero.
'''
numero_1 = int(input("Ingrese el primer numero"))
numero_2 = int(input("Infrese el segundo numero"))
resta = numero_1 - numero_2
if resta > 0:
print("El resultado de restar el segundo numero al primero es positivo")
elif resta < 0:
print("El resultado de restar el segundo numero al primero es negativo")
else:
print("El resultado de restar el segundo numero al primero es cero")
def ej2():
# Ejercicios de práctica con números
'''
Realice un programa que solicite el ingreso de tres números
enteros, y luego en cada caso informe si el número es par
o impar.
Para cada caso imprimir el resultado en pantalla.
'''
numero_1 = int(input("Ingrese el primer numero: "))
numero_2 = int(input("Ingrese el segundo numero: "))
numero_3 = int(input("Ingrese el tercer numero: "))
paridad_numero_1 = numero_1 % 2
paridad_numero_2 = numero_2 % 2
paridad_numero_3 = numero_3 % 2
if paridad_numero_1 == 0:
print("numero_1 es par")
else:
print("numero_1 es impar")
if paridad_numero_2 == 0:
print("numero_2 es par")
else:
print("numero_2 es impar")
if paridad_numero_3 == 0:
print("numero_3 es par")
else:
print("numero_3 es impar")
def ej3():
# Ejercicios de práctica con números
'''
Realice una calculadora, se ingresará por línea de comando dos números
Luego se ingresará como tercera entrada al programa el símbolo de la operación
que se desea ejecutar
- Suma (+)
- Resta (-)
- Multiplicación (*)
- División (/)
- Exponente/Potencia (**)
Se debe efectuar el cálculo correcto según la operación ingresada por consola
Imprimir en pantalla la operación realizada y el resultado
'''
numero_1 = int(input("Ingrese el primer numero: "))
numero_2 = int(input("Ingrese el segundo numero: "))
print("Ingrese que operacion desea realizar: ")
print("Ingrese '1' para suma, '2' para resta, '3' para multiplicacion")
print("'4' para division, '5' para potencia")
operacion = int(input())
if operacion == 1:
suma = numero_1 + numero_2
print("La suma es: ", suma)
elif operacion == 2:
resta = numero_1 - numero_2
print("La resta es: ", resta)
elif operacion == 3:
multiplicacion = numero_1 * numero_2
print("La multiplicacion es:", multiplicacion)
elif operacion == 4:
division = numero_1 / numero_2
print("La division es:", division)
elif operacion == 5:
potencia = numero_1 ** numero_2
print("La potencia es:", potencia)
# Otra opcion ingresando letras y no numeros para las opciones
numero_1 = int(input("Ingrese el primer numero: "))
numero_2 = int(input("Ingrese el segundo numero: "))
print("Ingrese que operacion desea realizar: ")
print("Ingrese 's' para suma, 'r' para resta, 'm' para multiplicacion")
print("'d' para division, 'p' para potencia")
operacion = str(input())
if operacion == 's':
suma = numero_1 + numero_2
print("La suma es: ", suma)
elif operacion == 'r':
resta = numero_1 - numero_2
print("La resta es: ", resta)
elif operacion == 'm':
multiplicacion = numero_1 * numero_2
print("La multiplicacion es:", multiplicacion)
elif operacion == 'd':
division = numero_1 / numero_2
print("La division es:", division)
elif operacion == 'p':
potencia = numero_1 ** numero_2
print("La potencia es:", potencia)
def ej4():
# Ejercicios de práctica con cadenas
'''
Realice un programa que solicite por consola 3 palabras cualesquiera
Luego el programa debe consultar al usuario como quiere ordenar las palabras
1 - Ordenar por orden alfabético (usando el operador ">")
2 - Ordenar por cantidad de letras (longitud de la palabra)
Si se ingresa "1" por consola se deben ordenar las 3 palabras por orden alfabético
e imprimir en pantalla de la mayor a la menor
Si se ingresa "2" por consola se deben ordenar las 3 palabras por cantidad de letras
e imprimir en pantalla de la mayor a la menor
'''
texto_1 = str(input("Ingrese la primera palabra\n"))
texto_2 = str(input("Ingrese la segunda palabra\n"))
texto_3 = str(input("Ingrese la tercer y ultima palabra\n"))
print("Como quiere ordenar las palabras?")
print("Ingrese '1' para ordenarlas alfabeticamente, si no,")
print("ingrese '2' para ordenarlas por canttidad de letras")
elegir = int(input())
long_texto_1 = len(texto_1)
long_texto_2 = len(texto_2)
long_texto_3 = len(texto_3)
# ----------------- Inove ----------------------#
# Este ejercicio en donde se plantea ordenar las letras alfabéticamente
# es tedioso y una de las mejores forrmas de resolverlo es un loop
# como planteaste, o usar listas directamente.
# Es bueno ver que hayas utilizado herramientas más complejtas,
# en la próxima clase veremos más en detalle los bucles "while", "for"
# y las listas!.
# ----------------- Inove ----------------------#
if elegir == 1:
texto_alto = ""
texto_medio = ""
texto_bajo = ""
letra_texto_1 = texto_1[0]
letra_texto_2 = texto_2[0]
letra_texto_3 = texto_3[0]
if letra_texto_1 == letra_texto_2 and letra_texto_1 != letra_texto_3:
if long_texto_1 >= long_texto_2:
longitud = long_texto_2
else:
longitud = long_texto_1
if letra_texto_1 > letra_texto_3:
texto_bajo = texto_3
else:
texto_alto = texto_3
contador_1 = 1
while contador_1 < longitud:
letra_texto_1 = texto_1[contador_1]
letra_texto_2 = texto_2[contador_1]
contador_1 += 1
if letra_texto_1 == letra_texto_2:
return
elif letra_texto_1 > letra_texto_2:
if texto_bajo == "":
texto_medio = texto_1
texto_bajo = texto_2
else:
texto_alto = texto_1
texto_medio = texto_2
elif letra_texto_1 < letra_texto_2:
if texto_bajo == "":
texto_medio = texto_2
texto_bajo = texto_1
else:
texto_alto = texto_2
texto_medio = texto_1
print(texto_alto, texto_medio, texto_bajo)
# break
else:
if letra_texto_1 == letra_texto_3 and letra_texto_1 != letra_texto_2:
if long_texto_1 >= long_texto_3:
longitud = long_texto_3
else:
longitud = long_texto_1
if letra_texto_1 > letra_texto_2:
texto_bajo = texto_2
else:
texto_alto = texto_2
contador_2 = 1
while contador_2 < longitud:
letra_texto_1 = texto_1[contador_2]
letra_texto_3 = texto_3[contador_2]
contador_2 += 1
if letra_texto_1 == letra_texto_3:
return
elif letra_texto_1 > letra_texto_3:
if texto_alto == "":
texto_alto = texto_1
texto_medio = texto_3
else:
texto_medio = texto_1
texto_bajo = texto_3
elif letra_texto_1 < letra_texto_3:
if texto_alto == "":
texto_alto = texto_3
texto_medio = texto_1
else:
texto_medio = texto_3
texto_bajo = texto_1
print(texto_alto, texto_medio, texto_bajo)
# break
else:
if letra_texto_2 == letra_texto_3 and letra_texto_2 != letra_texto_1:
if long_texto_2 >= long_texto_3:
longitud = long_texto_3
else:
longitud = long_texto_2
if letra_texto_2 > letra_texto_1:
texto_bajo = texto_1
else:
texto_alto = texto_1
contador_3 = 1
while contador_3 < longitud:
letra_texto_2 = texto_2[contador_3]
letra_texto_3 = texto_3[contador_3]
contador_3 += 1
if letra_texto_2 == letra_texto_3:
return
elif letra_texto_2 > letra_texto_3:
if texto_alto == "":
texto_alto = texto_2
texto_medio = texto_3
else:
texto_medio = texto_2
texto_bajo = texto_3
elif letra_texto_2 < letra_texto_3:
if texto_alto == "":
texto_alto = texto_3
texto_medio = texto_2
else:
texto_medio = texto_3
texto_bajo = texto_2
print(texto_alto, texto_medio, texto_bajo)
# break
else:
if letra_texto_1 != letra_texto_2 != letra_texto_3:
if (letra_texto_1 > letra_texto_2 and letra_texto_1 > letra_texto_3
and letra_texto_2 > letra_texto_3):
texto_alto = texto_1
texto_medio = texto_2
texto_bajo = texto_3
elif (letra_texto_1 > letra_texto_2 and letra_texto_1 > letra_texto_3
and letra_texto_2 < letra_texto_3):
texto_alto = texto_1
texto_medio = texto_3
texto_bajo = texto_2
elif (letra_texto_1 < letra_texto_2 and letra_texto_1 > letra_texto_3
and letra_texto_2 > letra_texto_3):
texto_alto = texto_2
texto_medio = texto_1
texto_bajo = texto_3
elif (letra_texto_1 < letra_texto_2 and letra_texto_1 < letra_texto_3
and letra_texto_2 > letra_texto_3):
texto_alto = texto_2
texto_medio = texto_3
texto_bajo = texto_1
elif (letra_texto_1 > letra_texto_2 and letra_texto_1 < letra_texto_3
and letra_texto_2 < letra_texto_3):
texto_alto = texto_3
texto_medio = texto_1
texto_bajo = texto_2
elif (letra_texto_1 < letra_texto_2 and letra_texto_1 < letra_texto_3
and letra_texto_2 < letra_texto_3):
texto_alto = texto_3
texto_medio = texto_2
texto_bajo = texto_1
print(texto_alto, texto_medio, texto_bajo)
print("")
if elegir == 2:
lista = [texto_1, texto_2, texto_3]
lista.sort(key = len, reverse = True)
print(lista)
def ej5():
# Ejercicios de práctica con números
'''
Realice un programa que solicite ingresar tres valores de temperatura
De las temperaturas ingresadas por consola determinar:
1 - ¿Cuáles de ellas es la máxima temperatura ingresada?
2 - ¿Cuáles de ellas es la mínima temperatura ingresada?
3 - ¿Cuál es el promedio de las temperaturas ingresadas?
En cada caso imprimir en pantalla el resultado
'''
temperatura_1 = 0.0
temperatura_2 = 0.0
temperatura_3 = 0.0
temperatura_1 = float(input("Ingrese un valor de temperatura:\n"))
temperatura_2 = float(input("Ingrese un nuevo valor de temperatura:\n"))
temperatura_3 = float(input("Ingrse un ultimo valor de temperatura:\n"))
promedio = float(temperatura_1 + temperatura_2 + temperatura_3) / 3
lista = [temperatura_1, temperatura_2, temperatura_3]
lista.sort()
print("")
print("La temperatura máxima es: ", lista[2], "ºC")
print("")
print("La temperatura mínima es: ", lista[0], "ºC")
print("")
print("El promedio de la temperatura es: ", "{0:.2f}".format(promedio), "ºC")
print("")
if __name__ == '__main__':
print("Ejercicios de práctica")
#ej1()
#ej2()
#ej3()
ej4()
#ej5()
|
57d9d25fe134eff49886a76ba6d8ea91f9498073 | nikhilpatil29/AlgoProgram | /algo/MenuDriven.py | 2,442 | 4.125 | 4 | '''
Purpose: Program to perform all sorting operation like
insertion,bubble etc
@author Nikhil Patil
'''
from utility import *
class MenuDriven:
x = utility()
choice = 0
while 1:
print "Menu : "
print "1. binarySearch method for integer"
print "2. binarySearch method for String"
print "3. insertionSort method for integer"
print "4. insertionSort method for String"
print "5. bubbleSort method for integer"
print "6. bubbleSort method for String"
print "7.Exit"
choice = int(input("\nenter your choice\n"))
if choice == 1:
numList = [1,3,6,9,11,32,54,59,61]
print numList
ele = input("enter the element to search")
pos = x.binarySearchInteger(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 2:
numList = ['a','b','c','d','e','f','g']
print numList
ele = raw_input("enter the element to search")
pos = x.binarySearchString(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 3:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print numList
array1 = x.insertionSortInteger(numList)
print"Sorted Insertion Sort Array : ",array1
elif choice == 4:
array = ["nikhil", "kunal", "zeeshan", "amar"]
print array
array1 = x.insertionSortString(array)
print"Sorted Insertion Sort Array : ",array1
elif choice == 5:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print "list before sort"
print numList, "\n"
print "list after sort"
print(x.bubbleSort(numList))
elif choice == 6:
array = ["nikhil","kunal","zeeshan","amar"]
print("Sorted Bubble Sort Array : ")
print array
print("Sorted Bubble Sort Array : ")
x.bubbleSortString(array)
else:
exit(0)
#
#
#
# insertionSortString(str1, size)
# print("Sorted Insertion Sort Array : ")
# printStringArray(str1, size)
# break
|
390fe2f7fb1ee8ee47365ad962ebcc34f65d83fa | VPDeb/LambData | /lambdata_vdeb/.ipynb_checkpoints/oop_examples-checkpoint.py | 2,449 | 3.71875 | 4 | """OOP Eaxamples for module 2 """
import pandas as pd
class MyDataFrame(pd.DataFrame):
def num_cells(self):
return self.shape[0] * self.shape[1]
class BareMinimumClass:
pass
class Complex:
def __init__(self, realpart, imagpart): #constructor
"""
Constructor for Complex numbers.
Complex numbers have a real part and imaginary part.
"""
self.r = realpart #attribute
self.i = imagpart #attribute
def add(self, other_complex):
self.r += other_complex.r
self.i += other_complex.i
def __repr__(self):
return '({},{})'.format(self.r, self.i)
class SocialMediaUser:
def __init__(self, name, location, upvotes=0):
self.name = str(name)
self.location = location
self.upvotes = int(upvotes)
def receive_upvotes(self, num_upvotes=1):
self.upvotes += num_upvotes
def is_popular(self): #is returns Boolean
return self.upvotes > 100
class Animal:
"""General representation of animales"""
def __init__(self, name, weight, diet_type):
self.name = str(name)
self.weight = float(weight)
self.diet_type = diet_type
def run(self):
return 'Vroom, Vroom, I go Vroom'
def eat(self, food):
return 'Huge fan of that food ' + str(food)
class Sloth(Animal):
"""Representation of Sloth, a subclass of Animal"""
def __init__(self, name, weight, diet_type, num_naps):
super().__init__(name,weight,diet_type) ##grabs parent class attributes, Animal
self.num_naps = int(num_naps)
def say_something(self):
return "T h i s i s a s l o t h t y p i n g"
# Example of overriding
def run(self):
return 'I am a slow sloth guy'
if __name__=='__main__':
num1 = Complex(3, 5) #1st Complex
num2 = Complex(4, 2) #Other Complex
num1.add(num2) #Adds both Complexes
print(num1.r, num1.i)
""" This if statement Stops this from running unless actually called"""
user1 =SocialMediaUser('Justin','Provo')
user2 = SocialMediaUser('Nick', 'Logan', 200)
user3 = SocialMediaUser('Carl', 'Costa Rica', 100000)
user4 = SocialMediaUser('George Washington', 'Djibouti', 2)
print('name: {}, is popular: {}, num upvotes: {}'.format(user4.name, user4.is_popular(), user4.upvotes))
print('name: {}, is popular: {}, num upvotes: {}'.format(user3.name, user3.is_popular(), user3.upvotes))
|
1651cd7f95534bc9710fddba9d052733cd62ae8e | gfbenatto/Simple-tests-in-Python | /reverse.py | 136 | 4.03125 | 4 | array = []
x = 1
while x <= 10:
v = float(input("Digite o valor: "))
array.append(v)
x += 1
array.reverse()
print(array) |
c569284e3f4a64ff2c27c01052a8be9f23f82fd8 | gfbenatto/Simple-tests-in-Python | /vcarro.py | 168 | 3.953125 | 4 | v = int(input("Digite a velocidade do carro."))
if v > 110:
m = 5 * (v - 110)
print("Voce foi multado no valor de ", m)
else:
print("Voce nao foi multado.") |
013d6c5744ac525562ab838d17c2ce8eaf327f6c | gfbenatto/Simple-tests-in-Python | /triangulo.py | 369 | 3.953125 | 4 | a = int(input("Digite o lado a."))
b = int(input("Digite o lado b."))
c = int(input("Digite o lado c."))
if a > b + c or b > a + c or c > a + b:
print("Nao pode ser um triangulo")
print("Um lado não pode ser maior que a soma dos outros dois lados.")
elif a == b == c:
print("Equilatero")
elif a != b != c:
print("Escaleno")
else:
print("Isoceles") |
3b2b2949b78caf861b7385b22e151ae671cc9650 | gfbenatto/Simple-tests-in-Python | /telefonia.py | 266 | 3.734375 | 4 | minutos = int(input("Digite os minutos."))
if minutos <200:
preco=0.20
else:
if minutos <= 400:
preco=0.18
else:
if minutos <= 800:
preco=0.15
else:
preco=0.08
print("Valor: ", minutos * preco) |
67f15d6ebff94c2240d2728f7eec42ac6186e785 | sreevidyachintala/Student-Report-Generation-With-Encryption-and-decryption-using-Keys | /dataGen.py | 879 | 3.8125 | 4 | import random
import csv
import datetime
#pre-defined list of names included in names.py
import names
#filename with current time
dt = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
filename = 'StudentData'+dt+'.csv'
#By default gave it to generate 4000 students data
num = int(input("Howmany students data needed???"))
#create StudentData file in folder - StudentData
myfile = open('StudentData/'+filename,'w', newline='')
columnTitleRow = "Student Name, Subject-I \n"
myfile.write(columnTitleRow)
for i in range(num):
#Random Name Generation using names.py data
name = random.choice(names.first_names)+' '+random.choice(names.last_names)
#Random Marks Generation
s1 = random.randint(0,100)
row = [name,s1]
wr = csv.writer(myfile)
wr.writerow(row)
#close file
myfile.close()
print(filename+ " Generated Successfully")
|
597b83e87de912ae37e8e16200259a5a06f16154 | sthephmaldonado/PFDM | /Exercises for Reflections/Wek2&3Excercice6.4.py | 173 | 3.578125 | 4 | #%%
#
# keyword : def
def add(value1,value2,value3):
return value1 + value2 + value3
#%%
# keyword : def
Value1= 4
Value2= 2
Value3= 10
print(add(4,2,10))
#%%
|
f9ef24ce6280cbb3ee946cfaf7e28b3e56b69726 | dimostht/Salesman-Problem-with-Genetic-Algorithm | /main.py | 5,316 | 3.671875 | 4 | import copy
import random
import matplotlib.pyplot as plt
# to random create N points within X and Y limits
def createPoints(n,maxX,maxY):
points = [[0 for _ in range(2)] for _ in range(n)]
# first point is 0 , 0
# the rest are randoms
for i in range(1,n):
while True:
point = [random.randrange(maxX), random.randrange(maxY)]
if point not in points:
points[i] = point
break
return points
# to random create a path of N numbers
def createPath(n):
path = []
# we start a the 0,0 block
path.append(0)
for i in range(1,n):
path.append(i)
random.shuffle(path[1:])
return path
# the 2d distance of 2 points
def distanceOfPoints(x,y):
d = (x[0] - y[0])**2 + (x[1] - y[1])**2
return d ** 0.5
# the distance of the path
def distanceOfPath(n, path, points):
d =0.0
for i in range(n-1):
d = d + distanceOfPoints(points[path[i]] , points[path[i+1]])
return d
# to find the M percentege of the paths with the least distance
def calculateBestPaths(m,paths,distance):
# sort the paths and the distances according to min distance
for i in range(n):
mid = i
for j in range(i+1,n):
if distance[mid] > distance[j]:
mid = j
# swap the distances and the paths
distance[i] , distance[mid] = distance[mid] , distance[i]
paths[i] , paths[mid] = paths[mid] , paths[i]
# return the M*N best paths
return paths[:int(m*n)]
# 2 points swap path mutation
def swapMutation(path,p1,p2):
temp = path[p1]
path[p1] = path[p2]
path[p2] = temp
return path
# 4 points swap path mutation
def swapMutation2(path,p1,p2,p3,p4):
temp = path[p1]
path[p1] = path[p2]
path[p2] = temp
temp = path[p3]
path[p3] = path[p4]
path[p4] = temp
return path
# it will compute from M*K paths a set of K paths
def mutatePaths(k,paths):
newPaths = []
while len(newPaths) < k:
x1 = random.randrange(n-1)+1 # 1-9
x2 = random.randrange(n-1) + 1 # 1-9
# we will create 4 paths from swapping the x1 and x2 points from the original paths
for i in range(len(paths)):
newPaths.append(swapMutation(copy.deepcopy(paths[i]), x1, x2))
x1 = random.randrange(n - 1) + 1
x2 = random.randrange(n - 1) + 1
x3 = random.randrange(n - 1) + 1
x4 = random.randrange(n - 1) + 1
# we will create 4 paths from swapping the x1,x2 and x3,x4 points from the original paths
for i in range(len(paths)):
newPaths.append(swapMutation2(copy.deepcopy(paths[i]), x1, x2, x3, x4))
# return the K new paths
return newPaths[:k]
# the number of points the salesman wants to visit
n = 10
# the max X and Y of the coordinates
maxX = 10
maxY = 10
#points = createPoints(n,maxX,maxY)
# we will use a standard set of points for example
points = [[0,0],[7,4],[2,7],[3,6],[1,5],[6,3],[2,7],[8,7],[4,6],[6,4]]
#points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]
# we want to visit each of these points starting from 0 0 with the least distance possible
# normally this problem needs O(n!) to be solved
# We will use a genetic algorithm
# We will create K random paths, we will keep the M percentege of them who have the best distance
# from this paths we will mutate them to have another set of K paths and repeat
# We save the best path each time so after some iterations we can be pretty close to a good solution
# the number K of paths we will have at each set
k = 20
# the percentege M of the fittest path we will use for mutations
m = 0.4
# the array of paths and their distances
paths = []
distances = []
# create the K paths and computing their distances
for i in range(k):
paths.append(createPath(n))
distances.append(distanceOfPath(n,paths[i],points))
# number of iterations we want
iterations = 500
# the best path and it's distance, we start from the first path
minPath = paths[0]
minDistance = distanceOfPath(n,paths[0],points)
# we start the iterations
for _ in range(iterations):
# find the best paths
bestPaths = calculateBestPaths(m, copy.deepcopy(paths), distances)
# from best paths calculate the mutations
paths = mutatePaths(k,copy.deepcopy(bestPaths))
#calculate the distance and compare to the min distance
for i in range(k):
distances[i] = distanceOfPath(n, paths[i], points)
if distances[i] < minDistance:
minDistance = distances[i]
minPath = paths[i]
# the complexity of the genetic algorithm iterations *( n^2 (to find best paths) + k (to mutate) + k(to find min distance))
# for n = 10 and iterations = 500 we have a complexity of O(5.000)
# which is better compared to n! for n > 6
print("The optimal path is ")
for i in range(n):
print(points[minPath[i]])
print("and the minimum distance ",minDistance)
x=[]
y=[]
for i in range(n):
x.append(points[minPath[i]][0])
y.append(points[minPath[i]][1])
# plot the path
plt.plot(x,y,linewidth=2)
x=[]
y=[]
# plot the points
for i in range(n):
x.append(points[i][0])
y.append(points[i][1])
plt.scatter(x,y,c='red')
plt.title("Shortest path according to the genetic algorithm")
plt.grid(True)
plt.show()
|
6040de0d0f7174d576cb5d370c9d90dfe65c97aa | noite-m/nlp2020 | /chart1/practice04.py | 881 | 4.03125 | 4 | '''
“Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”という文を単語に分解し,
1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭の2文字を取り出し,
取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
'''
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
text = text.replace(",","").replace(".","").split()
def wordTake(num , word):
if num in [1,5,6,7,8,9,15,16,19]:
return (word[0],num)
else:
return(word[:2],num)
#enumerate関数の使用
ans = [wordTake(num,word) for num , word in enumerate(text,1)]
print(dict(ans))
|
953f3587f7cba8d48585a093ce5e0c8e2942d35f | noite-m/nlp2020 | /chart1/practice09.py | 1,876 | 4.125 | 4 | '''
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
ただし,長さが4以下の単語は並び替えないこととする.
適当な英語の文
(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)
を与え,その実行結果を確認せよ.
'''
import random
'''
ランダムに複数の要素を選択(重複なし): random.sample()
randomモジュールの関数sample()で、リストからランダムで複数の要素を取得できる。要素の重複はなし(非復元抽出)。
第一引数にリスト、第二引数に取得したい要素の個数を指定する。リストが返される。
'''
def typoglycemia(word):
if len(word) <= 4:
return word
else:
text = random.sample(list(word[1:-1]),len(word[1:-1]))
return ''.join([word[0]] + text + [word[-1]])
sentense = input("解答1の英文>>")
ans = [typoglycemia(word) for word in sentense.split()]
print('解答1の変換結果:'+' '.join(ans))
'''
元のリストをシャッフル: random.shuffle()
randomモジュールの関数shuffle()で、元のリストをランダムに並び替えられる。
'''
#解答2
result = []
def Typoglycemia(target):
for word in target.split(' '):
if len(word) <= 4:
result.append(word)
else:
chr_list = list(word[1:-1])
random.shuffle(chr_list)
result.append(word[0] + ''.join(chr_list) + word[-1])
return ' '.join(result)
# 対象文字列の入力
target = input('解答2の英文--> ')
# タイポグリセミア
result = Typoglycemia(target)
print('解答2の変換結果:' + result) |
52419857d6f11ad7e2881f772e96b360336f3895 | noite-m/nlp2020 | /chart2/practice17/practice17.py | 350 | 3.921875 | 4 | #1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはcut, sort, uniqコマンドを用いよ.
#https://note.nkmk.me/python-pandas-value-counts/
import pandas as pd
df = pd.read_table('chart2/popular-names.txt',header=None,names=['name','sex','number','year'])
col1 = df['name']
print(sorted(list(set(col1))))
|
b82e7411b13dbad1c88ba6f73ca285733cee8fa1 | Mbank8/DojoAssignments | /Python/Fundamentals/names_pyth.py | 1,106 | 3.765625 | 4 | students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
def studentList(arr):
for student in students:
print student["first_name"], student["last_name"]
def userList(users):
for role in users:
counter = 0
print role
for person in users[role]:
counter += 1
first = person["first_name"].upper()
last = person["last_name"].upper()
length = len(first) + len(last)
print counter,"-", first, last,"-", length
studentList(students)
userList(users)
|
311b4cc1c9701a42c896bfddd6751d0b045e2b60 | Mbank8/DojoAssignments | /Python/Fundamentals/stars.py | 276 | 3.5 | 4 |
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def draw_stars(x):
total = 0
for value in x:
if isinstance(value, int):
print value * "*"
elif isinstance(value, str):
print value[0] * len(value)
print draw_stars(x) |
41c9e1e4e2196ae66bd80f936b7339b569df9df9 | ap9035/scientific-computing | /Ch6/Newton.py | 987 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
"""
Newton's method find root
參考:https://en.wikipedia.org/wiki/Newton%27s_method
"""
"""
對函數進行微分
Input:
func:
要微分的函數
x:
nparray or float number
dx(optional):
float number
Output:
在x點的微分值,type視輸入而定,可為float number 或 nparray
"""
def df(func, x, dx=0.0001):
return (func(x+dx)-func(x))/dx
"""
牛頓法尋根
Input:
func:
要找根的函數
x:
nparray or float number
eps:
允許的誤差值(或其加總)
Output:
根值的位置,視輸入而定,可為float number 或 nparray
"""
def Newton(func, x, eps=1e-10):
while np.sum(abs(func(x))) > eps:
x -= func(x)/df(func, x)
return x
def testfunc(x):
return (x+1)*(x-1)*(x+10)
def main():
print Newton(testfunc, np.linspace(-10, 15, 8))
print Newton(testfunc, 0.5)
if __name__ == "__main__":
main()
|
c354efb5adc7332549e2a2e16c009084eaf7e59a | ap9035/scientific-computing | /Ch6/bisection.py | 716 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
bisection method
在一給定區間找根,如兩者之間有奇數根,則f(x1)*f(x2)<0
"""
from math import fabs
def bisection(func, x1, x2):
eps = 1e-10
if func(x1)*func(x2) > 0:
return 0
while fabs(x2-x1) > eps:
xm = (x1+x2)/2
fxm = func(xm)
fx1 = func(x1)
fx2 = func(x2)
if fxm == 0:
return xm
elif fx1 == 0:
return fx1
elif fx2 == 0:
return fx2
if fxm*fx1 > 0:
x1 = xm
else:
x2 = xm
return x1
def testfunc(x):
return x**3-2
def main():
print bisection(testfunc, 0.5, 2)
if __name__ == "__main__":
main()
|
a8a515e8e66e150efa89fba6ea85184d137ee7d7 | singhpartap/Assignments | /assignment2.py | 305 | 3.890625 | 4 | #Q1:
print("Hello my name is Patap Singh")
#Q2:
print("Partap" "Singh")
#Q3:
x=input("Enter the value of x")
y=input("Enter the value of y")
z=input("Enter the value of z")
print(x,y,z)
#Q4:
print('"let\'s get started"')
#Q5:
s="acadview"
course="python"
fee="5000"
print(('%s\n%s\n%s')%(s, course, fee)) |
3612041b108d71ebca535520f3eabf05177d0f88 | rajday19/Data-Structures | /DP.py | 3,246 | 3.734375 | 4 | import sys
class Solution:
def numDecodings(self, s):
memo = {}
def f(s):
print ("\nThe input string is:",s)
if s == "":
return 1 #if s is a empty string there is only one way to decode it
elif s[0] == "0":
return 0 #if s[0] is 0 then the string is invalid, since no letter maps to 0, e.g 01 doesn't make sense
elif len(s) == 1:
return 1#if s is 1 long and it is 1-9 there is 1 way to decode it
elif s in memo:
return memo[s]# if the number of ways to decode s is in the dictionary we just retreive it and return
elif int(s[0] + s[1]) > 0 and int(s[0] + s[1]) <= 26:
#s will be longer than 1 at this case
#so if s[0]+s[1] converted to an int is in the range 1 to 26 inclusive this is what we do
ret = f(s[1:]) + f(s[2:]) #the number of ways to decode the string 123: decode("123") = decode("23") + decode("3") = 3
#this is because one way of decoding is picking 1 as a standalone number while the other way is picking 12 as a standalone number and decoding the rest of the string after those two numbers
# if we got to here the value for s won't be in the dictionary so we put it there for the future and return
memo[s] = ret
print ("\nReturn value is: ",ret)
print ("\nmemo is: ",memo)
return ret
else:
#if we got here it is exactly like the last case(the one above) except the string is like 323, 32 is not between 1 and 26
# so the number of ways to decode is just the number of ways you can decode 23
ret = f(s[1:])
memo[s] = ret
print ("\nReturn value is: ",ret)
print ("\nmemo is: ",memo)
return ret
return f(s)
def numDecodings1(self,s):
memo = {}
# Without memoization
if s == "0":
return 0
if len(s)==0 or len(s)==1:
return 1
if s[0]=="0":
return 0
if s in memo:
return memo[s]
if int(s[0]+s[1])<=26 and int(s[0]+s[1])>=10:
ret = self.numDecodings1(s[1:]) + self.numDecodings1(s[2:])
memo[s] = ret
return ret
else:
ret = self.numDecodings1(s[1:])
memo[s] = ret
return ret
def minwindowseq(self,S,T):
self.validstrings = []
y = self.helper(S,T,self.validstrings,0)
return y
#print (self.validstrings)
def helper(self,S,T,x,start_index):
print("\nS is: ",S)
print("\nT is: ",T)
#sys.exit()
if len(T)==0 or T=="" or not T:
print ("\nExit condition hit. The list is:",x)
#sys.exit()
#self.validstrings.append(x)
return x
if S[start_index:]=="" or len(S[start_index])==0:
return None
checklen = len(S)
while start_index < len(S):
if S[start_index]==T[0]:
x.append(start_index)
print(x)
print(S[start_index+1:])
print(T[1:])
if len(x)==2:
pass
#sys.exit()
#sys.exit()
return (self.helper(S,T[1:],x,start_index+1))
#self.helper(S,T[:],x,i+1)
else:
start_index+=1
def numWays(self,valueList,change,memo):
if change in valueList:
return 1
mincoins = change
if change in memo:
return memo[change]
for i in [c for c in valueList if c <= change]:
numcoins = 1 + self.numWays(valueList,change-i,memo)
if numcoins < mincoins:
memo[change] = numcoins
mincoins = numcoins
return mincoins
s = Solution()
print("Answer is:",s.numWays([1,2,10,21],63,{})) |
67691dbfcfd0580f0ce7009e88f76925c5b7f7ad | imdurgadas/PyFrameworks | /SQLAlchemy/sql_basics.py | 1,178 | 3.8125 | 4 | import sqlalchemy
__author__ = 'durgadas_kamath'
from sqlalchemy import *
import os
print sqlalchemy.__version__
os.remove('example.db') #Removing the example.db since below create operations will fail if it already exists
db = create_engine('sqlite:///example.db') #this will create example.db in your working directory
db.echo = False
metadata = MetaData(db)
users = Table('users', metadata,
Column('user_id',Integer, primary_key=True),
Column('name', String(40)),
Column('age', Integer),
Column('password', String),
)
users.create()
'''
if the table already exists , then you can use below with autoload = true
users = Table('users', metadata, autoload=true)
'''
i = users.insert()
i.execute(name='user1', age=25, password='secret')
'''
Either you can add single row or you can add multiple using dictionary within a tuple.
If you don't specify certain columns then it sets it to None except the primary key which is uniquely generated
'''
i.execute({'name': 'user2', 'age': 23},
{'name': 'user3', 'age': 24})
s = users.select()
rs = s.execute()
for row in rs:
print row.user_id, '--', row.name, ' -- ',row.age, '---',row.password
|
a6784a24f9b212b58836b898720567de4885de2d | nhrade/image-similarity | /Project/sift_similarity.py | 2,213 | 3.6875 | 4 | import cv2
import numpy as np
import os
def similarity(des1, des2):
"""
The similarity between two image descriptors by finding the closest
neighbor for each vector in des1, and then averaging them. Then averaging this distance
to find the distance between des1 and des2.
:param des1: First list of image descriptors
:param des2: Second list of image descriptors
:return: Distance between the two
"""
matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
matches = matcher.match(des1, des2)
distances = np.array([1 / (1 + m.distance) for m in matches])
return np.sum(distances) / len(distances)
def closest_image(source_im, images):
"""
Finds the closest image in images to im using SIFT similarity.
:param source_im: source image
:param images: images to compare against
:return: the index in images of the most similar image
"""
_, source_des = apply_sift(source_im)
similarities = []
for img in images:
_, des = apply_sift(img)
similarities.append(similarity(source_des, des))
max_index = np.argmax(similarities)
print('Similarity: {:3f}'.format(similarities[max_index]))
return max_index
def apply_sift(img):
"""
Apply SIFT to an image.
:param img: Image to apply
:return: SIFT keypoints
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp, des = sift.detectAndCompute(gray, None)
return kp, des
def display_closest_image(i, images):
closest_im_index = closest_image(images[i],
images[:i] + images[i+1:])
closest_img = images[closest_im_index]
cv2.imwrite('img1.jpg', images[i])
cv2.imwrite('img2.jpg', closest_img)
cv2.imshow('original', images[i])
cv2.imshow('most similar', closest_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images', 'desert')
images = []
for fname in os.listdir(path):
img_path = os.path.join(path, fname)
images.append(cv2.imread(img_path, cv2.IMREAD_COLOR))
display_closest_image(5, images)
|
f488729bfef85934b4867abfce47f4d8ffab3662 | trnkatom/python_learning | /GitTest/PythonGitTest.py | 544 | 3.53125 | 4 | import random
# random fun code
class GitTest:
number = 0
def __init__(self):
print("This is python_learning no.{}\n".format(self.generate_git_test_number()) + str(self))
def generate_git_test_number(self):
GitTest.number += 1
return self.number
def __str__(self):
return self.__class__.__name__ + str(self.number)
for num in range(random.randint(1, 11)):
gitTestInstance = "gitTest" + str(num)
gitTestInstance = GitTest()
# gitTest1 = python_learning()
# gitTest2 = python_learning() |
69e6f4c4b02561dc00d736bebce9c890251387da | wvzxtc/p2-201611090 | /w6Main11.py | 141 | 4.15625 | 4 | year=input("User input year : ")
if (year%4==0 and year%100!=0) and (year%400==0) :
print "Leap year"
else:
print "Not Leap year"
|
544aa5bc849622caa4348454bee69fb6101ba9a2 | sonal1999/Intelligent-voice-recorder | /text_speech.py | 994 | 3.796875 | 4 | import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
def speak(text):
tts = gTTS(text=text,lang='en') #text to speech
filename = 'voice.mp3'
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source) #reducing intencity of noise from input speech
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio) #speech to text
print(said)
except Exception as e:
print("Exception: "+str(e))
return said
text = get_audio() #taking speech and convering it into text and then print that on console
if "hello" in text:
speak("Good Evening") #converting given argument into speech and answering back to input
else:
speak("Have a great day")
|
cbfa94e5ab45819bb1dd9ee3834ec98d1b826911 | webfarer/python_by_example | /Chapter2/016.py | 317 | 4.125 | 4 | user_rainy = str.lower(input("Tell me pls - is a rainy: "))
if user_rainy == 'yes':
user_umbrella = str.lower(input("It is too windy for an umbrella?: "))
if user_umbrella == 'yes':
print("It is too windy for an umbrella")
else:
print("Take an umbrella")
else:
print("Enjoy your day") |
59a1d217903a06de0594dabc7abb8843feea5479 | webfarer/python_by_example | /Chapter3/024.py | 67 | 3.578125 | 4 | user_name = input("Print your name: ")
print(str.upper(user_name)) |
da35768f26e1f51a715f1983bad67e935097e597 | webfarer/python_by_example | /Chapter2/018.py | 181 | 3.890625 | 4 | user_numb = int(input("Input your number pls: "))
if user_numb < 10:
print("Too low")
elif user_numb >= 10 and user_numb <= 20:
print("Correct")
else:
print("Too high") |
1fd3768b7333b6be11d16437d3ab59d8b424c50b | WeiKangJian/turtlePicture | /tutor.py | 1,066 | 3.90625 | 4 | import turtle
# Author WeiKangJian
# Date 2019/11/6
turtle.left(90)
turtle.back(300)
turtle.forward(100)
toplevel = 7 # 绘制的叶子的分叉数目,也是递归的层数
leftangle = 30 #一开始偏移的角度
rightangle = 30 #向另一边偏移的角度
turtle.speed('fastest') #画笔绘画的快慢
turtle.color('blue','blue')# 图画的颜色
#递归画图
def diguiTree(length, deep):
turtle.left(leftangle) # 绘制左枝
turtle.forward(length)
if deep == toplevel: # 叶子
turtle.circle(5, 360) #画圆
if deep < toplevel: # 在左枝退回去之前递归.每次递归,层数加一
diguiTree(length - 10, deep + 1)
turtle.back(length)
turtle.right(leftangle + rightangle) # 绘制右枝
turtle.forward(length)
if deep == toplevel: # 叶子
turtle.circle(5, 360)
if deep < toplevel: # 在右枝退回去之前递归
diguiTree(length - 10, deep + 1)
turtle.back(length)
turtle.left(rightangle)
diguiTree(100, 1) #设定树枝干的长短
turtle.done()
|
3f18cc05e3d43fee4cab89e0d5f29f74e072d738 | jewarner57/CS-1.1-Flower_Project | /test_app.py | 329 | 3.84375 | 4 | from app import Flower
def test_get_turn_degrees():
"""Tests if get turn degrees gets the number of degrees needed to rotate for each petal"""
flower = Flower(10, "red", 0, 0, 0, 0)
assert flower.get_turn_degrees(10) == 36
assert flower.get_turn_degrees(100) == 3.6
assert flower.get_turn_degrees(45) == 8
|
4dfcd4aee55e71b078ea9d614de866f2c1f5457f | shchun/udacity_work | /freq.py | 283 | 3.53125 | 4 | #!/usr/bin/env python
def freq_analysis(message):
ret = []
len_message = len(message);
for i in range(0,26):
ret.append(0.0)
for ch in message:
ret[ord(ch) - ord('a')] += 1
for i in range(0,26):
ret[i] /= len_message
return ret
#Tests
print freq_analysis("abcd")
|
eaafd5ad99d9330ce73bb9064b08eb2be0aac193 | crawfonw/ChessPye | /chesspye/utils/Stack.py | 747 | 3.578125 | 4 | '''
Created on Mar 1, 2014
@author: Nick Crawford
'''
class Stack(object):
def __init__(self, initial_set=[]):
if isinstance(initial_set, list):
self.objs = initial_set
else:
self.objs = [initial_set]
def push(self, obj):
self.objs.append(obj)
def pop(self):
return self.objs.pop()
def peek(self):
if not self.is_empty():
return self.objs[-1]
def is_empty(self):
return len(self.objs) == 0
def __repr__(self):
return '%s(initial_set=%s)' % (self.__class__.__name__, self.objs)
def __str__(self):
return str(self.objs)
def __iter__(self):
return iter(self.objs) |
0fd60f60e7d27ad81641bcdb0b712e0510e43f41 | naamoonoo/leetcode | /sortArrayByParity/sortArrayByParity.py | 1,454 | 4.03125 | 4 | # class Solution:
# def sortArrayByParity(self, A: List[int]) -> List[int]:
class Solution:
def sortArrayByParity(self, A):
return list(filter(lambda x: x % 2 == 0, A)) + list(filter(lambda x: x % 2 == 1, A))
print(Solution().sortArrayByParity([3,1,2,4]))
#https://www.programiz.com/python-programming/methods/list/sort
# sort(key=..., reverse=...)
# key would be the function like len(built in function) or personal function
# in this time, key function return 0 or 1, but It is sorting algoritmm
# ######so, smaller number would comes first!#######
# 0 -> even , 1 -> odd
# python built in sort function
# Python uses an algorithm called Timsort:
# Timsort is a hybrid sorting algorithm, derived from merge
# sort and insertion sort, designed to perform well on many
# kinds of real-world data. It was invented by Tim Peters in
# 2002 for use in the Python programming language. The
# algorithm finds subsets of the data that are already
# ordered, and uses the subsets to sort the data more
# efficiently. This is done by merging an identified subset,
# called a run, with existing runs until certain criteria
# are fulfilled. Timsort has been Python's standard sorting
# algorithm since version 2.3. It is now also used to sort
# arrays in Java SE 7, and on the Android platform.
class SortSolution:
def sortArrayByParity(self, A):
A.sort(key = lambda x: x % 3)
return A
print(SortSolution().sortArrayByParity([3, 1, 2, 4, 5, 6]))
|
9afaf188cffc87d62a2aa530811046bc8b9abfe2 | perhamer/Find_Love_MusicCloud | /sql.py | 2,176 | 3.921875 | 4 | """
一般 Python 用于连接 MySQL 的工具:pymysql
"""
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='cloudmusic',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
# 获取用户所有歌单下的所有音乐
def get_musics_by_user(user_id):
with connection.cursor() as cursor:
sql = "SELECT DISTINCT music_id FROM playlist_music p LEFT JOIN user_playlist u ON p.playlist_id = u.playlist_id WHERE u.user_id = %s and music_id > 5412259 ORDER BY music_id ASC"
cursor.execute(sql, (user_id))
return cursor.fetchall()
# 保存用户的playlists
def insert_user_playlist(user_id, playlist_id, playlist_name):
with connection.cursor() as cursor:
sql = "INSERT INTO user_playlist (`user_id`,`playlist_id`,playlist_name) VALUES (%s, %s, %s)"
cursor.execute(sql, (user_id, playlist_id, playlist_name))
connection.commit()
# 获取用户的playlists
def get_playlists(user_id):
with connection.cursor() as cursor:
sql = "SELECT `playlist_id` FROM `user_playlist` WHERE user_id = %s"
cursor.execute(sql, (user_id))
return cursor.fetchall()
# 保存歌单的歌曲
def insert_playlist_music(playlist_id, musics):
with connection.cursor() as cursor:
sql = "INSERT INTO playlist_music (`playlist_id`,`music_id`) VALUES (%s, %s)"
for id in musics:
cursor.execute(sql, (playlist_id, str(id)))
connection.commit()
# 获取歌曲评论
def insert_comment(comment):
with connection.cursor() as cursor:
sql = "INSERT INTO comments (`music_id`, `user_id`,`content`, `reply_comment_id`, `reply_content`, `liked_count`, `comment_time`) VALUES (%s, %s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (
comment.music_id, comment.user_id, comment.content, comment.reply_id, comment.reply_content,
comment.liked_count, comment.comment_time))
connection.commit()
def dis_connect():
connection.close()
|
eb8a31c26d7b087e7ff7e806d8869dcfefc34d04 | mmcintyre1/python_morsels-exercises | /orderedset.py | 1,908 | 3.765625 | 4 | from collections.abc import MutableSet
from itertools import zip_longest
class OrderedSet(MutableSet):
def __init__(self, items):
# with python 3.7, dicts are guaranteed to maintain insertion order
self.items = dict.fromkeys(items, None)
super().__init__()
def __len__(self):
return len(self.items)
def __contains__(self, value):
return value in self.items
def __iter__(self):
# this can also be written as iter(self.items.keys())
# is there any difference?
yield from self.items
def __eq__(self, other):
if isinstance(other, OrderedSet):
# handling for exact order
return (self is other) or all(x == y for x, y in zip_longest(self, other))
elif isinstance(other, set):
return set(self) == other
return False
# another way to write this __eq__ is below:
# its probably cleaner, and I like the type()
# check as opposed to an explicit check against OrderedSet
# def __eq__(self, other):
# if isinstance(other, type(self)):
# return (
# len(self) == len(other) and
# all(x == y for x, y in zip(self, other))
# )
# return super().__eq__(other)
def __getitem__(self, index):
# this has to be turned into a list every index call
# we might be able to store this into a variable? use a sentinel
# on the add/discard methods to see if things have changed and turn
# into a list again?
return list(self.items.keys())[index]
def __str__(self):
return ", ".join(self.items.keys())
def add(self, value):
self.items[value] = None
def discard(self, value):
self.items.pop(value, None)
if __name__ == '__main__':
words = OrderedSet(['hello', 'hello', 'how', 'are', 'you'])
print(words[1])
|
fe3b3b55e4d537cab59c9c4943361b4714eabf64 | afeldman/sternzeit | /year/year.py | 2,904 | 4.78125 | 5 | #!/usr/bin/env python3
def is_leap_year(year):
""" if the given year is a leap year, then return true
else return false
:param year: The year to check if it is a leap year
:returns: It is a Leap leap year (yes or no).
"""
return (year % 100 == 0) if (year % 400 == 0) else (year % 4 == 0)
def year_month_day(year, day_of_year):
""" calculate the year, month and day form year and day as input
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to check the month and day in
:param day_of_year: the day you want to check for monath in the given year
:returns: the year, the month and the day of the given data
"""
K = 1 if (is_leap_year(year)) else 2
M = 1 if (day_of_year < 32) else int((9*(K + day_of_year)) / 275.0 + 0.98 )
D = day_of_year - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return K, M, D
def number_of_days_in_month(year, month):
""" check the number of days in the given month.
Because of leap years the year information is mandatory
:param year: The year to get the day of monthes
:param month: the month to check
:returns: number of days for a given month in a given year. If the month is bigger then 12 or smaller the 1, then -1 is returned
"""
if (month < 1) or (month > 12):
return -1
return {
1: 31,
2: 29 if (is_leap_year(year)) else 28,
3: 31,
4: 2,
5: 31,
6: 2,
7: 31,
8: 31,
9: 30,
10:31,
11:30,
12:31,
}[month]
def length_of_year(year):
""" the length of a day
:param year: The year you wuld like to know the length.
:returns: exact days. a day is longer then 365 days.
"""
return float(365.2564) if is_leap_year(year) else float(364.2564)
def day_of_year(year, month, day):
""" calculate the day of a year
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to calculate the day
:param month: month the day is in
:param day: day of month in the given year
:returns: the day in the given year
"""
K = 1 if is_leap_year(year) else 2
return (int((275 * month) / 9.0) - K * int((month + 9) / 12.0) + day - 30)
def minuts_in_the_year(year, month, day, hours, minute):
""" calculate the day of a year
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to calculate the day
:param month: month the day is in
:param day: day of month in the given year
:param houres: the hour of the day in the month of the requested year
:returns: the hour in the given year
"""
return float( day_of_year(year, month, day) - 1.0 + float(hours)/24.0 + float(minute)/1440.0)
|
ab78edacfb9e981771e94160431322b3b20f42a0 | nirmaldalmia/InterviewBit | /Binary Search/CountElementOccurence.py | 1,251 | 3.5 | 4 | def findCount(A,B):
A = list(A)
def findOccurence(Arr, B, searchFirst):
#A = list(A)
start = 0
end = len(A)
result = -1
while start <= end-1:
mid = (start + end) // 2
print(start, mid, end)
if A[mid] == B:
result = mid
if searchFirst:
end = mid - 1
else:
start = mid + 1
elif A[mid] < B:
start = mid + 1
else:
end = mid - 1
return result
firstOccurence = findOccurence(A, B, True)
lastOccurence = findOccurence(A, B, False)
print(firstOccurence, lastOccurence)
count = len(A[firstOccurence:lastOccurence + 1])
return count
A = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 ]
B = 10
print(findCount(A,B)) |
e5d06af566b672f70e1fa86541ade4d70d4fd8ee | nirmaldalmia/InterviewBit | /Arrays/generateMatrix.py | 1,091 | 3.75 | 4 | def generateMatrix(A):
matrix = [[0]*A for x in range(A)]
print(matrix)
top = 0
bottom = A - 1
left = 0
right = A - 1
num = 1
direction = 1
while top <= bottom and left <= right:
#direction = direction % 4
if direction == 1:
i = left
while i <= right:
matrix[top][i] = num
i += 1
num += 1
top+=1
direction = 2
if direction == 2:
for i in range(top, bottom+1):
matrix[i][right] = num
num += 1
right -= 1
direction = 3
if direction == 3:
for i in range (right, left-1, -1):
matrix[bottom][i] = num
num += 1
bottom -=1
direction = 4
if direction == 4:
for i in range (bottom, top-1, -1):
matrix[i][left] = num
num += 1
left +=1
direction = 1
return matrix
print (generateMatrix(4)) |
fb13eb0ac8bbdf1b8e6f7b13e9ce35646ea9ef17 | nirmaldalmia/InterviewBit | /Arrays/SetMatrixZeroes.py | 411 | 3.515625 | 4 | def setZeroes(A):
listA = []
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j] == 0:
listA.append((i,j))
for x in listA:
#print(x[0], x[1])
A[x[0]] = [0]*len(A[0])
for j in range(len(A)):
A[j][x[1]] = 0
#print(listA)
print(A)
#A = [[1, 0, 1],
# [1, 1, 1],
# [1, 1, 1]]
A = [[0,0], [1,1]]
setZeroes(A) |
f0da693b6260b05f5985c080629f2ffdc7900fac | matteokg/PDXcodeguild-fullstack-night-03052018 | /helloworld.py | 74 | 3.984375 | 4 | name = input ("What is your name?")
hello = "Hello"
print (hello + name)
|
1ab8bc8785c7e830e1e010b2135fd335911673e9 | matteokg/PDXcodeguild-fullstack-night-03052018 | /numberguess.py | 488 | 3.9375 | 4 | import random
x=random.randint(1,10)
i=0
while i<10:
guess = int(input("guess the number between 1 and 10?"))
i= i+1
if guess > x:
print ("Too high, guess again")
elif guess < x:
print ("Too low, guess again")
elif guess == x:
break
if guess == x and i == 1:
print("wow, you're a genius, it took 1 try. teach me your ways ")
elif guess == x and i>1:
print("you win! it took you " + str(i) + ' ' + "tries. Why so many ya dingus?")
|
0082218ec1f81d0161f2d59a5451d08b30454fb2 | ani03sha/potd | /Python/UncommonWordsFromTwoSentences.py | 909 | 3.9375 | 4 | """
Given two strings representing sentences, return the words that are not common to both strings
(i.e. the words that only appear in one of the sentences). You may assume that each sentence is
a sequence of words (without punctuation) correctly separated using space characters.
"""
from typing import List
class UncommonWordsFromTwoSentences:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
AB = (A + " " + B).split()
unique = {}
for i in range(len(AB)):
if AB[i] in unique:
unique[AB[i]] = unique[AB[i]] + 1
else:
unique[AB[i]] = 1
return [word for word in unique if unique[word] == 1]
if __name__ == "__main__":
u = UncommonWordsFromTwoSentences()
print(u.uncommonFromSentences("this apple is sweet", "this apple is sour"))
print(u.uncommonFromSentences("apple apple", "banana"))
|
c16f7de3de24eb693d24fc3ec777b51039a62445 | ani03sha/potd | /Python/IntersectionOfTwoArrays.py | 603 | 3.78125 | 4 | """
Given two arrays, write a function to compute their intersection.
"""
from typing import List
class IntersectionOfTwoArrays:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# Set for storing elements of first array
set1 = set(nums1)
# This set will store the elements of second array
set2 = set(nums2)
# Take only common elements
return list(set1 & set2)
if __name__ == "__main__":
i = IntersectionOfTwoArrays()
print(i.intersection([1, 2, 2, 1], [2, 2]))
print(i.intersection([4, 9, 5], [9, 4, 9, 8, 4]))
|
f502a1187eedc1885f47e2e11a9da38e5cff4b71 | ani03sha/potd | /Python/ValidAnagram.py | 1,019 | 3.84375 | 4 | """
Given two strings s and t return whether or not s is an anagram of t.
Note: An anagram is a word formed by reordering the letters of another word.
"""
class ValidAnagram:
def isAnagram(self, s: str, t: str) -> bool:
# Base condition
if len(s) != len(t):
return False
# Counter for character frequencies
counter = {}
# Loop for eac character in the string
for i in range(len(s)):
if s[i] in counter:
counter[s[i]] += 1
else:
counter[s[i]] = 1
if t[i] not in counter:
counter[t[i]] = 0
counter[t[i]] -= 1
# Check if there is character whose count is non-zero
for key, value in counter.items():
if value != 0:
return False
return True
if __name__ == "__main__":
v = ValidAnagram()
print(v.isAnagram("aa", "bb"))
print(v.isAnagram("anagram", "nagaram"))
print(v.isAnagram("rat", "car"))
|
a7d7644bb975a5fed15249d69821d64077028729 | ramonVDAKKER/mortgage_calculus | /mortgage_calculus/interest_and_redemption.py | 3,291 | 3.96875 | 4 | """This module provides functions related to redemptions and interest."""
from typing import Optional, Union, Tuple
import pandas as pd
import numpy as np
def determine_annuity(
months_to_legal_maturity: int, outstanding_balance: float, interest_rate:
float) -> float:
"""Calculate the (monthly) annuity.
For mortgage with specified months_to_legal_maturity (>=1), outstanding
balance, and interest rate (decimal, annual).
"""
tau = interest_rate / 12
kappa = (1 + tau) ** months_to_legal_maturity
return outstanding_balance * tau * kappa / (kappa - 1)
def determine_interest(outstanding_balance: float, interest_rate:
float) -> float:
"""Determine the interest of a mortgage.
In a month in case the principal at start of the month is given by
outstanding_balance and the interest rate is given by interest_rate
(as decimal, annual).
"""
return outstanding_balance * interest_rate / 12
def determine_redemption_linear(
months_to_legal_maturity: int, outstanding_balance: float
) -> float:
"""Determine the redemption of linear mortgage.
In month t in case the principal at start of the month is given by outstanding_balance
"""
return outstanding_balance / months_to_legal_maturity
def determine_redemption_bullet(months_to_legal_maturity: int, outstanding_balance: float
) -> float:
"""Determine the redemption of bullet mortgage.
In a month in case the principal at start of the month is given by outstanding_balance.
"""
return outstanding_balance if months_to_legal_maturity == 1 else 0
def determine_redemption_annuity(
months_to_legal_maturity: int,
outstanding_balance: float,
interest_rate: float,
annuity: Optional[float] = None,
) -> float:
"""Calculate the redemption of an annuity mortgage.
On basis of the outstanding_balance at the start of the month, the interest rate, and the
months to legal maturity. The annuity can optionally be given in case it has
been calculated elsewhere.
"""
if annuity is None:
annuity = determine_annuity(
months_to_legal_maturity, outstanding_balance, interest_rate
)
return annuity - determine_interest(outstanding_balance, interest_rate)
def determine_redemption(
months_to_legal_maturity: int,
outstanding_balance: float,
mortgage_type: str,
interest_rate: Optional[float] = None,
) -> float:
"""Determine the redemption of mortgage.
For mortgage of type mortgage_type, in a month in case the principal at
start of the month is given by outstanding_balance. In case of
annuity the interest_rate is required as input.
"""
if mortgage_type == "bullet":
return determine_redemption_bullet(
months_to_legal_maturity, outstanding_balance
)
elif mortgage_type == "linear":
return determine_redemption_linear(
months_to_legal_maturity, outstanding_balance
)
elif mortgage_type == "annuity":
return determine_redemption_annuity(
months_to_legal_maturity, outstanding_balance, interest_rate, None
)
|
19a4eec72c959963e8b9159b608facd021a487e9 | zdgriffith/exercism | /python/word-count/word_count.py | 371 | 3.75 | 4 | def word_count(phrase):
spaced_phrase = ''
for c in phrase:
if c.isalnum():
spaced_phrase += c.lower()
else:
spaced_phrase += ' '
words = {}
for word in spaced_phrase.split():
if word not in words.keys():
words[word] = 1
else:
words[word] += 1
return words
|
a283f8985295973b49feb41db7cc75bfd0729179 | zdgriffith/exercism | /python/isogram/isogram.py | 325 | 4.0625 | 4 | def is_isogram(word):
char_list = []
for char in word.lower(): #make all letters lowercase to avoid mixed cases
if char.isalpha(): #only care about letters in the phrase
if char in char_list:
return False
else:
char_list.append(char)
return True
|
965fd4b67e626cdedb5013e9ed2b9cd20238d738 | dheerajgss/onlineCodingProblems | /Coding Blocks/uglyNumber.py | 414 | 4.09375 | 4 | """Find out the nth ugly number. Ugly numbers are positive numbers whose prime factors only
include 2, 3, 5.
Ex: i/p -> n = 10
o/p -> 12
Explanation: 1 2 3 4 5 6 8 9 10 12 is the sequence of 1st 10 ugly numbers. So 10th ugly number is 12."""
n = int(input())
count = 1
i = 1
while(count < n):
i += 1
if(i % 2 == 0 or i % 3 == 0 or i % 5 == 0):
count += 1
print(i) |
89e569fdefc8d5ae00c7fe33caef19039580757b | dheerajgss/onlineCodingProblems | /Coding Blocks/sortedSquaredArray.py | 621 | 3.78125 | 4 | """Given a sorted array of integers, print the sorted array of squares of the given integers.
Ex: i/p = [-5, -3, 0, 1, 2, 4]
o/p = [0, 1, 4, 9, 16, 25]
Constraints:
1 <= n <= 100000
-100000 <= a[i] <= 100000
Note:
Input will be always given in sorted order. """
l = sorted(list(map(int, input().split())))
p1 = 0
pn = len(l) - 1
m = [0 for x in range(len(l))]
i = len(l) - 1
while(p1 <= pn):
if(l[p1]**2 > l[pn]**2):
m[i] = l[p1]**2
i -= 1
p1 += 1
else:
m[i] = l[pn]**2
i -= 1
pn -= 1
print(m) |
126ba2113fe13cb7a8008b772793718001df3c94 | KacperKubara/USAIS_Workshops | /Clustering/k-means.py | 1,734 | 4.1875 | 4 | # K-NN classification with k-fold cross validation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Read Data
dataset = pd.read_csv("Mall_Customers.csv")
# Choose which features to use
x = dataset.iloc[:, 3:5].values # Features - Age, annual income (k$)
"""
K-Means clustering is unsupervised ML algorithm. It means that
it will figure the classes on its own (contrary to ML classification algorithms)
The purpose of clustering is to find out if a certain group of data points have
similar charactertics, i.e. if they create a cluster
Therefore, we won't need train-test split. Feature scaling might also be unnecessary
as the 2 features have v.similar values
"""
inertia = []
cluster_count = []
from sklearn.cluster import KMeans
for i in range(1,15):
cluster = KMeans(n_clusters = i, random_state = 42)
cluster.fit(x)
inertia.append(cluster.inertia_)
cluster_count.append(i)
fig0, ax0 = plt.subplots()
ax0.plot(cluster_count, inertia)
ax0.set_title("Elbow Method")
ax0.set_xlabel("No. clusters")
ax0.set_ylabel("WCSS")
# By looking on the elbow method plot,
# let's choose n_clusters = 5
# Cluster the data and assign labels ('classes')
cluster = KMeans(n_clusters = 5, random_state = 42)
y_pred = cluster.fit_predict(x)
# Visualise Results
from matplotlib import colors
my_colors = list(colors.BASE_COLORS.keys())
fig1, ax1 = plt.subplots()
ax1.set_title("Clusters")
ax1.set_xlabel("Annual Income")
ax1.set_ylabel("Spending Score")
# Plotting cluster
for i, label in enumerate(cluster.labels_):
ax1.scatter(x[i, 0], x[i, 1], c = my_colors[label])
ax1.scatter(cluster.cluster_centers_[:, 0], cluster.cluster_centers_[:, 1],
s = 300, c = 'yellow', label = 'Centroids')
|
40bda47b522a9e360f849fb9c5dea651f55e5da0 | Chitrank-Dixit/PyAlgo | /build/lib/pyalgo.py | 479 | 4.03125 | 4 | """
This is the operations.py module that has all the basic operations specified that will be used frquently in programming
"""
class Swap(object):
"""
Takes two values and swaps them
Basic Usage:
swap_obj = Swap(1,2)
value2, value1 = swap_obj.get_swap_values()
"""
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
def get_swap_values(self):
return self.value2, self.value1
|
8b05426a7d8b2caa7544ac22231a3952aba13f67 | Chitrank-Dixit/PyAlgo | /algos/searching/linear_search.py | 732 | 3.875 | 4 | """
This is the operations module that has all the searching operations that will be used frequently in programming
"""
class LinearSearch(object):
"""
Takes two values and swaps them
Basic Usage:
>>> instance = LinearSearch([12,34,23,56,45,67])
>>> item_index = instance.search_item(23)
>>> print item_index
2
"""
def __init__(self, *args):
self.input_list = args[0]
def search_item(self, key):
found = []
for index, item in enumerate(self.input_list):
if key == item:
found.append(index)
if len(found) == 0:
return None
elif len(found) > 1:
return found
return found[0]
|
3adc3dc9ee49075fe30386b9d5364a64ae404042 | rishabh78sharma/BasicCoding | /geekcoders/prime.py | 191 | 3.6875 | 4 | a=int(input("enter first no."))
b =int(input("enter second no."))
c=0
for i in range(a,b+1):
for j in range(2,i):
if (i%j==0):
break
else:
print(i) |
27fc3284eee75420fca4efa411874dd04218536a | rishabh78sharma/BasicCoding | /geekcoders/intfunction.py | 123 | 3.921875 | 4 | number_=int(input("enter first number"))
number_2=int(input("enter second number"))
print("total is"+str(number_+number_2)) |
ba167f75d6c29f9346b3ed6378c2f945b767a0ed | rishabh78sharma/BasicCoding | /geekcoders/functionlist.py | 224 | 3.625 | 4 | global t
n=input("enter the number till the loop is work ")
t=int(n)
user=list(range(1,t))
def squalist(l):
square=[]
for i in l:
user =square.append(i**2)
return square
print(user)
print(squalist(user)) |
ffa28ca598e21a39dc5383b52d767b75ce5f1cc5 | rishabh78sharma/BasicCoding | /geekcoders/list.py | 150 | 3.734375 | 4 | list =['mango',"graped",1,1,1]
# print(list)
# list[0:]=["mango"]
# print(list)
# list.append("red")
# print(list)
list.insert(1,"hariom")
print(list) |
5145d5d6d484e1a564c31e0718e9675f889918c4 | liuxiang0/pi | /iteration_pi.py | 3,366 | 3.8125 | 4 | #!/usr/bin/python
# -*- encoding: UTF-8 -*-
"""
代数几何迭代算法, 迭代逼近单位圆的半周长 $\pi$, 从而得到圆周率 π
初始状态:取单位圆的内接正六边形,其变成为 1.
从正六边形得到正十二边形的半周长,以此类推,迭代以此,边数增加一倍。
求边长的迭代函数为 f(x)=sqrt(2-sqrt(4-x**2))
迭代次数:n
对应半周长:6*2**(n-1)*f(x)
采取:迭代生成器方法,和符号运算法则,得到迭代序列。需要时再计算某个迭代值。
讨论:如何通过相邻几个迭代值,计算出迭代误差值,或结果的精度。
好像只能字符判断,不能用浮点数判断。
"""
# from math import sqrt
from sympy import sqrt
import timeit
def HalfCircumference():
'''迭代生成器: 生成单位圆上的正 6*2**n 边形的半周长'''
L = 1 # 初始值,正六边形的边长为 L6 = 1
n = 0
while True:
L = sqrt(2-sqrt(4-L*L)) # 迭代公式
n = n + 1 # 迭代次数
yield 6*2**(n-1)*L # 迭代产生的半周长,符号运算结果
def iterate_HalfCircumference(n):
'''不用迭代生成器,直接生成指定迭代次数的正多边形的半周长'''
L = 1 # 初始值,正六边形的边长为 L6 = 1
k = 0
while k < n:
L = sqrt(2-sqrt(4-L*L))
k += 1
return 6*2**(n-1)*L
def Compare(a,b):
'''通过判断字符串的差异,得到两数之间的误差,获取精度,输出小数点后第几位开始不同 '''
k = 0
sup = min(len(a),len(b))
for i in range(sup):
if a[i]==b[i]:
k += 1
else:
break
return k-2 # 剔除首两位的 3.
def Fibo():
'''Fibonacci数列,斐波那契数列的迭代生成法 F_n = F_{n-1} + F_{n-2}'''
a,b = 0,1
while True:
a, b = b, a+b
yield a
if __name__=='__main__':
print("开始计算了......")
cir = HalfCircumference() # 几乎不花时间1.7999999999407379e-06
start = timeit.default_timer()
for i in range(100): # 150次迭代耗时最多,为77.1517524s
next(cir) # 舍弃前面的精度不高的值
#stop = timeit.default_timer()
#print('next Elapsed(s)={T}'.format(T=stop-start))
# TODO 如何得到精度值,通过相邻几个迭代值获取精度值?
Prev = next(cir).evalf(100)
#start = timeit.default_timer()
for i in range(30): # 计算在此花了 18.6607882秒
Next = next(cir).evalf(100)
print(Next) # 保留后面的精度较高的π值
print("精确到小数点后{0}位".format(Compare(str(Prev),str(Next))))
Prev = Next
stop = timeit.default_timer()
print('结束总耗时(s)={T}'.format(T=stop-start))
"""
fib = Fibo() # 测试迭代生成器的工作原理
for i in range(5):
print(next(fib))
"""
"""
nmin, valid = 12, 40
nmax = nmin + 10 # 每次迭代10个
print("min={0},max={1},valid={2}".format(nmin,nmax,valid))
for i in range(nmin, nmax):
pi = iterate_HalfCircumference(i).evalf(valid)
print(pi, end=',')
"""
|
29499975de28aeab41267755656eab4fd9862682 | eborche2/aoc2019 | /day12/day12.py | 3,122 | 3.5 | 4 | from itertools import combinations
import copy
def adjust_velocity(moon_pair):
first_moon = moon_pair[0]
second_moon = moon_pair[1]
for x in range(3):
if first_moon['p'][-1][x] > second_moon['p'][-1][x]:
first_moon['v'][-1][x] -= 1
second_moon['v'][-1][x] += 1
elif first_moon['p'][-1][x] < second_moon['p'][-1][x]:
first_moon['v'][-1][x] += 1
second_moon['v'][-1][x] -= 1
return first_moon, second_moon
def adjust_position(_moon):
for x in range(3):
_moon['p'][-1][x] += _moon['v'][-1][x]
_moon['p'][-1] = tuple(moon['p'][-1])
_moon['v'][-1] = tuple(moon['v'][-1])
return _moon
def _adjust_velocity(_new_pos, _new_vel, pos):
compared = [0]
for x, first in enumerate(_new_pos):
compared.append(x)
for z, second in enumerate(_new_pos):
if z in compared:
continue
if first[pos] > second[pos]:
_new_vel[x][pos] -= 1
_new_vel[z][pos] += 1
elif first[pos] < second[pos]:
_new_vel[x][pos] += 1
_new_vel[z][pos] -= 1
return _new_vel
def _adjust_position(_new_pos, pos):
for i, moon in enumerate(_new_pos):
_new_pos[i][pos] = moon[pos] + new_vel[i][pos]
return _new_pos
def check(position):
for i in range(4):
if pos[i][position] != new_pos[i][position]:
return False
if vel[i][position] != new_vel[i][position]:
return False
return True
Io = {
'p': [[-4, 3, 15]],
'v': [[0, 0, 0]]
}
Europa = {
'p': [[-11, -10, 13]],
'v': [[0, 0, 0]]
}
Ganymede = {
'p': [[2, 2, 18]],
'v': [[0, 0, 0]]
}
Callisto = {
'p': [[7, -1, 0]],
'v': [[0, 0, 0]]
}
moons = [Io, Europa, Ganymede, Callisto]
original = copy.deepcopy(moons)
for x in range(1000):
for moon in moons:
moon['p'].append(list(moon['p'][-1][:]))
moon['v'].append(list(moon['v'][-1][:]))
for pair in combinations(moons, 2):
moons[moons.index(pair[0])], moons[moons.index(pair[1])] = adjust_velocity(pair)
for i, moon in enumerate(moons):
moons[i] = adjust_position(moon)
total_energy = 0
for moon in moons:
vel = [abs(x) for x in moon['v'][-1]]
pos = [abs(x) for x in moon['p'][-1]]
total_energy += sum(vel) * sum(pos)
print(total_energy) #part 1
pos = [[-4, 3, 15], [-11, -10, 13], [2, 2, 18], [7, -1, 0]]
vel = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
path = [0, 0, 0]
new_pos = copy.deepcopy(pos)
new_vel = copy.deepcopy(vel)
# borrowed from https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-37.php
def gcd(x, y):
return y and gcd(y, x % y) or x
def lcm(x, y):
return x * y / gcd(x, y)
for position in range(3):
found = False
print("here")
while not found:
path[position] += 1
new_vel = _adjust_velocity(new_pos, new_vel, position)
new_pos = _adjust_position(new_pos, position)
found = check(position)
n = path[0]
for i in path:
n = lcm(n, i)
print(n) # Part 2 :(
|
cbd801cabdf6e7bba1ae2620557533d557e25b83 | hborawski/dailyprogrammer | /243Deficient/deficient | 445 | 3.90625 | 4 | #!/usr/bin/env python3
def main():
num = int(input("Input number:"))
sig = sigma(num)
if sig < num*2:
print("{} deficient".format(num))
elif sig > nm*2:
print("{} abundant by {}".format(num, sig-(num*2)))
else:
print("{} ~~neither~~".format(num))
def sigma(n):
sig = 0
for i in range(1, n+1):
if n%i == 0:
sig += i
return sig
if __name__ == "__main__":
main()
|
bbc0e8be78cfa289bd48b7f34f49d001483c9d48 | hborawski/dailyprogrammer | /217SpaceCode/space | 1,066 | 3.546875 | 4 | #!/usr/bin/env python3
def main():
words = [line.strip() for line in open('/usr/share/dict/words')]
for line in open("input.txt"):
line = line.strip().replace("\"","").split()
results = [earth(line), ryza(line), hoth(line), omicron(line)]
for result in results:
if result.split()[0].lower() in words:
print(result)
def omicron(chars):
result = ""
for char in chars:
bits = "{0:08b}".format(int(char))
newbits = bits[0:3]
if bits[3] == '0':
newbits += '1'
else:
newbits += '0'
newbits += bits[4:]
result += chr(int(newbits, 2))
return result
def hoth(chars):
result = ""
for char in chars:
result += chr(int(char) + 10)
return result
def ryza(chars):
result = ""
for char in chars:
result += chr(int(char) - 1)
return result
def earth(chars):
result = ""
for char in chars:
result += chr(int(char))
return result[::-1]
if __name__ == "__main__":
main()
|
ef176517aef87306214a52f1ef0ab37e89b0d269 | ganenchaoshi/PythonExercises | /100exercises/ex005.py | 484 | 3.5625 | 4 | # 输入三个整数x,y,z,请把这三个数由小到大输出。
# numbs = input('输入三个整数并以空格分隔')
# numbslist = numbs.split(' ')
# print(sorted(numbslist))
input1 = int(input('输入第一个整数'))
input2 = int(input('输入第二个整数'))
input3 = int(input('输入第三个整数'))
x = y = z = input1
ls = [input1, input2, input3]
for i in ls:
if i > x:
x = i
elif i < z:
z = i
else:
y = i
print(f'{z}\n{y}\n{x}') |
d993224020c27d65d748c9cbef2b05eba84b78bb | ganenchaoshi/PythonExercises | /100exercises/ex025.py | 233 | 3.59375 | 4 | # 求1+2!+3!+...+20!的和。
sum = 0
for i in range(1,21):
count = 1
for j in range(i,0,-1):
count *= j
sum += count
print(sum)
n = 0
s = 0
t = 1
for n in range(1,21):
t *= n
print(t)
s += t
print(s) |
0956ee7a737706c0362ef1c43c5cee24c673c448 | ganenchaoshi/PythonExercises | /lpthw3/projects/gothonweb/gothonweb/planisphere.py | 2,295 | 3.515625 | 4 | class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
self.paths.update(paths)
central_corridor = Room("Central Corridor",
"""
The Gothons of Planet Percal #25 have invaded your ship and
destroyed your entire crew. You are the last surviving
member and your last mission is to get the neutron destruct
bomb from the Weapons Armory, put it in the bridge, and
blow the ship up after getting into an escape pod.
You're running down the central corridor to the Weapons
Armory when a Gothon jumps out, red scaly skin, dark grimy
teeth, and evil clown costume flowing around his hate
filled body. He's blocking the door to the Armory and
about to pull a weapon to blast you.
""")
laser_weapon_armory = Room("Laser Weapon Armory",
"""
If you get the code wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
""")
the_bridge = Room("The Bridge",
"""
You burst into bridge and surprise 5 Gothons who are
trying to take control of the ship.
""")
escape_pod = Room("Escape pod", "There's 5 pod, which one do you take?")
the_end_winner = Room("The End", "You jump into pod 2.You Won!")
the_end_loser = Room("The End", "You jump into a random pod.the pod explodes.")
escape_pod.add_paths({
'2': the_end_winner,
'*': the_end_loser
})
generic_death = Room("death", "You died.")
the_bridge.add_paths({
'throw the bomb': generic_death,
'slowly place the bomb':escape_pod
})
laser_weapon_armory.add_paths({
'0132': the_bridge,
'*': generic_death
})
central_corridor.add_paths({
'shoot!': generic_death,
'dodge!': generic_death,
'tell a joke': laser_weapon_armory
})
START = 'central_corridor'
def load_room(name):
"""
There is a potential security problem here.
Who gets to set name? Can that expose a variable?
"""
return globals().get(name)
def name_room(room):
"""
Same possible security problem. Can you trust room?
What's a better solution than this global lookup?
"""
for key, value in globals().items():
if value == room:
return key
|
db5b1c33e04483ed3737725011bc9ad2516a7f76 | ganenchaoshi/PythonExercises | /Calculate_Pi/calcu_Pi01.py | 525 | 3.546875 | 4 | # 使用蒙特卡洛方法求Pi
import random
turns = int(input('请输入试验点数:')) # 实验次数
counts = 0 # 落在半径为1的圆内的点数
area = 0 # 四分之一圆的面积
i = 0 # 累加数
while i < turns:
a = random.random()
b = random.random()
if a**2 + b**2 <= 1: # 判断点是否在圆内
counts += 1
i += 1
else:
area = counts / turns # 边长为1的正方形乘以落在圆内的比例求面积
pi = 4 * area
print(f'通过{turns}试验点数求出的pi为{pi}')
|
f1437444cea1e8124849ed41f62ba4783afe5956 | ganenchaoshi/PythonExercises | /100exercises/ex002.py | 1,068 | 3.515625 | 4 | # 企业发放的奖金根据利润提成。
# 利润(I)低于或等于10万元时,奖金可提10%;
# 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
# 20万到40万之间时,高于20万元的部分,可提成5%;
# 40万到60万之间时高于40万元的部分,可提成3%;
# 60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,
# 从键盘输入当月利润I,求应发放奖金总数?
bonus = 0
i = float(input('输入当月利润(单位为万)'))
if i > 100:
bonus = (i - 100) * 0.01 + 40 * 0.015 + 20 * 0.03 + 20 * 0.05 + 10 * 0.075 + 10 * 0.1
elif i > 60:
bonus = (i - 60) * 0.015 + 20 * 0.03 + 20 * 0.05 + 10 * 0.075 + 10 * 0.1
elif i > 40:
bonus = (i - 40) * 0.03 + 20 * 0.05 + 10 * 0.075 + 10 * 0.1
elif i > 20:
bonus = (i - 20) * 0.05 + 10 * 0.075 + 10 * 0.1
elif i > 10:
bonus = (i - 10) * 0.075 + 10 * 0.1
else:
bonus = i * 0.1
print(f'奖金总数为{bonus}万')
|
cdb33f1546bf280ff205fe68e8f2b62e2fb2023b | Girech/Lista-2 | /Ex23.py | 122 | 3.765625 | 4 | metros = float(input("Digite o valor em jardas:"))
jardas = metros/0.91
print("o valor em jardas é de:{}".format(jardas)) |
d1ded0827b65a857206de62c9a5b419188290e10 | Girech/Lista-2 | /Ex4.py | 123 | 3.953125 | 4 | numero = float(input("Digite um numero real:"))
exp = numero**2
print("O quadrado de {} resulta em: {}".format(numero,exp)) |
ba4024c7bd3337e6e8495eb51c575aa9e2bba5b4 | charlie-boy/python | /prg.py | 359 | 3.890625 | 4 | def add(a,b):
return a+b
def mul(a,b):
return a*b
def sub(a,b):
return a-b
def div(a,b):
return a/b
a=int(raw_input("Enter first number:"))
b=int(raw_input("Enter second number:"))
x=raw_input("1.add\n2.mul\n3.sub\n4.div\nEnter your choice:")
if x=="1":
print(add(a,b))
elif x=="2":
print(mul(a,b))
elif x=="3":
print(sub(a,b))
else:
print(div(a,b))
|
93811c68b09b9135e41a166ecf0b1d88d015b486 | charlie-boy/python | /battleship.py | 2,339 | 3.9375 | 4 | from random import randint
#from goto import goto, label
b1=[]
b2=[]
count = 0
s1 = int(raw_input("Enter size of first battleship: "))
s2 = int(raw_input("Enter size of second battleship: "))
for i in range(0,s1):
b1.append(["O"]*s1)
for j in range(0,s2):
b2.append(["O"]*s2)
def print_board(board):
for row in board:
print " ".join(row)
print "Board 1:"
print_board(b1)
print "\n"
print "Board 2:"
print_board(b2)
def random_row(board):
return randint(0,len(board)-1)
def random_col(board):
return randint(0,len(board)-1)
#label rematch
ship_row_1 = random_row(b1)
ship_col_1 = random_col(b1)
ship_row_2 = random_row(b2)
ship_col_2 = random_col(b2)
for turn in range(2):
print "Turn - "
print turn+1
print "Player 1: "
guess_row_1 = int(raw_input("Guess the row of first ship: "))
guess_col_1 = int(raw_input("Guess the col of first ship: "))
print "Player 2: "
guess_row_2 = int(raw_input("Guess the row of second ship: "))
guess_col_2 = int(raw_input("Guess the col of second ship: "))
if guess_row_1 == ship_row_1 and guess_col_1 == ship_col_1:
print "Player 1 wins"
break
elif guess_row_2 == ship_row_2 and guess_col_2 == ship_col_2:
print "Player 2 wins"
break
else:
count = count + 1
if (guess_row_1 < 0 or guess_row_1 > s1-1) or (guess_col_1 < 0 or guess_col_1 > s1-1):
print "Oops, that's not even in the ocean. Player 1 play nice"
elif(b1[guess_row_1][guess_col_1] == "X"):
print "You guessed that one already. Player 1"
else:
print "You missed battleship! Player 1"
b1[guess_row_1][guess_col_1] = "X"
if (guess_row_2 < 0 or guess_row_2 > s2-1) or (guess_col_1 < 0 or guess_col_1 > s2-1):
print "Oops, that's not even in the ocean. Player 2 play nice"
elif(b2[guess_row_2][guess_col_2] == "X"):
print "You guessed that one already. Player 2"
else:
print "You missed battleship! Player 2"
b2[guess_row_2][guess_col_2] = "X"
print "Board 1 : "
print_board(b1)
print "\nBoard 2 : "
print_board(b2)
if count==2:
print "Game Over"
#choise = raw_input("Do you want a rematch?(y/n)")
#if choise == "y" or choise == "Y":
# goto rematch
#else:
# print "game over"
|
49d767e89a6ee8b815787451e5b509fc3a138884 | keyuzh/cs161 | /PS1/problem5.py | 850 | 3.65625 | 4 | def have_common_key(A: MaxHeap, B: MaxHeap, n: int) -> bool:
try:
while n > 0:
# get the max element of each max heap and compare them
max_A = A.max()
max_B = B.max()
if max_A == max_B:
# common key found
return True
# extract max from whichever max heap that has larger max value
if max_A > max_B:
A.extractMax()
else:
B.extractMax()
# decrement n since we removed an element
n -= 1
except Exception:
# assume that max() and extractMax() will throw an exception if the max heap
# becomes empty, in this case there is no common key
return False
# if both max heap becomes empty (n == 0), also indicates no common key
return False
|
c92ba28a2db8538eed1376126fd30f9f156e5c15 | betty29/code-1 | /recipes/Python/573452_Assertithat_code_fragment_throws_particular/recipe-573452.py | 2,264 | 3.640625 | 4 | #!/usr/bin/env python
#-*- coding: iso-8859-1 -*-
###############################################################################
class expected:
def __init__(self, e):
if isinstance(e, Exception):
self._t, self._v = e.__class__, str(e)
elif isinstance(e, type) and issubclass(e, Exception):
self._t, self._v = e, None
else:
raise Exception("usage: with expected(Exception): or with expected(Exception(\"text\"))")
def __enter__(self):
try:
pass
except:
pass # this is a Python 3000 way of saying sys.exc_clear()
def __exit__(self, t, v, tb):
assert t is not None, "expected {0:s} to have been thrown".format(self._t.__name__)
return issubclass(t, self._t) and (self._v is None or str(v).startswith(self._v))
###############################################################################
if __name__ == "__main__": # some examples
try:
with expected("foo"):
pass
except Exception as e:
assert str(e) == "usage: with expected(Exception): or with expected(Exception(\"text\"))", str(e)
else:
assert False
with expected(ZeroDivisionError):
1 / 0
with expected(ZeroDivisionError("int division or modulo by zero")):
1 / 0
with expected(ZeroDivisionError("int division")):
1 / 0
try:
with expected(ZeroDivisionError):
1 / 2
except AssertionError as e:
assert str(e) == "expected ZeroDivisionError to have been thrown", str(e)
else:
assert False
try:
with expected(ZeroDivisionError("failure !!!")):
1 / 0
except ZeroDivisionError as e:
assert str(e) == "int division or modulo by zero", str(e)
else:
assert False
try:
with expected(ZeroDivisionError):
{}["foo"]
except KeyError as e:
assert str(e) == "'foo'", str(e)
else:
assert False
with expected(KeyError):
with expected(ZeroDivisionError):
with expected(RuntimeError):
{}["foo"]
with expected(Exception("int division or modulo by zero")):
1 / 0
with expected(Exception):
1 / 0
|
f0749405938e25a640b1955262887d8e5924397a | betty29/code-1 | /recipes/Python/52316_Dialect_for_sort_by_then_by/recipe-52316.py | 1,587 | 4.15625 | 4 | import string
star_list = ['Elizabeth Taylor',
'Bette Davis',
'Hugh Grant',
'C. Grant']
star_list.sort(lambda x,y: (
cmp(string.split(x)[-1], string.split(y)[-1]) or # Sort by last name ...
cmp(x, y))) # ... then by first name
print "Sorted list of stars:"
for name in star_list:
print name
#
# "cmp(X, Y)" return 'false' (0) when X and Y compare equal,
# so "or" makes the next "cmp()" to be evaluated.
# To reverse the sorting order, simply swap X and Y in cmp().
#
# This can also be used if we have some other sorting criteria associated with
# the elements of the list. We simply build an auxiliary list of tuples
# to pack the sorting criteria together with the main elements, then sort and
# unpack the result.
#
def sorting_criterium_1(data):
return string.split(data)[-1] # This is again the last name.
def sorting_criterium_2(data):
return len(data) # This is some fancy sorting criterium.
# Pack the auxiliary list:
aux_list = map(lambda x: (x,
sorting_criterium_1(x),
sorting_criterium_2(x)),
star_list)
# Sort:
aux_list.sort(lambda x,y: (
cmp(x[1], y[1]) or # Sort by criteria 1 (last name)...
cmp(y[2], x[2]) or # ... then by criteria 2 (in reverse order) ...
cmp(x, y))) # ... then by the value in the main list.
# Unpack the resulting list:
star_list = map(lambda x: x[0], aux_list)
print "Another sorted list of stars:"
for name in star_list:
print name
|
bca0c6e7245fdea86fedf0b49e9243a3d4ee8187 | betty29/code-1 | /recipes/Python/302218_Joe_Strouts_chatserverpy_converted/recipe-302218.py | 7,170 | 3.8125 | 4 | #!/usr/bin/env python
# A simple 94(*) lines of code "chat" server. Creates a server on port 4000.
# Users telnet to your machine, at port 4000, and can chat with each other.
# Use "quit" to disconnect yourself, and "shutdown" to shut down the server.
#
# Adapted from J. Strout version at
# http://www.strout.net/info/coding/python/tidbits.html#server
# Modified by me (Steve <lonetwin@yahoo.com>) as a follow-up assignment for
# a basic python lecture I conducted.
#
# Instructions: I have put various comments in the code.
# Some comments are preceded with the marker [Tip]. These comments
# explain some coding-style rules that might commonly be seen in python code.
# Some comments are preceded with the marker [n], where 'n' is a number.
# These comments have questions that have to be answered by mail to me.
# Please write the question number before the answer. To find the answers to
# these questions you may have to read the python documentation or search the
# web. In any case, feel free to contact me if you find any that are hard to
# answer.
# The comments at the bottom of the file are enhancements to this
# program. You are expected to write these on your own. You are free to use
# any references, including any code that you might find on the net for this
# purpose, with the only condition being that you should credit the source
# when you hand in the assignment.
#
from socket import * # [1] What does this statement do ?
import time # [2] How does this statement differ from the previous?
# [Tip] Read Chap. 6 of the official Python Tutorial
# define global variables
HOST = '' # [Tip] In the socket module, an empty string for the
# hostname by default maps to 'localhost'
PORT = 4000 # [3] Can I use 40 here instead ? why ?
endl = "\r\n" # [4] What is this character sequence and why has
# it been defined separately ?
userlist = [] # list of connected users
# some constants used to flag the state of user
kAskName, kWaitName, kOK = 0, 1, 2
# [5] What is the scope of all the variables defined above ?
# [Tip] Read section 9.2 of the official Python Tutorial
class User:
"""
class to store info about connected users
"""
def __init__(self, conn, addr):
self.conn, self.addr = conn, addr
self.name, self.step = "", kAskName
def poll(self):
if self.step == kAskName: self.AskName()
# [Tip] blocks with single statements need not be written on an
# indented line.
def AskName(self):
self.conn.send("Name? ")
self.step = kWaitName
def HandleMsg(self, msg):
print "Handling message: %s" % msg
global userlist # [6] What is the purpose of this statement ?
# if waiting for name, record it
if self.step == kWaitName:
# try to trap initial garbage sent by some telnet programs ...
if len(msg) < 2 or msg == "#": return
print "Setting name to: %s" % msg
self.name, self.step = msg, kOK
self.SendMsg("Hello, %s" % self.name)
broadcast("%s has connected." % self.name)
return
if msg == "quit": # check for commands
broadcast("%s has quit." % self.name)
self.conn.close()
userlist.remove(self)
else: # otherwise, broadcast msg
broadcast("%s: %s" % (self.name, msg))
def SendMsg(self, msg):
self.conn.send(msg + endl)
def pollNewConn(s):
"""
Routine to check for incoming connections. Accepts a socket object 's' as
argument and returns a User object 'user'
"""
try:
conn, addr = s.accept() # [Tip] Read the socket HOWTO
except:
return None
print "Connection from ", addr
conn.setblocking(0) # [7] What is the effect of this call ?
user = User(conn, addr)
return user
def broadcast(msg): # [8] Does this belong to the User class ?? support your
# answer with sufficient reasoning.
"""
Routine to broadcast a message to all connected users. Takes the argument
message 'msg', in the form '<sender>: <message>'
"""
map(lambda u: u.SendMsg(msg), \
filter(lambda u: u.name != msg.split(':')[0], \
userlist))
# [9] Convert the above map+lambda+filter into a readable loop+conditional
# Main Program
def main():
# set up the server
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.setblocking(0)
s.listen(1)
print "Waiting for connection(s)..."
# loop until done, handling connections and incoming messages
done = 0 # set to 1 to shut this down
while not done:
try:
time.sleep(1) # sleep to reduce processor usage
u = pollNewConn(s) # check for incoming connections
if u:
userlist.append(u)
print "%d connection(s)" % len(userlist)
for u in userlist: # check all connected users
u.poll()
try:
data = u.conn.recv(1024)
data = filter(lambda x: x >= ' ' and x <= 'z', data)
# [10] Rewrite the above statement as a List Comprehension.
data = data.strip()
if data:
print "From %s: [%s]" % (u.name, data)
u.HandleMsg(data)
if data == "shutdown": done=1
except:
pass # [11] What exception are we ignoring ? and why ?
except KeyboardInterrupt:
done=1
else: # [12] What does this statement imply ?
print "Shutting down ..." # [Tip] Read section 4.4 of the official
s.shutdown(2) # Python Tutorial
s.close()
# We are done, close all connections
for u in userlist:
u.conn.close()
if __name__ == '__main__': # [Tip] Read about the if __name__ == '__main__'
main() # trick in chap. 2 at diveintopython.org
# Rewrite the server program to do the following things:
# a) Log it's status/action messages (*not* the actual chat msgs) to a log
# file as well as print it out to the console.
# b) Enhance the User class to recognize more commands besides 'quit'.
# [Tip] We can implement this using a 'dispatcher' for example, I should be
# able to do something like this in the HandleMsg method:
# if msg in commands:
# cmd = getattr(self, command)
# cmd()
# c) Design and implement a client for this server.
# d) Take care of the problem in question no. [11]
# [Tip] Read section 5 of the Python Socket Programming HOWTO.
# e) Create a chat client/server package
# [Tip] Read 6.4 of the Official Python Tutorial
# (*) 94 == `egrep -v "(^[ ]*#)|(^[ ]*$)" chat_server.py | wc -l`
# vim: set tw=80 et ai sts=4 sw=4 ts=8:
|
da7d9b543243c19783719c409b67347ce4b126a3 | betty29/code-1 | /recipes/Python/304440_Sorting_dictionaries_value/recipe-304440.py | 843 | 4.21875 | 4 | # Example from PEP 265 - Sorting Dictionaries By Value
# Counting occurences of letters
d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
# operator.itemgetter is new in Python 2.4
# `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter
# Items sorted by key
# The new builtin `sorted()` will return a sorted copy of the input iterable.
print sorted(d.items())
# Items sorted by key, in reverse order
# The keyword argument `reverse` operates as one might expect
print sorted(d.items(), reverse=True)
# Items sorted by value
# The keyword argument `key` allows easy selection of sorting criteria
print sorted(d.items(), key=itemgetter(1))
# In-place sort still works, and also has the same new features as sorted
items = d.items()
items.sort(key = itemgetter(1), reverse=True)
print items
|
81a9c92401b4c7e36861eb61b7337e65ac9d904e | betty29/code-1 | /recipes/Python/577679_naive_natural_sort/recipe-577679.py | 483 | 3.671875 | 4 | def keynat(string):
'''A natural sort helper function for sort() and sorted()
without using regular expression.
'''
r = []
for c in string:
if c.isdigit():
if r and isinstance(r[-1], int):
r[-1] = r[-1] * 10 + int(c)
else:
r.append(int(c))
else:
r.append(c)
return r
|
93942d481a8b6be961f5fcb6f23a0ac6667e482e | betty29/code-1 | /recipes/Python/299777_Simplified_Mutable_Instances/recipe-299777.py | 351 | 3.65625 | 4 | class MutableInstance(dict):
def __init__(self):
self.__dict__ = self
# This makes common tasks easier, not by much but conceptually it unifies things
Foo = MutableInstance()
Foo.x = 5
assert Foo['x'] == 5
Foo.y = 7
assert Foo.keys() == ['x', 'y']
assert Foo.values() == [5, 7]
# And now you can pass it to anything that wants a dictionary too.
|
eb5f5d1f627ae6e822a7a133c498395b64b558bf | betty29/code-1 | /recipes/Python/306865_Observer_pattern_scalar/recipe-306865.py | 6,770 | 4.0625 | 4 | """
Implement an observer pattern for attribute access.
Assumes that each attribute is used (exclusivly) for either scalar
values, lists or maps.
It does not work if you store a scalar in an attribute, and then later
a map or list.
A scalar attribute is an attribute whose values do not have internal
structure. Scalars are integers, floats, (short) strings, and
references to instances and classes.
Provides some support to observe lists and dictionaries which are
assigned to attributes.
Usage pattern:
class c(object):
...some definitions...
class observer_class(object):
...some definitions...
observer = observer_class()
c.x = scalar_observer("x", observer)
i = c()
i.x = 13
# The assignment above will trigger a method call to observer.
For lists, you can use:
c.l = list_observer_in_instance("l", observer)
i = c()
i.l = l = [1, [1, 2], 3]
i.l.append(4)
# The append above will trigger a method call to observer.
# Two caveats here:
# 1. i.l now points to a different list than l.
# (you should probably avoid such aliasing).
# If you want to continue to use l, you should
# probably add:
# l = i.l
# 2. The inner list [1, 2] is *not* monitored.
# (if desired, invoke list_observer([1, 2], observer) instead
# of just [1, 2]).
The attribute is replaced by a descriptor in the class. The attributes
in the instances have too leading underscores (__).
"""
from list_dict_observer import list_observer, dict_observer, printargs
class scalar_observer(object):
"""
Observes a scalar attribute.
Can be used for integers, longs, floats, (short) strings, and
references to instances or classes.
Lists and dictionaries have specialized classes.
All assignments to the attributes are intercepted by
descriptors. The values themselves are stored in an attribute with
a name __<attributename>.
"""
def __init__ (self, external_attributename, observer):
self.external_attributename = external_attributename
self.private_attributename = '__'+external_attributename
self.observer = observer
def __set__ (self, instance, value):
private_attributename = self.private_attributename
external_attributename = self.external_attributename
try:
oldvalue = getattr(instance, private_attributename)
except AttributeError:
setattr(instance, private_attributename, value)
self.observer.scalar_set(instance, private_attributename, external_attributename)
else:
if oldvalue!=value:
setattr(instance, private_attributename, value)
self.observer.scalar_modify(instance, private_attributename, external_attributename, oldvalue)
def __get__ (self, instance, owner):
return getattr(instance, self.private_attributename)
class list_observer_in_instance(object):
"""
Observes instance attributes which contain a list as a value.
Assignments to these attributes, which must be lists, are replaced by instances of 'list_observer'.
Note that you are not notified by changes to inner lists or maps.
You should also be aware of aliasing.
"""
def __init__ (self, external_attributename, observer):
self.external_attributename = external_attributename
self.internal_attributename = '__'+external_attributename
self.observer = observer
def __set__ (self, instance, value):
"""Intercept assignments to the external attribute"""
assert isinstance(value, type([]))
if isinstance(value, list_observer):
newvalue = value
# if the value is already a list observer, assume that this value
# already has an observer. Do new create a new list in this case.
else:
newvalue = list_observer(value, self.observer)
internal_attributename = self.internal_attributename
try:
oldvalue = getattr(instance, internal_attributename)
except AttributeError:
self.observer.list_assignment_new(instance, internal_attributename)
else:
self.observer.list_assignment_replace(instance, internal_attributename, oldvalue)
setattr(instance, self.internal_attributename, newvalue)
def __get__ (self,instance,owner):
try:
return instance.__dict__[self.internal_attributename]
except KeyError:
return instance.__dict__[self.external_attributename]
class dict_observer_in_instance(object):
"""
observes instance attributes which contain a list as a value.
Assignments to this attributes, which must be dictionaries, are
replaced by instances of 'dict_observer'.
Note that you are not notified by changes to inner lists or maps.
You should also be aware of aliasing.
"""
def __init__ (self, external_attributename, observer):
self.external_attributename = external_attributename
self.internal_attributename = '__'+external_attributename
self.observer = observer
def __set__ (self, instance, value):
"""Intercept assignments to the external attribute"""
assert isinstance(value,type({}))
if isinstance(value,dict_observer):
newvalue = value
# if the value is already a dict_observer,
# assume that the value is already monitored.
else:
newvalue = dict_observer(value, self.observer)
internal_attributename = self.internal_attributename
try:
oldvalue = getattr(instance, internal_attributename)
except AttributeError:
setattr(instance, self.internal_attributename, newvalue)
self.observer.list_assignment_new(instance, internal_attributename)
else:
setattr(instance, self.internal_attributename, newvalue)
self.observer.list_assignment_replace(instance, internal_attributename, oldvalue)
def __get__ (self, instance, owner):
try:
return instance.__dict__[self.internal_attributename]
except KeyError:
return instance.__dict__[self.external_attributename]
if __name__ == '__main__':
# minimal demonstration of the observer pattern.
class c(object):
pass
observer = printargs()
i = c()
c.s = scalar_observer("x", observer)
i.s = 1
i.s = "hello"
c.l = list_observer_in_instance("l", observer)
i.l = [1, 2, 3]
i.l.append(1)
|
28f414c966b639ce76b138c54dd7026b5e194db8 | betty29/code-1 | /recipes/Python/579115_Recognizing_speech_speechtotext_Pythspeech/recipe-579115.py | 246 | 3.8125 | 4 | import string
import speech
while True:
print "Talk:"
phrase = speech.input()
speech.say("You said %s" % phrase)
print "You said {0}".format(phrase)
#if phrase == "turn off":
if phrase.lower() == "goodbye":
break
|
00db2c8c3ed972b7163d98736f55e12ede747a2c | betty29/code-1 | /recipes/Python/577538_Poor_Man_unit_tests/recipe-577538.py | 3,826 | 3.734375 | 4 | #! /usr/bin/env python
######################################################################
# Written by Kevin L. Sitze on 2010-12-03
# This code may be used pursuant to the MIT License.
######################################################################
import sys
import traceback
from types import FloatType, ComplexType
__all__ = (
'assertEquals',
'assertNotEquals',
'assertException',
'assertFalse',
'assertNone',
'assertNotNone',
'assertSame',
'assertNotSame',
'assertTrue'
)
def colon( msg ):
if msg:
return ": " + str( msg )
else:
return ""
def assertEquals( exp, got, msg = None ):
"""assertEquals( exp, got[, message] )
Two objects test as "equal" if:
* they are the same object as tested by the 'is' operator.
* either object is a float or complex number and the absolute
value of the difference between the two is less than 1e-8.
* applying the equals operator ('==') returns True.
"""
if exp is got:
r = True
elif ( type( exp ) in ( FloatType, ComplexType ) or
type( got ) in ( FloatType, ComplexType ) ):
r = abs( exp - got ) < 1e-8
else:
r = ( exp == got )
if not r:
print >>sys.stderr, "Error: expected <%s> but got <%s>%s" % ( repr( exp ), repr( got ), colon( msg ) )
traceback.print_stack()
def assertNotEquals( exp, got, msg = None ):
"""assertNotEquals( exp, got[, message] )
Two objects test as "equal" if:
* they are the same object as tested by the 'is' operator.
* either object is a float or complex number and the absolute
value of the difference between the two is less than 1e-8.
* applying the equals operator ('==') returns True.
"""
if exp is got:
r = False
elif ( type( exp ) in ( FloatType, ComplexType ) or
type( got ) in ( FloatType, ComplexType ) ):
r = abs( exp - got ) >= 1e-8
else:
r = ( exp != got )
if not r:
print >>sys.stderr, "Error: expected different values but both are equal to <%s>%s" % ( repr( exp ), colon( msg ) )
traceback.print_stack()
def assertException( exceptionType, f, msg = None ):
"""Assert that an exception of type \var{exceptionType}
is thrown when the function \var{f} is evaluated.
"""
try:
f()
except exceptionType:
assert True
else:
print >>sys.stderr, "Error: expected <%s> to be thrown by function%s" % ( exceptionType.__name__, colon( msg ) )
traceback.print_stack()
def assertFalse( b, msg = None ):
"""assertFalse( b[, message] )
"""
if b:
print >>sys.stderr, "Error: expected value to be False%s" % colon( msg )
traceback.print_stack()
def assertNone( x, msg = None ):
assertSame( None, x, msg )
def assertNotNone( x, msg = None ):
assertNotSame( None, x, msg )
def assertSame( exp, got, msg = None ):
if got is not exp:
print >>sys.stderr, "Error: expected <%s> to be the same object as <%s>%s" % ( repr( exp ), repr( got ), colon( msg ) )
traceback.print_stack()
def assertNotSame( exp, got, msg = None ):
if got is exp:
print >>sys.stderr, "Error: expected two distinct objects but both are the same object <%s>%s" % ( repr( exp ), colon( msg ) )
traceback.print_stack()
def assertTrue( b, msg = None ):
if not b:
print >>sys.stderr, "Error: expected value to be True%s" % colon( msg )
traceback.print_stack()
if __name__ == "__main__":
assertNone( None )
assertEquals( 5, 5 )
assertException( KeyError, lambda: {}['test'] )
assertNone( 5, 'this assertion is expected' )
assertEquals( 5, 6, 'this assertion is expected' )
assertException( KeyError, lambda: {}, 'this assertion is expected' )
|
809a2e466bf5784e776a0249cf43460147cb14e0 | betty29/code-1 | /recipes/Python/578935_Garden_Requirements_Calculator/recipe-578935.py | 2,723 | 4.21875 | 4 | '''
9-16-2014
Ethan D. Hann
Garden Requirements Calculator
'''
import math
#This program will take input from the user to determine the amount of gardening materials needed
print("Garden Requirements Calculator")
print("ALL UNITS ENTERED ARE ASSUMED TO BE IN FEET")
print("_____________________________________________________")
print("")
#Gather all necessary input from user
side_length = input("Enter the length of one side of garden: ")
spacing = input("Enter the spacing between plants: ")
depth_garden = input("Enter the depth of the garden soil: ")
depth_fill = input("Enter the depth of the fill: ")
#Convert input to floats so that we can do math with them
side_length = float(side_length)
spacing = float(spacing)
depth_garden = float(depth_garden)
depth_fill = float(depth_fill)
#Calculate radius of each circle and semi-circle
r = side_length / 4
#1 - Number of plants for all semi-circles
area = (math.pi * (r**2)) / 2
number_plants_semi = math.trunc(area / (spacing**2))
#2 - Number of plants for the circle garden
area = math.pi * (r**2)
number_plants_circle = math.trunc(area / (spacing**2))
#3 - Total number of plants for garden
total_number_plants = number_plants_circle + (number_plants_semi*4)
#4 - Soil for each semi-circle garden in cubic yards
volume = (math.pi * (r**2) * depth_garden) / 2
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_semi = round(cubic_volume, 1)
#5 - Soil for circle garden in cubic yards
volume = math.pi * (r**2) * depth_garden
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_circle = round(cubic_volume, 1)
#6 - Total amount of soil for the garden
total_soil = (cubic_volume_rounded_semi * 4) + cubic_volume_rounded_circle
total_soil_rounded = round(total_soil, 1)
#7 - Total fill for the garden
volume_whole = (side_length**2) * depth_fill
all_volume_circle = (math.pi * (r**2) * depth_garden) * 3
total_volume_fill = volume_whole - all_volume_circle
cubic_total_volume_fill = total_volume_fill / 27
cubic_total_volume_fill_rounded = round(cubic_total_volume_fill, 1)
#Print out the results
print("")
print("You will need the following...")
print("Number of plants for each semi-circle garden:", number_plants_semi)
print("Number of plants for the circle garden:", number_plants_circle)
print("Total number of plants for the garden:", total_number_plants)
print("Amount of soil for each semi-circle garden:", cubic_volume_rounded_semi, "cubic yards")
print("Amount of soil for the circle garden:", cubic_volume_rounded_circle, "cubic yards")
print("Total amount of soil for the garden:", total_soil_rounded, "cubic yards")
print("Total amount of fill for the garden:", cubic_total_volume_fill_rounded, "cubic yards")
|
a5f84a55c7614def6497c4376b26ad7469a6a13e | betty29/code-1 | /recipes/Python/194371_Case_Insensitive_Strings/recipe-194371.py | 1,847 | 3.703125 | 4 | class iStr(str):
"""Case insensitive strings class.
Performs like str except comparisons are case insensitive."""
def __init__(self, strMe):
str.__init__(self, strMe)
self.__lowerCaseMe = strMe.lower()
def __repr__(self):
return "iStr(%s)" % str.__repr__(self)
def __eq__(self, other):
return self.__lowerCaseMe == other.lower()
def __lt__(self, other):
return self.__lowerCaseMe < other.lower()
def __le__(self, other):
return self.__lowerCaseMe <= other.lower()
def __gt__(self, other):
return self.__lowerCaseMe > other.lower()
def __ne__(self, other):
return self.__lowerCaseMe != other.lower()
def __ge__(self, other):
return self.__lowerCaseMe >= other.lower()
def __cmp__(self, other):
return cmp(self.__lowerCaseMe, other.lower())
def __hash__(self):
return hash(self.__lowerCaseMe)
def __contains__(self, other):
return other.lower() in self.__lowerCaseMe
def count(self, other, *args):
return str.count(self.__lowerCaseMe, other.lower(), *args)
def endswith(self, other, *args):
return str.endswith(self.__lowerCaseMe, other.lower(), *args)
def find(self, other, *args):
return str.find(self.__lowerCaseMe, other.lower(), *args)
def index(self, other, *args):
return str.index(self.__lowerCaseMe, other.lower(), *args)
def lower(self): # Courtesy Duncan Booth
return self.__lowerCaseMe
def rfind(self, other, *args):
return str.rfind(self.__lowerCaseMe, other.lower(), *args)
def rindex(self, other, *args):
return str.rindex(self.__lowerCaseMe, other.lower(), *args)
def startswith(self, other, *args):
return str.startswith(self.__lowerCaseMe, other.lower(), *args)
|
d122b9e1caf600e4ebb59aa4abb8bf2ded1c40a1 | betty29/code-1 | /recipes/Python/577691_Validate_ACNs_AustraliCompany/recipe-577691.py | 2,451 | 4 | 4 | def isacn(obj):
"""isacn(string or int) -> True|False
Validate an ACN (Australian Company Number).
http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit
Accepts an int, or a string of digits including any leading zeroes.
Digits may be optionally separated with spaces. Any other input raises
TypeError or ValueError.
Return True if the argument is a valid ACN, otherwise False.
>>> isacn('004 085 616')
True
>>> isacn('005 085 616')
False
"""
if isinstance(obj, int):
if not 0 <= obj < 10**9:
raise ValueError('int out of range for an ACN')
obj = '%09d' % obj
assert len(obj) == 9
if not isinstance(obj, str):
raise TypeError('expected a str or int but got %s' % type(obj))
obj = obj.replace(' ', '')
if len(obj) != 9:
raise ValueError('ACN must have exactly 9 digits')
if not obj.isdigit():
raise ValueError('non-digit found in ACN')
digits = [int(c) for c in obj]
weights = [8, 7, 6, 5, 4, 3, 2, 1]
assert len(digits) == 9 and len(weights) == 8
chksum = 10 - sum(d*w for d,w in zip(digits, weights)) % 10
if chksum == 10:
chksum = 0
return chksum == digits[-1]
if __name__ == '__main__':
# Check the list of valid ACNs from the ASIC website.
ACNs = '''
000 000 019 * 000 250 000 * 000 500 005 * 000 750 005
001 000 004 * 001 250 004 * 001 500 009 * 001 749 999
001 999 999 * 002 249 998 * 002 499 998 * 002 749 993
002 999 993 * 003 249 992 * 003 499 992 * 003 749 988
003 999 988 * 004 249 987 * 004 499 987 * 004 749 982
004 999 982 * 005 249 981 * 005 499 981 * 005 749 986
005 999 977 * 006 249 976 * 006 499 976 * 006 749 980
006 999 980 * 007 249 989 * 007 499 989 * 007 749 975
007 999 975 * 008 249 974 * 008 499 974 * 008 749 979
008 999 979 * 009 249 969 * 009 499 969 * 009 749 964
009 999 964 * 010 249 966 * 010 499 966 * 010 749 961
'''.replace('*', '\n').split('\n')
ACNs = [s for s in ACNs if s and not s.isspace()]
for s in ACNs:
n = int(s.replace(' ', ''))
if not (isacn(s) and isacn(n) and not isacn(n+1)):
print('test failed for ACN: %s' % s.strip())
break
else:
print('all ACNs tested okay')
|
ba92c3b1aa0f10c9a178db17fb368b60e10d49f1 | betty29/code-1 | /recipes/Python/498233_weighted_choice_short_easy_numpy/recipe-498233.py | 603 | 3.859375 | 4 | from numpy import *
from numpy.random import random
def toss(c, sh):
"""Return random samples of cumulative vector (1-D numpy array) c
The samples are placed in an array of shape sh.
Each element of array returned is an integer from 0 through n-1,
where n is the length of c."""
y = random(sh) #return array of uniform numbers (from 0 to 1) of shape sh
x = searchsorted(c,y)
return x
#sample usage:
p=array((0.1, 0.2, 0.6, 0.1)) #vector of probabilities, normalized to 1
c=cumsum(p) #cumulative probability vector
print toss(c, (10,)) #want 10 samples in 1-D array
|
28bbef757c905b8dda3a072af32a850ded041ba4 | betty29/code-1 | /recipes/Python/498261_Deeply_applying_str_across/recipe-498261.py | 7,252 | 3.5625 | 4 | """Utilities for handling deep str()ingification.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
Casual Usage:
from deepstr import deep_str
print deep_str(["hello", "world"])
Very unusual usage:
import deepstr
import xml.sax.saxutils
def handle_list(obj, deep_str):
if isinstance(obj, list):
results = []
results.append("<list>")
results.extend(["<item>%s</item>" % deep_str(x)
for x in obj])
results.append("</list>")
return ''.join(results)
def handle_int(obj, deep_str):
if isinstance(obj, int):
return "<int>%s</int>" % obj
def handle_string(obj, deep_str):
if isinstance(obj, str):
return ("<string>%s</string>" %
xml.sax.saxutils.escape(obj))
def handle_default(obj):
return "<unknown/>"
silly = deepstr.DeepStr(handle_default)
silly.recursive_str = deepstr.make_shallow_recursive_str(
"<recursion-detected/>")
silly.register(handle_list)
silly.register(handle_int)
silly.register(handle_string)
print silly([3, 1, "four", [1, "<five>", 9.0]])
x = []
x.append(x)
print silly(x)
This module provides a function called deep_str() that will do a deep
str() on objects. This module also provides utilities to develop
custom str() functions.
(What's largely undocumented is the fact that this isn't really about
strings, but can be used as a general --- and convoluted --- framework
for mapping some process across data.)
"""
import unittest
def make_shallow_recursive_str(recursion_label):
def f(obj, deep_str):
return recursion_label
return f
class DeepStr:
"""Deep stringifier."""
def __init__(self,
default_str=str,
recursive_str=make_shallow_recursive_str("...")):
"""
DeepStr: stringify_function handler -> stringify_function
Creates a new DeepStr. Once constructed, you can call as
if this were a function that takes objects and returns
strings.
default_str is the default function used on types that this
does not recognize. It must be able to take in an object and
return a string.
If we hit structure that's already been traversed,
we use recursive_str on that structure."""
self.handlers = []
self.default_str = default_str
self.recursive_str = recursive_str
def __call__(self, obj):
"""Takes an object and returns a string of that object."""
return self.deepstr(obj, {})
def deepstr(self, obj, seen):
## Notes: this code is a little trickier than I'd like, but
## I don't see a good way of simplifying it yet. Subtle parts
## include the construction of substructure_deepstr, and use
## of a fresh dictionary in 'new_seen'.
if id(obj) in seen:
## TRICKY CODE: the recursive function is taking in a
## stringifier whose 'seen' dictionary is empty.
def fresh_deepstr(sub_obj):
return self.deepstr(sub_obj, {})
return self.recursive_str(obj, fresh_deepstr)
def substructure_deepstr(sub_obj):
new_seen = dict(seen)
new_seen[id(obj)] = True
return self.deepstr(sub_obj, new_seen)
for h in self.handlers:
result = h(obj, substructure_deepstr)
if result != None:
return result
return self.default_str(obj)
def register(self, handler):
"""register: (object str_function -> string or None)
Registers a new handler type. Handers take in the object
as well as a str() function, and returns either a string if
it can handle the object, or None otherwise. The second
argument should be used on substructures."""
self.handlers.append(handler)
######################################################################
## Below here is a sample implementation for deep_str()
def handle_list(obj, deep_str):
if isinstance(obj, list):
return "[" + ", ".join([deep_str(x) for x in obj]) + "]"
return None
def handle_tuple(obj, deep_str):
if isinstance(obj, tuple):
return "(" + ", ".join([deep_str(x) for x in obj]) + ")"
return None
def handle_dict(obj, deep_str):
if isinstance(obj, dict):
return ("{" +
", ".join([deep_str(k) + ': ' + deep_str(v)
for (k, v) in obj.items()]) +
"}")
return None
def handle_recursion(obj, deep_str):
if isinstance(obj, list): return "[...]"
## tuples aren't handled; from my best understanding,
## it's not possible to construct a tuple that contains itself.
if isinstance(obj, dict): return "{...}"
return "..."
deep_str = DeepStr(str, handle_recursion)
deep_str.register(handle_list)
deep_str.register(handle_tuple)
deep_str.register(handle_dict)
######################################################################
## Sample exercising code. This is here just to show a wacky example.
def _exercise():
import xml.sax.saxutils
def handle_list(obj, deep_str):
if isinstance(obj, list):
results = []
results.append("<list>")
results.extend(["<item>%s</item>" % deep_str(x)
for x in obj])
results.append("</list>")
return ''.join(results)
def handle_int(obj, deep_str):
if isinstance(obj, int):
return "<int>%s</int>" % obj
def handle_string(obj, deep_str):
if isinstance(obj, str):
return "<string>%s</string>" % xml.sax.saxutils.escape(obj)
def handle_default(obj):
return "<unknown/>"
silly = DeepStr(handle_default)
silly.recursive_str = make_shallow_recursive_str(
"<recursion-detected/>")
silly.register(handle_list)
silly.register(handle_int)
silly.register(handle_string)
print silly([3, 1, "four", [1, "<five>", 9.0]])
x = []
x.append(x)
print silly(x)
######################################################################
## Test cases
class MyTests(unittest.TestCase):
def testSimpleThings(self):
for obj in [42, 'hello', 0+1j, 2.3, u'world']:
self.assertEquals(str(obj), deep_str(obj))
def testSimpleLists(self):
self.assertEquals(str([1, 2, 3]), deep_str([1, 2, 3]))
def testListsWithStrings(self):
self.assertEquals("[hello, world]", deep_str(["hello", "world"]))
def testRepeatedObjects(self):
self.assertEquals("[1, 1]", deep_str([1, 1]))
def testRecursion(self):
L = [1, 2]
L.append(L)
self.assertEquals("[1, 2, [...]]", deep_str(L))
def testSimpleDict(self):
self.assertEquals("{hello: world}", deep_str({'hello' : 'world'}))
def testDictWithRecursion(self):
D = {}
D[1] = D
self.assertEquals("{1: {...}}", deep_str(D))
def testNonRecursion(self):
a = ['a']
L = [a, a]
self.assertEquals("[[a], [a]]", deep_str(L))
if __name__ == '__main__':
unittest.main()
|
8889a1b811be8518702998a0485651e0e1d435de | betty29/code-1 | /recipes/Python/577182_Apparent_InfectiRate/recipe-577182.py | 1,141 | 3.640625 | 4 | # Created by Donyo Ganchev, Agricultural University, town of Plovdiv, Bulgaria
# donyo@abv.bg
import math
import datetime
choice=None
def air():
f_y, f_m, f_d=input('Enter first date in format "year, month, day": ')
s_y, s_m, s_d=input('Enter second date in format "year, month, day": ')
f_pdi=float(input('Enter pdi observed at first date: '))
s_pdi=float(input('Enter pdi observed at second date: '))
f_date=datetime.date(f_y, f_m, f_d)
s_date=datetime.date(s_y, s_m, s_d)
sdif=str(s_date-f_date)
int_dif=int(sdif[0:2])
r=(1/float(int_dif))*math.log((s_pdi*(1-f_pdi))/(f_pdi*(1-s_pdi)))
print \
"""
"""
print "%2.10f" %r
while choice!="0":
print \
"""
Apparent Infection Rate Calculation
Created by Donyo Ganchev - Agricultural University, Plovdiv, Bulgaria
1 - Begin calculation
0 - Exit
"""
choice= raw_input("Choice: ")
if choice == "0":
exit()
elif choice=="1":
air()
|
6fe36c6057450f367c510e40fade01474ef53d7c | betty29/code-1 | /recipes/Python/576613_Easy_State_Pattern__support_implementing_state/recipe-576613.py | 15,873 | 3.84375 | 4 | """
Supports implementation of state pattern.
State Machine is defined a class containing one or more StateTable objeects,
and using decorators to define Events and Transitions that are handled by the
state machine. Individual states are Subclasses of the state machine, with
a __metaclass__ specifier.
Author: Rodney Drenth
Date: January, 2009
Version: Whatever
Copyright 2009, Rodney Drenth
Permission to use granted under the terms and conditions of the Python Software
Foundation License
(http://www.python.org/download/releases/2.4.2/license/)
"""
#! /usr/bin/env Python
#
import types
class _StateVariable( object ):
"""Used as attribute of a class to maintain state.
State Variable objects are not directly instantiated in the user's state machine class
but are instantiated by the StateTable class attribute defined within the state machine.
"""
def __init__(self, stateTable):
""" Constructs state variable and sets it to the initial state
"""
self._current_state = stateTable.initialstate
self._next_state = stateTable.initialstate
self.sTable = stateTable
def _toNextState(self, context):
"""Sets state of to the next state, if new state is different.
calls onLeave and onEnter methods
"""
if self._next_state is not self._current_state:
if hasattr(self._current_state, 'onLeave'):
self._current_state.onLeave(context)
self._current_state = self._next_state
if hasattr(self._current_state, 'onEnter'):
self._current_state.onEnter(context)
def name(self):
"""Returns ame of current state."""
return self._current_state.__name__
def setXition(self, func):
""" Sets the state to transitionto upon seeing Transition event"""
# next_state = self.sTable.nextStates[self._current_state][func.__name__]
next_state = self._current_state.nextStates[func.__name__]
if next_state is not None:
self._next_state = next_state
def getFunc(self, func):
""" Gets event handler function based on current State"""
funky = getattr( self._current_state, func.__name__)
# print 'current State:', self._current_state.__name__
if funky is None:
raise NotImplementedError('%s.%s'%(self.name(),func.__name__))
# when funky.name is objCall, it means that we've recursed all the
# way back to the context class and need to call func as a default
return funky if funky.__name__ != 'objCall' else func
class StateTable( object ):
"""Defines a state table for a state machine class
A state table for a class is associated with the state variable in the instances
of the class. The name of the state variable is given in the constructor to the
StateTable object. StateTable objects are attributes of state machine classes,
not intances of the state machine class. A state machine class can have more
than one StateTable.
"""
def __init__(self, stateVarblName):
"""State Table initializer
stateVarblName is the name of the associated state variable, which will
be instantiated in each instance of the state machine class
"""
self.inst_state_name = stateVarblName
self.eventList = []
self.initialstate = None
nextStates = {}
def initialize(self, obj ):
"""Initialization of StateTable and state varible
obj is the instance of the state machine being initialized. This method
must be called in the __init__ method of the user's state machine.
"""
obj.__dict__[self.inst_state_name] = _StateVariable( self )
def _addEventHandler(self, funcName):
"""Notifies State table of a method that's handle's an transition.
This is called by @Transition and @TransitionEvent decorators,
whose definitions are below.
"""
self.eventList.append(funcName)
def nextStates(self, subState, nslList):
"""Sets up transitions from the state specified by subState
subState is a state class, subclassed from user's state machine class
nslList is a list of states that will be transitioned to upon Transitions.
This functions maps each @Transition decorated method in the state machine
class to a to the corresponding state in this list. None can be specified
as a state to indicate the state should not change.
"""
if len(nslList) != len(self.eventList):
raise RuntimeError( "Wrong number of states in transition list.")
subState.nextStates = dict(zip(self.eventList, nslList))
# self.nextStates[subState] = dict(zip( self.eventList, nslList))
def Event( state_table ):
"""Decorator for indicating state dependant method
Decorator is applied to methods of state machine class to indicate that
invoking the method will call state dependant method. States are implemented
as subclasses of the state machine class with a metaclass qualification.
"""
stateVarName = state_table.inst_state_name
def wrapper(func):
# no adding of event handler to statetable...
def objCall( self, *args, **kwargs):
state_var = getattr(self, stateVarName )
retn = state_var.getFunc(func)(self, *args, **kwargs)
return retn
return objCall
return wrapper
def Transition( state_table ):
"""Decorator for indicating the method causes a state transition.
Decorator is applied to methods of the state machine class. Invokeing
the method can cause a transition to another state. Transitions are defined
using the nextStates method of the StateTable class
"""
stateVarName = state_table.inst_state_name
def wrapper(func):
state_table._addEventHandler( func.__name__)
def objCall( self, *args, **kwargs):
state_var = getattr(self, stateVarName )
state_var.setXition(func)
rtn = func(self, *args, **kwargs)
state_var._toNextState(self)
return rtn
return objCall
return wrapper
def TransitionEvent( state_table ):
"""Decorator for defining a method that both triggers a transition and
invokes a state dependant method.
This is equivalent to, but more efficient than using
@Transition(stateTable)
@Event(stateTable)
"""
stateVarName = state_table.inst_state_name
def wrapper(func):
state_table._addEventHandler( func.__name__)
def objCall( self, *args, **kwargs):
state_var = getattr(self, stateVarName )
# if not issubclass( state_var._current_state, self.__class__):
# raise TypeError('expecting instance to be derived from %s'% baseClasss.__name__)
state_var.setXition(func)
retn = state_var.getFunc(func)(self, *args, **kwargs)
state_var._toNextState(self)
return retn
return objCall
return wrapper
class _stateclass(type):
""" A stateclass metaclass
Modifies class so its subclass's methods so can be called as methods
of a base class. Is used for implementing states
"""
def __init__(self, name, bases, cl_dict):
self.__baseClass__ = _bcType # global - set by stateclass(), which follows
if not issubclass(self, _bcType):
raise TypeError( 'Class must derive from %s'%_bcType.__name__ )
type.__init__(self, name, bases, cl_dict)
def __getattribute__(self, name):
if name.startswith('__'):
return type.__getattribute__(self, name)
try:
atr = self.__dict__[name]
if type(atr) == types.FunctionType:
atr = types.MethodType(atr, None, self.__baseClass__)
except KeyError, ke:
for bclas in self.__bases__:
try:
atr = getattr(bclas, name)
break
except AttributeError, ae:
pass
else:
raise AttributeError( "'%s' has no attribute '%s'" % (self.__name__, name) )
return atr
def stateclass( statemachineclass ):
"""A method that returns a metaclass for constructing states of the
users state machine class
"""
global _bcType
_bcType = statemachineclass
return _stateclass
# vim : set ai sw=3 et ts=6 :
-----------------------------------------------------------
"""
Example of setting up a state machine using the EasyStatePattern
module.
"""
import EasyStatePattern as esp
import math
class Parent(object):
""" the context for the state machine class """
moodTable = esp.StateTable('mood')
def __init__(self, pocketbookCash, piggybankCash):
"""Instance initializer must invoke the initialize method of the StateTable """
Parent.moodTable.initialize( self)
self.pocketBook = pocketbookCash
self.piggyBank = piggybankCash
"""The Transiton decorator defines a method which causes transitions to other
states"""
@esp.Transition(moodTable)
def getPromotion(self): pass
@esp.Transition(moodTable)
def severalDaysPass(self): pass
"""The Event decorator defines a method whose exact method will depend on the
current state. These normally do not cause a state transition.
For this example, this method will return an amount of money that the asker is to receive,
which will depend on the parent's mood, the amount asked for, and the availability of
money."""
@esp.Event(moodTable)
def askForMoney(self, amount): pass
"""The TransitionEvent decorator acts like a combination of both the Transition
and Event decorators. Calling this causes a transition(if defined in the state
table) and the called function is state dependant."""
@esp.TransitionEvent(moodTable)
def cashPaycheck(self, amount): pass
@esp.TransitionEvent(moodTable)
def getUnexpectedBill(self, billAmount ): pass
"""onEnter is called when entering a new state. This can be overriden in
the individual state classes. onLeave (not defined here) is called upon
leaving a state"""
def onEnter(self):
print 'Mood is now', self.mood.name()
#
# Below are defined the states. Each state is a class, States may be derived from
# other states. Topmost states must have a __metaclass__ = stateclass( state_machine_class )
# declaration.
#
class Normal( Parent ):
__metaclass__ = esp.stateclass( Parent )
"""Normal becomes the name of the state."""
def getPromotion(self):
"""This shouldn't get called, since get was defined as a transition in
the Parent context"""
pass
def severalDaysPass(self):
"""neither should this be called."""
pass
def askForMoney(self, amount):
amountToReturn = min(amount, self.pocketBook )
self.pocketBook -= amountToReturn
if 40.0 < self.pocketBook:
print 'Here you go, sport!'
elif 0.0 < self.pocketBook < 40.00:
print "Money doesn't grow on trees, you know."
elif 0.0 < amountToReturn < amount:
print "Sorry, honey, this is all I've got."
elif amountToReturn == 0.0:
print "I'm broke today ask your aunt."
self.mood.nextState = Broke
return amountToReturn
def cashPaycheck(self, amount):
self.pocketBook += .7 * amount
self.piggyBank += .3*amount
def getUnexpectedBill(self, billAmount ):
amtFromPktBook = min(billAmount, self.pocketBook)
rmngAmt = billAmount - amtFromPktBook
self.piggyBank -= rmngAmt
self.pocketBook -= amtFromPktBook
class Happy( Parent ):
__metaclass__ = esp.stateclass( Parent )
"""Grouchy becomes the name of the state."""
def askForMoney(self, amount):
availableMoney = self.pocketBook + self.piggyBank
amountToReturn = max(min(amount, availableMoney), 0.0)
amountFromPktbook = min(amountToReturn, self.pocketBook)
self.pocketBook -= amountFromPktbook
self.piggyBank -= (amountToReturn - amountFromPktbook)
if 0.0 < amountToReturn < amount:
print "Sorry, honey, this is all I've got."
elif amountToReturn == 0.0:
print "I'm broke today ask your aunt."
self.mood.nextState = Broke
else:
print 'Here you go, sport!'
return amountToReturn
def cashPaycheck(self, amount):
self.pocketBook += .75 * amount
self.piggyBank += .25*amount
def getUnexpectedBill(self, billAmount ):
print "why do these things always happen?"
amtFromPktBook = min(billAmount, self.pocketBook)
rmngAmt = billAmount - amtFromPktBook
self.piggyBank -= rmngAmt
self.pocketBook -= amtFromPktBook
def onEnter(self):
print 'Yippee! Woo Hoo!', self.mood.name()*3
class Grouchy( Parent ):
__metaclass__ = esp.stateclass( Parent )
"""Grouchy becomes the name of the state."""
def askForMoney(self, amount):
print """You're always spending too much. """
return 0.0
def cashPaycheck(self, amount):
self.pocketBook += .70 * amount
self.piggyBank += .30*amount
def getUnexpectedBill(self, billAmount ):
print 'These things always happen at the worst possible time!'
amtFromPktBook = min(billAmount, self.pocketBook)
rmngAmt = billAmount - amtFromPktBook
self.piggyBank -= rmngAmt
self.pocketBook -= amtFromPktBook
class Broke( Normal ):
# __metaclass__ = esp.stateclass( Parent )
""" No metaclass declaration as its as subclass of Grouchy. """
def cashPaycheck(self, amount):
piggyBankAmt = min ( amount, max(-self.piggyBank, 0.0))
rmngAmount = amount - piggyBankAmount
self.pocketBook += .40 * rmngAmount
self.piggyBank += (.60 * rmngAmount + piggyBankAmt)
def askForMoney(self, amount):
amountToReturn = min(amount, self.pocketBook )
self.pocketBook -= amountToReturn
if 40.0 < self.pocketBook:
print 'Here you go, sport!'
elif 0.0 < self.pocketBook < 40.00:
print "Spend it wisely."
elif 0.0 < amountToReturn < amount:
print "This is all I've got."
elif amountToReturn == 0.0:
print "Sorry, honey, we're broke."
self.mood.nextState = Broke
return amountToReturn
# After defining the states, The following lines set up the transitions.
# We've set up four transitioning methods,
# getPromotion, severalDaysPass, cashPaycheck, getUnexpectedBill
# Therefore there are four states in each list, the ordering of the states in the
# list corresponds toorder that the transitioning methods were defined.
Parent.moodTable.nextStates( Normal, ( Happy, Normal, Normal, Grouchy ))
Parent.moodTable.nextStates( Happy, ( Happy, Happy, Happy, Grouchy ))
Parent.moodTable.nextStates( Grouchy, ( Happy, Normal, Grouchy, Grouchy ))
Parent.moodTable.nextStates( Broke, ( Normal, Broke, Grouchy, Broke ))
# This specifies the initial state. Instances of the Parent class are placed
# in this state when they are initialized.
Parent.moodTable.initialstate = Normal
def Test():
dad = Parent(50.0, 60.0)
amount = 20.0
print amount, dad.askForMoney(amount)
print amount, dad.askForMoney(amount)
dad.cashPaycheck( 40.0)
print amount, dad.askForMoney(amount)
dad.cashPaycheck( 40.0)
dad.severalDaysPass()
print amount, dad.askForMoney(amount)
dad.getUnexpectedBill(100.0 )
print amount, dad.askForMoney(amount)
dad.severalDaysPass()
print amount, dad.askForMoney(amount)
dad.severalDaysPass()
dad.cashPaycheck( 100.0)
print amount, dad.askForMoney(amount)
dad.cashPaycheck( 50.0)
print amount, dad.askForMoney(amount)
dad.getPromotion()
dad.cashPaycheck( 200.0)
amount = 250
print amount, dad.askForMoney(amount)
Test()
|
e2f6af7d70e34e1fd89e1239bcbac0709810dc25 | betty29/code-1 | /recipes/Python/577344_Maclaurinsseriescos2x/recipe-577344.py | 1,458 | 4.15625 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/008/10
#version :2.6
"""
maclaurin_cos_2x is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos(2x) = 1- 2^2*x^2/2! + 2^4*x^4/4! - 2^6*x^6/6! ...........
"""
from math import *
def maclaurin_cos_2x(value,k):
"""
Compute maclaurin's series approximation for cos(2x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos(2x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos_2x_1 = maclaurin_cos_2x(60,100)
print maclaurin_cos_2x_1
maclaurin_cos_2x_2 = maclaurin_cos_2x(45,100)
print maclaurin_cos_2x_2
maclaurin_cos_2x_3 = maclaurin_cos_2x(30,100)
print maclaurin_cos_2x_3
######################################################################FT python "C:\
#urine series\M
#-0.5
#0.0
#0.5
|
773f3b389a7163d46c81503d44a8be6d530cc346 | betty29/code-1 | /recipes/Python/65445_Decorate_output_stream_printlike/recipe-65445.py | 801 | 3.953125 | 4 | class PrintDecorator:
"""Add print-like methods to any file-like object."""
def __init__(self, stream):
"""Store away the stream for later use."""
self.stream = stream
def Print(self, *args, **kw):
""" Print all arguments as strings, separated by spaces.
Take an optional "delim" keyword parameter, to change the
delimiting character.
"""
delim = kw.get('delim', ' ')
self.stream.write(delim.join(map(str, args)))
def PrintLn(self, *args, **kw):
""" Just like print(), but additionally print a linefeed.
"""
self.Print(*args+('\n',), **kw)
import sys
out = PrintDecorator(sys.stdout)
out.PrintLn(1, "+", 1, "is", 1+1)
out.Print("Words", "Smashed", "Together", delim='')
out.PrintLn()
|
b87a83bc4939269c32b7b78aeb2dd9b81451f2f6 | betty29/code-1 | /recipes/Python/457661_Generate_SQL_insertatiintable_dictionary/recipe-457661.py | 648 | 3.671875 | 4 | def insertFromDict(table, dict):
"""Take dictionary object dict and produce sql for
inserting it into the named table"""
sql = 'INSERT INTO ' + table
sql += ' ('
sql += ', '.join(dict)
sql += ') VALUES ('
sql += ', '.join(map(dictValuePad, dict))
sql += ');'
return sql
def dictValuePad(key):
return '%(' + str(key) + ')s'
def exampleOfUse():
import MySQLdb
db = MySQLdb.connect(host='sql', user='janedoe', passwd='insecure', db='food')
cursor = db.cursor()
insert_dict = {'drink':'horchata', 'price':10}
sql = insertFromDict("lq", insert_dict)
cursor.execute(sql, insert_dict)
|
732f2f0ff4a663fd79fb15e387482b1222153781 | betty29/code-1 | /recipes/Python/266480_popPeekpy/recipe-266480.py | 1,153 | 3.578125 | 4 | #!/usr/bin/python
import sys
import getpass
import poplib
def popPeek(server, user, port=110):
try:
P = poplib.POP3(server, port)
P.user(user)
P.pass_(getpass.getpass())
except:
print "Failed to connect to server."
sys.exit(1)
deleted = 0
try:
l = P.list()
msgcount = len(l[1])
for i in range(msgcount):
msg = i+1
top = P.top(msg, 0)
for line in top[1]:
print line
input = raw_input("D to delete, any other key to leave message on server: ")
if input=="D":
P.dele(msg)
deleted += 1
P.quit()
print "%d messages deleted. %d messages left on server" % (deleted, msgcount-deleted)
except:
P.rset()
P.quit()
deleted = 0
print "\n%d messages deleted. %d messages left on server" % (deleted, msgcount-deleted)
if __name__ == "__main__":
if len(sys.argv)<3:
print """
Usage: popPeek.py server username [port]
"""
else:
popPeek(sys.argv[1], sys.argv[2], sys.argv[3])
|
7ad891da593e2d3f3577051454c5e6f496e75e04 | betty29/code-1 | /recipes/Python/197530_Merging_two_sorted_iterators_insingle/recipe-197530.py | 2,471 | 4.09375 | 4 | #!/usr/bin/env python
"""An extended example of generators in action. Provides a function
called mergeiter that merges two iterators together.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""
from __future__ import generators
def mergeiter(i1, i2, cmp=cmp):
"""Returns the "merge" of i1 and i2. i1 and i2 must be iteratable
objects, and we assume that i1 and i2 are both individually sorted.
"""
left, right = ExtendedIter(i1), ExtendedIter(i2)
while 1:
if not left.has_next():
while 1: yield ('r', right.next())
if not right.has_next():
while 1: yield ('l', left.next())
comparison = cmp(left.peek(), right.peek())
if comparison < 0:
yield ('l', left.next())
elif comparison == 0:
right.next() ; yield ('=', left.next())
else:
yield ('r', right.next())
class ExtendedIter:
"""An extended iterator that wraps around an existing iterators.
It provides extra methods:
has_next(): checks if we can still yield items.
peek(): returns the next element of our iterator, but doesn't
pass by it."""
def __init__(self, i):
self._myiter = iter(i)
self._next_element = None
self._has_next = 0
self._prime()
def has_next(self):
"""Returns true if we can call next() without raising a
StopException."""
return self._has_next
def peek(self):
"""Nonexhaustively returns the next element in our iterator."""
assert self.has_next()
return self._next_element
def next(self):
"""Returns the next element in our iterator."""
if not self._has_next:
raise StopIteration
result = self._next_element
self._prime()
return result
def _prime(self):
"""Private function to initialize the states of
self._next_element and self._has_next. We poke our
self._myiter to see if it's still alive and kicking."""
try:
self._next_element = self._myiter.next()
self._has_next = 1
except StopIteration:
self.next_element = None
self._has_next = 0
def _test():
for item in mergeiter([2, 4, 6, 8], [1, 3, 4, 7, 9, 10]):
print item
if __name__ == '__main__':
## _test()
import sys
f1, f2 = open(sys.argv[1]), open(sys.argv[2])
for item in mergeiter(f1, f2):
print item
|
839b5f031ae104f4dd07345eb25556e7cdb5d8cc | betty29/code-1 | /recipes/Python/473844_Sudoku_solver/recipe-473844.py | 8,928 | 3.828125 | 4 | #!/usr/bin/env python
"""Sudoku solver
usage: python sudoku.py <file> [<depth>]
The input file should contain exactly 81 digits, with emtpy fields marked
with 0. Optionally, dots (.) may be used for empty fields if better
readability is required. All other characters are discarded.
The default guessing depth is 2.
"""
import pprint
from itertools import chain
def parseString(text):
s = text.replace('.', '0')
s = [int(x) for x in s if x.isdigit()]
s = [s[i:i+9] for i in range(0, 81, 9)]
return s
def parse(name):
f = open(name)
s = f.read()
f.close()
return parseString(s)
class NotSolvable(Exception):
"""Not solvable"""
pass
class IncorrectSolution(Exception):
"""Incorrect solution"""
pass
class Done(Exception):
"""Done!"""
pass
# These constants are speed optimizations for use in loops
MASK9 = set(range(1, 10))
NINE = tuple(range(9))
THREE = tuple(range(3))
def try_cross_and_region(matrix, depth=0):
"""Fill cells unambiguously determined by their lines and regions.
For every empty cell, find the values of known digits in its row, column,
and region. If there is exactly one digit left, it is the value of the
cell. If there are more and if search depth is non-zero, try solving the
puzzle for each of the values.
"""
result = False
for col in NINE:
yexist = set(m[col] for m in matrix)
rcol = col // 3
rcol3 = 3 * rcol
rcol3p3 = rcol3 + 3
for row in NINE:
if not matrix[row][col]:
xexist = set(matrix[row])
rrow = row // 3
rrow3 = 3 * rrow
region = [matrix[rrow3+i][rcol3:rcol3p3] for i in THREE]
rexist = set(chain(*region))
missing = MASK9 - xexist - yexist - rexist
size = len(missing)
if size == 1:
elem = list(missing)[0]
matrix[row][col] = elem
yexist.add(elem) # Speed optimization, see outer loop
result = True
elif size == 0:
raise NotSolvable()
elif size < 4 and depth > 0:
# The size limit was established by experimentation.
hypothesize(matrix, row, col, missing, depth-1)
return result
def try_adjacent_lines(matrix):
"""Fill cells unambiguously determined by same-region lines.
For every empty cell, find the values of known digits in the lines passing
through the same region. For the cell's line, the other two values in the
region should be known. For the remaining two lines, all digits in the
other two regions should be known. There should be exactly one value
happening twice on the other lines and not at all on the current line.
It is the value of the current cell.
If the above failed in one direction, try the other.
If both horizontal and vertical searches failed for a given cell but all
24 other-region values are known, there should be exactly one value
happening 4 times (each for one of the other regions checked). It is the
value of the current cell.
"""
result = False
for col in NINE:
rcol = col // 3
rcol3 = 3 * rcol
rcol3p3 = rcol3 + 3
othercolidxs = (rcol3 + (col+1)%3, rcol3 + (col+2)%3)
for row in NINE:
if not matrix[row][col]:
rrow = row // 3
rrow3 = 3 * rrow
otherrows = (rrow3 + (row+1)%3, rrow3 + (row+2)%3)
otherrows = [matrix[orow] for orow in otherrows]
othercols = [[m[ocol] for m in matrix]
for ocol in othercolidxs]
othercross = [] # Container for other-region known values
if _check_other_lines2(matrix, rcol, row, col, matrix[row],
otherrows, othercross):
result = True
elif _check_other_lines2(matrix, rcol, row, col,
[m[col] for m in matrix],
othercols, othercross):
result = True
elif len(othercross) == 24:
fours = [i for i in MASK9 if othercross.count(i) == 4]
if fours:
matrix[row][col] = fours[0]
result = True
return result
def _check_other_lines2(matrix, ridx, row, col, line, otherlines, othercross):
"""Helper function for try_adjacent_lines().
Check the values in one direction. As an artifact, known digit values
from the lines are collected into othercross.
"""
ridx3 = 3 * ridx
ridx3p3 = ridx3 + 3
line = line[ridx3:ridx3p3]
if line.count(0) != 1:
return False
allfields = []
for other in otherlines:
other = list(other)
del other[ridx3:ridx3p3]
allfields += other
if allfields.count(0):
return False
othercross += allfields
twos = set(i for i in MASK9 if allfields.count(i) == 2)
twos -= set(line)
if len(twos) == 1:
elem = list(twos)[0]
if elem not in line:
matrix[row][col] = elem
return True
return False
# Speed optimization in for loop
RLOCATIONS = set((row, col) for row in THREE for col in THREE)
def try_masking(matrix):
"""Fill cells that remain alone after "masking" by other cells.
For each digit value, "stamp out" the puzzle to see which regions have
empty cells that could potentially still be filled with that value. For
regions with single cells left, fill those cells with the value.
Known problems:
This function causes a 'Bad call' exception in the profile module
(see http://www.python.org/sf/1117670) in some Python installations.
"""
result = False
for digit in MASK9:
locations = set(RLOCATIONS)
matrix2 = [list(m) for m in matrix]
for row in NINE:
try:
idx = matrix2[row].index(digit)
except ValueError:
idx = -1
else:
matrix2[row] = [-1 for col in NINE]
for row2 in NINE:
matrix2[row2][idx] = -1
locations.discard((row//3, idx//3))
for rrow, rcol in locations:
rcol3 = 3 * rcol
rcol3p3 = rcol3 + 3
rrow3 = 3 * rrow
region2 = (matrix2[rrow3+i][rcol3:rcol3p3] for i in THREE)
region2 = [x for x in chain(*region2)]
if region2.count(0) == 1:
idx = region2.index(0)
row = rrow3 + idx // 3
col = rcol3 + idx % 3
matrix[row][col] = digit
result = True
return result
def hypothesize(matrix, row, col, values, depth):
"""Try further search with the specified cell equal to each of values."""
for x in values:
matrix2 = [list(m) for m in matrix]
matrix2[row][col] = x
try:
solve(matrix2, depth)
except (NotSolvable, IncorrectSolution):
pass
def check_done(matrix):
if 0 in chain(*matrix):
return False
for row in matrix:
if len(set(row)) < 9:
raise IncorrectSolution()
for col in range(9):
col = set(m[col] for m in matrix)
if len(col) < 9:
raise IncorrectSolution()
for rrow in range(3):
for rcol in range(3):
region = [matrix[3*rrow+i][3*rcol:3*(rcol+1)] for i in range(3)]
if len(set(chain(*region))) < 9:
raise IncorrectSolution()
return True
def solve(matrix, depth=2):
while try_cross_and_region(matrix):
pass
if check_done(matrix):
pprint.pprint(matrix)
raise Done()
while try_adjacent_lines(matrix):
pass
if check_done(matrix):
pprint.pprint(matrix)
raise Done()
while try_masking(matrix):
pass
if check_done(matrix):
pprint.pprint(matrix)
raise Done()
while try_cross_and_region(matrix, depth=depth):
pass
if check_done(matrix):
pprint.pprint(matrix)
raise Done()
if __name__ == "__main__":
import sys
matrix = parse(sys.argv[1])
depth = 2
if len(sys.argv) > 2:
depth = int(sys.argv[2])
try:
solve(matrix, depth)
print "Failed, this is all I could fill in:"
pprint.pprint(matrix)
except Done:
print "Done!"
except NotSolvable:
print "Not solvalbe, this is how I filled it in:"
pprint.pprint(matrix)
import os
utime, stime, cutime, cstime, elapsed = os.times()
print "cputime=%s" % (utime + stime)
# vim:et:ai:sw=4
|
391f0d3caa4402672e50a4bd596db8660a35ea06 | betty29/code-1 | /recipes/Python/163968_Generator_arbitrary/recipe-163968.py | 247 | 3.65625 | 4 | def peel(iterable, arg_cnt=1):
"""Use ``iterable`` to return ``arg_cnt`` number of arguments
plus the iterator itself.
"""
iterator = iter(iterable)
for num in xrange(arg_cnt):
yield iterator.next()
yield iterator
|
1f70e9aa9b8d60e390d035a078dfc4cef4359c34 | betty29/code-1 | /recipes/Python/580767_Unix_teelike_functionality/recipe-580767.py | 3,201 | 3.953125 | 4 | # tee.py
# Purpose: A Python class with a write() method which, when
# used instead of print() or sys.stdout.write(), for writing
# output, will cause output to go to both sys.stdout and
# the filename passed to the class's constructor. The output
# file is called the teefile in the below comments and code.
# The idea is to do something roughly like the Unix tee command,
# but from within Python code, using this class in your program.
# The teefile will be overwritten if it exists.
# The class also has a writeln() method which is a convenience
# method that adds a newline at the end of each string it writes,
# so that the user does not have to.
# Python's string formatting language is supported (without any
# effort needed in this class), since Python's strings support it,
# not the print method.
# Author: Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: https://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram
from __future__ import print_function
import sys
from error_exit import error_exit
class Tee(object):
def __init__(self, tee_filename):
try:
self.tee_fil = open(tee_filename, "w")
except IOError as ioe:
error_exit("Caught IOError: {}".format(repr(ioe)))
except Exception as e:
error_exit("Caught Exception: {}".format(repr(e)))
def write(self, s):
sys.stdout.write(s)
self.tee_fil.write(s)
def writeln(self, s):
self.write(s + '\n')
def close(self):
try:
self.tee_fil.close()
except IOError as ioe:
error_exit("Caught IOError: {}".format(repr(ioe)))
except Exception as e:
error_exit("Caught Exception: {}".format(repr(e)))
def main():
if len(sys.argv) != 2:
error_exit("Usage: python {} teefile".format(sys.argv[0]))
tee = Tee(sys.argv[1])
tee.write("This is a test of the Tee Python class.\n")
tee.writeln("It is inspired by the Unix tee command,")
tee.write("which can send output to both a file and stdout.\n")
i = 1
s = "apple"
tee.writeln("This line has interpolated values like {} and '{}'.".format(i, s))
tee.close()
if __name__ == '__main__':
main()
'''
The error_exit function is as follows - put it into a separate file called
error_exit.py in the same folder as the tee.py program, on put it on your PYTHONPATH:
# error_exit.py
# Author: Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: https://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram
# Purpose: This module, error_exit.py, defines a function with
# the same name, error_exit(), which takes a string message
# as an argument. It prints the message to sys.stderr, or
# to another file object open for writing (if given as the
# second argument), and then exits the program.
# The function error_exit can be used when a fatal error condition occurs,
# and you therefore want to print an error message and exit your program.
import sys
def error_exit(message, dest=sys.stderr):
dest.write(message)
sys.exit(1)
def main():
error_exit("Testing error_exit.\n")
if __name__ == "__main__":
main()
'''
|
327190b83ab01bda8e558dad150588420541e6c3 | betty29/code-1 | /recipes/Python/334621_List_Dictionaries_Memory/recipe-334621.py | 1,602 | 3.671875 | 4 | #!/usr/bin/python2.4
import types
class Table(object):
"""A structure which implements a list of dict's."""
def __init__(self, *args):
self.columns = args
self.rows = []
def _createRow(self, k,v):
return dict(zip(k, v))
def append(self, row):
if type(row) == types.DictType:
row = [row[x] for x in self.columns]
row = tuple(row)
if len(row) != len(self.columns):
raise TypeError, 'Row must contain %d elements.' % len(self.columns)
self.rows.append(row)
def __iter__(self):
for row in self.rows:
yield self._createRow(self.columns, row)
def __getitem__(self, i):
return self._createRow(self.columns, self.rows[i])
def __setitem__(self, i, row):
if type(row) == types.DictType:
row = [row[x] for x in self.columns]
row = tuple(row)
if len(row) != len(self.columns):
raise TypeError, 'Row must contain %d elements.' % len(self.columns)
self.rows[i] = row
def __repr__(self):
return ("<" + self.__class__.__name__ + " object at 0x" + str(id(self))
+ " " + str(self.columns) + ", %d rows.>" % len(self.rows))
if __name__ == "__main__":
import pickle
t = Table("a","b","c")
for i in xrange(10000):
t.append((1,2,3))
print "Table size when pickled:",len(pickle.dumps(t))
t = []
for i in xrange(10000):
t.append({"a":1,"b":2,"c":3})
print "List size when pickled: ",len(pickle.dumps(t))
|
43ba466012629085524d93e37f309a343401d116 | betty29/code-1 | /recipes/Python/363783_InverseExtend/recipe-363783.py | 3,059 | 3.796875 | 4 | """Iterate downward through a hierarchy calling a method at each step."""
__docformat__ = "restructuredtext"
def inverseExtend(boundMethod, *args, **kargs):
"""Iterate downward through a hierarchy calling a method at each step.
boundMethod -- This is the bound method of the object you're interested in.
args, kargs -- The arguments and keyword arguments to pass to the
top-level method.
You can call this method via something like this:
inverseExtend(object.method, myArg, myOtherArg)
When calling the method at each step, I'll call it like this:
Class.method(object, callNext, *args, **kargs)
However, the lowest level class's method has no callNext parameter,
since it has no one else to call:
Class.method(object, *args, **kargs)
In the method:
callNext(*args, **kargs)
should be called when it is time to transfer control to the subclass. This
may even be in the middle of the method. Naturally, you don't have to pass
*args, **kargs, but a common idiom is for the parent class to just receive
*args and **kargs and pass them on unmodified.
"""
# Build all the necessary data structures.
obj = boundMethod.im_self
methodName = boundMethod.im_func.__name__
# Figure out the classes in the class hierarchy. "classes" will
# contain the most senior classes first.
Class = obj.__class__
classes = [Class]
while Class.__bases__:
Class = Class.__bases__[0]
classes.insert(0, Class)
# Skip classes that don't define the method. Be careful with getattr
# since it automatically looks in parent classes.
last = None
methods = []
for Class in classes:
if (hasattr(Class, methodName) and
getattr(Class, methodName) != last):
last = getattr(Class, methodName)
methods.insert(0, last)
def callNext(*args, **kargs):
"""This closure is like super(), but it calls the subclass's method."""
method = methods.pop()
if len(methods):
return method(obj, callNext, *args, **kargs)
else:
return method(obj, *args, **kargs)
return callNext(*args, **kargs)
# Test out the code.
if __name__ == "__main__":
from cStringIO import StringIO
class A:
def f(self, callNext, count):
buf.write('<A count="%s">\n' % count)
callNext(count + 1)
buf.write('</A>')
class B(A):
# I don't have an f method, so you can skip me.
pass
class C(B):
def f(self, callNext, count):
buf.write(' <C count="%s">\n' % count)
callNext(count + 1)
buf.write(' </C>\n')
class D(C):
def f(self, count):
buf.write(' <D count="%s" />\n' % count)
expected = """\
<A count="0">
<C count="1">
<D count="2" />
</C>
</A>"""
buf = StringIO()
d = D()
inverseExtend(d.f, 0)
assert buf.getvalue() == expected
buf.close()
|
25e974baee920b8a33eadc100ebb42bf26cfca36 | betty29/code-1 | /recipes/Python/389639_Default_Dictionary/recipe-389639.py | 515 | 3.78125 | 4 | import copy
class DefaultDict(dict):
"""Dictionary with a default value for unknown keys."""
def __init__(self, default):
self.default = default
def __getitem__(self, key):
if key in self:
return self.get(key)
else:
## Need copy in case self.default is something like []
return self.setdefault(key, copy.deepcopy(self.default))
def __copy__(self):
copy = DefaultDict(self.default)
copy.update(self)
return copy
|
e26d4366ef53ccb0f3167905dffeb83d814dd918 | betty29/code-1 | /recipes/Python/577220_Decimal_binary_prefix/recipe-577220.py | 550 | 3.984375 | 4 | def binary_prefix(value, binary=True):
'''Return a tuple with a scaled down version of value and it's binary prefix
Parameters:
- `value`: numeric type to trim down
- `binary`: use binary (ICE) or decimal (SI) prefix
'''
SI = 'kMGTPEZY'
unit = binary and 1024. or 1000.
for i in range(-1, len(SI)):
if abs(value) < unit:
break
value/= unit
return (value, i<0 and '' or (binary and SI[i].upper() + 'i' or SI[i]))
|
e15306a1a7d6cae5419ed295cdfe5eeb245b320b | betty29/code-1 | /recipes/Python/578589_Poker_Hands/recipe-578589.py | 2,861 | 3.84375 | 4 | #!/usr/bin/env python3
import collections
import itertools
import random
SUIT_LIST = ("Hearts", "Spades", "Diamonds", "Clubs")
NUMERAL_LIST = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
class card:
def __init__(self, numeral, suit):
self.numeral = numeral
self.suit = suit
self.card = self.numeral, self.suit
def __repr__(self):
return self.numeral + "-" + self.suit
class poker_hand():
def __init__(self, card_list):
self.card_list = card_list
def __repr__(self):
short_desc = "Nothing."
numeral_dict = collections.defaultdict(int)
suit_dict = collections.defaultdict(int)
for my_card in self.card_list:
numeral_dict[my_card.numeral] += 1
suit_dict[my_card.suit] += 1
# Pair
if len(numeral_dict) == 4:
short_desc = "One pair."
# Two pair or 3-of-a-kind
elif len(numeral_dict) == 3:
if 3 in numeral_dict.values():
short_desc ="Three-of-a-kind."
else:
short_desc ="Two pair."
# Full house or 4-of-a-kind
elif len(numeral_dict) == 2:
if 2 in numeral_dict.values():
short_desc ="Full house."
else:
short_desc ="Four-of-a-kind."
else:
# Flushes and straights
straight, flush = False, False
if len(suit_dict) == 1:
flush = True
min_numeral = min([NUMERAL_LIST.index(x) for x in numeral_dict.keys()])
max_numeral = max([NUMERAL_LIST.index(x) for x in numeral_dict.keys()])
if int(max_numeral) - int(min_numeral) == 4:
straight = True
# Ace can be low
low_straight = set(("Ace", "2", "3", "4", "5"))
if not set(numeral_dict.keys()).difference(low_straight):
straight = True
if straight and not flush:
short_desc ="Straight."
elif flush and not straight:
short_desc ="Flush."
elif flush and straight:
short_desc ="Straight flush."
enumeration = "/".join([str(x) for x in self.card_list])
return "{enumeration} ({short_desc})".format(**locals())
class deck(set):
def __init__(self):
for numeral, suit in itertools.product(NUMERAL_LIST, SUIT_LIST):
self.add(card(numeral, suit))
def get_card(self):
a_card = random.sample(self, 1)[0]
self.remove(a_card)
return a_card
def get_hand(self, number_of_cards=5):
if number_of_cards == 5:
return poker_hand([self.get_card() for x in range(number_of_cards)])
else:
raise NotImplementedError
for i in range(100000):
print(deck().get_hand())
|
72c7d9c0053f142daa1f4bc97fc7400e5f921f18 | betty29/code-1 | /recipes/Python/363782_InverseExtendGenerators/recipe-363782.py | 4,019 | 3.765625 | 4 | """Iterate downward through a hierarchy calling a method at each step."""
__docformat__ = "restructuredtext"
import types
def inverseExtend(boundMethod, *args, **kargs):
"""Iterate downward through a hierarchy calling a method at each step.
boundMethod -- This is the bound method of the object you're interested in.
args, kargs -- The arguments and keyword arguments to pass to the
top-level method.
You can call this method via something like this:
inverseExtend(object.method, myArg, myOtherArg)
When calling the method at each step, I'll call it like this:
Class.method(object, *args, **kargs)
Each parent class method *must* be a generator with exactly one yield
statement (even if the yield statement never actually gets called), but the
lowest level class method must *not* be a generator. In the parent class:
yield args, kargs
should be called when it is time to transfer control to the subclass. This
may be in the middle of the method or not at all if the parent class does
not wish for the child class's method to get a chance to run.
"""
# Build all the necessary data structures.
obj = boundMethod.im_self
methodName = boundMethod.im_func.__name__
# Figure out the classes in the class hierarchy. "classes" will
# contain the most senior classes first.
Class = obj.__class__
classes = [Class]
while Class.__bases__:
Class = Class.__bases__[0]
classes.insert(0, Class)
# Skip classes that don't define the method. Be careful with getattr
# since it automatically looks in parent classes.
last = None
methods = []
for Class in classes:
if (hasattr(Class, methodName) and
getattr(Class, methodName) != last):
last = getattr(Class, methodName)
methods.append(last)
# Traverse down the class hierarchy. Watch out for StopIteration's which
# signify that the parent does not wish to call the child class's method.
# generatorMethods maps generators to methods which we'll need for nice
# error messages.
generators = []
generatorMethods = {}
for method in methods[:-1]:
generator = method(obj, *args, **kargs)
assert isinstance(generator, types.GeneratorType), \
"%s must be a generator" % `method`
try:
(args, kargs) = generator.next()
except StopIteration:
break
generators.insert(0, generator)
generatorMethods[generator] = method
# If we didn't have to break, then the lowest level class's method gets to
# run.
else:
method = methods[-1]
ret = method(obj, *args, **kargs)
assert not isinstance(ret, types.GeneratorType), \
"%s must not be a generator" % method
# Traverse back up the class hierarchy. We should get StopIteration's at
# every step.
for generator in generators:
try:
generator.next()
raise AssertionError("%s has more than one yield statement" %
`generatorMethods[generator]`)
except StopIteration:
pass
# Test out the code.
if __name__ == "__main__":
from cStringIO import StringIO
class A:
def f(self, count):
buf.write('<A count="%s">\n' % count)
yield (count + 1,), {}
buf.write('</A>')
class B(A):
# I don't have an f method, so you can skip me.
pass
class C(B):
def f(self, count):
buf.write(' <C count="%s">\n' % count)
yield (count + 1,), {}
buf.write(' </C>\n')
class D(C):
def f(self, count):
buf.write(' <D count="%s" />\n' % count)
expected = """\
<A count="0">
<C count="1">
<D count="2" />
</C>
</A>"""
buf = StringIO()
d = D()
inverseExtend(d.f, 0)
assert buf.getvalue() == expected
buf.close()
|
3a4eb198807f7867802a3f47c58abbb0dc6d1552 | betty29/code-1 | /recipes/Python/577350_Synchronizing_worker_threads_using_comminput/recipe-577350.py | 2,762 | 3.984375 | 4 | import threading
class WorkersLounge(object):
def __init__(self, total_workers_number):
"""
@param total_workers_number: the maximum number of worker threads
"""
self.total_workers_number = total_workers_number
self.waiting_place = threading.Condition()
self.work_done_event = threading.Event()
def rest(self):
"""
When a thread calls this method there are two possible options:
- either there are other active threads, in which case the current thread waits
- all other threads are already waiting, in which case they all exit
@return: True if the caller thread should go back to work
False if the caller thread should exit
"""
with self.waiting_place:
if (len(self.waiting_place._Condition__waiters) ==
self.total_workers_number-1):
# This is the last worker, and it has nothing to do
self.work_done_event.set()
self.waiting_place.notifyAll()
# Notify the caller there is no more work to do
return False
else:
# Wait for a signal
self.waiting_place.wait()
return not(self.work_done_event.isSet())
def back_to_work(self):
"""
Wake up all the waiting threads.
Should be called whenever a thread puts new input into the common source.
"""
# Wake up everybody
with self.waiting_place:
self.waiting_place.notifyAll()
if __name__ == "__main__":
# Run test code
import Queue
import time
print_lock = threading.Lock()
def sync_print(text):
with print_lock:
print text
def _thread_proc(input_queue, workers_lounge):
thread_name = threading.currentThread().name
while 1:
try:
# Attempt to get input from the common queue
input = input_queue.get(timeout=0.1)
# Do something with the input, possibly inserting more jobs
# back into the queue
sync_print("%s got input %s"%(thread_name, input))
time.sleep(1)
if (input < 5):
input_queue.put(input+1)
input_queue.put(input+1)
# Wake up any waiting thread
workers_lounge.back_to_work()
except Queue.Empty:
# The 'rest' method returns False if the thread should stop,
# and blocks until someone wakes it up
sync_print("%s is resting"%thread_name)
if (workers_lounge.rest() == False):
sync_print("%s finished working"%thread_name)
break
# Create an initial input source
input_queue = Queue.Queue()
input_queue.put(1)
input_queue.put(1)
# Run worker threads
threads_number = 5
workers_lounge = WorkersLounge(total_workers_number=threads_number)
for _i in range(threads_number):
threads.append(
threading.Thread(target=_thread_proc, args=(input_queue, workers_lounge)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.