blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
87ce7ec9d948734a446a7cf0bb40ded7fd62da19
|
tuseddomarcos/Python_Ahorcado_Basico
|
/manejoArchivo.py
| 2,665 | 3.5 | 4 |
import csv
import random
from tkinter import messagebox as mb
#Leo el archivo .csv y busco por nivel, luego busco una palabra ramdon y la retorno.
def seleccionoPalabrasPorNivel(nivel):
listPalabras = []
reader = csv.reader(open('ListaPalabras/ListaPalabras.csv'))
for row in reader:
listPalabras.append(row)
#Obtengo palabra al azar
palabra = obtenerPalabraAlAzar(listPalabras[nivel])
return palabra
#Recibo una lista de palabras y selecciono una random
def obtenerPalabraAlAzar(listaDePalabras):
palabraSeleccionada = random.choice(listaDePalabras)
return palabraSeleccionada
#Recivo una palabra y la inserto en el archivo .csv de palabras.
def ingresarNuevasPalabras(nivel , palabraNueva):
listPalabras = []
seguirIngresando = False
reader = csv.reader(open('ListaPalabras/ListaPalabras.csv'))
for row in reader:
listPalabras.append(row)
responseValidate = validoPalabra(palabraNueva,listPalabras,nivel)
if(responseValidate == False):
return True
else:
listPalabras[nivel].append(palabraNueva)
with open('ListaPalabras/ListaPalabras.csv','w' ,newline='') as file:
writer = csv.writer(file)
writer.writerows(listPalabras)
msg = "Letra Ingresada Correctamente. ¿Desea Agregar Otra?"
seguirIngresando = mb.askretrycancel(message=msg, title="Exitoo")
return seguirIngresando
def validoPalabra(palabraNueva, listaPalabras, nivel):
if(palabraNueva == ""):
mb.showwarning(message="No ha ingresado ninguna palabra", title="!Atencion")
return False
##Restricciones generales
if(palabraNueva in listaPalabras):
mb.showwarning(message="La palabra ingresada ya existe", title="!Atencion")
return False
numeros = "1234567890"
for i in palabraNueva:
if(i in numeros):
mb.showwarning(message="La palabra solo debe contener Letras", title="!Atencion")
return False
if(nivel == 0):
if(len(palabraNueva) > 5):
mb.showwarning(message="Las Palabras del nivel 1 deben tener como maximo 5 letras", title="!Atencion")
return False
if(nivel == 1):
if(len(palabraNueva) > 9):
mb.showwarning(message="Las Palabras del nivel 2 deben tener como maximo 9 letras", title="!Atencion")
return False
if(nivel == 2):
if(len(palabraNueva) < 5 and len(palabraNueva) > 10 ):
mb.showwarning(message="Las Palabras del nivel 3 deben tener como minimo 5 letras", title="!Atencion")
return False
|
8b2c0a803a26329b184b7d41eb48ec8d7f65e221
|
mauro-20/The_python_workbook
|
/chap2/ex50.py
| 835 | 4.375 | 4 |
# Richter Scale
magnitude = float(input('enter magnitude (from 0 to 10): '))
earthquake_description = ''
if magnitude < 2:
earthquake_description = 'micro'
elif magnitude < 3:
earthquake_description = 'very minor'
elif magnitude < 4:
earthquake_description = 'minor'
elif magnitude < 5:
earthquake_description = 'light'
elif magnitude < 6:
earthquake_description = 'moderate'
elif magnitude < 7:
earthquake_description = 'strong'
elif magnitude < 8:
earthquake_description = 'major'
elif magnitude < 10:
earthquake_description = 'great'
elif magnitude >= 10:
earthquake_description = 'meteoric'
if earthquake_description == '':
print('error')
else:
print('a magnitude %.1f earthquake is considered to be a %s earthquake' % (magnitude, earthquake_description))
|
0ae274aed659eea48b376f0cdc99257cee82dc00
|
brucehzhai/Python-JiangHong
|
/源码/Python课后上机实践源代码/ch10-模块和客户端/P10-prg-1-MyMath加减乘除幂.py
| 523 | 3.90625 | 4 |
#MyMath.py
def add(x, y): #定义函数
return x + y #加
def sub(x, y):
return x - y #减
def mul(x, y):
return x * y #乘
def div(x, y):
return x / y #除
def power(x, y):
return x ** y #幂
#测试代码
if __name__ == '__main__': #如果独立运行时,则运行测试代码
print('123 + 100 =', add(123, 100))
print('123 - 100 =', sub(123, 100))
print('123 * 100 =', mul(123, 100))
print('123 / 100 =', div(123, 100))
print('2 ** 10 =', power(2, 10))
|
39b792b2760106b0e495e17f33a6b0a47824c349
|
Feriow/Estacio-Python
|
/Tema 5 - Python em outros paradigmas/modulo 1/paradigmas.py
| 791 | 4.125 | 4 |
#Paradigma imperativo - O programador diz como fazer
print('### PARADIGMA IMPERATIVO ###')
numeros = [1,2,3,4]
total = 0
for numero in numeros:
total += numero
print('O total é', total)
print('\nsegundo exemplo')
if True:
print('Tudo certo')
else:
print('ops')
#Paradigma funcional - O que você quer fazer
print('\n### PARADIGMA FUNCIONAL ###')
print('O total é', sum(numeros))
print('\nsegundo exemplo')
print('Tudo certo' if True else 'ops')
#Operators e Reduce
print('\n### OPERATOR E REDUCE ###')
import operator
print('Adição de dois valores =',operator.add(10,20))
from functools import reduce
print ('Adição de múltiplos valores =',reduce(operator.add,[10,20,30]))
print ('Concatenação com reduce =',reduce(operator.concat,['Aprendendo reduce! ','Indo bem!']))
|
51a2c733609b056d0a79603e22b13f079628a47a
|
filipeclopes/courses
|
/AzeroPython/python-do-zero-master/python-do-zero-master/aulas/aula_1/problema_9.py
| 762 | 4.09375 | 4 |
"""
Faça um programa que peça uma nota, entre zero e dez.
Mostre uma mensagem caso o valor seja inválido e
continue pedindo até que o usuário informe um valor válido.
"""
cond = False
# Olhar antes de saltar
while not cond:
nota = input('Insira uma nota entre 0 e 10: ')
if nota.isdigit():
if float(nota) >= 0 and float(nota) < 11:
cond = True
print('Olá coleguinha, insira um valor válido')
# Melhor pedir perdão
while not cond:
nota = input('Insira uma nota entre 0 e 10: ')
try:
nota = float(nota)
if float(nota) >= 0 and float(nota) < 11:
cond = True
except:
print('Olá coleguinha, insira um valor válido')
print(f'Você inseriu {nota}, um valor válido')
|
105ced869e3db43818e8b4cc6681435a2d670fb2
|
dhirajgokuladas/PyGeo
|
/tests/test_objects.py
| 2,769 | 3.90625 | 4 |
from pygeo.objects import Point, Vector, Ray, Sphere
# Point.__eq__
def test__point_equal__given_two_equal_points__return_true():
assert (Point((1, 2, 3)) == Point((1, 2, 3))) is True
def test__point_equal__given_two_not_equal_points__return_false():
assert (Point((1, 2, 3)) == Point((4, 5, 6))) is False
# Vector.__eq__
def test__vector_equal__given_two_equal_vectors__return_true():
assert (Vector((1, 2, 3)) == Vector((1, 2, 3))) is True
def test__vector_equal__given_two_not_equal_vectors__return_false():
assert (Vector((1, 2, 3)) == Vector((4, 5, 6))) is False
# Point.__add__
def test__point_addition__given_point_and_vector__return_correct_point():
"""The result of a vector being added to a point is a point."""
assert Point((0, 1, 2)) + Vector((3, 4, 5)) == Point((3, 5, 7))
# Point.__radd__
def test__point_right_addition__given_vector_and_point__return_correct_point():
"""The result of a vector being added to a point is a point."""
assert Vector((0, 1, 2)) + Point((3, 4, 5)) == Point((3, 5, 7))
# Point.__sub__
def test__point_subtraction__given_two_points__return_correct_vector():
"""The result of a point being subtracted from another one is a vector."""
assert Point((0, 1, 2)) - Point((3, 4, 5)) == Vector((-3, -3, -3))
# Vector.__add__
def test__vector_addition__given_two_vector__return_correct_vector():
"""The result of a vector being added to another one is a vector."""
assert Vector((0, 1, 2)) + Vector((3, 4, 5)) == Vector((3, 5, 7))
# Vector.__sub__
def test__vector_subtraction__given_two_vectors__return_correct_vector():
"""The result of a vector being subtracted from another one is a vector."""
assert Vector((0, 1, 2)) - Vector((3, 4, 5)) == Vector((-3, -3, -3))
# Ray.__eq__
def test__ray_equal__given_two_equal_rays__return_true():
assert (Ray(direction=Vector((1,2,3)),origin=Point((3,5,6))) == Ray(direction=Vector((1,2,3)),origin=Point((3,5,6)))) is True
def test__ray_equal__given_two_not_equal_rays__return_false():
assert (Ray(direction=Vector((1,2,3)),origin=Point((3,5,6))) == Ray(direction=Vector((1,2,3)),origin=Point((4,5,7)))) is False
assert (Ray(direction=Vector((1,2,3)),origin=Point((3,5,6))) == Ray(direction=Vector((4,5,7)),origin=Point((3,5,6)))) is False
# Sphere.__eq__
def test__sphere_equal__given_two_equal_spheres__return_true():
assert (Sphere(center=Point((1,2,3)),radius=5) == Sphere(center=Point((1,2,3)),radius=5)) is True
def test__sphere_equal__given_two_not_equal_spheres__return_false():
assert (Sphere(center=Point((1,2,3)),radius=5) == Sphere(center=Point((1,2,3)),radius=6)) is False
assert (Sphere(center=Point((1,2,3)),radius=5) == Sphere(center=Point((3,5,6)),radius=5)) is False
|
f44298e2461fafc62425af390aa107fb7ea04670
|
HappyRocky/pythonAI
|
/LeetCode/131_Palindrome_Partitioning.py
| 1,027 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
"""
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
给定一个字符串 s,将 s 进行划分,每个子串都是一个回文子串。
返回所有可能的 s 的回文划分。
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
def partition(s: str) -> list:
"""
递归,先提取出前缀子串,再继续处理剩下的。
"""
result = []
for i in range(1, len(s) + 1):
if s[:i] == s[i-1::-1]:
for part in partition(s[i:]):
result.append([s[:i]] + part)
if not result:
return [[]]
return result
def partition2(s: str) -> list:
"""
将方法一改写为一行
"""
return [[s[:i]] + part
for i in range(1, len(s) + 1)
if s[:i] == s[i-1::-1]
for part in partition(s[i:])
] or [[]]
if '__main__' == __name__:
s = "aab"
print(partition2(s))
|
93b30072642e9170365fc62184aff381196b03f5
|
gabrielizalo/jetbrains-academy-python-coffee-machine
|
/Problems/snake_case/task.py
| 192 | 4.15625 | 4 |
lower_camel_case = input()
snake_case = ""
for char in lower_camel_case:
if char.isupper():
snake_case += "_" + char.lower()
else:
snake_case += char
print(snake_case)
|
8cec4a945db8d8718e1782100db1481b45826fe9
|
diegojfcampos/hashgame
|
/hash.py
| 3,764 | 3.796875 | 4 |
#HASH GAME
"Globals"
board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
position = 0
game = True
player = 1
"""IMPORT´s"""
"""Def's"""
def DesignBoard(tabuleiro):
print(" GAME BOARD ")
tab = ""
for i in range(0, 9):
mark = " "
if board[i] == 1:
mark = "X"
elif board[i] == -1:
mark = "0"
tab += " | " + mark
if i == 2 or i == 5 or i == 8:
print(tab + " | ")
tab = ""
print("---------------")
def Restart(restart):
global board
global position
global game
global player
board[0:9] = [0, 0, 0, 0, 0, 0, 0, 0, 0]
position = 0
game = True
player = 1
print(f"===============\n GAME RESTARTED\n===============")
DesignBoard(board)
def Test(test):
test1 = board[0] + board[1] + board[2]
test2 = board[3] + board[4] + board[5]
test3 = board[6] + board[7] + board[8]
test4 = board[0] + board[4] + board[8]
test5 = board[2] + board[4] + board[6]
test6 = board[0] + board[3] + board[6]
test7 = board[1] + board[4] + board[7]
test8 = board[2] + board[5] + board[8]
if test1 == 3 or test2 == 3 or test3 == 3 or test4 == 3 or test5 == 3 or test6 == 3 or test7 == 3 or test8 == 3:
print("PLAYER 1 WIN")
ScoreBoard(1)
Restart(board)
elif test1 == -3 or test2 == -3 or test3 == -3 or test4 == -3 or test5 == -3 or test6 == -3 or test7 == -3 or test8 == -3:
print("PLAYER 2 WIN")
ScoreBoard(2)
Restart(board)
def Drawn(drawn):
test1 = board[0] + board[1] + board[2]
test2 = board[3] + board[4] + board[5]
test3 = board[6] + board[7] + board[8]
test4 = board[0] + board[4] + board[8]
test5 = board[2] + board[4] + board[6]
test6 = board[0] + board[3] + board[6]
test7 = board[1] + board[4] + board[7]
test8 = board[2] + board[5] + board[8]
if test1 != 0 and test1 > -3 and test1 < 3:
if test2 != 0 and test2 > -3 and test2 < 3:
if test3 != 0 and test3 > -3 and test3 < 3:
if test4 != 0 and test4 > -3 and test4 < 3:
if test5 != 0 and test5 > -3 and test5 < 3:
if test6 != 0 and test6 > -3 and test6 < 3:
if test7 != 0 and test7 > -3 and test7 < 3:
if test8 != 0 and test8 > -3 and test8 < 3:
print(" DRAWN ")
ScoreBoard(3)
Restart(board)
def ScoreBoard(scoreboard):
player1 = []
player2 = []
drawn = []
if scoreboard == 3:
drawn.extend('3')
else:
if scoreboard == 1:
player1.extend('1')
else:
player2.extend('2')
print(f"SCOREBOARD\n\nPLAYER 1: {len(player1)}\nPlAYER 2: {len(player2)}\nDRAWN: {len(drawn)}")
#JOGO
while game == True:
Test(board)
if player == 1:
print("PLAYER 1")
else:
print("PLAYER 2")
position = int(input("Choose Position 0 to 8: "))
if position < 0 or position > 8:
print("Invalid Position, type: 1 to 8.")
elif board[position] == 1 or board[position] == -1:
print("Unavailable Position, try another position: 0 to 8.")
else:
if player == 1 and board[position] == 0:
board[position] = 1
DesignBoard(board)
player = -1
Test(board)
Drawn(board)
if player == -1 and board[position] == 0:
board[position] = -1
DesignBoard(board)
player = 1
Test(board)
Drawn(board)
|
d0b5904893f81cc3b0ad833bd0ee62ef6f3739dd
|
billjordan/walksf_flask
|
/walkSFapp/graph.py
| 4,447 | 3.59375 | 4 |
#!/usr/bin/python3.4
from edge import SF_street
from node import SF_intersection
class Digraph(object):
"""
directed graph
"""
def __init__(self):
self.nodes = set([])
self.edges = {}
def add_node(self, node):
if node in self.nodes:
raise ValueError('Duplicate node')
else:
self.nodes.add(node)
self.edges[node] = []
def add_edge(self, edge):
src = edge.get_source()
dest = edge.get_destination()
if not(src in self.nodes and dest in self.nodes):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
def children_of(self, node):
for edge in self.edges[node]:
yield edge.get_destination()
def has_node(self, node):
return node in self.nodes
def __str__(self):
res = ''
for key in self.edges.keys():
for dest in self.edges[key]:
res = res + str(key) + '->' + str(dest) + '\n'
return res[:-1]
class SF_graph(Digraph):
"""
Directed graph of the SF street grid
Nodes are SF_intersection
Edges are SF_street
all nodes are connected in both directions, but the paths are different
"""
def add_edge(self, edge):
#add the street that was given
src = edge.get_source()
dest = edge.get_destination()
#make sure the nodes are in the graph
if not(src in self.nodes and dest in self.nodes):
raise ValueError('Node not in graph')
#if the edge is not already in the graph add it
if edge not in self.edges[src]:
self.edges[src].append(edge)
#add the reverse of the street if it is not already in the graph
reverse_street = SF_street(dest, src, edge.get_streetname())
if reverse_street not in self.edges[dest]:
self.add_edge(reverse_street)
#if street and reverse of street are both in graph function will exit
def __str__(self):
res = ''
for key in self.edges.keys():
for edge in self.edges[key]:
res = res + "{} -> {} || sn: {}; len: {}; elev_ch: {}\n".format(edge.get_source(), edge.get_destination(), edge.get_streetname(), edge.get_length(), edge.get_elev_change())
return res[:-1]
def get_edge(self, src, dest):
# print type(self.edges)
# print type(self.edges[])
if src not in self.nodes:
raise ValueError("Source node {} does not exist".format(src))
if dest not in self.nodes:
raise ValueError("Destination node {} does not exist".format(dest))
for edge in self.edges[src]:
if edge.get_destination() == dest:
return edge
raise ValueError("There is no edge from src:{} to dest:{}".format(src, dest))
def get_edges(self):
"""
returns the dict of edges
"""
return self.edges
def get_nodes(self):
"""
:rtype : set of SF_intersections
"""
return self.nodes
if __name__ == '__main__':
from intersection import loadIntersections
from street import load_streets
ints = loadIntersections()
streets = load_streets()
twenty1_folsom = "24079000"
twenty2_folsom = "24077000"
shotwell_21 = "24080000"
shotwell_22 = "24078000"
twenty1 = "1105000"
twenty2 = "1187000"
shotwell = "11839000"
folsom = "5696000"
intList = [twenty1_folsom, twenty2_folsom, shotwell_21, shotwell_22]
streetList = [folsom, shotwell, twenty1, twenty2]
graph = SF_graph()
for node in intList:
node = ints[node]
sf_node = SF_intersection(node.get_cnn(), node.get_streets(), node.get_loc(), node.get_elev())
graph.add_node(sf_node)
for edge in streetList:
edge = streets[edge]
node = ints[edge.get_start()]
start = SF_intersection(node.get_cnn(), node.get_streets(), node.get_loc(), node.get_elev())
node = ints[edge.get_end()]
end = SF_intersection(node.get_cnn(), node.get_streets(), node.get_loc(), node.get_elev())
sf_edge = SF_street(start, end, edge.get_streetname())
graph.add_edge(sf_edge)
print(graph)
print(graph.nodes)
|
7c2ac8c6581a2ac2b1ebc659e8a4934a50882fe3
|
teoespero/PythonStuff
|
/list-manip-03.py
| 547 | 4.25 | 4 |
# More Python list manipulation
# Teo Espero
# GIST I
# BOF
# initialize our vars
cars = ['bmw', 'audi', 'toyota', 'subaru']
# print the current list
print('print the current list')
print(cars)
# sort the elements on the list
print('sort the elements on the list')
cars.sort()
# print the sorted list
print('print the sorted list')
print(cars)
# reverse sort the elements on the list
print('reverse sort the elements on the list')
cars.sort(reverse=True)
# print the reverse sorted list
print('print the reverse sorted list')
print(cars)
# EOF
|
65437f9f3062fe6b0c6f0730ce8e60690fae7410
|
sigurdo/fysikklab
|
/x_til_index.py
| 238 | 3.546875 | 4 |
def from_x_to_index(x,x_list):
diff_0 = abs(x_list[0]-x)
x_1 = 0
for num in range(1,len(x_list)):
diff = abs(x_list[num]-x)
if (diff < diff_0):
diff_0 = diff
x_1 = num
return x_1
|
5da9295713abe976debeacd3db949cb939e30b7d
|
mice73jp/completePython3Course
|
/readwriteFile.py
| 317 | 3.765625 | 4 |
newfile = open("newfile.txt", "w+")
string = "This is the content that will be written to the text file."
newfile.write(string)
newfile.close()
readfile = open("newfile.txt", "r")
getStr1 = readfile.readline(10)
getStr2 = readfile.readline()
print("content :", getStr1)
print("content :", getStr2)
readfile.close()
|
9c3804b86338e4106b3d46b89c1db3532c260820
|
Abdul-Nassar/Anand-Python-Class
|
/Chapter2/List/map.py
| 92 | 3.5 | 4 |
import sys
n = int(sys.argv[1])
def map(n):
return [ x*x for x in range(n)]
print map(n)
|
d0cf14b39ca7468ac3899ba8f178e09aecfb431a
|
prathik-kumar/python
|
/Fundamentals/func_overload.py
| 641 | 3.59375 | 4 |
class ServiceInfo(object):
def __init__(self, id, name, description):
self.id = id
self.name = name
self. description = description
#default arguments for omitting calling arguments
def alter(self, id, name = None, description = None):
self.id = id
if name != None:
self.name = name
if description != None:
self.description = description
#string representation for printing
def __str__(self):
return f'{self.id} {self.name}: {self.description}'
s = ServiceInfo(1021, 'synchronization-job', 'File synchronization process')
print(s)
s.alter(1021, 'sync-job', 'File sync process')
print(s)
s.alter(1051)
print(s)
|
8336bf6b9f6f08fce6ab5ad383530b8b6c31023c
|
pratik149/data-science-practice
|
/logistic Regression.py
| 1,032 | 3.53125 | 4 |
import pandas
iris=pandas.read_excel(r"C:\Users\Pratik\PycharmProjects\DS&ML\Iris.xls")
#print(iris)
column=iris.columns.values
print(column)
X=iris[column[0:4]] #0 to 3 columns
Y=iris[column[4]] #or column[-1] #last target column
#print(X)
#print(Y)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X,Y,train_size=0.7)
#order of variable should be same i.e x,x,y,y
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
from sklearn.linear_model import LogisticRegression
lrmodel=LogisticRegression()
#fitting a model and training a model is one and the same thing
lrmodel.fit(x_train,y_train)
print(lrmodel.coef_) #coefficients for logictic quation #Assignment
print(lrmodel.intercept_) #Assignment
yprd=lrmodel.predict(x_test)
#print(yprd) #Predicated Values
#print(y_test) #Actual values
from sklearn.metrics import accuracy_score
accuracy= accuracy_score(y_test,yprd)
print(accuracy)
|
b8d95dda2fd1a3e31d266c3d870787328e5932b0
|
sathishvinayk/Python-Advanced
|
/Inheritance_python.py
| 336 | 3.984375 | 4 |
#Creating a second class which inherits the superclass
from Class_in_python import FirstClass
class SecondClass(FirstClass):
def display(self):
print('Current value = "%s"' %self.data)
#make instances
z=SecondClass()
z.setdata(42)
z.display()
#calling firstClass instance again will show undistrupted value
x.display()
|
1a7148a9336976efa4881ac1ebc01ab253196e81
|
Ubastic/sts_simulator
|
/player.py
| 1,315 | 3.5 | 4 |
class Player:
def __init__(self, deck, health, energy = 3):
self.deck = deck
self.health = health
self.max_health = health
self.max_energy = energy
class Deck:
def __init__(self):
self.cards = []
def add_card(self, card):
self.cards.append(card)
def remove_card(self, card):
self.cards.remove(card)
class Card:
def __init__(self, name, cost, card_type, fx, target_type, exhaust):
self.name = name
self.upgraded = 1 if '+' in name else 0
self.cost = cost # cost of the card in order to use (-1 is X, -2 is X+1...)
self.card_type = card_type # of type Card_Type
self.fx = fx # function that takes in (combat, target) and does something
self.target_type = target_type # of type Target
self.exhaust = exhaust # boolean indicating whether the card exhausts
self.count = 0
def apply(self, combat, target):
self.fx(combat, target, self.count)
def __str__(self):
return self.name
def __repr__(self):
return self.name
def __eq__(self, other):
return other is not None and (self.name == other.name and self.card_type == other.card_type and self.count == other.count)
def __hash__(self):
return hash(self.name)
|
2e5fbca6379e124e9066fdda688b0b672035b73c
|
Rao-Varun/py_ds
|
/client_server_lock_implementation/utils/socket_handler.py
| 6,031 | 3.84375 | 4 |
"""
Module to handle sockets of both Client and Server.
Author: Varun Rao
UTA id: 1001681430
"""
import socket
class SocketHandler(object):
def __init__(self, ip="127.0.0.1", port=12345):
self.ip = ip
self.port = port
self.client = False
self.server = False
self.py_socket = None
def create_client_socket(self):
"""
Creates a client socket.
steps:
1.Creates a generic socket using socket.socket().
2.Notes that a client socket is created by setting self.client to True
:return: None
"""
self.py_socket = socket.socket()
self.client = True
def verify_if_client(self):
"""
Verifies if client socket is created is created or not.
steps:
1.Checks if self.client is True. If False exception is raised
:return: None
"""
if not self.client:
raise Exception("Client socket not created")
def connect_to_server(self):
"""
Function for a client socket to connect to a server.
ip address and port must be specified while creating SocketHandler object.
1)Function verifies if client socket is created.
2)If yes function uses socket object's connect() to a server
:return: None
"""
self.verify_if_client()
print("Client socket connecting to server")
self.py_socket.connect((self.ip, self.port))
def receive_message_from_server(self):
"""
Gets message from server. Dedicated for client socket.
1)uses socket object's recv() function to obtain.
:return: string containing message from server
"""
print("Fetching response...")
message = self.py_socket.recv(2048)
print(str(message))
return str(message.decode("utf-8"))
def send_message_to_server(self, message):
"""
Function to send client message to server. Dedicated for client socket.
1)Function uses send() of socket object.
:param message: contains message string.
:return: None
"""
print("Sending message to server...")
self.py_socket.send(message.encode())
def terminate_socket(self):
"""
Use to terminate both client or server socket.
1)Uses close() function of socket object
:return: None
"""
if not self.client:
print("Server socket terminating...")
else:
print("Client socket terminating...")
self.py_socket.close()
def create_server_socket(self):
"""
Function to create a server socket and binds it to its ip.
1)Creates socket object using socket() function of "socket" library.
2)Bind the new socket to its ip using bind() of socket object.
:return: None
"""
self.server = True
print("Creating Server socket...")
self.py_socket = socket.socket()
print("Binding socket")
self.py_socket.bind(("", self.port))
def listen_to_incoming_client_request(self, request_queue=5):
"""
Function to listen to incoming client requests.
1)verifies if server socket is created.
2)uses listen() function of socket object.
:param request_queue: number of incoming clients that are kept in queue. If exceeded, rest of the requests are
discarded
:return: None
"""
self._verify_if_server()
print("Server listening to incoming client requests")
self.py_socket.listen(request_queue)
def accept_incoming_client_request(self):
"""
Accepts the request from the client. One at a time.
1)Verifies if server socket is created.
2)uses accept() function of socket object to accept
:return: tuple containing client object and client address string
"""
self._verify_if_server()
client_obj, client_addr = self.py_socket.accept()
print("Client request accepted from {}".format(client_addr))
return client_obj, client_addr
@staticmethod
def terminate_client_connection(client_obj, client_addr=""):
"""
Static function that terminates server socket connection with a client socket.
1)use close() function of client object.
:param client_obj: client object.
:param client_addr: string containing client address.
:return: None
"""
print("Terminating connection with client {}".format(client_addr))
client_obj.close()
@staticmethod
def send_message_to_client(message, client_obj, client_addr=""):
"""
Static function to send server message to client.
1)uses send() of client object to send message to client.
:param message: message string that is to be sent to client
:param client_obj: client object
:param client_addr: string containing client address
:return: None
"""
print("Sending message to client {}\n{}".format(client_addr, message))
client_obj.send(message.encode())
@staticmethod
def receive_message_from_client(client_obj, client_addr=""):
"""
Static function to receive message from a client.
1) uses recv() function of client object.
:param client_obj: client object.
:param client_addr: string containing client address.
:return: string containing message from client
"""
message = client_obj.recv(2048)
print("Message received from client {}\n{}".format(client_addr, str(message)))
return str(message.decode("utf-8"))
def _verify_if_server(self):
"""
Function to verify if server is created.
1)If self.server variable is not set to True, then exception is raised.
:return: None
"""
if not self.server:
raise Exception("Server server not created")
|
f0ca97bee5d37f0324b72f943b9edf5d135aa971
|
MikeYeromenko/homework
|
/courier.py
| 776 | 3.921875 | 4 |
def stage_entrance(number, stages, flats_stage):
num_entrance = number // (flats_stage * stages + 1) + 1
if number > flats_stage * stages:
number = number - (num_entrance - 1) * flats_stage * stages
num_stage = number // (flats_stage + 1) + 1
return num_stage, num_entrance
print('Enter the flat number')
flat_number = int(input())
print('Enter the quantity of stages in the house')
quantity_stages = int(input())
print('Enter the quantity of flats on a stage')
flats_on_stage = int(input())
number_stage, number_entrance = stage_entrance(flat_number, quantity_stages, flats_on_stage)
print(f'For you to find the flat number {flat_number} you have to come to the \n'
f'entrance number {number_entrance} and go to the {number_stage} floor')
|
1501238572fdbc95c6e2fd6a1c972c2b29dcc9a8
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/meetup/1f04f464c3294c8fbcea4b7886f2c6fd.py
| 1,464 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
from datetime import date
import calendar
def meetup_day(year, month, wd, order):
dict = {'Monday':0,'Tuesday':1,'Wednesday':2,'Thursday':3,'Friday':4, 'Saturday':5, 'Sunday':6}
lst = calendar.monthcalendar(year, month)
ret = date(1,1,1)
matchcnt = 0
bkflg = False
for i in lst:
for y in i:
if y == 0 :
continue
else:
weekday = calendar.weekday(year, month, y)
if weekday == dict[wd]:
if order == 'teenth' and y >= 10 and y < 20:
ret = date(year, month, y)
bkflg = True
return ret
elif order == '1st' and matchcnt == 0:
ret = date(year, month, y)
return ret
elif order == '2nd' and matchcnt == 1:
ret = date(year, month, y)
return ret
elif order == '3rd' and matchcnt == 2:
ret = date(year, month, y)
return ret
elif order == '4th' and matchcnt == 3:
ret = date(year, month, y)
return ret
elif order == 'last':
ret = date(year, month, y)
matchcnt += 1
if bkflg:
break
return ret
|
67d6743cba7059af14ac61ef1a391fb660306586
|
prateksha/Source-Code-Similarity-Measurement
|
/Datasets/py-if-else/Correct/073.py
| 248 | 3.875 | 4 |
#!/bin/python3
import sys
n = int(input().strip())
if (n % 2 == 1):
print ('Weird')
else:
if (2<= n <= 5):
print ('Not Weird')
elif (6<= n <= 20):
print ('Weird')
elif (n> 20):
print ('Not Weird')
|
1c9c568081340c999ce2852c1f092a9cc7b26a9a
|
JChinchilla91/Intro-Python-II
|
/src/player.py
| 1,174 | 3.546875 | 4 |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, location, items = []):
self.name = name
self.location = location
self.items = items
def move(self, direction):
new_location = self.location.location_move(direction)
if new_location is not None and len(new_location.room_items) == 0:
self.location = new_location
print(f'\n{self.name}: You are now in the {new_location.name}.. {self.location}')
elif new_location is not None:
self.location = new_location
print(f'\n{self.name}: You are now in {new_location.name}. \nIn this room you see... {new_location.items}')
else:
if direction == 'N':
direction = 'North'
if direction == 'E':
direction = 'East'
if direction == 'S':
direction = 'South'
if direction == 'W':
direction = 'West'
print(f'Nothing to the {direction}! Please choose another direction!')
def __str__(self):
return f'{self.name}'
|
257af5ac4152544c27c69f02c85e2d4c1c4c6aa9
|
amstocker/aoc2019
|
/day1.py
| 357 | 3.90625 | 4 |
def mass_to_fuel(m):
return max((m // 3) - 2, 0)
def total_fuel(m):
total = 0
while m > 0:
m = mass_to_fuel(m)
total += m
return total
with open("day1.txt") as f:
data = [int(l) for l in f.read().rstrip().split('\n')]
# part 1
print(sum(mass_to_fuel(m) for m in data))
# part 2
print(sum(total_fuel(m) for m in data))
|
52a4dd85acce041b5e30bdd3419e30c55953e3e1
|
kevincrossgrove/Bananagrams-Solver
|
/server/board.py
| 1,385 | 3.890625 | 4 |
from tile import tile
class board:
banana_board = []
'''
To access dictionary
-> [length of word][first letter]
'''
banana_dictionary = []
@classmethod
def placeWord(cls, word, startX, startY, direction):
for index, letter in enumerate(word):
if direction == 'down':
new_tile = tile(letter=letter, x=startX, y=startY+index, direction=direction)
elif direction == 'right':
new_tile = tile(letter=letter, x=startX+index, y=startY, direction=direction)
cls.banana_board.append(new_tile)
@classmethod
def printBoard(cls):
minX = 1000
minY = 1000
maxX = -1000
maxY = -1000
for tile in cls.banana_board:
if tile.x > maxX:
maxX = tile.x
if tile.x < minX:
minX = tile.x
if tile.y > maxY:
maxY = tile.y
if tile.y < minY:
minY = tile.y
xDistance = maxX - minX
yDistance = maxY - minY
print_board = [['' for i in range(xDistance+3)] for j in range(yDistance+3)]
for tile in cls.banana_board:
print_board[tile.y + (minY * -1) + 1][tile.x + (minX * -1) + 1] = tile.letter
for row in print_board:
print(row)
return print_board
|
c8a82681027066fc775d866c9f9b163979fb46b3
|
YashJain2/AP_LAB_WORK
|
/Application_programming(Lab_Work)/Q-9/9(python_programs)/tkinker.py
| 1,029 | 3.5 | 4 |
from tkinter import *
from tkinter import ttk
def get_sum(*args):
try:
num1_val=float(num1.get())
num2_val=float(num2.get())
solution.set(num1_val+num2_val)
except ValueError:
pass
root=Tk()
root.title("Calculator")
frame =ttk.Frame(root,padding="10 10 10 10")
frame.grid(column=0,row=0,sticky=(N,W,E,S))
root.columnconfigure(0,weight=1)
root.rowconfigure(0,weight=1)
num1 =StringVar()
num2=StringVar()
solution=StringVar()
num1_entry=ttk.Entry(frame, width=7,textvariable=num1)
num1_entry.grid(column=1,row=1,sticky=(W,E))
ttk.Label(frame,text="+").grid(column=2,row=1,sticky=(W,E))
num2_entry=ttk.Entry(frame,width=7,textvariable=num2)
num2_entry.grid(column=3,row=1,sticky=(W,E))
ttk.Button(frame,text="ADD",command=get_sum).grid(column=1,row=2,sticky=(W,E))
solution_entry=ttk.Entry(frame,width=7,textvariable=solution)
solution_entry.grid(column=3,row=2,sticky=(W,E))
num1_entry.focus()
root.bind('<Return>',get_sum)
root.mainloop()
|
25360abe687c64fdb659982b035f0d92120ee247
|
LukeLaScala/advent-of-code-2016
|
/day3/solve1.py
| 510 | 3.640625 | 4 |
lengths = list()
possible = 0
impossible = 0
with open('in.txt') as f:
for line in f:
lengths.append(line.lstrip(' ').strip('\n').split(' '))
def check(l1, l2, l3):
return (l1 + l2) > l3 and (l2 + l3) > l1 and (l1 + l3) > l2
for length in lengths:
length = filter(lambda a: a != '', length)
if check(int(length[0]), int(length[1]), int(length[2])):
possible += 1
else:
impossible += 1
print("Impossible: " + str(impossible))
print("Possible: " + str(possible))
|
63ab2b061ac1e2b5fff66840dd283d40dd7e21da
|
pomonykr/DataScience
|
/Python,Pandas,Mysql/Python_3일차/Python03_08_ForExp01_김병수.py
| 272 | 4.15625 | 4 |
a = [2*4,3*6,9*4,3*3]
#result = []
#for num in a:
# result.append(num*3)
#
#print(result)
#
#
#result = [num * 1]
#print(result)
#변수를 정수 말고 이름으로 해볼것
result = []
for num in a:
result.append(num*3)
print(result)
#[3, 6, 9, 12]
#[3, 6, 9, 12]
|
206cbdcfad26c6a7f1d577c72faf53b677946fff
|
threegenie/algo_problem
|
/prefixsum.py
| 1,334 | 3.546875 | 4 |
import time, random
def prefixSum1(X, n):
# code for prefixSum1
for i in range(n):
S = 0
for j in range(i+1):
S += X[j]
def prefixSum2(X, n):
# code for prefixSum2
S = X[0]
for i in range(1, n):
S += X[i]
random.seed() # random 함수 초기화
n = int(input()) # n 입력받음
X = [random.randint(-999, 999) for _ in range(n)]
# 리스트 X를 randint를 호출하여 n개의 랜덤한 숫자로 채움
before = time.clock()
prefixSum1(X, n) # prefixSum1 호출
after = time.clock()
print('prefixSum1이 수행된 시간 : %f 초' % (after-before)) # 수행시간 출력
before = time.clock()
prefixSum2(X, n) # prefixSum1 호출
after = time.clock()
print('prefixSum2이 수행된 시간 : %f 초' % (after-before)) # 수행시간 출력
#수행시간 비교
runtime = [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,20000,30000,40000,50000,60000,70000,80000,90000,100000]
for i in runtime:
X = [random.randint(-999, 999) for _ in range(i)]
before = time.clock()
prefixSum1(X, i)
after = time.clock()
run1 = after - before
before = time.clock()
prefixSum2(X, i)
after = time.clock()
run2 = after - before
print("n이 %s일 때 O(n^2)의 수행시간은 O(n)의 수행시간의 %s배" %(i, run1/run2))
|
44d17f40e6f0e3b49d1b8fe305e19ff11d54d18c
|
jasper2326/HackerRank
|
/offer/_11.py
| 896 | 3.578125 | 4 |
class Solution:
def powerNormal(self, base, exponent):
if exponent == 0:
return 1
elif exponent == 1:
return base
if exponent < 0:
flag = 1
exponent = -exponent
else:
flag = 0
result = 1
temp = base
while exponent != 0:
if exponent & 1 == 1:
result = result * temp
temp = temp ** 2
exponent = exponent >> 1
if flag == 0:
return result
else:
return 1 / result
def powerNormalRecursive(self, base, exponent):
if exponent == 0:
return 1
elif exponent == 1:
return base
result = self.powerNormalRecursive(base, exponent >> 1)
result *= result
if exponent & 1 == 1:
result *= base
return result
|
02457e25a3e1322da15afd797241b8d6b3ca904f
|
haodonghui/python
|
/learning/py3/RuntimeError Set changed size during iteration解决方法/1.py
| 659 | 3.75 | 4 |
'''
参考:
https://blog.csdn.net/weixin_43848469/article/details/106470927
写代码的时候报了这样一个错,有一种非常简单的解决方法,因为一般是你 set 删除了一些东西,可以使用复制一个相同的集合进行循环,这样就不会报错了,比如
'''
order_delivery_no_set = set()
# 会报错 RuntimeError: Set changed size during iteration
for order_delivery_no in order_delivery_nos:
order_delivery_nos.discard(order_delivery_no)
# order_delivery_nos.copy() 复制一个相同的集合进行循环
for order_delivery_no in order_delivery_nos.copy():
order_delivery_nos.discard(order_delivery_no)
|
eb16eeb0765d572d65b05b17f9cdc8a1dc5ff774
|
pythonfoo/pythonfoo
|
/beginnerscorner/crashcourse-0/05_input.py
| 495 | 3.921875 | 4 |
#!/usr/bin/env python
# get user input
myInput = raw_input("enter some foo: ")
# THIS is BALLZ (in python 2.6/2.7), describe why!
#myInput = input("enter some foo: ")
print "you entered:", myInput
# do stuff ONLY if this the input is a digit
if myInput.isdigit() == True:
print 'yes we digit'
numberOne = 11
numberTwo = 0
# this would fail
#numberTwo = myInput
# convert FIRST
numberTwo = int(myInput)
numberOne += numberTwo
print numberOne
else:
print 'just text dude'
|
401135cd8985f8c777b666fc87e185bedfe94980
|
namphung1998/Comp123_code
|
/untitled1/work.py
| 805 | 3.5625 | 4 |
from tkinter import *
class Yeller:
def __init__(self):
self.root = Tk()
self.inptVar = StringVar()
self.inpt = Entry(self.root, font = ("Bradley Hand", 30), textvariable = self.inptVar)
self.inpt.grid(row = 0, column = 0)
self.btn = Button(self.root, text = "yell now!", command = self.click)
self.btn.grid(row=0, column=1)
self.outVar = StringVar()
self.outVar.set("HEY THERE YALL")
self.out = Label(self.root, font = ("Bradley Hand",30), textvariable = self.outVar)
self.out.grid(row=1, column = 0, columnspan = 2)
def go(self):
self.root.mainloop()
def click(self):
inStr = self.inptVar.get()
capsStr = inStr.upper()
self.outVar.set(capsStr)
yell = Yeller()
yell.go()
|
02514dc8173d54f03a86e681fb35b7a3da5a78cf
|
Gnurka/adventofcode-2017
|
/day7/day7.py
| 1,510 | 3.5625 | 4 |
import re
class Node:
def __init__(self, root, weight, children):
self.root = root
self.weight = weight
self.children = children
#self.child_weights = []
def __repr__(self):
return self.root + "(" + str(self.weight) + ") -> " + str(self.children) # + ". Child weights: " + str(self.child_weights)
def open_nodes_file(file):
with open(file) as fp:
nodes = []
for line in fp:
l = re.findall('\w+', line)
children = l[2:]
nodes.append(Node(l[0], int(l[1]), children))
return nodes
def star1():
nodes = open_nodes_file('input.txt')
print(find_root(nodes))
def find_root(nodes):
for a in nodes:
found = False
for b in nodes:
if a.root in b.children:
found = True
break
if not found:
return a
def node_weight(node):
pass
def find_unbalanced_node(node, nodes):
if len(node.children) == 0:
return node.weight
weights = []
for i, c in enumerate(node.children):
child = [n for n in nodes if c == n.root]
w = find_unbalanced_node(child[0], nodes)
weights.append(w)
if i > 0 and w != weights[0]:
print(child[0], weights)
node.child_weights = weights
return sum(weights) + node.weight
def star2():
nodes = open_nodes_file('input.txt')
root = find_root(nodes)
find_unbalanced_node(root, nodes)
star1()
star2()
|
b9eccaf484d5bd0ce7631d54f1aa1e7fdf347308
|
zhouf1234/untitled927
|
/21点小游戏.py
| 7,227 | 3.609375 | 4 |
import random
import sys
import time
class Card:
"""定义扑克牌类。每个对象代表一张扑克牌。
"""
def __init__(self, card_type, card_text, card_value):
"""初始化方法。
card_type : str
牌的类型。(红桃,黑桃,梅花,方片)
card_text : str
牌面显示的文本。(A,K,Q,J)
card_value : int
牌面真实的点数。(如A为1点或11点。K为10点等)
"""
self.card_type = card_type
self.card_text = card_text
self.card_value = card_value
# s = Card('♣','2','2')
# print(s.card_value)
class Role:
"""定义角色类,用来表示电脑(庄家)与我们用户(玩家)。"""
def __init__(self):
"""初始化方法"""
# 定义列表,用来保存当前角色手中的牌。初始牌为空。
self.cards = []
def show_card(self):
"""向控制台打印手中所有的牌。"""
for card in self.cards:
print(card.card_type, card.card_text, sep="", end="")
# 打印当前角色手中所有牌之后,再进行一个换行。
print()
def get_value(self, min_or_max):
"""获得当前角色手中牌的点数。(分为最小值与最大值)。
min_or_max : str,值为min或max。
当值为min时,返回的是最小点数。即所有的A当成是1时的点数。(用来判断是否爆牌的情况。)
当值为max时,返回在不爆牌的前提下,可表示的最大点数。此时A可能表示为11,也可能表示为1。
value : int
返回手中牌的点数。(最小点数或最大点数。)
"""
# 总的点数
sum2 = 0
# 牌面中A的数量。(有几张A)
A = 0
for card in self.cards:
# 累计相加牌面所有的点数
sum2 += card.card_value
# 累计A的数量
if card.card_text == "A":
A += 1
if min_or_max == "max":
# 逐渐减少A的数量,选择一个小于等于21点的最大值。
for i in range(A):
# 在总的点数上减去10,相当于将A当成1点看待。(减去几个10,就相当于
# 是将几个A当成1点来看待。)
value = sum2 - i * 10
if value <= 21:
return value
# 如果把所有的A都当成1,则最大值与最小值是相同的。
return sum2 - A * 10
def burst(self):
"""判断是否爆牌,是返回True,否则返回False。
b : bool
是否爆牌,爆牌返回True,否则返回False。
"""
# 判断是否爆牌,只需要判断最小值是否大于21点即可。
# print('ok')
return self.get_value("min") > 21
# r = Role()
# # print(r) #<__main__.Role object at 0x00000121FADCEB00>
# r.burst()
# r.get_value('min')
# r.show_card()
class CardManager:
"""扑克牌管理类。管理一整副扑克牌,并且能够进行发牌。"""
def __init__(self):
"""初始化方法"""
# 定义列表,用来保存一整副扑克牌(52张)
self.cards = []
# 定义所有牌的类型。
all_card_type = "♥♠♣♦"
# 定义所有牌面显示的文本
all_card_text = ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"]
# 定义牌面文本对应的真实点数
all_card_value = [11, 10, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2]
# 对牌面类型与牌面文本进行嵌套循环。
for card_type in all_card_type:
# print(card_type)
for index, card_text in enumerate(all_card_text):
# 创建Card类型的对象。(一张扑克牌),调用Card扑克牌类方法
card = Card(card_type, card_text, all_card_value[index])
# 将创建好的card对象加入到整副扑克牌cards列表当中。
self.cards.append(card)
# 洗牌操作
random.shuffle(self.cards)
def send_card(self, role, num=1):
"""给电脑或者玩家发牌。
role : Role
电脑或玩家对象。
num : int
发牌的张数。默认为1。
"""
for i in range(num):
card = self.cards.pop() #发牌后,cards列表少一张牌card,玩家或电脑多一张牌card
role.cards.append(card)
# cm = CardManager()
# print(cm.cards)
# print(len(cm.cards)) 52张牌(52个列表)总共,打乱顺序
# for i in cm.cards:
# print(i.card_text,end='')
# 创建扑克牌管理器类
cards = CardManager()
# 创建电脑角色对象
computer = Role()
# 创建玩家角色对象
player = Role()
# 初始时,给庄家发一张牌,给玩家发两张牌。
cards.send_card(computer)
cards.send_card(player, 2)
# 显示庄家与玩家手中牌。
computer.show_card()
player.show_card()
# 询问玩家是否要牌,要则继续发牌,否则停牌。
while True:
# 询问玩家是否要牌,y:要牌,n:停牌。
choice = input("是否再要一张牌?【y/n】")
# 玩家选择要牌
if choice == "y":
# 向玩家发牌
cards.send_card(player)
# 发牌后,显示庄家与玩家手中的牌。
computer.show_card()
player.show_card()
# 判断每次玩家要牌后,是否爆牌。如果爆牌,则玩家负。
# 如果没有爆牌,则继续向玩家询问是否要牌。
if player.burst():
print("爆牌,您输了!")
# 退出程序
sys.exit()
# 否则,没有要牌,则退出循环。(停牌)
else:
break
# 玩家停牌之后,庄家发牌。庄家在小于17点时,必须一直要牌。在大于等于17点,小于等于21点时,必须停牌。
while True:
print("庄家发牌中……")
# 因为庄家发牌不需要向玩家那样进行询问,所以没有停顿时间。程序会显示非常快速。
# 为了能有一个很好的间隔性,我们在每次发牌时,暂停1秒。
time.sleep(1)
# 向庄家发牌
cards.send_card(computer)
# 更新显示庄家与玩家手中的牌。
computer.show_card()
player.show_card()
# 判断庄家是否爆牌。如果爆牌,则庄家负。
if computer.burst():
print("庄家爆牌,您赢了!")
sys.exit()
# 如果没有爆牌,则判断庄家的牌面值是否达到17点,如果达到17点,则庄家必须停牌,否则,庄家必须继续要牌。
elif computer.get_value("max") >= 17:
break
# 如果庄家与玩家都没有爆牌,则根据手中的牌面点数,比价大小。
# 获取在不爆牌的前提下,可表示的最大点数。
player_value = player.get_value("max")
computer_value = computer.get_value("max")
# 比较点数大小,多者胜出。如果一样大,则平局。
if player_value > computer_value:
print("您赢了!")
elif player_value == computer_value:
print("平均")
else:
print("您输了")
|
1dfb83b0d0e9af206dfc81fdbe2fff8a48443e03
|
ang027/r1-ticpy
|
/reto1.py
| 316 | 3.609375 | 4 |
Polacos= int (input("Candidatos Polacos: "))
Hungaros= int ((Polacos*2)+4)
Lituanos= int ((Polacos + Hungaros)/5)
print(Polacos, Hungaros, Lituanos)
if Lituanos in range(0,20):
print("Uno")
if Lituanos in range(21,30):
print("Dos")
if Lituanos in range(31,50):
print("Tres")
if (Lituanos>50):
print("Cuatro")
|
5a8448913babbf7e385c003e23e02e531a088703
|
aakin03/CS-115
|
/lab3.py
| 553 | 3.5625 | 4 |
'''
Created on Feb 12, 2015
@author: Ayse Akin
'''
def minimum(x, y):
if x < y:
return x
return y
def change(amount, coins):
if amount == 0:
return 0
elif coins == []:
return float("inf")
else:
firstCoin = coins[0]
if firstCoin > amount:
return change(amount, coins[1:])
else:
useIt = 1 + change(amount-firstCoin, coins)
loseIt = change(amount, coins[1:])
return minimum(useIt, loseIt)
print change(48, [1,5,10,25])
|
ad029472ea16da8948aba0742424b3b46ff28cae
|
FLINKBLINK/Curso-Python
|
/arquivos de python aleatorios/Exercicios/Exercicio006.py
| 233 | 4.125 | 4 |
numero = int(input('Digite aqui um número inteiro: '))
dobro = numero * 2
triplo = numero * 3
raiz = numero ** (1/2)
print('o dobro de {} é {}, seu triplo é {} e sua raiz quadrada é {}'.format(numero, dobro, triplo, raiz))
|
b0efb2143103655eae3a797f7d3ce0f7e3f34fae
|
JohnOyster/ComputerVision
|
/SpatialTransformations/spatial_transformations.py
| 2,742 | 4.0625 | 4 |
#!/usr/bin/env python3
"""CIS 693 - Spatial Transformations Homework.
Author: John Oyster
Date: May 22, 2020
Description:
List of Functions:
1. Convert to Grayscale
2. Negative Transformation
3. Logarithmic Transformation
4. Gamma Transformation
"""
import cv2
import numpy as np
def convert_to_grayscale(image):
"""Convert RGB Image to grayscale using RGB weights with dot product.
:param image: Original Image
:type: numpy.ndarray
:return: Grayscale Image
:rtype: numpy.ndarray
"""
rgb_weights = [0.2989, 0.5870, 0.1140]
new_image = np.dot(image[..., :3], rgb_weights)
new_image = new_image.astype(np.uint8)
return new_image
def negative_transform(image):
"""Grayscale negative image transformation.
:param image: Original Image
:type: numpy.ndarray
:return: inverted image file
:rtype: numpay.ndarray
"""
L = 2 ** int(round(np.log2(image.max()))) # Input gray level
new_image = (L - 1) - image # s = L - 1 - r
new_image = new_image.astype(np.uint8)
return new_image
def log_transform(image):
"""Logarithmic Transformation of grayscale image.
:param image: Original Image
:type: numpy.ndarray
:return: log transformed image file
:rtype: numpy.ndarray
"""
# Selecting c to help normalize r
c = np.iinfo(image.dtype).max / np.log(1 + np.max(image))
new_image = c * np.log(1 + image)
new_image = new_image.astype(np.uint8)
return new_image
def gamma_transformation(image, gamma=1.0):
"""Power-Law (Gamma) Transformation of grayscale image.
:param image: Original Image
:type: numpy.ndarray
:param gamma: Gamma value to apply
:type: float
:return: gamma transformed image file
:rtype: numpy.ndarray
"""
c = 255
norm_image = image / np.max(image)
new_image = c * np.power(norm_image, gamma)
new_image = new_image.astype(np.uint8)
return new_image
if __name__ == '__main__':
image_file = cv2.imread("./Cleveland.jpg")
cv2.imshow('Original Image', image_file)
cv2.waitKey(0)
gray_image = convert_to_grayscale(image_file)
cv2.imshow('Grayscale Image', gray_image)
cv2.waitKey(0)
negative_image = negative_transform(gray_image)
cv2.imshow('Inverted Image', negative_image)
cv2.waitKey(0)
log_image = log_transform(gray_image)
cv2.imshow('Logarithmic Transformed Image', log_image)
cv2.waitKey(0)
gamma_image = gamma_transformation(gray_image, 2.0)
cv2.imshow('Gamma Correction', gamma_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
7819fba779264926bb58176dd12c32cfbde42378
|
ElmiraSargsyan/Machine_Learning
|
/Handwritten digit recognition/gradient_descent.py
| 3,942 | 3.6875 | 4 |
import numpy as np
def stochastic_gradient_descent(data, labels, gradloss,
learning_rate=1):
"""Calculate updates using stochastic gradient descent algorithm
:param data: numpy array of shape [N, dims] representing N datapoints
:param labels: numpy array of shape [N]
representing datapoints' labels/classes
:param gradloss: function, that calculates the gradient of the loss
for the given array of datapoints and labels
:param learning_rate: gradient scaling parameter
:yield: yields scaled gradient
"""
# Yield gradient for each datapoint
indexes = np.arange(len(data))
np.random.shuffle(indexes)
data = [data[i] for i in indexes]
labels = [labels[i] for i in indexes]
for datapoint, label in zip(data, labels):
yield learning_rate * gradloss(np.array([datapoint]), np.array([label]))
def minibatch_gradient_descent(data, labels, gradloss,
batch_size=10, learning_rate=0.1):
"""Calculate updates using minibatch gradient descent algorithm
:param data: numpy array of shape [N, dims] representing N datapoints
:param labels: numpy array of shape [N]
representing datapoints' labels/classes
:param gradloss: function, that calculates the gradient of the loss
for the given array of datapoints and labels
:param batch_size: number of datapoints in each batch
:param learning_rate: gradient scaling parameter
:yield: yields scaled gradient
"""
# Split the data into batches of batch_size
# If there is a remaining part with less length than batch_size
# Then use that as a batch
# Yield gradient for each batch of datapoints
if batch_size == 1:
for datapoint, label in zip(data, labels):
yield learning_rate * gradloss(np.array([datapoint]), np.array([label]))
else:
indexes = np.arange(len(data))
np.random.shuffle(indexes)
data = [data[i] for i in indexes]
labels = [labels[i] for i in indexes]
N = len(data) // batch_size + 1*(len(data) // batch_size != len(data) / batch_size)
for i in range(N):
data_ = np.array(data[i * batch_size:(i + 1) * batch_size])
labels_ = np.array(labels[i * batch_size:(i + 1) * batch_size])
yield learning_rate * gradloss(data_, labels_)
def batch_gradient_descent(data, labels, gradloss,
learning_rate=1):
"""Calculate updates using batch gradient descent algorithm
:param data: numpy array of shape [N, dims] representing N datapoints
:param labels: numpy array of shape [N]
representing datapoints' labels/classes
:param gradloss: function, that calculates the gradient of the loss
for the given array of datapoints and labels
:param learning_rate: gradient scaling parameter
:yield: yields scaled gradient
"""
# Yield the gradient of right scale
yield np.array(gradloss(data, labels))
def newton_raphson_method(data, labels, gradloss, hessianloss):
"""Calculate updates using Newton-Raphson update formula
:param data: numpy array of shape [N, dims] representing N datapoints
:param labels: numpy array of shape [N]
representing datapoints' labels/classes
:param gradloss: function, that calculates the gradient of the loss
for the given array of datapoints and labels
:param hessianloss: function, that calculates the Hessian matrix
of the loss for the given array of datapoints and labels
:yield: yield once the update of Newton-Raphson formula
"""
gradient = gradloss(data, labels)
hessian = hessianloss(data, labels)
yield np.linalg.inv(hessian) @ gradient
|
453456830ed86cc790f41ccbdaf9831e6b18299a
|
PythonCoder8/python-174-exercises-wb
|
/Intro-to-Programming/exercise-7.py
| 732 | 4.0625 | 4 |
'''
Exercise 7: Sum of the first n positive integers
Write a program that reads a positive integer, n, from the user and then displays the
sum of all the integers from one to n. The sum of the first n positive integers can be
calculated using the formula:
sum = (n)(n + 1) divided by 2
(I didn't use the formula)
'''
import sys
userInput = input("Enter a positive integer: ")
if isinstance(userInput, float) == True:
sys.exit("Decimals are not allowed. Only whole numbers are.")
try:
userNumber = int(userInput)
except:
sys.exit("Your input is not a number.")
userSum=0
for i in range(1,userNumber+1):
userSum += i
print(f"The sum of the numbers from 1 to {userInput} is {userSum}.")
|
b9bee08964257334949d5b51e7d4a39fcd474cfb
|
Karenahv/holbertonschool-interview
|
/0x03-minimum_operations/0-minoperations.py
| 472 | 3.78125 | 4 |
#!/usr/bin/python3
"""Minumun operations"""
def minOperations(n):
"""num of operations for n H"""
if n < 2 or type(n) is not int:
return 0
num_op = 0
act = 1
cpy_all = 0
paste = 0
while act != n:
if n % act == 0:
cpy_all = act
paste = act + cpy_all
num_op = num_op + 2
else:
paste = act + cpy_all
num_op = num_op + 1
act = paste
return num_op
|
864a70f00ef99f161fab4a212d3acbde87041eb6
|
adebuyss/knapsack
|
/Waiter.py
| 7,259 | 4.09375 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Waiter.py
A waiter who looks at a customers financial situation and suggests a
menu
"""
from decimal import Decimal
import re
import collections
def _check_money(price):
"""Check that we don't have fractions of cent"""
price = Decimal(str(price))
return ((price * 100) % 1) == 0
def parse_text_menu(target_function):
"""Decorator:
Parse a text input menu for the read_customer_request function.
allows us to easily support more input types in the future
by adding more decorators
"""
def call_wrapper(self, text_input):
if not isinstance(text_input, str):
raise UserWarning("Menu data should be in String Format")
price_re = re.compile(r"^(\$)*(\d*(\.\d+)*)$")
price_target = None
line_num = -1
menu_items = []
for line in text_input.splitlines():
line_num += 1
line = line.strip()
if len(line) == 0:
#we assume a blank line may be user error and continue
#in case the rest of the data is correct
continue
if price_target is None:
match = price_re.match(line)
if (match is None or
_check_money(match.group(2)) == False):
raise UserWarning(
"Invalid target entered: %s, line %s" %
(line, line_num))
price_target = Decimal(match.group(2))
continue
menu_item = [x.strip() for x in line.split(',')]
if len(menu_item) != 2:
raise UserWarning(
"Menu data seems incorrect: %s, line: %s" %
(line, line_num))
match = price_re.match(menu_item[1])
if match is None or _check_money(match.group(2)) == False:
raise UserWarning(
"Invalid price entered: %s, line %s" %
(menu_item[1], line_num))
menu_items.append(MenuItem(menu_item[0], match.group(2)))
if price_target is None or len(menu_items) == 0:
raise UserWarning("Either a price target was ommited or" +
" no menu items were listed!")
return target_function(self, price_target, menu_items)
return call_wrapper
class MenuItem(object):
"""Simple struct to define menuitems"""
def __init__(self, name, price):
self.name = str(name).strip()
#we convert price to a string to drop any hidden floating point
#if the argument happened to be a float
self.price = Decimal(str(price))
def __repr__(self):
return "MenuItem(\"%s\",%.2f)" % (self.name, self.price)
def __str__(self):
return "%s: $%.2f" % (self.name, self.price)
def __cmp__(self,other):
if self.price < other.price:
return -1
elif self.price > other.price:
return 1
#basic string compare
if self.name < other.name:
return -1
elif self.name > other.name:
return 1
return 0
class Waiter(object):
"""
Waiter Class
"""
def __init__(self):
self._target_price = None
self._menu_items = None
@property
def target_price(self):
return self._target_price
@target_price.setter
def target_price(self, price):
if _check_money(price) == False:
raise UserWarning(
"Prices with fractions of a penny are not accepted")
self._target_price = Decimal(str(price))
@property
def menu_items(self):
return self._menu_items
@menu_items.setter
def menu_items(self, menu_items):
for item in menu_items:
if hasattr(item, 'price') == False:
raise UserWarning(
"All items must have a price to be considered!")
self._menu_items = menu_items
@parse_text_menu
def read_customer_request(self, price_target, menu_item_list=[]):
"""
this function sets our menu information so the waiter can make
an order suggestion
"""
self.target_price = price_target
self.menu_items = list(menu_item_list)
def make_suggestion(self, price_target=None):
"""
This function will find a solution for the the customer based
on a target price and the list of items previously set
Intended to use self.target_price but this can be ovveridden
"""
if price_target is None:
price_target = self.target_price
elif _check_money(price_target):
price_target = Decimal(str(price_target))
else:
raise UserWarning("Bad price Target: %s!" % (price_target,))
if price_target == 0:
return []
if len(self.menu_items) == 0:
return []
#in the rare case when the item prices are divisable by 1,
#we dont have to convert them to integers. We spend time doing
#this check becase it will greatly reduce our solution space
multiply = 100
if(price_target % 1 == 0) and (
0 == len([x for x in self.menu_items if x.price % 1 != 0])):
multiply = 1
price_target *= multiply
#we solve this problem like a standard knapsack problem using
#dynamic programing and a bottem up traversal of the solution
#space. Solve time is n*r where r is the price_target.
#
#If memory is a concern or we need every solution saved
#the best we can do is probably a
#bactrace tree with enumarting the multiple item duplicates
#into individual items to reduce to a 0-1 knapsack.
#This would be (n * r)(reduction time) -> (n * r) * r , or nr^2
#This solution would often run faster becasue we are not
#solving the entire space, like with DP. The worst case of
#no solution would be much slower, however
table = dict()
table[0] = 0
TableEntry = collections.namedtuple(
'TableEntry', 'menu_item back_pointer')
for item in self.menu_items:
price = item.price * multiply
if price_target not in table:
for target in xrange(price, price_target+1):
if target not in table and (target-price) in table:
#save the item, and the location of the last
#"optimal" solution
table[target] = TableEntry(item, target - price)
if price_target not in table:
return []
else:
#here we walk back across the table to generate the return
#list. Saving the full list each step above would be faster
#but much more memory intensive
solution_list = []
current_location = price_target
while current_location != 0:
solution_list.append(table[current_location].menu_item)
current_location = table[current_location].back_pointer
return solution_list
if __name__ == '__main__':
pass
|
d4558b0be3d3f841ce448f0de89eaa9b6070eb30
|
JinleeJeong/Algorithm
|
/20년 2월/1406.py
| 67 | 3.734375 | 4 |
enStr = str(input())
if(enStr == "love"):
print("I love you.")
|
0354a62971df05b02b9c30824b5e29ce2f967c70
|
Number1788/Python
|
/tutorial/lists/1.py
| 3,934 | 3.96875 | 4 |
L=[123,'123',1.23]
print(len(L)) #Длина строки
print(L[0]) #Возвращаем элемент по индексу
print(L[:1]) # делаем срез до второго элемента
print(L + [4,5,6]) # контатация сторк
print(L)
print(len([1,2,3])) #длина
print([1,2,3] + [4,5,6]) #конктенация
print(['Ni!'] * 4) #повторение
print(3 in [1,2,3]) #Проверка на вхождение
for x in [1,2,3]:
print(x,end=' ') #Итерации
res = [c * 4 for c in 'SPAM'] #генератор списка
print(res)
res = []
for c in 'SPAM':
res.append(c * 4) #эквивалент генератор списка
print(res)
print(list(map(abs, [-1,-2,0,1,2]))) #Функция map применяется последованости
L= ['spam','Spam','SPAM!']
print(L[2]) #Отчет смещений начинается с нуля
print(L[-2]) #Отрицательное смещение: отчитывается справа
print(L[1:]) #Операция извлечения среза возвращает разделы списка
matrix =[[1,2,3],[4,5,6],[7,8,9]] #Работа с многомерным массивом
print(matrix[1])
print(matrix[2][0])
print(matrix)
print(matrix[1][1])
L = ['spam','Spam', 'SPAM!']
L[1]= 'eggs' #Присваивание по индексу элементу
print(L)
L[0:2] = ['eat','more'] #ПРисваивание срезу:удаление + вставка
print(L)
L.append('please') #Вызов метода добавление элемента в конец списка
print(L)
L.sort() #Сортировка элементов списка (S<e)
print(L)
L=['abc','ABD','aBe']
L.sort()
print(L)
L.sort(key=str.lower) #Приведение символов к нижнему регистру
print(L)
L.sort(key=str.lower,reverse =True) #изменяет напрваление сортировки
print(L)
L = sorted(L, key = str.lower, reverse = True) #Встроенная функция сортировки
print(L)
L = sorted([x.lower() for x in L], reverse = True) #Элементы изменяются предварительно
print(L)
L=[1,2]
L.extend([3,4,5]) #Добавление несколько элементов в конец
print(L)
print(L.pop()) #Удаляет и возвращает послдедний элемент из списка
print(L)
L.reverse() #Изменяет порядок следования на обратный
print(L)
L=list(reversed(L)) #Встроенная функция сортировки в обратном порядке
print(L)
#Реализация стека-последний пришел, первый ушел(LIFO)
L=[]
L.append(1) #Втолкнуть на стек
L.append(2)
print(L)
L.pop() #Вытолкнуть со стека
print(L)
#---end---
L = ['spam', 'eggs', 'ham']
print(L.index('eggs')) #Индекс объекта
L.insert(1,'toast') #Вставка в требуемую позицию
print(L)
L.remove('eggs') #Удаление элемента с определнныи значением
print(L)
print(L.pop(1)) #Удаление элемента в указанной позиции
print(L)
|
412183a790a82a1e3aa9f98f849af688be90d939
|
josephjose99/genskills
|
/wallis.py
| 145 | 3.953125 | 4 |
def wallis(n):
x=1
n=int(n)
i=1
while(i<=n):
x*=((2*i)**2)/(((2*i)**2)-1)
i+=1
return x*2
n=input("enter the n:")
print(wallis(n))
|
73dd1c5056ac871a92e1979443428f98504331d9
|
DaHuO/Supergraph
|
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_Haolan_cs.py
| 1,485 | 4 | 4 |
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return 0
# 2 is the only even prime number
if n == 2:
return 0
# all other even numbers are not primes
if not n & 1:
return 2
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return x
return 0
def trans(digits,base):
size = len(digits)
s = sum(digits[i]*(base**i) for i in range(size))
return s
def next(digs):
size = len(digs)
carry = 0
for i in range(1,size-1):
if digs[i] == 0:
digs[i] = 1
return
else:
digs[i] = 0
times = 1#int(input())
for t in range(times):
print 'Case #'+str(t+1)+':'
(N,J) = (16,50)#[int(a) for a in raw_input().split(' ')]
j = 0
digits = [1]+[0 for i in range(N-2)]+[1]
while j < J:
ls = []
success = True
for base in range(2,11):
a = isprime(trans(digits,base))
if a == 0:
success = False
break
else:
ls.append(a)
if success:
digits.reverse()
digstr = ''.join([str(a) for a in digits])
print digstr+' '+' '.join([str(a) for a in ls])
j += 1
next(digits)
|
37ee56b2c9bfbbb7ab2b8b047543b0e8ae9d6692
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/leap/11128d9321e24cc185d83f165d0938f4.py
| 313 | 3.875 | 4 |
def is_leap_year(year):
divisible_by_4 = year % 4 == 0
divisible_by_100 = year % 100 == 0
divisible_by_400 = year % 400 == 0
if divisible_by_4:
if divisible_by_100 and not divisible_by_400:
return False
else:
return True
else:
return False
|
93d9e899a8ac54fc88f13f764fd894f5e0e967ea
|
bosonfields/MazeRunner
|
/Mazeclass.py
| 3,562 | 3.6875 | 4 |
import numpy as np
import random
import matplotlib.cm as cm
from matplotlib import pyplot as plt
#Generalize a maze with dimension and probability
class Maze:
def __init__(self, num, p = 0):
self.dim = num
self.M = np.random.rand(self.dim, self.dim)
blank = self.M >= p
blocked = self.M<p
self.M[blank] = 1
self.M[blocked] = 0
self.M[0,0]=1
self.M[self.dim - 1, self.dim - 1] = 1
def readMaze(self, m):
self.dim = len(m)
self.M = m
#Return the available
def get_available_neighbors(self, node):
rows, cols = node
adj = [(rows - 1, cols), (rows + 1, cols), (rows, cols - 1), (rows, cols + 1)] #left, right, down, up
choice = []
if adj[0][0] >= 0 and self.M[adj[0]]==1:
choice.append(adj[0])
if adj[1][0] <self.dim and self.M[adj[1]]==1:
choice.append(adj[1])
if adj[2][1] >= 0 and self.M[adj[2]]==1:
choice.append(adj[2])
if adj[3][1] <self.dim and self.M[adj[3]]==1:
choice.append(adj[3])
return choice
def Euclidean_distance(self, node):
row, col = node
distance = np.sqrt((self.dim - row) ** 2 + (self.dim - col) ** 2)
return distance
def get_nearest_neighbors(self, node):
rows, cols = node
adj = [(rows - 1, cols), (rows, cols - 1), (rows + 1, cols), (rows, cols + 1) ] # left, up, right, down
choice = []
if adj[0][0] >= 0 and self.M[adj[0]] == 1:
choice.append(adj[0])
if adj[1][1] >= 0 and self.M[adj[1]]== 1:
choice.append(adj[1])
if adj[2][0] < self.dim and self.M[adj[2]] == 1:
choice.append(adj[2])
if adj[3][1] < self.dim and self.M[adj[3]] == 1:
choice.append(adj[3])
return choice
def show_figure(self, route=[(0,0)]):
if self.dim<=75:
self.showMaze_route_grid(route)
else:
self.showMaze_route(route)
# Generalize a image with some grids
def showMaze_route_grid(self, route):
image = np.zeros((self.dim * 10 + 1, self.dim * 10 + 1), dtype = np.uint8)
for row in range(self.dim):
for col in range(self.dim):
for i in range(10 * row+1, 10* row +10):
if (row, col) in route and self.M[row, col] ==0:
print("Route conflicted with blocks")
elif (row, col) in route:
image[i, range(10 * col+1, 10 * col + 10)] = np.uint8(128)
elif self.M[row,col]==0:
image[i, range(10 * col+1, 10 * col + 10)] = np.uint8(0)
else:
image[i, range(10 * col + 1, 10 * col + 10)] = np.uint8(225)
plt.imshow(image, cmap=cm.Greys_r, vmin=0, vmax=255, interpolation='none')
plt.show()
def showMaze_route(self,route):
image = self.M.astype(np.uint8).copy()
image[image==np.uint8(1)] = np.uint8(255)
for row, col in route:
image[row, col]=np.uint8(128)
plt.imshow(image, cmap=cm.Greys_r, vmin=0, vmax=255, interpolation='none')
plt.show()
def random_change_pairs(self):
blank = np.random.randint(self.dim, size = 2)
block = np.random.randint(self.dim, size = 2)
self.M[block] = 0
self.M[blank] = 1
self.M[0,0] = 1
self.M[self.dim - 1, self.dim - 1] = 1
return ((block[0], block[1]), (blank[0],blank[1]))
|
6453cf86aaf67f828b46fe5991293c29197a27fb
|
kzh980999074/my_leetcode
|
/src/math/172. Factorial Trailing Zeroes.py
| 315 | 4.125 | 4 |
'''
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
'''
def trailingZeros(n):
count=0
while n>0:
count+=n//5
n=n//5
return count
|
f03cd755ed946eefb1828173843c9861c33c3da0
|
elshadow11/Prog
|
/ejercicios terminados/Python/Ejercicios programas/raices.py
| 680 | 4.21875 | 4 |
#Programa: raices.py
#Propósito: Calcular la raíz cuadrada y la raíz cúbica de un número
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 13/10/2019
#
#Variables a usar:
# n1 es el numero que vamos a usar
# sq1 es la raíz cuadrada
# sq2 es la raíz cúbica
#
#Algoritmo:
# LEER n1
# sq1 <-- math.sqrt(n1)
# sq2 <-- n1 ** (1/3)
# ESCRIBIR sq1 y sq2
print("Calcular la raíz cuadrada y la raíz cúbica")
print("------------------------------------------\n")
import math
#Leemos los datos
n1 = int(input("Ingrese un número: "))
#Calculamos
sq1 = math.sqrt(n1)
sq2 = n1 ** (1/3)
#Escribimos los resultados
print("El resultado de la raíz cuadrada es ", sq1, " y el de la raíz cúbica es ", sq2)
|
30c43127770096540cf10c087a9bc901b6dbb0ce
|
susanmpu/sph_code
|
/python-programming/learning_python/ascii_to_plain.py
| 574 | 4.15625 | 4 |
#!/usr/bin/env python
# by Samuel Huckins
def main():
"""
Print the plain text form of the ASCII codes passed.
"""
import sys
import string
print "This program will compute the plain text equivalent of ASCII codes."
ascii = raw_input("Enter the ASCII codes: ")
print "Here is the plaintext version:"
plain = ""
for a in string.split(ascii):
ascii_code = eval(a)
plain = plain + chr(ascii_code)
print ""
print plain
if raw_input("Press RETURN to exit."):
sys.exit(0)
if __name__ == '__main__':
main()
|
98b28d95edbd6bc1a60469775efa6004048ecc05
|
ShiYujin/IntroductionToAlgorithms
|
/MergeSort.py
| 728 | 3.6875 | 4 |
# Merge sort.chapter2.3.1
__author__ = 'ShiYujin'
__date__ = '2015.5.24'
def merge(A, p, q, r):
import copy
L = copy.deepcopy(A[p:q])
R = copy.deepcopy(A[q:r])
L.append(float("inf")) # sentinel
R.append(float("inf"))
i = 0
j = 0
for k in range(p, r):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
return A
def MSort(A, p, r):
if p < r - 1:
q = (p + r) / 2
MSort(A, p, q)
MSort(A, q, r)
merge(A, p, q, r)
return A
def MergeSort(A):
a = A[:]
return MSort(a, 0, a.__len__())
# little test
a = [6, 5, 4, 3, 2, 1, 0]
a = MergeSort(a)
for i in a:
print(i)
|
7fdaf297479afb9008a6d573e00c1b1fd8852624
|
kurtrm/linear_algebra_pure
|
/src/matrix_multiplication.py
| 1,041 | 3.984375 | 4 |
"""
Module supplying a function for matrix multiplication.
Numpy is way better, I'm strictly trying to solidify my understanding
by implementing it in Python.
"""
def multiply_matrices(m_1: list, m_2: list) -> list:
"""
Parameters
----------
m_1 : list of lists =>
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
m_2 : list of lists =>
[[10, 11, 12],
[13, 14, 15],
[17, 18, 19]]
Returns
------
transformation : list of lists =>
[[ 87, 93, 99],
[207, 222, 237],
[327, 351, 375]]
"""
if len(m_1[0]) != len(m_2):
raise ValueError("Size mismatch: m_1 columns do not match m_2 rows")
transformation = [[] for _ in m_1]
for column_idx, _ in enumerate(m_2[0]):
for i, m1_row in enumerate(m_1):
m_2_column = [m2_row[column_idx] for m2_row in m_2]
positional_sum = sum(a * b for a, b in zip(m1_row, m_2_column))
transformation[i].append(positional_sum)
return transformation
|
6e80d387ab8c3c50348300e1727df2b7d3575a71
|
SimonFans/LeetCode
|
/OA/MS/Maximum Length of a Concatenated String with Unique Characters.py
| 1,029 | 3.796875 | 4 |
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
class Solution:
def maxLength(self,arr):
lst, m = [""], 0
for s in arr:
for i in range(len(lst)):
t = s + lst[i]
l = len(t)
if l == len(set(t)):
lst.append(t)
m = max(m, l)
return m
# Solution 2: using DP https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/414172/PythonC%2B%2BJava-Set-Solution
def maxLength(self, A):
dp = [set()]
for a in A:
if len(set(a)) < len(a): continue
a = set(a)
for c in dp[:]:
if a & c: continue
dp.append(a | c)
return max(len(a) for a in dp)
|
b438ce2a54a301f4d7ac33b0fa70a13f87aab285
|
Aasthaengg/IBMdataset
|
/Python_codes/p02712/s145621527.py
| 93 | 3.578125 | 4 |
n = int(input())
ans = sum(x for x in range(1, n+1) if x % 3 != 0 and x % 5 != 0)
print(ans)
|
06ba3f92ee3a1bfecd73d8b99f2978f3bac14aff
|
evanqianyue/Python
|
/day16/高阶函数-map与reduce/map和reduce.py
| 515 | 4.0625 | 4 |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@ Author :Evan
@ Date :2018/11/1 15:28
@ Version : 1.0
@ Description:
@ Modified By:
"""
# python内置map() 和 reduce()
# map(fn,lsd)
# fn是函数,lsd是序列
# 功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回
def char2int(chr):
return {"0": 0, "1": 1, "2": 2, "3": 3}[chr]
myList = ["2", "3", "0"]
res = map(char2int, myList)
print(res)
print(list(res))
|
00721ac764c57a8d634221b2e282d1e724dc09e9
|
harshit-dot/python-programs
|
/ga.py
| 479 | 3.59375 | 4 |
n=int(input())
s=list()
for i in range(0,n):
c=input().split()
if c[0]=='print':
print(s)
elif c[0]=='append':
b=int(c[1])
s.append(b)
elif c[0]=='insert':
b=int(c[1])
d=int(c[2])
s.insert(b,d)
elif c[0]=='remove':
b=int(c[1])
s.remove(b)
elif c[0]=='pop':
s.pop()
elif c[0]=='sort':
s.sort()
elif c[0]=='reverse':
s.reverse()
|
b82cb382740964c8d14872c0333bde9ffb8ea19c
|
jagruti8/basic_algorithms
|
/dutch_national_flag.py
| 3,311 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 07:50:52 2020
@author: JAGRUTI
"""
import random
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
# return empty list if list is empty
if len(input_list) == 0:
return []
# Three indices are maintained one for 0, one for 2 and one index for traversing. The '0' index
# maintains position where next '0' should be inserted and samewise '2' index for keeping track of position 2.
# By inserting 0 and 2 at the correct positions, 1 will be automatically in the correct position.
# index where next 0 will be inserted
index_0 = 0
# index where next 2 will be inserted
index_2 = len(input_list)-1
# current index
index = 0
# loop will run until current index is greater than the index for keeping track of position 2
while(index<=index_2):
number = input_list[index]
# if current number is 0 swap it with element present at index_0 and increment both the counters
if number == 0:
input_list[index] = input_list[index_0]
input_list[index_0] = number
index_0 += 1
index += 1
# if current number is 2 swap it with element present at index_2 and decrement index_2 position.
# check the number at present index again
elif number == 2:
input_list[index] = input_list[index_2]
input_list[index_2] = number
index_2 -= 1
# if neither 1 or 2 at current index, simply increment it
else:
index += 1
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
# Edge Cases:
test_function([]) # [] | Pass
# Normal Cases:
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) # [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2] | Pass
test_function([1, 0, 0, 2, 0]) # [0, 0, 0, 1, 2] | Pass
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2] | Pass
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
# [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] | Pass
test_function([0]) # [0] | Pass
test_function([1]) # [1] | Pass
test_function([2]) # [2] | Pass
test_function([0, 0]) # [0, 0] | Pass
test_function([1, 1]) # [1, 1] | Pass
test_function([2, 2]) # [2, 2] | Pass
test_function([0, 1, 2]) # [0, 1, 2] | Pass
test_function([2, 1, 0]) # [0, 1, 2] | Pass
test_function([0, 1, 0, 1]) # [0, 0, 1, 1] | Pass
test_function([2, 2, 0]) # [0, 2, 2] | Pass
# Large Lists
list_1 = [0 for i in range(1000000)]
list_2 = [1 for i in range(5000000)]
list_3 = [2 for i in range(7000000)]
final_list = list_1 + list_2 + list_3
#print(final_list)
random.shuffle(final_list)
#print(final_list)
test_function(final_list) # Pass
print("Great! All Done") # Great! All Done
|
0937d8d598e23fdafecc86265a0017beb1691ddd
|
phanrahan/magma
|
/magma/passes/tsort.py
| 2,214 | 4.09375 | 4 |
def tsort(graph):
"""
Repeatedly go through all of the nodes in the graph, moving each of
the nodes that has all its edges resolved, onto a sequence that
forms our sorted graph. A node has all of its edges resolved and
can be moved once all the nodes its edges point to, have been moved
from the unsorted graph onto the sorted one.
"""
# This is the list we'll return, that stores each node/edges pair
# in topological order.
graph_sorted = []
# Convert the unsorted graph into a hash table. This gives us
# constant-time lookup for checking if edges are unresolved, and
# for removing nodes from the unsorted graph.
graph_unsorted = dict(graph)
# Run until the unsorted graph is empty.
while graph_unsorted:
# Go through each of the node/edges pairs in the unsorted
# graph. If a set of edges doesn't contain any nodes that
# haven't been resolved, that is, that are still in the
# unsorted graph, remove the pair from the unsorted graph,
# and append it to the sorted graph. Note here that by using
# using the items() method for iterating, a copy of the
# unsorted graph is used, allowing us to modify the unsorted
# graph as we move through it. We also keep a flag for
# checking that that graph is acyclic, which is true if any
# nodes are resolved during each pass through the graph. If
# not, we need to bail out as the graph therefore can't be
# sorted.
acyclic = False
for node, edges in list(graph_unsorted.items()):
for edge in edges:
if edge in graph_unsorted:
break
else:
acyclic = True
del graph_unsorted[node]
graph_sorted.append((node, edges))
if not acyclic:
# Uh oh, we've passed through all the unsorted nodes and
# weren't able to resolve any of them, which means there
# are nodes with cyclic edges that will never be resolved,
# so we bail out with an error.
raise RuntimeError("A cyclic dependency occurred")
return graph_sorted
|
536c2a23bfeedb497e941ec98f2fccf47723f094
|
reberhardt7/sofa
|
/sofa/writers.py
| 514 | 3.78125 | 4 |
"""
Contains common writer functions for converting information received via the
API into a format for database storage.
"""
from datetime import datetime
def boolean_writer(value):
if str(value).lower() in ['true', '1']:
return True
elif str(value).lower() in ['false', '0']:
return False
else:
raise ValueError('%r is not a valid boolean' % value)
def date_writer(value):
return datetime.strptime(value, '%Y-%m-%d')
def datetime_writer(value):
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
|
01c0c081228f555be2498aaf1731367ff97e491d
|
Jiezhi/myleetcode
|
/src/128-LongestConsecutiveSequence.py
| 1,132 | 3.609375 | 4 |
#!/usr/bin/env python
"""
CREATED AT: 2022/3/3
Des:
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag:
See:
Time Spent: min
"""
from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
"""
Ref: https://leetcode.com/problems/longest-consecutive-sequence/solution/
Runtime: 298 ms, faster than 62.88%
Memory Usage: 27.7 MB, less than 29.96%
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
"""
if not nums:
return 0
num_set = set(nums)
ret = 1
tmp_ret = 1
for num in num_set:
if num - 1 in num_set:
continue
tmp_num = num
while tmp_num + 1 in num_set:
tmp_num += 1
tmp_ret += 1
ret = max(ret, tmp_ret)
tmp_ret = 1
return ret
def test():
assert Solution().longestConsecutive(nums=[100, 4, 200, 1, 3, 2]) == 4
assert Solution().longestConsecutive(nums=[0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9
if __name__ == '__main__':
test()
|
e8e95b26fd35a1225b69bc15e850cd474ad57916
|
caaden/python
|
/tkinter/tutorial/buttons.py
| 804 | 3.609375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 21 11:01:29 2019
@author: caden
"""
import tkinter as tk
#%%
#Define master widget
class Window(tk.Frame): #Window inherits from frame... Window is a frame
def __init__(self,master):
tk.Frame.__init__(self,master=None)
self.master=master
self.init_window()
def init_window(self):
#change title
self.master.title('GUI')
#fill entire root window with widget
self.pack(fill=tk.BOTH,expand=1)
#create button
quitButton=tk.Button(self,text='Quit')
quitButton.place(x=0,y=0)
#%% Create gui as myApp
myApp=tk.Tk()
myApp.geometry("400x300") #size
#%%configure the gui
app=Window(myApp)
#%% launch the gui
myApp.mainloop()
|
a93df82026d72cb7a5e375cc7a4a3bad9f595454
|
tulans/LearnDataScience
|
/RegressionWithSKLearn/MultipleLinearRegressionSKLearn.py
| 2,150 | 3.9375 | 4 |
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set()
data = pd.read_csv('../data/linear-regression/1.02.Multiple_linear_regression.csv')
print(data.head())
print(data.describe())
from sklearn.linear_model import LinearRegression
x = data[['SAT', 'Rand 1,2,3']]
y = data['GPA']
reg = LinearRegression()
reg.fit(x,y)
#1. R Score value
# Same function is used for both multiple and linear regression
print('R Squared Score ' + str(reg.score(x,y)))
#Find Adjusted R score. SK Learn library doesn't have the ability to identify r sqaured
r2 = reg.score(x, y)
n = x.shape[0]
p = x.shape[1]
adjusted_r2 = 1 - (1-r2)*(n-1)/(n-p-1)
if(r2 > adjusted_r2):
print('Some of the attributes used have little or no explanatory power since adjusted R2 is less than R Squared')
#Identify pvalue for each of the features used in the linear regression model
# using sk learn. We had seen this as part of statsmodel.
#we know - if the pvalue is > 0.05 then we can disregard that feature.
#There is no direct method to get the pvalue but SK Learn provides a method to find the
#F Stats i.e Feature selection based on the linear regression model for each of the feature
#Example - impact of SAT on GPA
#Example - impact of Rand 1,2,3 on GPA
from sklearn.feature_selection import f_regression
print('Feature selection stats for the features (Fstats Array + PValues Array) - '+str(f_regression(x,y)))
#output is in scientific notations - e-11 === * 10 to the power of -11 = /10 to the power of 11
p_values = f_regression(x,y)[1]
print('PValues ' + str(p_values))
new_p_values = p_values.round(3)
print('Pvalues rounded '+str(new_p_values))
#Note that - these are univariate p-values reached or derived from simple linear models
#They do not reflect the interconnection of the features in our multiple linear regression
reg_summary = pd.DataFrame(data=x.columns.values, columns=['Features'])
reg_summary['Coefficients'] = reg.coef_
reg_summary['p-values'] = p_values.round(3)
print(reg_summary)
#2. Coefficient
print('Coefficient Arrays ' + str(reg.coef_))
#3. Intercept
print('Intercept or constant ' + str(reg.intercept_))
|
4e5d217271c586257e78d304b22a69ae90c36518
|
TMAC135/Pracrice
|
/intersection_of_two_linked_list.py
| 5,101 | 3.796875 | 4 |
#coding=utf-8
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
Example
The following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Note
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Challenge
Your code should preferably run in O(n) time and use only O(1) memory.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
"""
# @param headA: the first list
# @param headB: the second list
# @return: a ListNode
"""
Brute force method,time limit exceed,
"""
def getIntersectionNode(self, headA, headB):
# Write your code here
if not headA or not headB:
return None
# cur1=headA
cur2=headB
while cur2:
cur1=headA
while(cur1):
if cur1 is cur2:
return cur1
cur1=cur1.next
cur2=cur2.next
return None
"""
Time complexity O(m+n);
1. 得到2个链条的长度。
2. 将长的链条向前移动差值(len1 - len2)
3. 两个指针一起前进,遇到相同的即是交点,如果没找到,返回null.
相当直观的解法。空间复杂度O(1), 时间复杂度O(m+n)
总结: 注意 intersection 的定义,此题定义为 intersection 后面的节点肯定是
一样的,即:
[22,32,1,2,3,4]
[32,31,23,45,34,1,2,3,4] =》 交点为1
我刚开始认为第一个相同的点,即
[22,32,1,321,42]
[43,3,23,1,34,34,24,22] =》交点为1
这种理解是错误的,因此解法一是错的暴力。
"""
def getIntersectionNode2(self, headA, headB):
# Write your code here
if not headA or not headB:
return None
# wal through the two lists and get the length of each list
lengthA=0
cur=headA
while cur:
lengthA+=1
cur=cur.next
lengthB=0
cur=headB
while cur:
lengthB+=1
cur=cur.next
# min_list and max_list are the lists corresponding to the min length and maxlength
if lengthB >= lengthA:
min_list=headA
max_list=headB
else:
min_list=headB
max_list=headA
for _ in xrange(abs(lengthA-lengthB)):
max_list=max_list.next
while min_list:
if min_list is max_list:
return min_list
else:
min_list=min_list.next
max_list=max_list.next
return None
"""
Two pointer solution (O(n+m) running time, O(1) memory):
Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A.
If at any point pA meets pB, then pA/pB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6),
pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would.
So in the second iteration, they are guaranteed to reach the intersection node at the same time.
If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.
1 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
2 if (headA == null || headB == null) {
3 return null;
4 }
5
6 ListNode pA = headA;
7 ListNode pB = headB;
8
9 ListNode tailA = null;
10 ListNode tailB = null;
11
12 while (true) {
13 if (pA == null) {
14 pA = headB;
15 }
16
17 if (pB == null) {
18 pB = headA;
19 }
20
21 if (pA.next == null) {
22 tailA = pA;
23 }
24
25 if (pB.next == null) {
26 tailB = pB;
27 }
28
29 //The two links have different tails. So just return null;
30 if (tailA != null && tailB != null && tailA != tailB) {
31 return null;
32 }
33
34 if (pA == pB) {
35 return pA;
36 }
37
38 pA = pA.next;
39 pB = pB.next;
40 }
41 }
"""
if __name__ == '__main__':
a1=ListNode(0)
a2=ListNode(2)
a1.next=a2
a3=ListNode(0)
a2.next=a3
b1=ListNode(0)
b1.next=a2
print Solution().getIntersectionNode(a1,b1).val
|
6b37f663e565158f647549961042902c3b71fdc6
|
Srinvitha/python_classes
|
/Week_08/HW2.py
| 292 | 3.984375 | 4 |
# Loop through the above list (HW1) and print elements individually only if they are integers.
list = [1,12, 4.2, False,"Not imporant", True, "V.V.V.I.P", 42, 24.09, 63]
x = 0
for l in list:
if type(list[x]) == int:
print list[x]
x = x + 1
else:
x = x + 1
|
4b921f8ffa510f3ccc7de42a6e8620f18a4585b4
|
hackettccp/CIS106
|
/SourceCode/Module13/PartA/bicycle.py
| 1,282 | 4.09375 | 4 |
#Imports the Tire object
from tire import Tire
"""
Bicycle Object.
"""
#Class Header
class Bicycle :
#Initializer
def __init__(self) :
self.front_tire = Tire(45, 27)
self.back_tire = Tire(50, 27)
self.speed = 0
#Retrieves the front tire pressure
def getfrontpressure(self) :
return self.front_tire.getpressure()
#Changes the front tire pressure
def setfrontpressure(self, pressure_in) :
try :
self.front_tire.setpressure(pressure_in)
except ValueError :
print("Invalid Front Tire Pressure Provided")
except TypeError :
print("Invalid Front Tire Data Type Provided")
#Retrieves the back tire pressure
def getbackpressure(self) :
return self.back_tire.getpressure()
#Changes the back tire pressure
def setbackpressure(self, pressure_in) :
try :
self.back_tire.setpressure(pressure_in)
except ValueError :
print("Invalid Back Tire Pressure Provided")
except TypeError :
print("Invalid Back Tire Data Type Provided")
#Increases the speed
def speedup(self) :
if self.getfrontpressure() < 5 or self.getbackpressure() < 5 :
self.speed = 0 #Tire is too flat
else :
self.speed += 5
#Retreives the speed field
def getspeed(self) :
return self.speed
|
9bfba4dbe85b5988f07298be09de59eaae7830a2
|
jordynojeda/sudoku_backtracking
|
/solver.py
| 2,026 | 3.671875 | 4 |
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(the_board):
find = find_empty(the_board)
if not find:
return True
else:
row, column = find
for i in range(1,10):
if valid(the_board,i, (row,column)):
the_board[row][column] = i
if solve(the_board):
return True
the_board[row][column] = 0
return False
def valid(the_board, number, position):
# Check row
for i in range(len(the_board[0])):
if the_board[position[0]][i] == number and position[1] != i:
return False
# Check Column
for i in range(len(the_board)):
if the_board[i][position[1]] == number and position[0] != i:
return False
# Check 3x3 box
box_x = position[1] // 3
box_y = position[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if the_board[i][j] == number and (i,j) != position:
return False
return True
def print_board(the_board):
for i in range(len(the_board)):
if i % 3 == 0 and i != 0:
print(" - - - - - - - - - - - - - ")
for j in range(len(the_board[0])):
if j == 0:
print("| ", end="")
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(str(the_board[i][j]) + " |")
else:
print(str(the_board[i][j]) + " ", end="")
def find_empty(the_board):
for i in range(len(the_board)):
for j in range(len(the_board[0])):
if the_board[i][j] == 0:
return(i,j) # row, column
return None
print_board(board)
solve(board)
print("")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("")
print_board(board)
|
4e6edba4d8de64ee1d61b69dcd6f1a979b4e9277
|
vsoch/algorithms
|
/reverse-without-special-char/reverse.py
| 1,052 | 4.5625 | 5 |
# Given a string, that contains special character together with alphabets
# (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string in a way that
# special characters are not affected.
def reverse_string(string):
# Idea: iterate through string from both sides
# First turn string into a list
lst = [x for x in string]
# Start on both sides, these are indices
left = 0
right = len(lst) - 1
# While we haven't crossed over
while left < right:
# Check if left is alphanumeric, if so, do nothing
if not lst[left].isalpha():
left = left + 1
elif not lst[right].isalpha():
right = right - 1
# Otherwise, they both are alpha numeric, and we can switch
else:
lst[left], lst[right] = lst[right], lst[left]
right -= 1
left += 1
return "".join(lst)
print(reverse_string("a,b$c"))
print(reverse_string("Ab,c,de!$"))
assert reverse_string("a,b$c") == "c,b$a"
assert reverse_string("Ab,c,de!$") == "ed,c,bA!$"
|
2959676c2dbba1a65fccfd32b97083ef89d761fe
|
sanoojm/Python-Training
|
/psgen.py
| 312 | 4.1875 | 4 |
"""
generators
-expression
-function
all generators are iterators
"""
items = [item for item in range(1, 10)]
print(items)
print()
items = (item for item in range(1, 3)) # generator
print(items)
"""print()
print(next(items))
print(next(items))
print(next(items))"""
for i in items:
print(i)
|
f0e5646618a173eb2557fa7ef1fa228a4de47c80
|
spinellimariana/OperadoresCondicionaisPython
|
/exeSucessorAntecessor.py
| 355 | 4.21875 | 4 |
'''
Exercício 5 - Aula 07
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e o seu antecessor.
'''
print('***MOSTRANDO O SUCESSOR E O ANTECESSOR DE UM NÚMERO INTEIRO***')
print()
n = int(input('Digite um número qualquer: '))
print('O antecessor de {} é {}; \nO sucessor de {} é {}.'.format(n, (n-1), n, (n+1)))
|
d27ad641ec739f25a2986929a0a209c7fe9ed2ea
|
liutongju/Fridolph
|
/python学习/python基础学习/08函数/8.3.2.py
| 361 | 4.0625 | 4 |
# 让实参变成可选的
def getFullname(firstName, lastName, middleName=''):
if middleName:
fullName = firstName + ' ' + lastName
else:
fullName = firstName + ' ' + middleName + ' ' + lastName
return fullName.title()
musician = getFullname('jimi', 'hendrix')
print(musician)
musician = getFullname('john', 'hooker', 'lee')
print(musician)
|
ee536a862ca45990fa87167cc8bade7474e6b035
|
nimanp/Project-Euler
|
/055.py
| 390 | 3.59375 | 4 |
def lychrelNumbers():
lychrels = 0
for i in range(1, 10001):
product = i
for j in range(0, 50):
reverse = int(str(product)[::-1])
product += reverse
if isPalindrome(product) == 1:
break
if j == 49:
lychrels += 1
print lychrels
def isPalindrome(num):
reverse = int(str(num)[::-1])
if reverse == num:
return 1
return 0
lychrelNumbers()
|
e18f7bca40803c554768aa3790dccb6a4fc4d03f
|
SSBsoren/Python-Fundamentals
|
/elif02.py
| 233 | 4 | 4 |
num =int(input('Enter the number :'))
if 9 < num < 99:
print('Two digit number')
elif 99 < num < 999:
print('Three digit number')
elif 999 < num <9999:
print('Four digit number')
else:
print('Number is <=9 or >=9999')
|
75c6f1b02f4204e1b5539d1bfe2e33c369c365f5
|
hudy7/poker-game
|
/card.py
| 629 | 3.625 | 4 |
'''
This class could be built out to print out actual cards.
Also debating this turning into the Deck class and giving it the ability to
generate a deck.
'''
class Card:
def __init__(self, val, suit):
self.val = val
self.suit = suit
self.card_values = {
2 : '2',
3 : '3',
4 : '4',
5 : '5',
6 : '6',
7 : '7',
8 : '8',
9 : '9',
10 : '10',
11 : 'J',
12 : 'Q',
13 : 'K',
14 : 'A'
}
self.str_val = self.card_values[self.val]
|
6849e6a879d7f8d3d8b70824282b765b598c0fdd
|
MatanNadav/sudoku-bot
|
/sudoku-bot.py
| 2,225 | 3.984375 | 4 |
# This Project is a Sudoku Bot solving any 9x9 board using Backtracking Algorithm.
# board = [
# [7, 8, 0, 4, 0, 0, 1, 2, 0],
# [6, 0, 0, 0, 7, 5, 0, 0, 9],
# [0, 0, 0, 6, 0, 1, 0, 7, 8],
# [0, 0, 7, 0, 4, 0, 2, 6, 0],
# [0, 0, 1, 0, 5, 0, 9, 3, 0],
# [9, 0, 4, 0, 6, 0, 0, 0, 5],
# [0, 7, 0, 3, 0, 0, 0, 1, 2],
# [1, 2, 0, 0, 0, 7, 4, 0, 0],
# [0, 4, 9, 2, 0, 6, 0, 0, 7]
# ]
board = [
[0,2,0,0,5,0,7,8,0],
[4,0,0,0,0,0,0,0,3],
[0,8,9,0,0,0,4,0,0],
[0,0,0,3,0,5,0,0,0],
[0,6,0,0,0,7,0,0,0],
[0,9,0,0,0,0,0,0,0],
[0,0,0,0,0,2,0,0,8],
[0,4,2,0,7,0,0,0,0],
[0,0,8,0,0,0,6,0,0],
]
def print_board(board):
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("------------------------")
for j in range (len(board[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(str(board[i][j]) + " ")
else:
print(str(board[i][j]) + " ", end="")
def find_empty_slot(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
def is_valid(board, num, pos):
#row
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
#column
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
#square
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if board[i][j] == num and (i,j) != pos:
return False
return True
def solve(board):
find = find_empty_slot(board)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
|
a0c5d5274ca48198bdf1a15b5fbd52789f4104a5
|
JaceTSM/Project_Euler
|
/euler034.py
| 945 | 3.671875 | 4 |
# !/Python34
# Copyright 2015 Tim Murphy. All rights reserved.
# Project Euler 034 - Digit Factorials
'''
Problem:
19 is a curious number, as 1! + 9! = 1 + 362880 = 362881 which is divisible by 19.
Find the sum of all numbers below N which divide the sum of the factorial of their digits.
Note: as 1!,2!, ... 9! are not sums they are not included.
Input:
Input contains an integer N
Output:
Print the answer corresponding to the test case.
Constraints:
10 <= N <= 10**5
'''
import math
# Input n, initialize nums list to store all numbers which divide the sum of the factorial of their digits
n = int(input())
nums = []
# For each number 10 to n, test for the trait in question
for i in range(10, n):
digits = list(map(int, str(i)))
for j in range(len(digits)):
digits[j] = math.factorial(digits[j])
facsum = sum(digits)
if facsum % i == 0:
nums += [i]
# Print results
print(sum(nums))
|
436c883bda93139ca507904547bb324d5f60b1ba
|
saarikabhasi/Data-Structure-and-Algorithms-in-python
|
/queue/linked-list-implementation/circularQ-in-LL.py
| 2,055 | 3.90625 | 4 |
"""
Implementing circular Q in Linked list
"""
class Node:
def __init__(self,data) -> None:
self.data = data
self.next = None
class cQueue:
def __init__(self,maxSize) -> None:
self.front = None
self.rear = None
self.maxsize = maxSize
self.size =0
def isFull(self):
return self.size == self.maxsize
def isEmpty(self):
return self.front ==self.rear==None
def peek(self):
return self.front.data
def print(self):
p = self.rear
if p == self.front:
#single item
print(p.data)
else:
while p.next != self.rear:
print(p.data)
p = p.next
print(p.data)
def enqueue(self,data):
if self.isFull():
print("EnQ Fail, Full")
else:
newNode = Node(data)
print("EnQ",data)
if self.front == None:
#first enQ
self.front = self.rear = newNode
# self.front.next = self.rear
else:
newNode.next = self.rear
self.rear = newNode
self.front.next = newNode
self.size +=1
return
def dequeue(self):
if self.isEmpty():
print("DeQ fail, Empty")
else:
print("DeQ",self.front.data)
if self.front == self.rear:
#one item
self.front.data=None
self.front = None
self.rear = None
else:
p =self.rear
while p.next != self.front:
p = p.next
self.front.data = None
self.front = p
p.next =self.rear
self.size -=1
return
c = cQueue(3)
c.enqueue(1)
c.enqueue(2)
c.enqueue(3)
c.enqueue(4)
c.print()
c.dequeue()
c.print()
c.enqueue(5)
c.print()
print("peek",c.peek())
|
01a2f25fd91bcf7d4c2f739f412b16e6e2f4c75b
|
BoatInTheRiver/data_structure
|
/binaryTree.py
| 5,187 | 3.8125 | 4 |
# coding:utf-8
from collections import deque
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = None
self.right = None
class Tree(object):
'''
二叉树
add(item):往二叉树上加一个节点,满足完全二叉树
levelOrder1(root):层序遍历
levelOrder2(root):层序遍历
preorder1(root):先序遍历--递归版
inorder1(root):中序遍历--递归版
postorder1(root):后续遍历--递归版
preorder2(root):先序遍历--迭代版
inorder2(root):中序遍历--迭代版
postorder2(root):后续遍历--迭代版
'''
def __init__(self):
self.root = None
def add(self, item):
node = TreeNode(item)
if not self.root:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if not cur_node.left:
cur_node.left = node
return
else:
queue.append(cur_node.left)
if not cur_node.right:
cur_node.right = node
return
else:
queue.append(cur_node.right)
def levelOrder1(self, root):
if not root:
return
res = []
queue = [root]
while queue:
node = queue.pop(0)
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
def levelOrder2(self, root):
'''之字型层序遍历'''
if not root:
return
res = []
queue = deque()
queue.append(root)
while queue:
tmp = deque()
for _ in range(len(queue)):
node = queue.popleft()
if len(res) % 2 == 1:
tmp.appendleft(node.val)
else:
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(list(tmp))
return res
def preorder1(self, root):
'''先序,递归版'''
res = []
def dfs(node):
if not node:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return res
def preorder2(self, root):
'''先序,迭代版,借助栈'''
WHITE, GRAY = 0, 1
res = []
stack = [(WHITE, root)]
while stack:
color, node = stack.pop()
if not node:
continue
if color == WHITE:
stack.append((WHITE, node.right))
stack.append((WHITE, node.left))
stack.append((GRAY, node))
else:
res.append(node.val)
return res
def inorder1(self, root):
'''中序,递归版'''
res = []
def dfs(node):
if not node:
return
dfs(node.left)
res.append(node.val)
dfs(node.right)
dfs(root)
return res
def inorder2(self, root):
'''中序,迭代版,借助栈'''
WHITE, GRAY = 0, 1
res = []
stack = [(WHITE, root)]
while stack:
color, node = stack.pop()
if not node:
continue
if color == WHITE:
stack.append((WHITE, node.right))
stack.append((GRAY, node))
stack.append((WHITE, node.left))
else:
res.append(node.val)
return res
def postorder1(self, root):
'''后序,递归版'''
res = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
res.append(node.val)
dfs(root)
return res
def postorder2(self, root):
'''后序,迭代版,借助栈'''
WHITE, GRAY = 0, 1
res = []
stack = [(WHITE, root)]
while stack:
color, node = stack.pop()
if not node:
continue
if color == WHITE:
stack.append((GRAY, node))
stack.append((WHITE, node.right))
stack.append((WHITE, node.left))
else:
res.append(node.val)
return res
if __name__ == '__main__':
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
print(tree.levelOrder1(tree.root))
print(tree.levelOrder2(tree.root))
print('--------------')
print(tree.preorder1(tree.root))
print(tree.preorder2(tree.root))
print('--------------')
print(tree.inorder1(tree.root))
print(tree.inorder2(tree.root))
print('--------------')
print(tree.postorder1(tree.root))
print(tree.postorder2(tree.root))
|
99e12742a7b45e1c4a655ffbb87330f320a83e50
|
wanghuafeng/lc
|
/剑指 Offer/33. 二叉搜索树的后序遍历序列.py
| 703 | 3.765625 | 4 |
#!-*- coding:utf-8 -*-
"""
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。
如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
"""
class Solution(object):
def verifyPostorder(self, postorder):
"""
:type postorder: List[int]
:rtype: bool
"""
|
2ab98c9d689dfd570d9741bbc478c690704278aa
|
estysdesu/exercism
|
/python/hamming/hamming.py
| 282 | 4.0625 | 4 |
def distance(strand_a: str, strand_b: str) -> int:
"""The Hamming distance of two equal length strings."""
if len(strand_a) != len(strand_b):
raise ValueError("strand_a and strand_b must be equal lengths")
return sum(a != b for a, b in zip(strand_a, strand_b))
|
60e36ee6b2d9941db8597f83f34b883f7967c847
|
ankitomss/python_practice
|
/partitionList.py
| 984 | 3.65625 | 4 |
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def partition(self, head, x):
temp, second=head, head
count=0
while temp!=None:
if temp.val < x:
count+=1
second=second.next
temp=temp.next
first=head
while second!=None:
while first and first.val <x:
first=first.next
while second and second.val >= x:
second=second.next
if not second: break
temp, first.val, second.val=first.val, second.val, temp
temp=head
while temp!=None:
print temp.val
temp=temp.next
#1->4->3->2->5->2
head=ListNode(1)
head.next=ListNode(4)
head.next.next=ListNode(3)
head.next.next.next=ListNode(2)
head.next.next.next.next=ListNode(5)
head.next.next.next.next.next=ListNode(2)
Solution().partition(head,3)
|
64ac2da9d780103a9041e6e5e3588734829e285b
|
kim-kiwon/Baekjoon-Algorithm
|
/삼성 기출/[5373]큐빙.py
| 6,541 | 3.5625 | 4 |
#그림 그려가며 구현.
#디버깅의 중요성
from collections import deque
cube = [[[0]* 3 for _ in range(3)] for _ in range(6)]
def init():
global cube
cube = [[['w', 'w', 'w'], ['w', 'w', 'w'], ['w', 'w', 'w']], #상
[['r', 'r', 'r'], ['r', 'r', 'r'], ['r', 'r', 'r']], #앞
[['g', 'g', 'g'], ['g', 'g', 'g'], ['g', 'g', 'g']], #좌
[['b', 'b', 'b'], ['b', 'b', 'b'], ['b', 'b', 'b']], #우
[['y', 'y', 'y'], ['y', 'y', 'y'], ['y', 'y', 'y']], #밑
[['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']]] #뒤
def c_rotate(arr):
ret_arr = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
ret_arr[i][j] = arr[2-j][i]
return ret_arr
def ac_rotate(arr):
ret_arr = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
ret_arr[i][j] = arr[j][2-i]
return ret_arr
t = int(input())
for _ in range(t):
init()
n = int(input())
data = deque(list(input().split()))
while data:
val = data.popleft()
if val[0] == 'U':
if val[1] == '+':
cube[5][0], cube[3][0], cube[1][0], cube[2][0] = cube[2][0], cube[5][0], cube[3][0], cube[1][0]
cube[0] = c_rotate(cube[0])
elif val[1] == '-':
cube[5][0], cube[3][0], cube[1][0], cube[2][0] = cube[3][0], cube[1][0], cube[2][0], cube[5][0]
cube[0] = ac_rotate(cube[0])
elif val[0] == 'F':
if val[1] == '+':
temp1, temp2, temp3 = cube[0][2][0], cube[0][2][1], cube[0][2][2]
cube[0][2][0], cube[0][2][1], cube[0][2][2] = cube[2][2][2], cube[2][1][2], cube[2][0][2]
cube[2][0][2], cube[2][1][2], cube[2][2][2] = cube[4][0][0], cube[4][0][1], cube[4][0][2]
cube[4][0][0], cube[4][0][1], cube[4][0][2] = cube[3][2][0], cube[3][1][0], cube[3][0][0]
cube[3][0][0], cube[3][1][0], cube[3][2][0] = temp1, temp2, temp3
cube[1] = c_rotate(cube[1])
elif val[1] == '-':
temp1, temp2, temp3 = cube[0][2][0], cube[0][2][1], cube[0][2][2]
cube[0][2][0], cube[0][2][1], cube[0][2][2] = cube[3][0][0], cube[3][1][0], cube[3][2][0]
cube[3][0][0], cube[3][1][0], cube[3][2][0] = cube[4][0][2], cube[4][0][1], cube[4][0][0]
cube[4][0][0], cube[4][0][1], cube[4][0][2] = cube[2][0][2], cube[2][1][2], cube[2][2][2]
cube[2][0][2], cube[2][1][2], cube[2][2][2] = temp3, temp2, temp1
cube[1] = ac_rotate(cube[1])
elif val[0] == 'L':
if val[1] == '+':
temp1, temp2, temp3 = cube[0][0][0], cube[0][1][0], cube[0][2][0]
cube[0][0][0], cube[0][1][0], cube[0][2][0] = cube[5][2][2], cube[5][1][2], cube[5][0][2]
cube[5][0][2], cube[5][1][2], cube[5][2][2] = cube[4][2][0], cube[4][1][0], cube[4][0][0]
cube[4][0][0], cube[4][1][0], cube[4][2][0] = cube[1][0][0], cube[1][1][0], cube[1][2][0]
cube[1][0][0], cube[1][1][0], cube[1][2][0] = temp1, temp2, temp3
cube[2] = c_rotate(cube[2])
elif val[1] == '-':
temp1, temp2, temp3 = cube[0][0][0], cube[0][1][0], cube[0][2][0]
cube[0][0][0], cube[0][1][0], cube[0][2][0] = cube[1][0][0], cube[1][1][0], cube[1][2][0]
cube[1][0][0], cube[1][1][0], cube[1][2][0] = cube[4][0][0], cube[4][1][0], cube[4][2][0]
cube[4][0][0], cube[4][1][0], cube[4][2][0] = cube[5][2][2], cube[5][1][2], cube[5][0][2]
cube[5][0][2], cube[5][1][2], cube[5][2][2] = temp3, temp2, temp1
cube[2] = ac_rotate(cube[2])
elif val[0] == 'R':
if val[1] == '+':
temp1, temp2, temp3 = cube[1][0][2], cube[1][1][2], cube[1][2][2]
cube[1][0][2], cube[1][1][2], cube[1][2][2] = cube[4][0][2], cube[4][1][2], cube[4][2][2]
cube[4][0][2], cube[4][1][2], cube[4][2][2] = cube[5][2][0], cube[5][1][0], cube[5][0][0]
cube[5][0][0], cube[5][1][0], cube[5][2][0] = cube[0][2][2], cube[0][1][2], cube[0][0][2]
cube[0][0][2], cube[0][1][2], cube[0][2][2] = temp1, temp2, temp3
cube[3] = c_rotate(cube[3])
elif val[1] == '-':
temp1, temp2, temp3 = cube[1][0][2], cube[1][1][2], cube[1][2][2]
cube[1][0][2], cube[1][1][2], cube[1][2][2] = cube[0][0][2], cube[0][1][2], cube[0][2][2]
cube[0][0][2], cube[0][1][2], cube[0][2][2] = cube[5][2][0], cube[5][1][0], cube[5][0][0]
cube[5][0][0], cube[5][1][0], cube[5][2][0] = cube[4][2][2], cube[4][1][2], cube[4][0][2]
cube[4][0][2], cube[4][1][2], cube[4][2][2] = temp1, temp2, temp3
cube[3] = ac_rotate(cube[3])
elif val[0] == 'D':
if val[1] == '+':
cube[1][2], cube[3][2], cube[5][2], cube[2][2] = cube[2][2], cube[1][2], cube[3][2], cube[5][2]
cube[4] = c_rotate(cube[4])
elif val[1] == '-':
cube[1][2], cube[3][2], cube[5][2], cube[2][2] = cube[3][2], cube[5][2], cube[2][2], cube[1][2]
cube[4] = ac_rotate(cube[4])
elif val[0] == 'B':
if val[1] == '+':
temp1, temp2, temp3 = cube[3][0][2], cube[3][1][2], cube[3][2][2]
cube[3][0][2], cube[3][1][2], cube[3][2][2] = cube[4][2][2], cube[4][2][1], cube[4][2][0]
cube[4][2][0], cube[4][2][1], cube[4][2][2] = cube[2][0][0], cube[2][1][0], cube[2][2][0]
cube[2][0][0], cube[2][1][0], cube[2][2][0] = cube[0][0][2], cube[0][0][1], cube[0][0][0]
cube[0][0][0], cube[0][0][1], cube[0][0][2] = temp1, temp2, temp3
cube[5] = c_rotate(cube[5])
elif val[1] == '-':
temp1, temp2, temp3 = cube[3][0][2], cube[3][1][2], cube[3][2][2]
cube[3][0][2], cube[3][1][2], cube[3][2][2] = cube[0][0][0], cube[0][0][1], cube[0][0][2]
cube[0][0][0], cube[0][0][1], cube[0][0][2] = cube[2][2][0], cube[2][1][0], cube[2][0][0]
cube[2][0][0], cube[2][1][0], cube[2][2][0] = cube[4][2][0], cube[4][2][1], cube[4][2][2]
cube[4][2][0], cube[4][2][1], cube[4][2][2] = temp3, temp2, temp1
cube[5] = ac_rotate(cube[5])
for i in range(3):
result = ''.join(cube[0][i])
print(result)
|
7c407227405cbf58b85779608790e550fd106ec6
|
leemarreros/Data-Analytics-for-Cyber-Security-Spam-Classification-by-R
|
/SMSSPAM.py
| 11,209 | 3.671875 | 4 |
#!/usr/bin/env python
# coding: utf-8
# ## Project Objective
# ##
#
# Spam detection is one of the major applications of Machine Learning in the interwebs today. Pretty much all of the major email service providers have spam detection systems built in and automatically classify such mail as 'Junk Mail'.
#
# In this project we will be using the Naive Bayes algorithm to create a model that can classify SMS messages as spam or not spam, based on the training we give to the model. It is important to have some level of intuition as to what a spammy text message might look like. Usually they have words like 'free', 'win', 'winner', 'cash', 'prize' and the like in them as these texts are designed to catch your eye and in some sense tempt you to open them. Also, spam messages tend to have words written in all capitals and also tend to use a lot of exclamation marks. To the recipient, it is usually pretty straightforward to identify a spam text and our objective here is to train a model to do that for us!
#
# Being able to identify spam messages is a binary classification problem as messages are classified as either 'Spam' or 'Not Spam' and nothing else. Also, this is a supervised learning problem, as we will be feeding a labelled dataset into the model, that it can learn from, to make future predictions.
#
#
#
# ### Step 1.1: Understanding our dataset ###
#
# The columns in the data set are currently not named and as you can see, there are 2 columns.
#
# The first column takes two values, 'ham' which signifies that the message is not spam, and 'spam' which signifies that the message is spam.
#
# The second column is the text content of the SMS message that is being classified.
# >** Instructions: **
# * Import the dataset into a pandas dataframe using the read_table method. Because this is a tab separated dataset we will be using '\t' as the value for the 'sep' argument which specifies this format.
# * Also, rename the column names by specifying a list ['label, 'sms_message'] to the 'names' argument of read_table().
# * Print the first five values of the dataframe with the new column names.
# In[1]:
import pandas as pd
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
os.chdir('C:\\Users\\SPEED TAIL\\Desktop\\Naive-Bayes-Spam')
df = pd.read_table('data', names = ['label', 'sms_message'])
##df.rename(columns = {'v1':'label','v2':'sms'},inplace=True)
# Output printing out first 5 columns
df.head()
# ### Step 1.2: Data Preprocessing ###
#
#
# >**Instructions: **
# * Convert the values in the 'label' column to numerical values using map method as follows:
# {'ham':0, 'spam':1} This maps the 'ham' value to 0 and the 'spam' value to 1.
# * Also, to get an idea of the size of the dataset we are dealing with, print out number of rows and columns using
# 'shape'.
# In[2]:
df['label'] = df.label.map({'ham':0, 'spam':1})
# In[3]:
df.shape
# In[6]:
# adding a column to represent the length of the tweet
df['len'] = df['sms_message'].str.len()
df.head(10)
# In[7]:
# describing by labels
df.groupby('label').describe()
#So from the above results we can see that there is a message with 910 characters.
# In[8]:
#Lets take a look at that message to see if the particular message is spam or ham
df[df['len']==910]['sms_message'].iloc[0]
# In[ ]:
# In[9]:
df['len'].plot(bins=50,kind='hist')
##If you see, length of the text goes beyond 800 characters (look at the x axis).
##This means that there are some messages whose length is more than the others
# ## relation between spam messages and length
# In[10]:
plt.rcParams['figure.figsize'] = (10, 8)
sns.boxenplot(x = df['label'], y = df['len'])
plt.title('Relation between Messages and Length', fontsize = 25)
plt.show()
# ### checking the most common words in the whole dataset
# In[43]:
get_ipython().system('pip install WordCloud')
# In[12]:
from wordcloud import WordCloud
wordcloud = WordCloud(background_color = 'gray', width = 800, height = 800, max_words = 20).generate(str(df['sms_message']))
plt.rcParams['figure.figsize'] = (10, 10)
plt.title('Most Common words in the dataset', fontsize = 20)
plt.axis('off')
plt.imshow(wordcloud)
# #### for ham and spam visualize it in pie chart
# In[13]:
sns.set(style="darkgrid")
plt.title('# of Spam vs Ham')
sns.countplot(df['label'])
# ## Now lets try to find some distinguishing feature between the messages of two sets of labels - ham and spam
# In[14]:
df.hist(column='len',by='label',bins=50,figsize=(12,7))
# In[ ]:
# In[ ]:
# In[15]:
size = [4825, 747]
labels = ['spam', 'ham']
colors = ['Cyan', 'lightblue']
plt.pie(size, colors = colors, labels = labels, shadow = True, autopct = '%.2f%%')
plt.axis('off')
plt.title('Pie Chart for Labels', fontsize = 20)
plt.legend()
plt.show()
# ## checking the most common words in spam messages
# In[16]:
spam = ' '.join(text for text in df['sms_message'][df['label'] == 0])
wordcloud = WordCloud(background_color = 'pink', max_words = 50, height = 1000, width = 1000).generate(spam)
plt.rcParams['figure.figsize'] = (10, 10)
plt.axis('off')
plt.title('Most Common Words in Spam Messages', fontsize = 20)
plt.imshow(wordcloud)
# ### checking the most common words in ham messages
# In[17]:
ham = ' '.join(text for text in df['sms_message'][df['label'] == 1])
wordcloud = WordCloud(background_color = 'purple', max_words = 50, height = 1000, width = 1000).generate(ham)
plt.rcParams['figure.figsize'] = (10, 10)
plt.axis('off')
plt.title('Most Common Words in Ham Messages', fontsize = 20)
plt.imshow(wordcloud)
# In[18]:
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
words = cv.fit_transform(df.sms_message)
sum_words = words.sum(axis=0)
words_freq = [(word, sum_words[0, i]) for word, i in cv.vocabulary_.items()]
words_freq = sorted(words_freq, key = lambda x: x[1], reverse = True)
frequency = pd.DataFrame(words_freq, columns=['word', 'freq'])
frequency.head(30).plot(x='word', y='freq', kind='bar', figsize=(15, 7), color = 'Cyan')
plt.title("Most Frequently Occuring Words - Top 30")
# >>**Machine Learning Model Instructions:**
# Import the sklearn.feature_extraction.text.CountVectorizer method and create an instance of it called 'count_vector'.
# In[19]:
from sklearn.feature_extraction.text import CountVectorizer
count_vector = CountVectorizer()
# In[20]:
'''
Practice node:
Print the 'count_vector' object which is an instance of 'CountVectorizer()'
'''
print(count_vector)
# >>**Instructions:**
# Convert the array we obtained, loaded into 'doc_array', into a dataframe and set the column names to
# the word names(which you computed earlier using get_feature_names(). Call the dataframe 'frequency_matrix'.
#
# ### Step 3.1: Training and testing sets ###
#
# Now that we have understood how to deal with the Bag of Words problem we can get back to our dataset and proceed with our analysis. Our first step in this regard would be to split our dataset into a training and testing set so we can test our model later.
#
# >>**Instructions:**
# Split the dataset into a training and testing set by using the train_test_split method in sklearn. Split the data
# using the following variables:
# * `X_train` is our training data for the 'sms_message' column.
# * `y_train` is our training data for the 'label' column
# * `X_test` is our testing data for the 'sms_message' column.
# * `y_test` is our testing data for the 'label' column
# Print out the number of rows we have in each our training and testing data.
#
# In[24]:
# split into training and testing sets
# USE from sklearn.model_selection import train_test_split to avoid seeing deprecation warning.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
df['label'],
random_state=1)
print('Number of rows in the total set: {}'.format(df.shape[0]))
print('Number of rows in the training set: {}'.format(X_train.shape[0]))
print('Number of rows in the test set: {}'.format(X_test.shape[0]))
# In[27]:
# Instantiate the CountVectorizer method
count_vector = CountVectorizer()
# Fit the training data and then return the matrix
training_data = count_vector.fit_transform(X_train)
# Transform testing data and return the matrix. Note we are not fitting the testing data into the CountVectorizer()
testing_data = count_vector.transform(X_test)
# ### Step 5: Naive Bayes implementation using scikit-learn ###
#
# Thankfully, sklearn has several Naive Bayes implementations that we can use and so we do not have to do the math from scratch. We will be using sklearns `sklearn.naive_bayes` method to make predictions on our dataset.
#
# Specifically, we will be using the multinomial Naive Bayes implementation. This particular classifier is suitable for classification with discrete features (such as in our case, word counts for text classification). It takes in integer word counts as its input. On the other hand Gaussian Naive Bayes is better suited for continuous data as it assumes that the input data has a Gaussian(normal) distribution.
# In[28]:
'''
We have loaded the training data into the variable 'training_data' and the testing data into the
variable 'testing_data'.
Import the MultinomialNB classifier and fit the training data into the classifier using fit(). Name your classifier
'naive_bayes'. You will be training the classifier using 'training_data' and y_train' from our split earlier.
'''
# In[29]:
from sklearn.naive_bayes import MultinomialNB
naive_bayes = MultinomialNB()
naive_bayes.fit(training_data, y_train)
# In[ ]:
'''
Instructions:
Now that our algorithm has been trained using the training data set we can now make some predictions on the test data
stored in 'testing_data' using predict(). Save your predictions into the 'predictions' variable.
'''
# In[30]:
'''
Solution
'''
predictions = naive_bayes.predict(testing_data)
# #### Now that predictions have been made on our test set, Now we need to check the accuracy of our predictions.
# ### Step 6: Evaluating our model ###
#
# Now that we have made predictions on our test set, our next goal is to evaluate how well our model is doing.
#
# We will be using all 4 metrics to make sure our model does well. For all 4 metrics whose values can range from 0 to 1, having a score as close to 1 as possible is a good indicator of how well our model is doing.
# In[31]:
'''
Compute the accuracy, precision, recall and F1 scores of your model using your test data 'y_test' and the predictions
you made earlier stored in the 'predictions' variable.
'''
# In[32]:
'''
Solution
'''
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy score: ', format(accuracy_score(predictions, y_test)))
print('Precision score: ', format(precision_score(predictions, y_test)))
print('Recall score: ', format(recall_score(predictions, y_test)))
print('F1 score: ', format(f1_score(predictions, y_test)))
|
d635f631a0a5ebdf87c1be51ae59ea00d3d70ee3
|
adam-barnett/LeetCode
|
/palindrome-number.py
| 2,082 | 4.15625 | 4 |
"""
Determine whether an integer is a palindrome. Do this without extra space.
Problem found here:
http://oj.leetcode.com/problems/palindrome-number/
"""
import math
"""
my initial solution. This works and satisfies the requirement of using no
extra space, but it uses the math library which isn't available on leetcode
so it wasn't acceptable as a solution.
"""
class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
while x > 0:
if x/(10**int(math.log10(x))) == x % 10:
x = ((x - (x/(10**int(math.log10(x))))*
10**int(math.log10(x))) / 10)
while x % 10 == 0 and x != 0:
x = x / 10
else:
return False
return True
"""
My second solution, defining my own log10 function so it could be accepted.
Additionally I decided that since I needed them for the log10 function I would
allow local variables elsewhere to improve the readability.
"""
class Solution2:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
while x > 0:
magnitude = 10**int(self.log10(x))
first_digit = x/magnitude
last_digit = x % 10
if first_digit == last_digit:
x = (x - (first_digit * magnitude)) / 10
while x % 10 == 0 and x != 0:
x = x / 10
else:
return False
return True
def log10(self, x):
val = 10
power = 0
while True:
if x < val:
return power
else:
power += 1
val = val * 10
#test
sol = Solution2()
numbers = {123454321 : True,
1232100 : False,
1 : True,
0 : True,
12 : False,
-1 : False,
10011001 : True}
for (num, expected) in numbers.iteritems():
print 'for number: ', num, ' expected: ', expected,
print 'returned: ', sol.isPalindrome(num)
|
4efd541683b2df2d4ef87adcb42fd82ce9d844b9
|
VijayEluri/ads
|
/python/optimization/simulatedannealing.py
| 3,626 | 4.0625 | 4 |
#!/usr/bin/env python
"""
The 0-1 knapsack problem resolved using the Simulated Annealing algorithm
"""
import math
import operator
import pprint
import random
import sys
COOLING_STEPS = 1000
TEMP_ALPHA = 0.8
random.seed()
def generate_items(n_items=100):
"Generate a list of items that could be stealed"
items = []
for n in range(0, n_items):
# use a uniform distribution both for values and for weights
cost = random.randint(1, 100)
weight = random.uniform(1, 20)
items.append((cost, weight))
return items
def main(args):
items = generate_items()
pprint.pprint(items)
start_sol = generate_random_solution(items, max_weight=40)
print("Random solution: %s" % start_sol)
print("value: (cost: %d, weight: %f)" % compute_cost(start_sol, items))
solution = simulated_annealing(start_sol, items, max_weight=40)
print("Final solution: %s" % solution)
print("value: (cost: %d, weight: %f)" % compute_cost(solution, items))
return False
def generate_random_solution(items, max_weight):
"Generate a starting random solution"
# generate a random solution by adding a random item
# until we don't get over the weight
solution = []
while compute_cost(solution, items)[1] <= max_weight:
idx = random.randint(0, len(items) - 1)
# skip duplicates
if idx not in solution:
solution.append(idx)
# last item makes us get over the weight so simply remove it
# we'll look for better results after
solution = solution[:-1]
return solution
def simulated_annealing(solution, items, max_weight):
"Apply the simulated annealing for solving the knapsack problem"
best = solution
best_value = compute_cost(solution, items)[0]
current_sol = solution
temperature = 1.0
while True:
current_value = compute_cost(best, items)[0]
for i in range(0, COOLING_STEPS):
moves = generate_moves(current_sol, items, max_weight)
idx = random.randint(0, len(moves) - 1)
random_move = moves[idx]
delta = compute_cost(random_move, items)[0] - \
compute_cost(best, items)[0]
if delta > 0:
best = random_move
best_value = compute_cost(best, items)[0]
current_sol = random_move
else:
if math.exp(delta / float(temperature)) > random.random():
current_sol = random_move
temperature = TEMP_ALPHA * temperature
if current_value >= best_value or temperature <= 0:
break
return best
def generate_moves(solution, items, max_weight):
"""
Generate all the ammissible moves starting from the input
solution
"""
moves = []
# try to add another item and save as a possible move
for idx, item in enumerate(items):
if idx not in solution:
move = solution[::]
move.append(idx)
if compute_cost(move, items)[1] <= max_weight:
moves.append(move)
# try to remove one item
for idx, item in enumerate(solution):
move = solution[::]
del move[idx]
if move not in moves:
moves.append(move)
return moves
def compute_cost(solution, items):
"""
Return a tuple in the format (id_item1, id_item2, ...)
for the input solution
"""
cost, weight = 0, 0
for item in solution:
cost += items[item][0]
weight += items[item][1]
return (cost, weight)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
019625173c57d59fd7aa08942bb68763c51b4099
|
skyfielders/python-skyfield
|
/skyfield/trigonometry.py
| 2,208 | 3.78125 | 4 |
"""Routines whose currency is Angle objects."""
from numpy import arctan2, sin, cos, tan
from skyfield.constants import tau
from skyfield.units import Angle
def position_angle_of(anglepair1, anglepair2):
"""Return the position angle of one position with respect to another.
Each argument should be a tuple whose first two items are
:class:`~skyfield.units.Angle` objects, like the tuples returned by
:meth:`~skyfield.positionlib.ICRF.radec()`,
:meth:`~skyfield.positionlib.ICRF.frame_latlon()`, and
:meth:`~skyfield.positionlib.ICRF.altaz()`.
If one of the two angle items is signed (if its ``.signed``
attribute is true), then that angle is used as the latitude and the
other as the longitude; otherwise the first argument is assumed to
be the latitude.
If the longitude has a ``.preference`` attribute of ``'hours'``, it
is assumed to be a right ascension which is positive towards the
east. The position angle returned will be 0 degrees if position #2
is directly north of position #1 on the celestial sphere, 90 degrees
if east, 180 if south, and 270 if west.
Otherwise, the longitude is assumed to be azimuth, which measures
north to east around the horizon. The position angle returned will
be 0 degrees if position #2 is directly above position #1 in the
sky, 90 degrees to its left, 180 if below, and 270 if to the right.
>>> from skyfield.trigonometry import position_angle_of
>>> from skyfield.units import Angle
>>> a = Angle(degrees=0), Angle(degrees=0)
>>> b = Angle(degrees=1), Angle(degrees=1)
>>> position_angle_of(a, b)
<Angle 315deg 00' 15.7">
"""
lat1, lon1 = anglepair1[0], anglepair1[1]
if lon1.signed:
lat1, lon1 = lon1, lat1
lat2, lon2 = anglepair2[0], anglepair2[1]
if lon2.signed:
lat2, lon2 = lon2, lat2
lat1 = lat1.radians
lon1 = lon1.radians if lon1.preference == 'hours' else -lon1.radians
lat2 = lat2.radians
lon2 = lon2.radians if lon2.preference == 'hours' else -lon2.radians
return Angle(radians=arctan2(
sin(lon2 - lon1),
cos(lat1) * tan(lat2) - sin(lat1) * cos(lon2 - lon1),
) % tau)
|
82781a27a46c1045a91c8019f1aa43010024ba3f
|
llanoxdewa/python
|
/Projek mandiri/save_pw.py
| 682 | 3.828125 | 4 |
import sys
def save_account():
if sys.argv[1] == '#help':
print('silahkan tulis seperti #<account> #<username> #<password>')
sys.exit()
else:
print('your user and password accoutn has been saved !!')
try:
# deklarai user dan password user
input_user_account = sys.argv[1].replace('#','')
input_user_name = sys.argv[2].replace('#','')
input_user_password = sys.argv[3].replace('#','')
except:
print('account tidak valid')
# proses input user name dan password
with open('pw.txt','a+') as pw_file:
pw_file.write(f"""#account {input_user_account}\nusername {input_user_name}\npassword {input_user_password}\n""")
if __name__ == '__main__':
save_account()
|
c688c2939ca65f40d22e9ef885273aeb301088f9
|
glissader/Python
|
/ДЗ Урок 2/main2.py
| 777 | 4.21875 | 4 |
# Для списка реализовать обмен значений соседних элементов.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т. д.
# При нечётном количестве элементов последний сохранить на своём месте.
# Для заполнения списка элементов нужно использовать функцию input().
in_str = input("Введите элементы, разделенные пробелом ")
result_list = in_str.strip().split(" ")
print(result_list)
for idx in range(0, len(result_list) - 1, 2):
result_list[idx], result_list[idx + 1] = result_list[idx + 1], result_list[idx]
print(result_list)
|
0ce47a864a51d5c50333cbf874dc9a8b17461c9f
|
captainhcg/leetcode-in-py-and-go
|
/bwu/linked_list/147-insertion-sort-list.py
| 1,393 | 3.984375 | 4 |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
dummy = ListNode(0)
newhead = ListNode(0)
newhead.next = head
dummy.next = head.next
head.next = None
cache = {'largest': head.val, 'last': head}
def insert(node, nh):
if node.val >= cache['largest']:
cache['last'].next = node
cache['largest'] = node.val
cache['last'] = node
node.next = None
return
curr = nh
while curr.next and curr.next.val <= node.val:
curr = curr.next
if curr.next:
node.next = curr.next
curr.next = node
else:
curr.next = node
node.next = None
cache['largest'] = node.val
cache['last'] = node
while dummy.next:
tmp = dummy.next.next
insert(dummy.next, newhead)
dummy.next = tmp
return newhead.next
|
e2c37787e349cd43b2f7e5692f990c4cd2d366b2
|
gadboisb5877/CTI110
|
/M2T1_SalesPrediction_GadboisBrian.py
| 271 | 3.765625 | 4 |
# CTI-110
# M2T1 - Sales Prediction
# Brian Gadbois
# 9/19/2017
# Program made to figure out the annual profit
annualProfit = .23
totalSales = float (input ('What is the total sales:',))
profit = totalSales * annualProfit
print ('Your profit will be $',profit)
|
d1f4e9762fe7d1085b1dcb237bdc69c50d64b7f1
|
kenji955/python_Task
|
/kadai_0/kadai0_6.py
| 242 | 3.71875 | 4 |
nameList=["たんじろう","ぎゆう","ねずこ","むざん"]
def nameCheck(checkName):
for name in nameList:
if name == checkName:
print(checkName+'は含まれます')
testName = 'ぎゆう'
nameCheck(testName)
|
1ecb60ef067f1e18181711f2f06e470bb35dd381
|
nduprincekc/papa
|
/student.py
| 544 | 4.25 | 4 |
#Write a function named readable_timedelta.
# The function should take one argument, an integer days, and return a string that says how many weeks and days that is.
# For example, calling the function and printing the result like this:
# print(readable_timedelta(10))
# should output the following:
# 1 week(s) and 3 day(s).
# write your function here
def readable_timedelta(days):
weeks = days // 7
day = days % 7
return 'The weeks and days in ',days,'are {} weeks and {}days'.format(weeks,day)
print(readable_timedelta(10))
|
9bd0fc0d6c4a2aa5da29e0eb6d68cf7b84d3d0e9
|
mengnan1994/Surrender-to-Reality
|
/py/0339_nested_list_weight_sum.py
| 2,043 | 4.15625 | 4 |
"""
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Input: [[1,1],2,[1,1]]
Output: 10
Explanation: Four 1's at depth 2, one 2 at depth 1.
Example 2:
Input: [1,[4,[6]]]
Output: 27
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27.
"""
class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
def add(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""
def setInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""
def getInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
class Solution:
def depth_sum(self, nestedList):
summation = 0
for l in nestedList:
summation += self._dfs_calc_weighted_sum(l, 1)
return summation
def _dfs_calc_weighted_sum(self, node : NestedInteger, depth):
if node.isInteger():
return depth * node.getInteger()
summation = 0
for l in node.getList():
summation += self._dfs_calc_weighted_sum(l, depth + 1)
return summation
|
669b95b17e96bd9c0ba5c04124cb8a8165991855
|
asouzajr/algoritmosLogicaProgramacao
|
/lingProgPython/cursoemVideo/desafio002.py
| 101 | 3.71875 | 4 |
nome = input('Qual é o seu nome? ')
print('Olá {}! É uma satisfação te conhecer!'.format(nome))
|
c550a1f6e75fab3373e8b3020184427856426db2
|
topicus/musily
|
/server/models/people.py
| 1,549 | 3.546875 | 4 |
import csv
class People(object):
def __init__(self, file_path):
people_file = open(file_path, 'r')
self.people_reader = csv.DictReader(people_file, delimiter='|')
self.__people = {}
self.load()
def load(self):
for p in self.people_reader:
self.__people[p['usuario']] = p
def all(self):
if not self.__people:
self.people.load()
return self.__people
def between(self, item, ft):
return min(ft['value']) <= float(item[ft['field']]) <= max(ft['value'])
def eq(self, item, ft):
if ft['field'] in item:
return item[ft['field']] == ft['value']
else:
return True
def gt(self, item, ft):
if ft['field'] in item:
return item[ft['field']] > ft['value']
else:
return True
def lt(self, item, ft):
if ft['field'] in item:
return item[ft['field']] < ft['value']
else:
return True
def gte(self, item, ft):
if ft['field'] in item:
return item[ft['field']] >= ft['value']
else:
return True
def lte(self, item, ft):
if ft['field'] in item:
return item[ft['field']] <= ft['value']
else:
return True
def filter(self, filters):
filtered = {}
for k, p in self.__people.iteritems():
if self.should_be(self.__people[k], filters):
filtered[k] = p
return filtered
def should_be(self, item, filters):
sb = True
for ft in filters:
filter_func = getattr(self, ft['type'])
if not filter_func(item, ft):
sb = False
break
return sb
|
3fe74a84b0fbe1b3d4b380574eaf166bdaba6bbb
|
GabrielNagy/Year3Projects
|
/AI/Project1.py
| 7,004 | 3.515625 | 4 |
#!/usr/bin/env python
from __future__ import print_function
import heapq
import logging
import sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class Cell(object):
def __init__(self, x, y, reachable):
# Cell constructor
self.reachable = reachable # is cell reachable
self.x = x # x coordinate
self.y = y # y coordinate
self.parent = None
self.g = 0 # cost to move from starting cell to given cell
self.h = 0 # cost to move from given cell to ending cell
self.f = 0 # sum of costs
class IDAStar(object):
def __init__(self, name):
self.name = name
self.opened = []
heapq.heapify(self.opened) # open list
self.closed = set() # visited cells list
self.cells = [] # grid cells
self.grid_height = None
self.grid_width = None
def initialize_grid(self, size, walls, start, end):
self.grid_height = size
self.grid_width = size
for x in range(self.grid_width):
for y in range(self.grid_height):
if (x, y) in walls:
reachable = False
else:
reachable = True
self.cells.append(Cell(x, y, reachable))
self.start = self.get_cell(*start)
self.end = self.get_cell(*end)
def get_distance(self, cell):
# computes distance between this cell and ending cell and multiplies by 10
return (abs(cell.x - self.end.x) + abs(cell.y - self.end.y)) * 10
def get_cell(self, x, y):
# returns cell from the list
return self.cells[x * self.grid_height + y]
def get_adjacent_cells(self, cell):
# returns adjacent cells of a cell, clockwise starting from the right
cells = []
if cell.x < self.grid_width - 1:
cells.append(self.get_cell(cell.x + 1, cell.y))
if cell.y > 0:
cells.append(self.get_cell(cell.x, cell.y - 1))
if cell.x > 0:
cells.append(self.get_cell(cell.x - 1, cell.y))
if cell.y < self.grid_height - 1:
cells.append(self.get_cell(cell.x, cell.y + 1))
return cells
def display_path(self):
# print found path from ending cell to starting cell
cell = self.end
path = [(cell.x, cell.y)]
while cell.parent is not self.start:
cell = cell.parent
path.append((cell.x, cell.y))
# logging.debug('path: cell: %d, %d' % (cell.x, cell.y))
path.append((self.start.x, self.start.y))
path.reverse()
return path
def print_table(self):
# draw table
print("===== TABLE %s =====" % self.name)
matrix = [[0 for x in range(0, self.grid_width + 1)] for y in range(0, self.grid_height + 1)]
for i in range(0, self.grid_width):
for j in range(0, self.grid_height):
cell = self.get_cell(i, j)
if cell.reachable:
if cell == self.start:
matrix[self.grid_width - j - 1][i] = 'S'
elif cell == self.end:
matrix[self.grid_width - j - 1][i] = 'F'
else:
matrix[self.grid_width - j - 1][i] = '.'
else:
matrix[self.grid_width - j - 1][i] = '#'
for i in range(0, self.grid_width):
for j in range(0, self.grid_height):
print(matrix[i][j], end=" ")
print('\n')
def update_cell(self, adjacent, cell):
# updates adjacent cell to current cell
adjacent.g = cell.g + 10
adjacent.h = self.get_distance(adjacent)
adjacent.parent = cell
adjacent.f = adjacent.h + adjacent.g
def process(self):
limit = self.get_distance(self.start)
INFINITY = float("inf")
# logging.debug("Starting limit: %d" % limit)
while limit < INFINITY:
self.opened = []
self.closed = set()
heapq.heapify(self.opened) # open list
heapq.heappush(self.opened, (self.start.f, self.start))
while len(self.opened): # while we have elements in the open list
# logging.debug("Current open list: ")
# logging.debug(self.opened)
# logging.debug("Current closed list: ")
# logging.debug(self.closed)
# pop cell from heap queue
f, cell = heapq.heappop(self.opened)
# logging.debug("Current cell: (%d, %d), f value: %d" % (cell.x, cell.y, f))
if f > limit:
heapq.heappop(self.opened)
# add cell to closed list
self.closed.add(cell)
# if cell is ending cell, display path
if cell is self.end:
print("FOUND PATH!")
return self.display_path()
# get adjacent cells
adjacent_cells = self.get_adjacent_cells(cell)
for adjacent_cell in adjacent_cells:
if adjacent_cell.reachable and adjacent_cell not in self.closed:
if (adjacent_cell.f, adjacent_cell) in self.opened:
# logging.debug("CHECK IF PATH IS BETTER FOR EXISTING CELL - Current cell: (%d, %d), f value: %d" % (adjacent_cell.x, adjacent_cell.y, adjacent_cell.f))
# if adjacent cell is in open list
# check if current path is better than the previous one for this adjacent cell
if adjacent_cell.g > cell.g + 10:
self.update_cell(adjacent_cell, cell)
else:
self.update_cell(adjacent_cell, cell)
# add adjacent cell to open list
if adjacent_cell.f <= limit:
heapq.heappush(self.opened, (adjacent_cell.f, adjacent_cell))
limit += 10
print("Did not find solution. Raising f limit to: %d" % limit)
# logging.debug("Current limit: %d" % (limit))
if __name__ == "__main__":
a = IDAStar('smaller_table')
a.initialize_grid(6, ((0, 5), (1, 0), (1, 1), (1, 5), (2, 3), (3, 1), (3, 2), (3, 5), (4, 1), (4, 4), (5, 1)), (0, 0), (5, 5))
a.print_table()
print(a.process())
b = IDAStar('larger_table')
b.initialize_grid(12, ((1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 7), (3, 7), (4, 7), (5, 0), (5, 1), (5, 2), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (6, 0), (6, 1), (6, 8), (6, 9), (6, 10), (7, 0), (7, 1), (7, 8), (7, 10), (7, 9), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (8, 10), (8, 11), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10)), (0, 0), (11, 11))
b.print_table()
print(b.process())
|
3616b072bd82250e68e8dc67b9840083ff18617f
|
hevervie/Python
|
/high.py
| 156 | 3.921875 | 4 |
#!/usr/bin/env python
#coding=utf-8
def max(a,b):
if a>b:
return a
return b
def MAX(a,b,c,f):
return f(f(a,b),c)
print(MAX(1,2,8,max))
|
8fbbb4f84e5776ed71c2d1a5ef1824766112772a
|
r0ckburn/d_r0ck
|
/The Modern Python 3 Bootcamp/4 - Boolean and Conditional Logic/getting_user_input.py
| 562 | 4.40625 | 4 |
# there is a built-in function in Python called "input" that will prompt the user and store the result to a variable
name = input("Enter your name here: ")
print(name)
# you can combine the variable that an end user input something to with a string
data = input("What's your favorite color?")
print("You said " + data)
# preferred to do a print statement first, then declare the variable and print the variable later -- this also puts the input on a separate line
print("What's your favorite color?")
data = input()
print("You said " + data)
|
de338ad59cdbc44c528722475c5aca7bc0e9d381
|
anitasandjaja/fundamental-python
|
/function.py
| 3,949 | 4.125 | 4 |
# Function
# Sekumpulan / block code yang dapat diberikan nama
# dan dapat digunakan berulang
# Dapat memiliki input, output, atau keduanya
# Contoh function tidak menerima inputan apapun
# def call():
# print("Hello, neighbour")
# # Menerima satu input
# def greet(name):
# print(f'Hello, (name)')
# # Menerima dua input
# def plus(x, y):
# res = x + y
# # memiliki satu output
# # variabel yang ada di dalam function tidak dapat diakses di luar function
# # kode setelah return tidak akan diproses
# return res # output dari function plus()
# result = plus(2, 3)
# print(f'Nilai result: {result}')
# Default parameter
# def multiple(x, y = 3):
# res = x * y
# return res
# resMultiple = multiple(5,2)
# print(resMultiple)
# resMultiple = multiple(5) # manggil default parameter y = 3, 5*3 = 15
# print(resMultiple)
# Function dapat menerima function
# def oneFun():
# print('Hello, i\'am oneFun')
# def twoFun(fun):
# fun()
# twoFun(oneFun)
# def threeFun(fun, x, y):
# res = fun(x, y)
# res = res + 2
# print(f"Hasil akhir: {res}")
# def fourFun(a,b):
# result = a*b
# return result
# threeFun(fourFun, 2, 3)
# List
# Index dimulai dari 0
# days =['Sunday', 'Monday', 'Tuesday']
# fruits = ['Apple', 'Mango', 'Banana']
# print(days[1])
# print(fruits[2])
# def renderDays(data):
# for i in data:
# print(f'Today is {i}')
# renderDays(days)
#1
# buat sebuah function yang menerima list
# akan me-return hasil kali dua dari semua angka yang ada di dalam list
# function bersifat dinamis, bisa menerima isi yg lebih dr 4 input
# nilaiAwal = [1, 3, 5, 7]
# # hasilAkhir = [2, 6, 10, 14]
# def kaliDua(num):
# for i in num:
# result = num*2
# kaliDua(listNumber)
# print (hasilAkhir)
# my_list = [1, 3, 5, 7]
# def multiplyByTwo(data):
# my_new_list = []
# for i in data:
# res = i * 2
# my_new_list.append(res)
# return my_new_list
# finalResult = multiplyByTwo(my_list)
# print(my_list)
# print(finalResult)
# buah = ['Jeruk', 'Nanas', 'Apel', 'Mangga']
# buah[1] = 'Kelapa'
# print(buah)
# Sebuah function yang dapat memisahkan nilai genap dan ganjil
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 22, 34, 41, 52, 63, 71, 86]
# [0, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9]
# mixNumber = [11, 22, 34, 41, 52, 63, 71, 86]
# def oddEven(mixNumber):
# ev_list = []
# od_list = []
# finalList = []
# for i in mixNumber:
# if (i % 2 == 0):
# ev_list.append(i)
# else:
# od_list.append(i)
# finalList.append(ev_list)
# finalList.append(od_list)
# return finalList
# result = oddEven (mixNumber)
# print(result)
#######################################
# vowels = 'aiueo'
# searchWord = input('Put your word: ')
# def changeWord(word):
# if word[0] in 'aiueo':
# word = word + 'ay'
# else:
# word = word[1:] + word[0] + 'ay'
# print(word)
# changeWord('apple')
# changeWord('banana')
###############################
# def pig_latin(word):
# if word[0] in "aeiou":
# return word + 'yay'
# else:
# return word[1:] + word[0] + 'ay'
# sentence = input("Enter a word: ")
# print(' '.join(pig_latin(word) for word in sentence.split()))
################################
# Reversed Sentence
def sentRev(word):
word = word.split()
word.reverse()
word = ' '.join(word)
print(word)
sentRev("Hello my friend")
###### Has 99
# def has99(lis):
# idx = lis.index(9)
# if lis [idx + 1] == 9:
# return True
# else:
# return False
# print (has99([1, 9, 9]))
# print (has99([5, 9, 2, 9]))
# print (has99([9, 3, 9]))
# print (has99([7, 9, 9, 6]))
def has99(lis):
idx = lis.index(9)
return lis [idx + 1] == 9
print (has99([1, 9, 9]))
print (has99([5, 9, 2, 9]))
print (has99([9, 3, 9]))
print (has99([7, 9, 9, 6]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.