blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b5e3c7d35cda605a4b4004dee7be3da1979f0c7e | valdinei-mello/python | /definindo funções.py | 2,546 | 4.40625 | 4 | """
Definindo funções
- funções são pequenos trechos de codico que realizam tarefas especificas;
- pode ou não receber entradas de dados e retornar uma saida de dados;
- muito uteis para executar procedimentos similares por repetidas vezes;
OBS: se voce escrever uma função que realiza varias tarefas dentre dela
e bom fazer uma verificação para que a função seja simplificada;
ja utilizamos varias funções, desde que iniciamos o curso:
- print()
- len()
- max()
- min()
- count()
- e muita outras;
"""
# exemplo de utilização de funções
# cores = ['verde', 'azul', 'amarelo', 'branco']
# utilizando funções integrada (built-in) do python print()
# print(cores)
# curso = 'programação em python'
# print(curso)
# cores.append('roxo')
# print(cores)
# cores.clear()
# print(cores)
# DRY - don't repeat tourself - não repetiva você mesmo
# mas então, como definir funções ?
"""
em python a forma geral de definir uma função é:
def nome_da_função(parametro_de_entrada):
blodo de função
Onde:
- nome da função = sempre com letras minusculas e se for nome composto separado por underline (snake case);
- parametros de entrada = são opcionais onde tendo mais de um ,cada um separado por virgula, podendo ser opcionais ou não;
bloco da função = tambem chamdo de corpo da função ou implementação e onde o prcessamento da função acontece,
neste bloco pode ter ou não retorno da função;
OBG: veja que para definir uma função, utilizamos a palavra reservada 'DEF' informando ao python que estamos
definindo uma função. Também abrimos o bloco de codigo com o já conhecido dosi pontos ':' que é utilizado em python
para definir blocos
"""
# definindo função:
# exeplo 1:
def diz_oi():
print('oi')
"""
OBS:
1 - veja que dentro das nossas funções podemos utilizar outras funções;
2 - veja que nossa função so executa uma tarefa, ou seja, veja que ela apenas diz 'oi';
3 - veja que esta função não recebe nenhum parametro de entrada;
4 - veja que esta função não retorna nada;
"""
# utilizando funções
# OBS: atenção nuca esqueça o parênteses ao executar uma função;
diz_oi()
# exemplo 2:
def cantar_parabens():
print('parabens')
print('muitas felicidades')
print('saude')
for n in range(5):
cantar_parabens()
print('--------------')
# EM python podemos inclusive criar variaveis do tipo função e executar esta função através da variavél
canta = cantar_parabens
canta()
|
b29980d26d92e69517eb618b9c897ace10cde422 | micheaszmaciag/organizer | /przedmiot.py | 1,577 | 3.53125 | 4 | from abc import ABC, abstractmethod
class przedmiot(ABC):
def __init__(self, typ, priorytet):
self.typ = typ
self.priorytet = priorytet
@abstractmethod
def __str__(self):
pass
class notatka(przedmiot):
def __init__(self, priorytet, tytul, tresc, id):
super().__init__('notatka', priorytet)
self.tytul = tytul
self.tresc = tresc
self.id = id
def __str__(self):
info = self.typ + '\n' + 'Priorytet: ' + self.priorytet + '\n'
info += self.tytul + '\n'
info += self.tresc + '\n'
info += self.id + '\n'
return info
class wizytowka(przedmiot):
def __init__(self, priorytet, imie, nazwisko, telefon):
super().__init__('wizytowka', priorytet)
self.imie = imie
self.nazwisko = nazwisko
self.telefon = telefon
def __str__(self):
info = self.typ + 'Priorytet' + self.priorytet + '\n'
info += self.imie + ' ' + self.nazwisko + '\n'
info += self.telefon + '\n'
return info
class kuponRabatowy(przedmiot):
def __init__(self, imie, nazwisko, telefon, wartosc, priorytet):
super().__init__('kuponrabatowy', priorytet)
self.imie = imie
self.nazwisko = nazwisko
self.telefon = telefon
self.wartosc = wartosc
def __str__(self):
info = self.typ + '\n' + 'Priorytet:' + self.priorytet + '\n'
info += self.imie + ' ' + self.nazwisko + '\n'
info += self.telefon + '\n'
info += self.wartosc + '\n'
return info
|
30d3b01b6c3d4a44d4cb84412478d8e62eca6285 | beingp/Python-Beginner-To-Advance | /python basic/python list 1.py | 216 | 3.515625 | 4 | var = [1,2,3,4,5,"ashik"]
# print(var[-6])
# print(111 in var)
# var[0] = "Rafi"
# var[2] = 33
# print(var)
# del var
# print(var)
# del var[0]
# print(var[0])
l1 = [1,2,3,4]
l2 = [5,6,7,8]
l1 = l1+l2
print(l1) |
2bb869108f110856da18de58016b947acb5f3ac3 | zadraleks/Stepik.Python_3.First_steps | /Lesson 1-4/1-4-2.py | 174 | 4.03125 | 4 | #Напишите программу, которая считает квадрат введённого вещественного числа.
a = float(input())
print(a**2) |
9b4c1af08c692c76d842037238abcb60a2b8d63a | helectron/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,234 | 4.03125 | 4 | #!/usr/bin/python3
'''
module square
Class
Square
'''
from models.rectangle import Rectangle
class Square(Rectangle):
'''
Creates a Square object
Properties:
size (int): represent width and height
from Rectangle class
x (int): x coordenate
y (int): y coordenate
id (int): object identificator
'''
def __init__(self, size, x=0, y=0, id=None):
'''
Constructor
All parameters are set by the parent class Rectangle
Arguments
---------
size (int): represent width and height
x (int): x coordenate
y (int): y coordenate
id (int): object identificator
'''
super().__init__(size, size, x, y, id)
def __str__(self):
'''
overloading __str__ method that returns
'[Square] (<id>) <x>/<y> - <size>' -
in our case, width or height
'''
return '[Square] ({}) {}/{} - {}'\
.format(self.id, self.x, self.y, self.width)
# Properties
@property
def size(self):
''' Return size '''
return self.width
@size.setter
def size(self, size):
''' Set size '''
self.width = size
self.height = size
def update(self, *args, **kwargs):
'''
Update the object's attributes
Arguments
----------
args (int): packed list, the order of arguments
must be as follow:
- 1st argument should be the id attribute
- 2nd argument should be the size attribute
- 3rd argument should be the x attribute
- 4th argument should be the y attribute
'''
attributes = ['id', 'size', 'x', 'y']
if args and args[0]:
for i in range(len(args)):
setattr(self, attributes[i], args[i])
else:
for key in kwargs:
setattr(self, key, kwargs[key])
def to_dictionary(self):
'''
Returns the dictionary representation
of the object
'''
return {
'id': self.id,
'size': self.size,
'x': self.x,
'y': self.y
}
|
eaa7ba3bba44d4e5babbf559fae992fa419fbecf | D40124880/Python-Django-Flask | /Fundamentals/type_list.py | 838 | 4.03125 | 4 | # listing = [1, 5, 2, 7, 4]
# listing = ['magical','unicorns']
listing = ['magical unicorns',19,'hello',98.98,'world']
sum_all = 0
count_num = 0
count_str = 0
string = ''
for x in range(0, len(listing)):
if isinstance(listing[x], int) or isinstance(listing[x], float):
sum_all += listing[x]
elif isinstance(listing[x], str):
string += listing[x] + ' '
else:
continue
if sum_all != 0:
count_num = 1
if string != '':
count_str = 1
if count_num == 1 and count_str == 1:
print "The list you entered is of mixed type"
print "String: ", string
print "Sum: ", sum_all
elif count_num == 1:
print "The list you entered is of integer type"
print sum_all
elif count_str == 1:
print "The list you entered is of string type"
print "String: " + string
else:
print "Nope!" |
f31d51bc75bf36df3791d6a5861d11262720397e | ramvibhakar/hacker_rank | /Algorithms/Warmup/utopian_tree.py | 219 | 3.828125 | 4 | __author__ = 'ramvibhakar'
T = input()
while T > 0:
height = 1
N = input()
for i in range(0,N):
if i%2 == 0:
height *= 2
else:
height += 1
print height
T -= 1
|
12d74a39ec871d3e55c883a1dfaefc7d12cd2647 | ryderaka/pykivy | /pycrpt/imagecrypt/crypt_text.py | 664 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import hashlib
def encryption(password, input_text):
password = hashlib.sha256(password.encode('utf-8')).digest()
encryption_suite = AES.new(password, AES.MODE_CBC, 'This is an IV456')
while len(input_text) % 16 != 0:
input_text += ' '
cipher_text = encryption_suite.encrypt(input_text)
return cipher_text
def decryption(password, input_text):
password = hashlib.sha256(password.encode('utf-8')).digest()
encryption_suite = AES.new(password, AES.MODE_CBC, 'This is an IV456')
cipher_text = encryption_suite.encrypt(input_text)
return cipher_text.strip()
|
fa0890f25a4314b054341e36e367220e8640dc0b | lettier/bbautotune | /experiments/1/scripts/dist_to_standard.py | 8,158 | 3.53125 | 4 | '''
David Lettier (C) 2013.
http://www.lettier.com/
This script calculates the Lettier Distance, the Frechet Distance, and the Hausdorff Distance
between the standard ball's trajectory (P) and any tweaked parameter ball's trajectory (Q).
'''
import os;
import sys;
from os import listdir;
from os.path import isfile, join;
import math;
def Lettier_Distance( P, Q ):
'''
Imagine you have a rubber band connected to the two starting point positions
in both P and Q. At each step, you advance one end of the rubber band to the
next point in P and the other end of the rubber band to the next point in Q.
If the distance grows between points Pi and Qi, the rubber band stretches but
never shrinks. The resulting length of the rubber band is the max Euclidean
distance once you reach Pn and Qn.
If |P| < |Q| then keep advancing through the points in Q while keeping the one
end of the rubber band fixed at the last point in P.
If |P| > |Q| then keep advancing through the points in P while keeping the one
end of the rubber band fixed at the last point in Q.
'''
max_distance = 0.0;
i = 0;
for Pi in P:
Qi = None;
try:
Qi = Q[ i ];
except IndexError:
# |P| > |Q|
i = i - 1;
# Last point in Q.
Qi = Q[ i ];
delta_x = Qi[ 0 ] - Pi[ 0 ];
delta_y = Qi[ 1 ] - Pi[ 1 ];
delta_z = Qi[ 2 ] - Pi[ 2 ];
distance = math.sqrt( math.pow( delta_x, 2 ) + math.pow( delta_y, 2 ) + math.pow( delta_z, 2 ) );
if max_distance < distance:
max_distance = distance;
i = i + 1;
# i = |P| - 1
i = i - 1;
# Last point index in P.
j = i;
if i != len( Q ) - 1:
# |P| < |Q|
# Last point in P.
Pi = P[ j ];
for k in xrange( i + 1, len( Q ) ):
# Keep advancing through Q.
Qi = Q[ k ];
delta_x = Qi[ 0 ] - Pi[ 0 ];
delta_y = Qi[ 1 ] - Pi[ 1 ];
delta_z = Qi[ 2 ] - Pi[ 2 ];
distance = math.sqrt( math.pow( delta_x, 2 ) + math.pow( delta_y, 2 ) + math.pow( delta_z, 2 ) );
if max_distance < distance:
max_distance = distance;
return max_distance;
def Frechet_Distance( P, Q ):
distance_matrix_PxQ = [ ];
for Pi in P:
Pi_distances = [ ];
for Qi in Q:
delta_x = Qi[ 0 ] - Pi[ 0 ];
delta_y = Qi[ 1 ] - Pi[ 1 ];
delta_z = Qi[ 2 ] - Pi[ 2 ];
distance = math.sqrt( math.pow( delta_x, 2 ) + math.pow( delta_y, 2 ) + math.pow( delta_z, 2 ) );
Pi_distances.append( distance );
distance_matrix_PxQ.append( Pi_distances );
i = 0;
j = 0;
max_distance = 0.0;
while True:
if ( i == len( P ) - 1 ) and ( j == len( Q ) - 1 ):
break;
elif i == len( P ) - 1: # i is all the way down the matrix.
# You can only go to the right in the matrix.
right_distance = distance_matrix_PxQ[ i ][ j + 1 ];
if max_distance < right_distance:
max_distance = right_distance
j = j + 1;
elif j == len( Q ) - 1: # j is all the way to the right of the matrix.
# You can only go down the matrix.
down_distance = distance_matrix_PxQ[ i + 1 ][ j ];
if max_distance < down_distance:
max_distance = down_distance
i = i + 1;
else:
diagonal_distance = distance_matrix_PxQ[ i + 1 ][ j + 1 ]; # a
right_distance = distance_matrix_PxQ[ i ][ j + 1 ]; # b
down_distance = distance_matrix_PxQ[ i + 1 ][ j ]; # c
if diagonal_distance <= right_distance: # If a <= b
if diagonal_distance <= down_distance: # If a <= c
# Go diagonal.
if max_distance < diagonal_distance:
max_distance = diagonal_distance
i = i + 1;
j = j + 1;
else: # c < a
# Go down.
if max_distance < down_distance:
max_distance = down_distance
i = i + 1;
else: # b < a
if right_distance <= down_distance: # If b <= c
# Go right.
if max_distance < right_distance:
max_distance = right_distance
j = j + 1;
else: # c < b
# Go down.
if max_distance < down_distance:
max_distance = down_distance
i = i + 1;
return max_distance;
def Hausdorff_Distance( P, Q ):
def Directed_Hausdorff_Distance( P, Q ):
max_min_distance = 0.0;
for Pi in P:
min_distance = sys.float_info.max;
for Qi in Q:
delta_x = Qi[ 0 ] - Pi[ 0 ];
delta_y = Qi[ 1 ] - Pi[ 1 ];
delta_z = Qi[ 2 ] - Pi[ 2 ];
distance = math.sqrt( math.pow( delta_x, 2 ) + math.pow( delta_y, 2 ) + math.pow( delta_z, 2 ) );
if distance < min_distance:
min_distance = distance;
if min_distance > max_min_distance:
max_min_distance = min_distance;
return max_min_distance;
return max( Directed_Hausdorff_Distance( P, Q ), Directed_Hausdorff_Distance( Q, P ) );
# Ball path experiment data directory.
directory = "../data/";
# Get and sort file names.
experiment_files = [ f for f in listdir( directory ) if isfile( join( directory, f ) ) ];
if ( len( experiment_files ) == 0 ):
print( "\nNo files.\n" );
sys.exit( 0 );
# Get rid of the max distances file as one of the files to read in.
distances_file_index = 0;
for i in xrange( 0, len( experiment_files ) ):
if experiment_files[ i ].find( "distances_to_standard" ) != -1:
distances_file_index = i;
break;
del experiment_files[ distances_file_index ];
# Y_M_D_H_M_S.N-N#0,0#.csv
# 0 5
experiment_files = sorted( experiment_files, key = lambda x: int( "".join( x.split( "_" )[ 0 : 5 ] ) ) );
standard_file_index = 0;
for i in xrange( 0, len( experiment_files ) ):
if experiment_files[ i ].find( "Standard" ) != -1:
standard_file_index = i;
break;
print "File chosen as the standard: " + experiment_files[ standard_file_index ];
# Open standard file and read in the 3D points.
csv_file = None;
try:
csv_file = open( directory + experiment_files[ standard_file_index ], "r" );
except:
print( "File does not exist: " + directory + experiment_files[ standard_file_index ] );
sys.exit( 1 );
# Gather points.
standard_file_points = [ ];
titles = csv_file.readline( );
line = csv_file.readline( );
while ( line != "" ):
line = line.rstrip( '\n' );
line = line.rsplit( "," );
standard_file_points.append( ( float( line[ 1 ] ), float( line[ 2 ] ), float( line[ 3 ] ) ) );
line = csv_file.readline( );
del experiment_files[ standard_file_index ];
distances_to_standard_csv_file = open( directory + "distances_to_standard.csv", "w+" );
distances_to_standard_csv_file.write( ",'Lettier Distance','Frechet Distance','Hausdorff Distance'\n" );
i = 0;
while len( experiment_files ) != 0:
# Open file and read in the 3D points.
csv_file = None;
try:
csv_file = open( directory + experiment_files[ i ], "r" );
except:
print( "File does not exist: " + directory + experiment_files[ i ] );
sys.exit( 1 );
print "Calculating distances for: " + experiment_files[ i ];
# Gather points.
file_points = [ ];
titles = csv_file.readline( );
line = csv_file.readline( );
while ( line != "" ):
line = line.rstrip( '\n' );
line = line.rsplit( "," );
file_points.append( ( float( line[ 1 ] ), float( line[ 2 ] ), float( line[ 3 ] ) ) );
line = csv_file.readline( );
trajectory_name = experiment_files[ i ].split( "." )[ 1 ];
parameter_name = " ".join( trajectory_name.split( "#" )[ 0 ].split( "-" ) );
parameter_value = ".".join( trajectory_name.split( "#" )[ 1 ].split( "," ) );
trajectory_name = parameter_name + ": " + parameter_value;
distances_to_standard_csv_file.write( "'" + trajectory_name + "'," );
lettier_distance = Lettier_Distance( standard_file_points, file_points );
frechet_distance = Frechet_Distance( standard_file_points, file_points );
hausdorff_distance = Hausdorff_Distance( standard_file_points, file_points );
distances_to_standard_csv_file.write( str( lettier_distance ) + "," + str( frechet_distance ) + "," + str( hausdorff_distance ) + "\n" );
del experiment_files[ i ];
distances_to_standard_csv_file.close( );
|
b34a8e2afb2d70f1d2558540e55994bdb14a9189 | tA-bot-git/python-logisticReg | /cost_func.py | 1,573 | 4.0625 | 4 | from sigmoid import sigmoid
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn.model_selection import train_test_split
def cost_function(theta, X, y):
"""
Computes the cost of using theta as the parameter for logistic regression
Args:
theta: Parameters of shape [num_features]
X: Data matrix of shape [num_data, num_features]
y: Labels corresponding to X of size [num_data, 1]
Returns:
l: The cost for logistic regression
"""
l = None
#######################################################################
# TODO: #
# Compute and return the log-likelihood l of a particular choice of #
# theta. #
# #
#######################################################################
observations = len(y)
theta_transp = np.transpose(theta)
theta_x = np.dot(X, theta_transp)
predictions = sigmoid(theta_x)
class1_cost = -y * np.log(predictions)
class2_cost = (1 - y) * np.log(1 - predictions)
cost = class1_cost - class2_cost
l = np.sum(cost) / observations
pass
pass
#######################################################################
# END OF YOUR CODE #
#######################################################################
return l
|
cedfd8534d6a2ba214cccc59bd948b30fd5862a0 | blaoke/leetcode_answer | /周赛/5213.py | 398 | 3.5625 | 4 | # !/usr/bin/env/ python
# -*- coding:utf-8 -*-
class Solution:
def minCostToMoveChips(self, chips: [int]) -> int:
chips=sorted(chips)
b = [0] * 3
for i in range(len(chips)):
if chips[i]%2==0:
b[2] += 1
else:
b[1]+=1
print(min(b[1],b[2]))
a=Solution()
a.minCostToMoveChips(chips=[3,3,1,2,2])
|
dbe8d8e8701291da575972eb199a5e541ca8ce84 | sabarna/codefights | /2sigma/Round1.py | 2,324 | 3.75 | 4 | #Two Sigma engineers process large amounts of data every day, much more than any single
# server could possibly handle. Their solution is to use collections of servers, or server farms, to handle the massive
# computational load. Maintaining the server farms can get quite expensive, and because each server farm is simultaneously
# used by a number of different engineers, making sure that the servers handle their backlogs efficiently is critical.
#Your goal is to optimally distribute a list of jobs between servers within the same farm. Since this problem cannot be
#solved in polynomial time, you want to implement an approximate solution using the Longest Processing Time (LPT) algorithm.
# This approach sorts the jobs by their associated processing times in descending order and then assigns them to the server
# that's going to become available next. If two operations have the same processing time the one with the smaller index is
# listed first. If there are several with the same availability time, then the algorithm assigns the job to the server
# with the smallest index.
#Given a list of job processing times, determine how the LPT algorithm will distribute the jobs between the servers within
# the farm.
#Example
#For jobs = [15, 30, 15, 5, 10] and servers = 3, the output should be
#serverFarm(jobs, servers) = [[1],
# [0, 4],
# [2, 3]]
#job with index 1 goes to the server with index 0;
#job with index 0 goes to server 1;
#job with index 2 goes to server 2;
#server 1 is going to be available next, since it got the job with the shortest processing time (15).
# Thus job 4 goes to server 1;
#finally, job 3 goes to server 2.
jobs = []
servers = 8
def serverFarm(jobs, servers):
serverList = [0] * servers
tempJobList = jobs
op_map = {}
op_list =[]
for i in range(servers):
op_map[i] = []
if tempJobList != []:
while max(tempJobList) != 0:
JobInd = tempJobList.index(max(tempJobList))
ServInd = serverList.index(min(serverList))
serverList[ServInd] += tempJobList[JobInd]
tempJobList[JobInd] = 0
op_map[ServInd].append(JobInd)
for k,v in op_map.items():
op_list.append(v)
return op_list
print(serverFarm(jobs, servers)) |
44ed72747887af5a03c35c16e3119fd5745b4ef3 | AlfredoSG97/Prueba4_ProgramacionAlgoritmos_DuocUC | /Funciones_Pasajes.py | 6,865 | 3.546875 | 4 | import sys
from itertools import cycle
DatosCliente=[[],[],[]]
rutClientes=[]
validarut=0
validanombre=0
#Tarifas
tarifanormal=78900
validatelefono=0
tarifavip=240000
contadorN=0
contadorV=0
pagonormal=0
pagovip=0
totales=[]
#Pagos
descuento=0
def menu_asientos ():
print ("------MENU------")
print ("1.- ver asientos disponibles ")
print ("2.- comprar asientos")
print ("3.- anular vuelo ")
print ("4.- modificar datos del pasajero ")
print ("5.- salir")
def salir():
print("Gracias por comprar con nosotros.")
def validar_rut(validarut):
while validarut<=0:
rut=int(input("Ingresa tu rut para el registro. : "))
if rut==():
print("debes ingresar los datos solicitados.")
if rut <=999999999 and rut >=1000000:
registra_rut(rut)
validarut=validarut+1
else:
print("Rut incorrecto, verifica los datos ingresados.")
def modificar_datos(rut,validatelefono,validanombre):
try:
rut=int(input("Ingresa tu rut para buscar en el registro. : "))
rutClientes.index(rut)
print("Rut Encontrado")
modificar=int(input("1.- Modificar telefono , 2.- Modificar Nombre: "))
if modificar==1:
DatosCliente[2].pop()
print("Telefono eliminado con exito. ")
while validatelefono<=0:
telefono=int(input("Ingresa tu nuevo telefono para el registro :+569 "))
if telefono==():
print("Ingresa un telefono valido")
if telefono <=99999999 and telefono >=11111111:
registra_telefono(telefono)
validatelefono=validatelefono+1
input("Ingresa enter para continuar")
else:
print("Ingresa un numero valido")
if modificar==2:
DatosCliente[1].pop()
print("Nombre eliminado de la lista")
while validanombre<=0:
Nombre=input("Ingresa el nuevo nombre: ")
if Nombre==():
print("Ingresa un nombre valido.")
else:
registra_Nombre(Nombre)
validanombre=validanombre+1
print(DatosCliente)
except ValueError:
print("Rut no registrado")
def validar_nombre(validanombre):
while validanombre<=0:
Nombre=input("Ingresa tu nombre: ")
if Nombre==():
print("Ingresa un nombre valido.")
else:
registra_Nombre(Nombre)
validanombre=validanombre+1
def validar_telefono(validatelefono):
while validatelefono<=0:
telefono=int(input("Ingresa tu telefono para el registro :+569 "))
if telefono==():
print("Ingresa un telefono valido")
if telefono <=99999999 and telefono >=11111111:
registra_telefono(telefono)
validatelefono=validatelefono+1
input("Ingresa enter para continuar")
else:
print("Ingresa un numero valido")
def liberar_asientos(asiento,fila1,fila2,fila3,fila4,fila5,fila6,fila7,fila,Nombre,telefono,rut):
if fila == 1:
if asiento <1 or asiento >6:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila1[asiento] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila ==2:
if asiento <7 or asiento >12:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila2[asiento-6] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila == 3:
if asiento <13 or asiento > 18:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila3[asiento-12] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila == 4:
if asiento <19 or asiento > 24:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila4[asiento-18] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila ==5:
if asiento <25 or asiento >30:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila5[asiento-24] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila ==6:
if asiento <31 or asiento >36:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila6[asiento-30] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
if fila == 7:
if asiento <37 or asiento >42:
print("usted a ingresado un numero de asiento que no corresponde a la fila ")
else:
fila7[asiento-36] = asiento
DatosCliente[0].pop()
DatosCliente[1].pop()
DatosCliente[2].pop()
def remplazar_asientos (asiento,fila1,fila2,fila3,fila4,fila5,fila6,fila7,fila,contador,contadorVip):
if fila==1:
fila1[asiento] = "X"
contador=contador+1
if fila==2:
fila2[asiento-6] = "X"
contador=contador+1
if fila==3:
fila3[asiento-12] = "X"
contador=contador+1
if fila==4:
fila4[asiento-18] = "X"
contador=contador+1
if fila==5:
fila5[asiento-24] = "X"
contador=contador+1
if fila==6:
fila6[asiento-30] = "X"
contadorVip=contadorVip+1
if fila==7:
fila7[asiento-36] = "X"
contadorVip=contadorVip+1
def mostrar_disponibles(fila1,fila2,fila3,fila4,fila5,fila6,fila7,Division):
print("Los Asientos disponibles son: ")
print(fila1)
print(fila2)
print(fila3)
print(fila4)
print(fila5)
print(Division)
print(fila6)
print(fila7)
return mostrar_disponibles
def registra_rut(rut):
DatosCliente[0].append(rut)
rutClientes.append(rut)
print("Rut Ingresado Correctamente. ")
return registra_rut
def registra_Nombre(Nombre):
DatosCliente[1].append(Nombre)
print("Nombre Ingresado Correctamente. ")
return registra_Nombre
def registra_telefono(telefono):
DatosCliente[2].append(telefono)
print("Telefono Ingresado Correctamente. ")
return registra_telefono
|
2453912649ddbc3c55209b8cbb5db17a3a81c1f7 | maoyalu/leetcode | /Python/200-299/242_Valid_Anagram.py | 1,003 | 3.65625 | 4 | import unittest
from collections import Counter
def solution(s, t):
# ********** Attempt 1 - 2019/09/24 **********
count_s = Counter(s)
count_t = Counter(t)
return count_s == count_t
# ********** Attempt 1 - 2019/09/24 **********
# word_dict = {}
# for c in s:
# if c not in word_dict:
# word_dict[c] = 1
# else:
# word_dict[c] += 1
# for c in t:
# if c not in word_dict:
# return False
# else:
# word_dict[c] -= 1
# if word_dict[c] < 0:
# return False
# for key in word_dict:
# if word_dict[key] != 0:
# return False
# return True
class TestSolution(unittest.TestCase):
def test1(self):
s = 'anagram'
t = 'nagaram'
self.assertTrue(solution(s, t))
def test2(self):
s = 'rat'
t = 'car'
self.assertFalse(solution(s, t))
if __name__ == "__main__":
unittest.main() |
b3fac82ade6509bca1b457eb41ae3638caf4ddfb | qiurenping/tiger | /python/study100/4.py | 384 | 4.0625 | 4 | # -*- coding:UTF-8 -*-
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
days = [0,31,59,90,120,151,181,212,243,274,304,334]
all_days = 0
if 0 < month <=12:
all_days = days[month-1]
all_days += day
else:
all_days = day
if ((year % 4 == 0 and year % 100 ==0) or (year % 400 == 0))and month >=3:
all_days += 1
print(all_days)
|
07eeb92c77fcc63530182b9850828f531b59daa4 | jasonfilippou/Python-ML | /Python-ML/PP01/pa01/code/wdknn.py | 3,344 | 3.96875 | 4 | '''
Created on Sep 23, 2012
@author: Jason
'''
from knn import KNN
import numpy as np
''
class WDKNN(KNN):
'''
WDKNN, which stands for "Weighted Distance K-Nearest Neighbors", is a subclass of KNN, which
simply stands for "K-Nearest Neighbors".
The only method of the superclass that we will override is the "classify" method, so that
the n-th neighbor (where n = 1, ... , K) gets a vote that is an exponential function of
its distance from the test point
'''
def classify(self, testdat, k=None):
"""
Description: Classify a set of samples.
Arguments:
testdat: pandas.DataFrame
k: None, integer, or integer list of ascending k values
Returns:
matrix of (+1/-1) labels (if k is a list)
list of labels, if k is integer
"""
testdat = testdat.values
ntest_samples = testdat.shape[0]
if k is None:
k = self.k
# check if k is an integer, if so wrap into list
try:
len(k)
except TypeError:
k = [k]
# compute cross-products of training and testing samples
# This is done in order to exploit vectorized implementations
# when computing the distances.
xy = self.traindat.dot(testdat.T)
# compute norms. Also useful for computing the distance
xx = np.sum(self.traindat * self.traindat, 1)
yy = np.sum(testdat * testdat, 1)
# now iterate over testing samples
out = np.empty((ntest_samples, len(k)))
for i in range(ntest_samples): # for every testing example
# Compute distance to all training samples
# note: this is where we use a vectorized implementation
# instead of for looping
dists = np.sqrt(xx - 2*xy[:,i] + yy[i])
# Find the indexes that sort the distances.
# You need to do this to find the K nearest
# neighbors, i.e the K neighbors with the
# smallest distance to the test point.
sorted_indexes = np.argsort(dists)
# Now iterate over the first k values to compute labels
thesum = 0
start = 0
for j in range(len(k)): # index the list of values of K
cur_k = k[j] # the current value of K is cur_k
# Add votes up to the current k value. Lines 7 to 10
# of Algorithm 3 in CIML chapter 2.
for l in range(start, cur_k): # for every neighbor from 1 to K
thesum = thesum + self.trainlabs[sorted_indexes[l]] # calculate the contribution of every neighbor
# Tally the votes.
out[i,j] = np.sign(thesum)
start = cur_k
# end of examples loop
# Massage the output if only one k was used
if len(k) == 1:
out = out.reshape(ntest_samples)
return out
|
8c5e1d769125c0c1787dd04b69d59e99aef03d8e | wellszhao/intro_ds_wy_course | /ch02_python/code/basic_function.py | 649 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 18:05:12 2018
@author: tgbaggio
"""
# 定义函数f
def f(a, b):
return a + b
f(1, 2)
# lambda表达式定义与f一摸一样的函数
g = lambda a, b: a + b
g(1, 2)
l = [1, 2, 3]
def h(a):
return a + 1
# 使用map和函数h对l里面的每一个元素加1
list(map(h, l))
# map加上lambda表达式可以达到同样的效果
list(map(lambda a: a + 1, l))
# 使用filter对数据进行过滤
list(filter(lambda a: a >= 2, l))
# 使用reduce对数据进行加和
from functools import reduce
reduce(lambda accvalue, newvalue: accvalue + newvalue, l, 10)
|
534bc5edd8ba7d03b2feebeb5226e3b14f71fb20 | lincappu/pycharmlearningproject | /日常练习/2022/2022-00/变量.py | 3,666 | 4 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# !!!全局变量:
a = 3
def Fuc():
print (a)
a = a + 1
Fuc()
这个就会出现未定义而使用的情况,因为Fuc里面的a会变成局部变量,如果要引用的是全局的那个a
a = 3
def Fuc():
global a
print (a)
a = a + 1
Fuc()
要首先申明称全局变量,才可以。但是main函数除外
a = 3
def Fuc():
global a
print (a) # 1
a = a + 1
if __name__ == "__main__":
print (a) # 2
a = a + 1
Fuc()
print (a) # 3
main 函数中不加global依然调用的全局变量。
类变量作为全局变量使用,定义一个类变量,然后用类名.来引用。
同样要注意事项变量绑定语句还是变量操作语句:
num = 100
def func():
x = num + 100 这是一个变量操作语句,它会按照顺序进行查找num,最后会找到全局变量中的num,所以这个num是全局变量,不会报错。
print(x)
func()
# !!!类变量和实例变量:
# 实例变量是对于每个实例都独有的数据,而类变量是该类所有实例共享的属性和方法
# 实例一旦修改类变量,这个类变量就会自动进入实例的命令空间,会创建相同名称的变量,
# 如果是类自己修改了类变量,那么还在引用类变量的实例会对应变化。
# 在函数中如果啊要引用类变量要加 类名.属性 来引用,不过一般用的比较少。
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name
d1 = Dog('1')
d2 = Dog('2')
d3 = Dog('3')
print(d1.kind)
print(d2.kind)
print(d3.kind)
print(d1.name)
print(d2.name)
print(d3.name)
d1.kind = '1'
print(d1.kind)
print(d2.kind)
print(Dog.kind)
Dog.kind = 'heklo'
print(d1.kind)
print(d2.kind)
# 是否会在实例上创建新的变量,关键是看是否是属性绑定语句还是属性操作语句,
# 这个就是属性绑定语句:
class Dog:
kind = 'canine' # 类变量也就是静态变量,定义在类中,并且没有在任何方法下面,不带self
country = 'China'
def __init__(self, name, age, country): # 在init中定义的带sel发的变量都是实例变量也就是成员变量。
self.name = name
self.age = age
self.country = country
dog = Dog('Lily', 3, 'Britain')
print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 canine Britain
print(dog.__dict__) # {'name': 'Lily', 'age': 3, 'country': 'Britain'}
dog.kind = 'feline'
print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 feline Britain
print(dog.__dict__)
print(Dog.kind) # canine 没有改变类属性的指向
# {'name': 'Lily', 'age': 3, 'country': 'Britain', 'kind': 'feline'}
# 下面救赎属性操作语句:
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick) # 这个就是属性操作语句,操作的类属性,既所有实例都可以对这个类变量
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
print(d.tricks) # ['roll over', 'play dead']
# 方法属性:
class MethodTest:
def inner_test(self):
print('in class')
def outer_test():
print('out of class')
mt = MethodTest()
mt.outer_test = outer_test
print(type(MethodTest.inner_test)) # <class 'function'>
print(type(mt.inner_test)) # <class 'method'>
print(type(mt.outer_test)) # <class 'function'>
# 实例只有在引用方法属性的时候才会将自身作为第一个参数传递,调用实例的普通函数则不会, |
c4ba156edf9ec98ec9769159a31c8ba3421b6854 | jastiso/statLearningTasks | /mTurk_graph_learn_blocks/mTurk-10-node-breaks/experiment/utilities/visualize.py | 805 | 3.796875 | 4 | import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
def animate_walk(G, walk):
"""
Takes a graph and walk and creates an animation that can
be saved to a movie
e.g.
anim.save(filename.mp4, writer='ffmpeg', fps=15, dpi=dpi)
"""
fig = plt.figure(figsize=(8, 8))
pos = nx.spring_layout(G)
nc = np.ones(15)
nodes = nx.draw_networkx_nodes(G, pos, node_color=nc)
edges = nx.draw_networkx_edges(G, pos)
def update(n):
nc = np.ones(15)
# nc = np.random.random(15)
nc[walk[n]] = 0
nodes.set_array(nc)
return nodes,
anim = FuncAnimation(fig, update, frames=len(walk),
interval=500, blit=True)
plt.close()
return anim
|
a14619b0caace6ad496edae4bb997c776c631391 | alexchou094/Python200805 | /Day3-6.py | 1,400 | 3.78125 | 4 | print("歡迎進入系統")
d = {}
while True:
print("1. 新增詞彙")
print("2. 列出所有單字")
print("3. 英翻中")
print("4. 中翻英")
print("5. 測驗學習成果")
print("6. 離開")
x = input("選擇功能 : ")
if x == '1':
while True:
addv = input("請輸入要新增的單字(按0跳出) : ")
if addv == '0':
break
else:
addc = input("請輸入該單字的解釋 : ")
d[ addv ] = addc
if x == '2':
for i in d:
print(i,"是",d[i])
if x == '3':
while True:
inqv = input("請輸入要查詢的單字(按0退出) : ")
if inqv == '0':
break
elif inqv in d:
inqc = d[inqv]
print(inqv,"的解釋是",inqc)
else :
print("查無此字")
if x == '4':
while True:
y = input("請輸入要查詢的中文(按0退出) : ")
for voc,chi in d.items():
if y == '0':
break
elif y == chi:
print("這個字是",voc)
else:
print("查無此字")
if x == '6':
break
|
11a1b7877877624c654c9ae2f86383f92580ef50 | Tulasi59/python | /Python_prac/programs/examples.py | 7,004 | 4.25 | 4 | """factorial of a number
For example factorial of 6 is 6*5*4*3*2*1 which is 720.
"""
from functools import reduce
# with recursion
def factorial(n):
if n==1 or n==0:
return 1
else:
return n*factorial(n-1)
# print(factorial(6))#720
#without recursion
def factorial_without_recursion(n):
res =1
for i in range(1,n+1):
res*=i
return res
# print(factorial_without_recursion(6))
""" check Armstrong Number
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
"""
def armstrong(n):
num =len(str(n))
l= sum([int(i)**num for i in str(n)])
if n==l:
return "{0} is armstrong".format(n)
else:
return "{0} is not armstrong".format(n)
# print(armstrong(153))
""" print all Prime numbers in an Interval """
def all_prime_num(start,end):
for n in range(start,end):
if n>1:
for i in range(2,n):
if n%i ==0:
break
else:
print("{0} is prime".format(n))
# l = [n else break if n%i==0for i in range(2,n) for n in range(start,end) if n>1]
# all_prime_num(11,25)
""" check whether a number is Prime or not """
def check_prime_num(n):
if n>1:
for i in range(2,n):
if n%i==0:
break
else:
print("{0} is prime".format(n))
# check_prime_num(11)
""" n-th Fibonacci number """
#with recursion
def n_th_fibonacci_number_with_recursion(n):
if n<=0:
return "incorrect input"
elif n==1:
return 0
elif n==2:
return 1
else:
return n_th_fibonacci_number_with_recursion(n-1)+n_th_fibonacci_number_with_recursion(n-2)
# print(n_th_fibonacci_number_with_recursion(9)) #21
def n_th_fibonacci_number_without_recursion(n):
n1,n2 =0,1
for i in range(n-1):
n1,n2=n2,n1+n2
return n1
# print(n_th_fibonacci_number_without_recursion(-6))
"""Fibonacci numbers
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……...
"""
def fibonacci_series(n):
n1,n2 =0,1
for i in range(n):
print(n1)
n1,n2=n2,n1+n2
# print(fibonacci_series(9))
def check_fibonacci_num(n):
n1,n2=0,1
for i in range(n):
if n1==n:
print("yes")
# break
n1,n2=n2,n1+n2
# print(check_fibonacci_num(5))
"""print ASCII Value of a character"""
# print(ord("g"))
"""
smallest value and largest value in list
"""
lst=[-4,-3,-55,-2,-33]
min =lst[0]
max =lst[0]
for n in lst:
if n > max:
max =n
if n < min:
min=n
# print(max) #-2
# print(min)#2
""" find second largest number in a list"""
def second_largest(lst):
first= lst[0]
second= 0
for i in lst:
if i>first:
first,second =i,first
elif first > i > second:
second= i
return second
# print(second_largest([7,-4,1,-4,-5,2,-6]))#2
# minimum = float('-inf')
# first, second = minimum, minimum
# for n in numbers:
# if n > first:
# first, second = n, first
# elif first > n > second:
# second = n
# return second if second != minimum else None
"""find N largest elements from a list"""
def N_max_elements(lst,n):
final=[]
for i in range(n):
max =0
for ele in lst:
if ele > max:
max=ele
lst.remove(max)
final.append(max)
return final
# print(N_max_elements([1,3,2,4,5,1,60,],3)) #[60,5,4]
""" duplicates from a list of integers?"""
def duplicates(lst):
unique=[]
duplicate =[]
for i in lst:
if i in unique:
if i not in duplicate:
duplicate.append(i)
else:
unique.append(i)
return duplicate
# print(duplicates([1,1,3,3,4,1,2,2,4,5,7]))#[1,2,3,4]
"""find Cumulative sum of a list
Input : list = [10, 20, 30, 40, 50]
Output : [10, 30, 60, 100, 150]
"""
def cumulative(lst):
l =[sum(lst[:i+1]) for i in range(len(lst))]
return l
# print(cumulative([10,20,30,40,50]))
"""Break a list into chunks of size N in Python"""
def break_list(lst,n):
return [lst[i:i+n] for i in range(0,len(lst),n)]
# print(break_list([1,2,3,4,5,6,7,8,9,10],2))#[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
""" Sort the values of first list using second list
Input : list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Output :['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
"""
"""check if a string is palindrome or not"""
def str_palindrome(s):
r =s[::-1]
if r==s:
print("palindrome")
else:
print("not palindrome")
# print(str_palindrome("hah"))
"""Reverse words in a given String in Python
Input : str = "geeks quiz practice code"
Output : str = "code practice quiz geeks"
"""
def reverse_word(s):
lst = s.split(" ")
print(" ".join(lst[::-1]))#code practice quiz geeks
res_s = " ".join([i[::-1] for i in lst])
print(res_s) #skeeg ziuq ecitcarp edoc
# reverse_word("geeks quiz practice code")
"""check if a string contains any special character"""
# print(any([not c.isalnum() for c in " Geeks$For$Geeks"]))#True
"""removing i-th character from a string"""
st ="testing"
n=4
f_st =""
for i in range(len(st)):
if i==n:
continue
f_st+=st[i]
# print(f_st)#testng
"""Execute a String of Code in Python
Given few lines of code inside a string variable and execute the code inside the string."""
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
# exec_code()#120
"""
Linear Search------------
Linear search is one of the simplest searching algorithms, and the easiest to understand. We can think of it as a ramped-up version of our own implementation of Python's in operator.
The algorithm consists of iterating over an array and returning the index of the first occurrence of an item once it is found:"""
def leaner_search(lst,st):
for i in range(len(lst)):
if lst[i]==st:
return i
return -1
result = leaner_search([1,2,'a','b'],'a')
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result);
"""
Bubble Sort --------------------
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order."""
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n =len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
return (arr)
arr = [64, 34, 25,12, 12, 22, 11, 90]
print(bubbleSort(arr))#[11, 12, 12, 22, 25, 34, 64, 90]
|
171833217a85a6eac7b4103d8e390371c7617f16 | Krugger1982/Algoritmes_SD | /Less_2_10.py | 5,762 | 3.5625 | 4 | class Vertex:
def __init__(self, val):
self.Value = val
self.Hit = False
class Stack:
def __init__(self):
self.stack = []
def size(self):
return len(self.stack)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
return None
def push(self, value):
self.stack.append(value)
class SimpleGraph:
def __init__(self, size):
self.max_vertex = size
self.m_adjacency = [[0] * size for _ in range(size)]
self.vertex = [None] * size
def AddVertex(self, v):
# ваш код добавления новой вершины
# с значением value
# в свободное место массива vertex
Vert = Vertex(v) # создаем вершину Vert
index = self.vertex.index(None) # находим ближайшее свободное место в списке Vertex
if index != -1:
self.vertex[index] = Vert # и вставляем на это место вершину Vert
def RemoveVertex(self, v):
for i in self.m_adjacency: # пробегаем по 1 измерению - строки матрицы
i[v] = 0 # и обнуляем v-тый столбец
self.m_adjacency[v] = [0] * self.max_vertex # а потом обнуляем v-тую строку
self.vertex[v] = None # и удаляем вершину из списка
def IsEdge(self, v1, v2):
# True если есть ребро между вершинами v1 и v2
return self.m_adjacency[v1][v2] == 1 and self.m_adjacency[v2][v1]
def AddEdge(self, v1, v2):
# добавление ребра между вершинами v1 и v2
# в матрице смежности напротив этих индексов проставляем 1
self.m_adjacency[v1][v2] = 1
if v1 != v2:
self.m_adjacency[v2][v1] = 1
def RemoveEdge(self, v1, v2):
# удаление ребра между вершинами v1 и v2
# в матрице смежности напротив этих индексов проставляем 0
self.m_adjacency[v1][v2] = 0
self.m_adjacency[v2][v1] = 0
def DepthFirstSearch(self, VFrom, VTo):
# узлы задаются позициями в списке vertex
# возвращается список узлов -- путь из VFrom в VTo
# или [] если пути нету
result = Stack()
for Vertexes in self.vertex:
if Vertexes is not None:
Vertexes.Hit = False # помечаем все существующие вершины графа как непосещенные
self.vertex[VFrom].Hit = True # посещаем исходную вершину
result.push(self.vertex[VFrom]) # заносим ее в "Путь"
if self.m_adjacency[VFrom][VTo] == 1: # если искомая вершина - смежная с текущей
result.push(self.vertex[VTo]) # то просто добавляем ее в "путь"
return result.stack
for Nearby in range(len(self.m_adjacency[VFrom])): # пробегаем по строчке в матрице смежности, которая соответствует VFrom
if (self.m_adjacency[VFrom][Nearby] == 1 and not self.vertex[Nearby].Hit # рассматриваем только непосещенные смежные узлы
and result.size() - self.Search_Way_recourcive(Nearby, VTo, result).size() != 0):
# Если в результате поиска в очередном узле размер пути изменился, то путь найден
return result.stack
return [] # если путь не найден, возвращаем пустой список
def Search_Way_recourcive(self, VFrom, VTo, Way):
'''рекурсивный метод для поиска куска пути без предварительных очисток'''
self.vertex[VFrom].Hit = True # посещаем исходную вершину
Way.push(self.vertex[VFrom]) # заносим ее в "Путь"
if self.m_adjacency[VFrom][VTo] == 1: # если искомая вершина - смежная с текущей
Way.push(self.vertex[VTo]) # то просто добавляем ее в "путь"
return Way
for Nearby in range(len(self.m_adjacency[VFrom])): # пробегаем по строчке в матрице смежности, которая соответствует VFrom
if (self.m_adjacency[VFrom][Nearby] == 1 and not self.vertex[Nearby].Hit
and Way.size() - self.Search_Way_recourcive(Nearby, VTo, Way).size() != 0):
# Если в результате поиска в очередном непосещенном узле размер пути изменился, то путь найден
return Way
Way.pop() # В противном случае - делаем вывод: из этого узла пути нет
# Удаляем этот узел из стека
return Way
|
a8e294a911745e8ae91f84e29b189632e8d78fa6 | lakshyarawal/pythonPractice | /Bitwise Operators/basic_operators.py | 1,278 | 4.46875 | 4 | """ Bitwise Operators """
""" AND Operator: 1 when both bits are 1 """
def and_operator(a, b) -> int:
return a & b
""" OR Operator: 1 when any one of the bits is 1 """
def or_operator(a, b) -> int:
return a | b
""" XOR Operator" 1 when both bits are different """
def xor_operator(a, b) -> int:
return a ^ b
""" Left Shift Operator: If we assume that the leading y bits are 0, then result of x << y is equal to x * 2^y """
def left_shift_operator(a, b) -> int:
return a << b
""" Right Shift Operator: Totally opposite of Left Shift. x >> y is equal to floor of x / 2^y """
def right_shift_operator(a, b) -> int:
return a >> b
""" Not Operator: Reverts all set bits 1 -> 0 and 0 -> 1 """
def not_operator(a) -> int:
return ~a
def main():
val1 = int(input("Enter your value: "))
val2 = int(input("Enter another value: "))
ans = and_operator(val1, val2)
ans2 = or_operator(val1, val2)
ans3 = xor_operator(val1, val2)
ans4 = left_shift_operator(val1, val2)
ans5 = right_shift_operator(val1, val2)
ans6 = not_operator(val1)
print(ans)
print(ans2)
print(ans3)
print(ans4)
print(ans5)
print(ans6)
# Using the special variable
# __name__
if __name__ == "__main__":
main() |
75d5209d0b72233136af8b88c12b4e989f6aee0a | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P12xx/P1268_SearchSuggestionsSystem.py | 3,959 | 3.953125 | 4 | """
tag: trie, recursion
Given an array of strings products and a string searchWord. We want to design
a system that suggests at most three product names from products after each
character of searchWord is typed. Suggested products should have common prefix
with the searchWord. If there are more than three products with a common prefix
return the three lexicographically minimums products.
Return list of lists of the suggested products after each character of searchWord is typed.
Example 1: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
Example 2: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Example 3: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
Example 4: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]
Constraints:
- 1 <= products.length <= 1000
- There are no repeated elements in products.
- 1 <= Σ products[i].length <= 2 * 10^4
- All characters of products[i] are lower-case English letters.
- 1 <= searchWord.length <= 1000
- All characters of searchWord are lower-case English letters.
"""
from collections import OrderedDict
from typing import List
class Solution:
def suggestedProducts(
self, products: List[str], searchWord: str
) -> List[List[str]]:
SD = dict() # search dictionary
def create_search_dict():
products.sort()
for prod in products:
curr_lvl_dict = SD
for c in prod:
curr_lvl_dict[c] = curr_lvl_dict.get(c, dict())
curr_lvl_dict = curr_lvl_dict[c]
curr_lvl_dict[1] = 1
def get_search_str_level_dict(curr_str):
if curr_str[0] not in SD:
return {}
curr_dict = SD
for c in curr_str:
if c not in curr_dict:
return curr_dict
curr_dict = curr_dict[c]
return curr_dict
def get_word_suggestions(word, word_sugg_dict, sugg_list, n):
if len(sugg_list) == n:
return
if 1 in word_sugg_dict:
sugg_list.append(word)
if len(word_sugg_dict.keys()) == 1:
return
for key, new_dict in word_sugg_dict.items():
if key == 1:
continue
get_word_suggestions(word + key, new_dict, sugg_list, n)
create_search_dict()
curr_search_str = ""
result_lol = []
for c in searchWord:
curr_search_str += c
curr_search_str_dict = get_search_str_level_dict(curr_search_str)
curr_word_sugg_list = []
get_word_suggestions(
curr_search_str, curr_search_str_dict, curr_word_sugg_list, 3
)
result_lol.append(curr_word_sugg_list)
return result_lol
print(
Solution().suggestedProducts(
["mobile", "mouse", "moneypot", "monitor", "mousepad"], "mouse",
)
)
print(Solution().suggestedProducts(["havana"], "havana"))
print(
Solution().suggestedProducts(["bags", "baggage", "banner", "box", "cloths"], "bags")
)
print(Solution().suggestedProducts(["havana"], "tatiana"))
|
afc02dbc54281ccbb197b72f334eee6f9f78165c | GLAU-TND/python-lab-chiragsr | /q2.py | 292 | 3.921875 | 4 | while True:
try:
x = int(input("Hey, enter a no."))
break
except (AttributeError):
print("Its, not a valid attribute.")
except (TypeError):
print("Its, not a valid type.")
except (ValueError):
print("Its, not a valid value.")
|
472f0cb42c1fce6033b169989cabb6a45ac353c5 | Mark1002/ds_algo_pratice | /leetcode/106.py | 1,439 | 3.875 | 4 | """106. Construct Binary Tree from Inorder and Postorder Traversal
url: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
"""
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if len(postorder) == 0 or len(postorder) == 0:
return
# get last element as root
root_val = postorder[-1]
root = TreeNode(val=root_val)
# find root index in inorder
root_index = inorder.index(root_val)
# get left and right sub inorder
in_lefts, in_rights = inorder[:root_index], inorder[root_index+1:]
# get left and right sub postorder
post_lefts, post_rights = postorder[:len(in_lefts)], postorder[len(in_lefts):-1]
root.left = self.buildTree(in_lefts, post_lefts)
root.right = self.buildTree(in_rights, post_rights)
return root
def preorder_traveral(root):
if root is None:
return
print(root.val)
preorder_traveral(root.left)
preorder_traveral(root.right)
def main():
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
s = Solution()
root = s.buildTree(inorder, postorder)
preorder_traveral(root)
if __name__ == "__main__":
main()
|
972de7c7132745f38bd8f9fbafc38be24923fbc0 | Christian12c/Pathfinding-Algorithm-Visualisation-Tool | /recursiveDivisionVisualised.py | 5,623 | 3.71875 | 4 | #Importing modules, procedures and constants that are referenced in this file
from random import choices
from random import randint
from random import randrange
from math import floor
import pygame
import sys
from pygame_Setup import SCREEN, BLACK, WHITE, PURPLE, BLOCK_SIZE, GRID_HEIGHT, GRID_WIDTH
from time import sleep
#Initialises all imported pygame modules
pygame.init()
grid = []
for i in range(GRID_HEIGHT):
grid.append([])
for j in range(GRID_WIDTH):
grid[i].append([])
originalY1,originalX1,originalY2,originalX2 = 0,0,GRID_HEIGHT-1,GRID_WIDTH-1
#Divides the grid horizontally
def divideH(grid,y1,x1,y2,x2):
pygame.event.get()
#If the smallest subgrid is of width/height of 1
if x2-x1<=1 or y2-y1<=1:
return
#Finds a y-coordinate that the wall can be drawn from
wallYPosition = -1
while wallYPosition == -1:
wallYPosition = choices([2*i+1 for i in range(floor(y1/2), floor(y2/2))])[0]
if x1 == originalX1 and x2 == originalX2:
if " " in grid[wallYPosition][x1:x2+2]:
wallYPosition = -1
elif x1 != originalX1 and x2 == originalX2:
if " " in grid[wallYPosition][x1-1:x2+2]:
wallYPosition = -1
elif x1 == originalX1 and x2 != originalX2:
if " " in grid[wallYPosition][x1:x2+3]:
wallYPosition = -1
elif x1 != originalX1 and x2 != originalX2:
if " " in grid[wallYPosition][x1-1:x2+3]:
wallYPosition = -1
#Adds the "blocks" to make the wall
for i in range(x1,x2+1):
grid[wallYPosition][i] = "•"
pygame.draw.rect(SCREEN, PURPLE, (BLOCK_SIZE*i + 1.5, BLOCK_SIZE*wallYPosition + 70, BLOCK_SIZE - 3, BLOCK_SIZE - 3))
pygame.display.flip()
sleep(0.03)
#Finds an x-coordinate that can be a gap
wallXGap = -1
while wallXGap == -1:
wallXGap = choices([2*i for i in range(floor(x1/2), floor((x2+1)/2))])[0]
grid[wallYPosition][wallXGap] = " "
pygame.draw.rect(SCREEN, WHITE, (BLOCK_SIZE*wallXGap + 1.5, BLOCK_SIZE*wallYPosition + 70, BLOCK_SIZE - 3, BLOCK_SIZE - 3))
pygame.display.flip()
#Recursion for the top subGrid
height = (wallYPosition-1)-y1
width = x2-x1
if width > height:
divideV(grid,y1,x1,wallYPosition-1,x2)
elif width < height:
divideH(grid,y1,x1,wallYPosition-1,x2)
else:
x = randint(0,1)
if x == 0:
divideV(grid,y1,x1,wallYPosition-1,x2)
else:
divideH(grid,y1,x1,wallYPosition-1,x2)
#Recursion for the bottom subGrid
height = y2-(wallYPosition+1)
width = x2-x1
if width > height:
divideV(grid,wallYPosition+1,x1,y2,x2)
elif width < height:
divideH(grid,wallYPosition+1,x1,y2,x2)
else:
x = randint(0,1)
if x == 0:
divideV(grid,wallYPosition+1,x1,y2,x2)
else:
divideH(grid,wallYPosition+1,x1,y2,x2)
#Divides the grid horizontally
def divideV(grid,y1,x1,y2,x2):
pygame.event.get()
#If the smallest subgrid is of width/height of 1
if x2-x1<=1 or y2-y1<=1:
return
#Finds an x-coordinate that the wall can be drawn from
wallXPosition = -1
while wallXPosition == -1:
wallXPosition = choices([2*i+1 for i in range(floor(x1/2), floor(x2/2))])[0]
if y1 == originalX1 and y2 == originalY2:
if " " in [grid[i][wallXPosition] for i in range(y1,y2+1)]:
wallYPosition = -1
elif y1 != originalX1 and y2 == originalY2:
if " " in [grid[i][wallXPosition] for i in range(y1-1,y2+1)]:
wallYPosition = -1
elif y1 == originalX1 and y2 != originalY2:
if " " in [grid[i][wallXPosition] for i in range(y1,y2+2)]:
wallYPosition = -1
elif y1 != originalX1 and y2 != originalY2:
if " " in [grid[i][wallXPosition] for i in range(y1-1,y2+2)]:
wallXPosition = -1
#Adds the "blocks" to make the wall
for i in range(y1,y2+1):
grid[i][wallXPosition] = "•"
pygame.draw.rect(SCREEN, PURPLE, (BLOCK_SIZE*wallXPosition + 1.5, BLOCK_SIZE*i + 70, BLOCK_SIZE - 3, BLOCK_SIZE - 3))
pygame.display.flip()
sleep(0.03)
#Finds a y-coordinate that can be a gap
wallYGap = -1
while wallYGap == -1:
wallYGap = choices([2*i for i in range(floor(y1/2), floor((y2+1)/2))])[0]
grid[wallYGap][wallXPosition] = " "
pygame.draw.rect(SCREEN, WHITE, (BLOCK_SIZE*wallXPosition + 1.5, BLOCK_SIZE*wallYGap + 70, BLOCK_SIZE - 3, BLOCK_SIZE - 3))
pygame.display.flip()
#Recursion for the left subGrid
height = y2-y1
width = (wallXPosition-1)-x1
if width > height:
divideV(grid,y1,x1,y2,wallXPosition-1)
elif width < height:
divideH(grid,y1,x1,y2,wallXPosition-1)
else:
x = randint(0,1)
if x == 0:
divideV(grid,y1,x1,y2,wallXPosition-1)
else:
divideH(grid,y1,x1,y2,wallXPosition-1)
#Recursion for the right subGrid
height = y2-y1
width = x2-(wallXPosition+1)
if width > height:
divideV(grid,y1,wallXPosition+1,y2,x2)
elif width < height:
divideH(grid,y1,wallXPosition+1,y2,x2)
else:
x = randint(0,1)
if x == 0:
divideV(grid,y1,wallXPosition+1,y2,x2)
else:
divideH(grid,y1,wallXPosition+1,y2,x2)
|
556e44bc1fbfc4357f21caea828af854702da5a2 | HaliteChallenge/Halite-II | /bot-bosses/tscommander/hlt/entity.py | 14,889 | 3.8125 | 4 | import math
from . import constants
import abc
from enum import Enum
class Entity:
"""
Then entity abstract base-class represents all game entities possible. As a base all entities possess
a position, radius, health, an owner and an id. Note that ease of interoperability, Position inherits from
Entity.
:ivar id: The entity ID
:ivar x: The entity x-coordinate.
:ivar y: The entity y-coordinate.
:ivar radius: The radius of the entity (may be 0)
:ivar health: The planet's health.
:ivar owner: The player ID of the owner, if any. If None, Entity is not owned.
"""
__metaclass__ = abc.ABCMeta
def _init__(self, x, y, radius, health, player, entity_id):
self.x = x
self.y = y
self.radius = radius
self.health = health
self.owner = player
self.id = entity_id
def calculate_distance_between(self, target):
"""
Calculates the distance between this object and the target.
:param Entity target: The target to get distance to.
:return: distance
:rtype: float
"""
return math.sqrt((target.x - self.x) ** 2 + (target.y - self.y) ** 2)
def calculate_angle_between(self, target):
"""
Calculates the angle between this object and the target in degrees.
:param Entity target: The target to get the angle between.
:return: Angle between entities in degrees
:rtype: float
"""
return math.degrees(math.atan2(target.y - self.y, target.x - self.x)) % 360
def closest_point_to(self, target, min_distance=3):
"""
Find the closest point to the given ship near the given target, outside its given radius,
with an added fudge of min_distance.
:param Entity target: The target to compare against
:param int min_distance: Minimum distance specified from the object's outer radius
:return: The closest point's coordinates
:rtype: Position
"""
angle = target.calculate_angle_between(self)
radius = target.radius + min_distance
x = target.x + radius * math.cos(math.radians(angle))
y = target.y + radius * math.sin(math.radians(angle))
return Position(x, y)
@abc.abstractmethod
def _link(self, players, planets):
pass
def __str__(self):
return "Entity {} (id: {}) at position: (x = {}, y = {}), with radius = {}"\
.format(self.__class__.__name__, self.id, self.x, self.y, self.radius)
def __repr__(self):
return self.__str__()
class Planet(Entity):
"""
A planet on the game map.
:ivar id: The planet ID.
:ivar x: The planet x-coordinate.
:ivar y: The planet y-coordinate.
:ivar radius: The planet radius.
:ivar num_docking_spots: The max number of ships that can be docked.
:ivar current_production: How much production the planet has generated at the moment. Once it reaches the threshold, a ship will spawn and this will be reset.
:ivar remaining_resources: The remaining production capacity of the planet.
:ivar health: The planet's health.
:ivar owner: The player ID of the owner, if any. If None, Entity is not owned.
"""
def __init__(self, planet_id, x, y, hp, radius, docking_spots, current,
remaining, owned, owner, docked_ships):
self.id = planet_id
self.x = x
self.y = y
self.radius = radius
self.num_docking_spots = docking_spots
self.current_production = current
self.remaining_resources = remaining
self.health = hp
self.owner = owner if bool(int(owned)) else None
self._docked_ship_ids = docked_ships
self._docked_ships = {}
def get_docked_ship(self, ship_id):
"""
Return the docked ship designated by its id.
:param int ship_id: The id of the ship to be returned.
:return: The Ship object representing that id or None if not docked.
:rtype: Ship
"""
return self._docked_ships.get(ship_id)
def all_docked_ships(self):
"""
The list of all ships docked into the planet
:return: The list of all ships docked
:rtype: list[Ship]
"""
return list(self._docked_ships.values())
def is_owned(self):
"""
Determines if the planet has an owner.
:return: True if owned, False otherwise
:rtype: bool
"""
return self.owner is not None
def is_full(self):
"""
Determines if the planet has been fully occupied (all possible ships are docked)
:return: True if full, False otherwise.
:rtype: bool
"""
return len(self._docked_ship_ids) >= self.num_docking_spots
def _link(self, players, planets):
"""
This function serves to take the id values set in the parse function and use it to populate the planet
owner and docked_ships params with the actual objects representing each, rather than IDs
:param dict[int, gane_map.Player] players: A dictionary of player objects keyed by id
:return: nothing
"""
if self.owner is not None:
self.owner = players.get(self.owner)
for ship in self._docked_ship_ids:
self._docked_ships[ship] = self.owner.get_ship(ship)
@staticmethod
def _parse_single(tokens):
"""
Parse a single planet given tokenized input from the game environment.
:return: The planet ID, planet object, and unused tokens.
:rtype: (int, Planet, list[str])
"""
(plid, x, y, hp, r, docking, current, remaining,
owned, owner, num_docked_ships, *remainder) = tokens
plid = int(plid)
docked_ships = []
for _ in range(int(num_docked_ships)):
ship_id, *remainder = remainder
docked_ships.append(int(ship_id))
planet = Planet(int(plid),
float(x), float(y),
int(hp), float(r), int(docking),
int(current), int(remaining),
bool(int(owned)), int(owner),
docked_ships)
return plid, planet, remainder
@staticmethod
def _parse(tokens):
"""
Parse planet data given a tokenized input.
:param list[str] tokens: The tokenized input
:return: the populated planet dict and the unused tokens.
:rtype: (dict, list[str])
"""
num_planets, *remainder = tokens
num_planets = int(num_planets)
planets = {}
for _ in range(num_planets):
plid, planet, remainder = Planet._parse_single(remainder)
planets[plid] = planet
return planets, remainder
class Ship(Entity):
"""
A ship in the game.
:ivar id: The ship ID.
:ivar x: The ship x-coordinate.
:ivar y: The ship y-coordinate.
:ivar radius: The ship radius.
:ivar health: The ship's remaining health.
:ivar DockingStatus docking_status: The docking status (UNDOCKED, DOCKED, DOCKING, UNDOCKING)
:ivar planet: The ID of the planet the ship is docked to, if applicable.
:ivar owner: The player ID of the owner, if any. If None, Entity is not owned.
"""
class DockingStatus(Enum):
UNDOCKED = 0
DOCKING = 1
DOCKED = 2
UNDOCKING = 3
def __init__(self, player_id, ship_id, x, y, hp, vel_x, vel_y,
docking_status, planet, progress, cooldown):
self.id = ship_id
self.x = x
self.y = y
self.owner = player_id
self.radius = constants.SHIP_RADIUS
self.health = hp
self.docking_status = docking_status
self.planet = planet if (docking_status is not Ship.DockingStatus.UNDOCKED) else None
self._docking_progress = progress
self._weapon_cooldown = cooldown
def thrust(self, magnitude, angle):
"""
Generate a command to accelerate this ship.
:param int magnitude: The speed through which to move the ship
:param int angle: The angle to move the ship in
:return: The command string to be passed to the Halite engine.
:rtype: str
"""
return "t {} {} {}".format(self.id, int(magnitude), int(angle))
def dock(self, planet):
"""
Generate a command to dock to a planet.
:param Planet planet: The planet object to dock to
:return: The command string to be passed to the Halite engine.
:rtype: str
"""
return "d {} {}".format(self.id, planet.id)
def undock(self):
"""
Generate a command to undock from the current planet.
:return: The command trying to be passed to the Halite engine.
:rtype: str
"""
return "u {}".format(self.id)
def navigate(self, target, game_map, speed, avoid_obstacles=True, max_corrections=90, angular_step=1,
ignore_ships=False, ignore_planets=False):
"""
Move a ship to a specific target position (Entity). It is recommended to place the position
itself here, else navigate will crash into the target. If avoid_obstacles is set to True (default)
will avoid obstacles on the way, with up to max_corrections corrections. Note that each correction accounts
for angular_step degrees difference, meaning that the algorithm will naively try max_correction degrees before giving
up (and returning None). The navigation will only consist of up to one command; call this method again
in the next turn to continue navigating to the position.
:param Entity target: The entity to which you will navigate
:param game_map.Map game_map: The map of the game, from which obstacles will be extracted
:param int speed: The (max) speed to navigate. If the obstacle is nearer, will adjust accordingly.
:param bool avoid_obstacles: Whether to avoid the obstacles in the way (simple pathfinding).
:param int max_corrections: The maximum number of degrees to deviate per turn while trying to pathfind. If exceeded returns None.
:param int angular_step: The degree difference to deviate if the original destination has obstacles
:param bool ignore_ships: Whether to ignore ships in calculations (this will make your movement faster, but more precarious)
:param bool ignore_planets: Whether to ignore planets in calculations (useful if you want to crash onto planets)
:return string: The command trying to be passed to the Halite engine or None if movement is not possible within max_corrections degrees.
:rtype: str
"""
# Assumes a position, not planet (as it would go to the center of the planet otherwise)
if max_corrections <= 0:
return None
distance = self.calculate_distance_between(target)
angle = self.calculate_angle_between(target)
ignore = () if not (ignore_ships or ignore_planets) \
else Ship if (ignore_ships and not ignore_planets) \
else Planet if (ignore_planets and not ignore_ships) \
else Entity
if avoid_obstacles and game_map.obstacles_between(self, target, ignore):
new_target_dx = math.cos(math.radians(angle + angular_step)) * distance
new_target_dy = math.sin(math.radians(angle + angular_step)) * distance
new_target = Position(self.x + new_target_dx, self.y + new_target_dy)
return self.navigate(new_target, game_map, speed, True, max_corrections - 1, angular_step)
speed = speed if (distance >= speed) else distance
return self.thrust(speed, angle)
def can_dock(self, planet):
"""
Determine whether a ship can dock to a planet
:param Planet planet: The planet wherein you wish to dock
:return: True if can dock, False otherwise
:rtype: bool
"""
return self.calculate_distance_between(planet) <= planet.radius + constants.DOCK_RADIUS
def _link(self, players, planets):
"""
This function serves to take the id values set in the parse function and use it to populate the ship
owner and docked_ships params with the actual objects representing each, rather than IDs
:param dict[int, game_map.Player] players: A dictionary of player objects keyed by id
:param dict[int, Planet] players: A dictionary of planet objects keyed by id
:return: nothing
"""
self.owner = players.get(self.owner) # All ships should have an owner. If not, this will just reset to None
self.planet = planets.get(self.planet) # If not will just reset to none
@staticmethod
def _parse_single(player_id, tokens):
"""
Parse a single ship given tokenized input from the game environment.
:param int player_id: The id of the player who controls the ships
:param list[tokens]: The remaining tokens
:return: The ship ID, ship object, and unused tokens.
:rtype: int, Ship, list[str]
"""
(sid, x, y, hp, vel_x, vel_y,
docked, docked_planet, progress, cooldown, *remainder) = tokens
sid = int(sid)
docked = Ship.DockingStatus(int(docked))
ship = Ship(player_id,
sid,
float(x), float(y),
int(hp),
float(vel_x), float(vel_y),
docked, int(docked_planet),
int(progress), int(cooldown))
return sid, ship, remainder
@staticmethod
def _parse(player_id, tokens):
"""
Parse ship data given a tokenized input.
:param int player_id: The id of the player who owns the ships
:param list[str] tokens: The tokenized input
:return: The dict of Players and unused tokens.
:rtype: (dict, list[str])
"""
ships = {}
num_ships, *remainder = tokens
for _ in range(int(num_ships)):
ship_id, ships[ship_id], remainder = Ship._parse_single(player_id, remainder)
return ships, remainder
class Position(Entity):
"""
A simple wrapper for a coordinate. Intended to be passed to some functions in place of a ship or planet.
:ivar id: Unused
:ivar x: The x-coordinate.
:ivar y: The y-coordinate.
:ivar radius: The position's radius (should be 0).
:ivar health: Unused.
:ivar owner: Unused.
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = 0
self.health = None
self.owner = None
self.id = None
def _link(self, players, planets):
raise NotImplementedError("Position should not have link attributes.")
|
256318081ce2ae6b6dfdaaa922a449f15a8ebb0a | Ankit-Developer143/Programming-Python | /edabit/Check Array One Is Similar To Other.py | 137 | 3.59375 | 4 | def check_equals(lst1, lst2):
if (lst1[::] == lst2[::]):
return True
else:
return False
print(check_equals([1, 2], [1, 3]) )
#False |
3768f849a4129191f322b6d20b3becdd7101bc89 | ApexTone/Learn-Python | /PythonBasic/23TryExcept.py | 340 | 3.9375 | 4 | # Like try/catch error handling
try:
cursed_value = 10/0 # Produce ZeroDivisionError
number = int(input("Enter a number: ")) # User might try input string here
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input")
except: # Generic exception
print("Something wrong") |
17ee04365dd398ece2b5b6bf3dfa0bdc4b6e1383 | amansouri3476/ML-Course-HW | /HW1/Plotter.py | 4,050 | 3.515625 | 4 | # Import Pandas
import pandas as pd
# importing libraries for the plots.
# import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Load data
file_name = "iris.csv"
name = ["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm", "Species"]
iris = pd.read_csv(file_name, sep=",", names=name, header=0)
iris = iris.sample(frac=1).reset_index(drop=True)
# I have used first 70 data as the train data.
train_data = iris.loc[0:69].Species
# I have used last 30 data as the test data.
test_data = iris.loc[70:].Species
# Their values(setosa or virginica) is stored in the variable temp.
temp = train_data.values
# temp variable is transformed to an array using np.array
temp = np.array(temp)
# I am finding the indexes where setosa occurred. (This is done to have a better visualization in plots by
# distinguishing the classes of data)
setosa_indexes = np.where(temp == 'setosa')
# The same is done for the other class
virginica_indexes = np.where(temp == 'virginica')
# creating a scatter plot of "Species" using "SepalLengthCm" and "SepalWidthCm" features
plt.title('scatter plot of "Species" using "SepalLengthCm" and "SepalWidthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].SepalLengthCm, iris.loc[setosa_indexes].SepalWidthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].SepalLengthCm, iris.loc[virginica_indexes].SepalWidthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('SepalLengthCm')
plt.ylabel('SepalWidthCm')
plt.show()
# creating a scatter plot of "Species" using "SepalLengthCm" and "PetalLengthCm" features
plt.title('scatter plot of "Species" using "SepalLengthCm" and "PetalLengthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].SepalLengthCm, iris.loc[setosa_indexes].PetalLengthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].SepalLengthCm, iris.loc[virginica_indexes].PetalLengthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('SepalLengthCm')
plt.ylabel('PetalLengthCm')
plt.show()
# creating a scatter plot of "Species" using "SepalLengthCm" and "PetalWidthCm" features
plt.title('scatter plot of "Species" using "SepalLengthCm" and "PetalWidthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].SepalLengthCm, iris.loc[setosa_indexes].PetalWidthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].SepalLengthCm, iris.loc[virginica_indexes].PetalWidthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('SepalLengthCm')
plt.ylabel('PetalWidthCm')
plt.show()
# creating a scatter plot of "Species" using "SepalWidthCm" and "PetalLengthCm" features
plt.title('scatter plot of "Species" using "SepalWidthCm" and "PetalLengthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].SepalWidthCm, iris.loc[setosa_indexes].PetalLengthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].SepalWidthCm, iris.loc[virginica_indexes].PetalLengthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('SepalWidthCm')
plt.ylabel('PetalLengthCm')
plt.show()
# creating a scatter plot of "Species" using "SepalWidthCm" and "PetalWidthCm" features
plt.title('scatter plot of "Species" using "SepalWidthCm" and "PetalWidthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].SepalWidthCm, iris.loc[setosa_indexes].PetalWidthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].SepalWidthCm, iris.loc[virginica_indexes].PetalWidthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('SepalWidthCm')
plt.ylabel('PetalWidthCm')
plt.show()
# creating a scatter plot of "Species" using "PetalLengthCm" and "PetalWidthCm" features
plt.title('scatter plot of "Species" using "PetalLengthCm" and "PetalWidthCm"', color='b')
plt.plot(iris.loc[setosa_indexes].PetalLengthCm, iris.loc[setosa_indexes].PetalWidthCm, '.', color='r')
plt.plot(iris.loc[virginica_indexes].PetalLengthCm, iris.loc[virginica_indexes].PetalWidthCm, '.', color='b')
plt.legend(['setosa', 'virginica'])
plt.xlabel('PetalLengthCm')
plt.ylabel('PetalWidthCm')
plt.show()
|
8116adb47a51dc01d5520a17a8539182c90dded5 | mmarget/project-euler-python | /problem003.py | 562 | 3.84375 | 4 | #Project Euler Problem #003: Largest prime factor
#What is the largest prime factor of the number 600851475143
cunt = 600851475143
i = 1
largestPrime = 0
def isPrime ( i ):
c = 2
ret = True
while c < (i**0.5) + 1:
if i % c == 0:
ret = False
break
c = c + 1
return ret
while i < (cunt**0.5)+1:
if (isPrime(i) == True) and (cunt % i == 0):
largestPrime = i
#print("New largest prime is ",largestPrime)
#print(i)
i = i + 1
print("The largest Prime of",cunt,"is:",largestPrime)
|
000ffcb23548df284ba54de3b0a04587105fa3a9 | kleberfsobrinho/python | /Desafio031 - Custo da Viagem.py | 201 | 3.734375 | 4 | distancia = float(input('Entre com a distancia da viagem: '))
if distancia <= 200:
preco = distancia*0.5
else:
preco = distancia*0.45
print('O preço da viagem ficou por: {} R$'.format(preco))
|
d776ba38813bfd3d9567b74bdbb06b85ddb89d46 | yjiakang/Bioinfo-Practice | /extract_fa.py | 658 | 3.703125 | 4 | # -*- coding: utf-8 -*-
'''
#This is a script for extracting sequence from a fasta file
'''
import sys
def usage():
print('Usage: python3 script.py [fasta_file] [idlist_file] [outfile_name]')
def main():
fo = open(sys.argv[3],"w")
dic = {}
with open(sys.argv[1],"r") as fi:
for line in fi:
if line.startswith(">"):
name = line.strip().split()[0][1:]
dic[name] = ""
else:
dic[name] += line.replace("\n","")
with open(sys.argv[2],"r") as listf:
for i in listf:
i = i.strip()
for key in dic:
if key == i:
fo.write(">" + key + "\n")
fo.write(dic[key] + "\n")
fo.close()
try:
main()
except IndexError:
usage()
|
7084a1772eda50c6326361314aa6b43c01d67716 | emmacallahan/tic-tac-toe | /tictactoe.py | 1,808 | 4 | 4 | print("Let's play Tic-Tac-Toe!")
board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
player_1 = 'X'
player_2 = 'O'
current_player = player_1
def print_board():
for row in board:
print(row)
def is_input_valid(row, column):
if 0 > row or row > 2 or 0 > column or column > 2:
return False
return True
def is_space_free(row, column):
if board[row][column] == ' ':
return True
return False
def read_input():
play_input = input(f'Player {current_player}. Your move: ')
row, column = play_input.split(' ')
try:
row = int(row)
column = int(column)
except ValueError:
print('ILLEGAL MOVE')
return read_input()
if not is_input_valid(row, column):
print('ILLEGAL MOVE')
return read_input()
return row, column
def is_there_a_free_space():
for row in board:
if ' ' in row:
return True
return False
def no_winner():
for row in board:
if row[0] != ' ' and row[0] == row[1] == row[2]:
return False
for value in range(3):
if board[0][value] != ' ' and board[0][value] == board[1][value] == board[2][value]:
return False
if board[0][0] != ' ' and board[0][0] == board[1][1] == board[2][2]:
return False
if board[2][0] != ' ' and board[2][0] == board[1][1] == board[0][2]:
return False
return True
while no_winner() and is_there_a_free_space():
row, column = read_input()
while not is_space_free(row, column):
row, column = read_input()
board[row][column] = current_player
print_board()
current_player = player_1 if current_player == player_2 else player_2
current_player = player_1 if current_player == player_2 else player_2
print(f'PLAYER {current_player} WON!')
|
f95b776ee7418c016e15d87795717892503bf7be | kasrasadeghi/cs373 | /notes/07-05.py | 1,998 | 3.734375 | 4 | # -----------
# Wed, 5 Jul
# -----------
"""
mimic relational algebra in Python
select
project
joins
cross join
theta join
natural join
"""
"""
movie
title, year, director, genre
"shane", 1953, "george stevens", "western"
"star wars", 1977, "george lucas", "western"
...
"""
"""
director
1 "george stevens"
2 "george lucas"
...
movie
title, year, director ID, genre
"shane", 1953, 1, "western"
"star wars", 1977, 2, "western"
...
"""
a = [2, 3, 4]
b = [5, 6, 7]
print(a + b)
a = (2, 3, 4)
b = (5, 6, 7)
print(a + b)
a = {2, 3, 4}
b = {5, 3, 7}
print(a || b)
a = {2:"abc", 3:"def", 4:"ghi"}
b = {5:"abc", 6:"def", 7:"ghi"}
print(dict(a, **b))
def cross_join (r, s) :
for a in r :
for b in s :
yield dict(a, **b)
def cross_join (r, s) :
return (dict(a, **b) for a in r for b in s)
def theta_join (r, s, bp) :
for a in r :
for b in s :
if bp(a, b)
yield dict(a, **b)
def theta_join (r, s, bp) :
return (dict(a, **b) for a in r for b in s if bp(a, b))
print(all([True, 2, 2.5, "a", [2], (2), {2}, {"a": 2}])) # True
print(none([False, 0, 0.0, "", [], (), {}, dict()])) # False
def theta_join (r, s) :
def bp (u, v) :
for k in u :
if k in v :
if u[k] != v[k]
return False
return True
def bp (u, v) :
return all(u[k] == v[k] for k in u if k in v)
for a in r :
for b in s :
if bp(a, b)
yield dict(a, **b)
"""
regular expression incredibly valuable
"""
# ---------
# Questions
# ---------
"""
What is cross_join()?
What is theta_join()?
Under what circumstances does theta_join produce nothing?
Under what circumstances does theta_join become cross_join?
What is natural_join()?
Under what circumstances does natural_join produce nothing?
Under what circumstances does natural_join become cross_join?
What is all()?
What is a regular expression?
What does *, +, ?, ^, $, [] do?
"""
|
60b73a744e6ba191e4d4f2a9262173306d6b2346 | OksKV/python | /Lesson1.py | 2,213 | 4.15625 | 4 | # Task 1
variable1 = 10
variable2 = 4.5
print("This is an example of integer number: " + str(variable1) + "\nAnd this is an example of float number: " + str(
variable2))
name = input("What is your name?")
age = input("How old are you?")
print(f"Hey, {name}! You don\'t look like you\'re {age} years old!")
# Task 2 - Time converter
time = int(input("How many seconds did you spend to do this homework?"))
hours = time // 3600
min = (time // 60) % 60
sec = time % 60
print(f"You\'ve spent {hours}:{min}:{sec} for your homework??? Wow!")
# Task 3 Sum of numbers
num = int(input("Give me some integer number."))
total_sum = num + int(str(num) + str(num)) + int(str(num) + str(num) + str(num))
print(f"The sum of {num}, {num}{num} and {num}{num}{num} will be: {total_sum}")
# Task 4 The biggest element
num = int(input("Give me some big random number."))
num_max = 0
for i in str(num):
if num_max < int(i):
num_max = int(i)
else:
continue
print(f"Methode 1. \nThe biggest element in this number is: {num_max}")
# Or with While loop
while num > 0:
num = num // 10
a = num % 10
if a > num_max:
num_max = a
else:
continue
print(f"Methode 2. \nThe biggest element in this number is: {num_max}")
# Task 5 Income calculation
revenue = int(input("Please insert your Company's revenue"))
costs = int(input("Please insert your Company's costs"))
if revenue <= costs:
print("Sorry, your company is operating at a loss")
else:
income = revenue - costs
profitability = int(income / revenue * 100)
print(f"Congratulations, you have a profit! \nYour profitability index is {profitability}%")
workers = int(input("How many workers are in your Company?"))
income_per_person = int(income / workers)
print(f"The company's income per person is {income_per_person}$")
# Task 6 Sportsman
start_distance = int(input("How many kilometers a sportsman did on first day?"))
required_distance = int(input("What is a required distance for him?"))
day_num = 0
while int(start_distance) != required_distance:
day_num += 1
start_distance += start_distance * 0.1
print(f"The sportsman will do {required_distance} kilometers on the day {day_num}") |
2ee57917b0c36c3aaa7f967801eb591a739b11f3 | MEAJIN/Baekjoon | /L5/2577. 숫자의 개수.py | 478 | 3.921875 | 4 | #1
A = int(input())
B = int(input())
C = int(input())
all_multiplication_str = str(A*B*C)
for i in range(10):
all_multiplication_count = all_multiplication_str.count(str(i))
print(all_multiplication_count)
#2
total = 1
for _ in range(3):
i = int(input())
total *= i # 3개의 정수를 곱함
total_str = str(total) # 숫자를 str타입으로 변환
for num in range(10): # 0부터 9까지
num_count = total_str.count(str(num))
print(num_count)
|
17904f27eb1046d423431234493967e54dc44b9e | lucsikora/exercise | /201710_ex06.py | 430 | 4.40625 | 4 | # practicepython.py
#
# Solution by: Lukasz Sikora
# Date: 25th October, 2017
#
# Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
a = input("Hi, Please give me random word: ")
b = a[::-1]
if a == b:
print("Congratulation! It's a Palindrome!")
else:
print("Ohhh, that's not a palindrone type of word, please try again") |
0dbfb8c2812fbf50a17b7a5458711aa625cd6a95 | GoodieBag/chat-server-iot | /bot.py | 1,498 | 3.96875 | 4 | from motor_driver import Motor
import time
class Bot:
"""
A class used to represent a bot with two DC motors
Attributes
----------
NA
Methods
-------
move_forward()
moves the Bot in forward direction
move_backward()
moves the Bot in backward direction
turn_left()
turns the Bot left
turn_right()
turns the Bot right
stop()
stops the Bot
"""
def __init__(self):
"""Function to init two motors used by the Bot"""
self.motor1 = Motor(12, 11)
self.motor2 = Motor(15, 16)
def move_forward(self):
"""Function to move bot in forward direction"""
self.motor1.turn_clockwise()
self.motor2.turn_clockwise()
time.sleep(1)
self.stop()
def move_backward(self):
"""Function to move bot in backward direction"""
self.motor1.turn_anticlockwise()
self.motor2.turn_anticlockwise()
time.sleep(1)
self.stop()
def turn_left(self):
"""Function to turn bot left"""
self.motor1.turn_anticlockwise()
self.motor2.turn_clockwise()
time.sleep(1)
self.stop()
def turn_right(self):
"""Function to turn bot right"""
self.motor1.turn_clockwise()
self.motor2.turn_anticlockwise()
time.sleep(1)
self.stop()
def stop(self):
"""Function to stop bot"""
self.motor1.stop()
self.motor2.stop()
|
1ee290978482cfdd70864c26c3e7636baa152f8f | Harshil78/Python | /str.py | 340 | 4 | 4 | str = 'hello world'
print(str)
print(str[0:9])
print(str[-7:-3])
print(str[:5])
print(str[6])
str1 = input("Enter any String:")
print(str1.isalnum())
print(str1.isalpha())
print(str1.isdigit())
print(str1.islower())
print(str1.isupper())
print(str1.isspace())
print(str1.find('co', 10))
print(str1.find('co', 10, 15))
print('co' in str1)
|
32807790b88b45c2461d30ec38eae6c63079124a | DSHaworth/MurachPython | /Assignment/Assign4a.py | 607 | 3.890625 | 4 | def main():
size = int(input("Hello, please enter an integer value the size of your list: "))
star_list = []
for i in range(size):
val = int(input("Please enter a value between 1 and 10 (inclusive): "))
if val > 10:
val = 10
elif val <= 0:
val = 1
star_list.append(val)
print()
print("Printing your entries as a chart:")
for item in range(size):
# for star_count in range(star_list[item]):
# print("*", end="")
print("*" * star_list[item])
if __name__ == "__main__":
main() |
a283a9a03926914ce04668593630a31ab8b08725 | zVelto/Python-Basico | /aula12/aula12.py | 447 | 3.9375 | 4 | """
Operadores Lógicos
and, or, not
in e not in
a = ''
b = 0
if not a:
print('Ta errado')
nome = 'Welton Carvalho'
if 'n' in nome:
print('ta aqui')
if 'w' not in nome:
print('Aqui tbm')
"""
usuario = input('Nome de usuário: ')
senha = input('Senha do usuário: ')
usuario_db = 'Welton'
senha_db = '123456'
if usuario_db == usuario and senha_db == senha:
print('Você está logado')
else:
print('Você não está logado')
|
50da1687240712828ddb5e8404f73bedafe3ec3a | ofentsekgomotso94/higher-lower-game | /main.py | 2,381 | 3.71875 | 4 | from art import logo, vs
from game_data import data
import random
import os
print(logo)
end_of_game = False
score = 0
# print(len(data))
def generate_list_dictionary_A():
dictionary_A = random.choice(data)
# print(dictionary_A)
return dictionary_A
def generate_list_dictionary_B():
dictionary_B = random.choice(data)
# print(dictionary_B)
return dictionary_B
compare_A = generate_list_dictionary_A()
compare_B = generate_list_dictionary_B()
if compare_A == compare_B:
compare_B = generate_list_dictionary_B
# print(compare_A["follower_count"])
# print(compare_B["follower_count"])
# While loop should start here.
while end_of_game == False:
if compare_A == compare_B:
compare_B = generate_list_dictionary_B()
print(
f"Campare A: {compare_A['name']}, a {compare_A['description']}, from {compare_A['country']}.")
print(vs)
print(
f"Against B: {compare_B['name']}, a {compare_B['description']}, from {compare_B['country']} ")
user_choice = input("Who has more followers? Type 'A' or 'B': ").casefold()
dictionary_A_Followers = compare_A['follower_count']
dictionary_B_Followers = compare_B['follower_count']
if user_choice == 'a':
user_take = dictionary_A_Followers
if user_take > dictionary_B_Followers:
score += 1
os.system('cls' if os.name == 'nt' else 'clear')
print(logo)
print(f"You're right! Current score: {score}.")
compare_A = compare_B
else:
end_of_game = True
os.system('cls' if os.name == 'nt' else 'clear')
print(logo)
print(f"Sorry, that's wrong. Final score: {score}.")
elif user_choice == 'b':
user_take = dictionary_B_Followers
if user_take > dictionary_A_Followers:
score += 1
os.system('cls' if os.name == 'nt' else 'clear')
print(logo)
print(f"You're right! Current score: {score}.")
compare_A = compare_B
else:
end_of_game = True
os.system('cls' if os.name == 'nt' else 'clear')
print(logo)
print(f"Sorry, that's wrong. Final score: {score}.")
if end_of_game == False:
compare_B = generate_list_dictionary_B()
|
596aedcf32f114a5b035e699a18db81f4c2e05e1 | likeweilikewei/Python-study-demo | /pandas_test/pandas_to_dict.py | 935 | 3.5625 | 4 | #! /user/bin/env python
# -*- coding=utf-8 -*-
import pandas as pd
pd_dict = {'code': ['000001', '000002'], 'inc': [1, 1.1], 'name': ['平安银行', '万科A'], 'price': [3, 3.1], 'rate0': [4, 4.1],
'rate1': [5, 5.1], 'rate2': [6, 6.1]}
pdData = pd.DataFrame(pd_dict)
print(pdData)
print(pdData.to_dict())
# T会让索引为键,默认列名为键
dict_country = pdData.set_index('code').T.to_dict()
print(dict_country)
# 不指定索引会使用默认的索引为键
print(pdData.T.to_dict())
print(pdData.T)
# 将空df转为dict
blocks = pd.DataFrame(columns=['inst', 'name', 'current_price', 'cost_price', 'quantity',
'quantity_sell', 'profit_count', 'profit', 'market_value',
'cost_value', 'status', 'hold_days', 'percent'])
print(blocks.to_dict())
dict_country = blocks.set_index('inst').T.to_dict()
print(dict_country)
|
f6da547ef7d818a505e3618e7c8c9eecfdbfff91 | indranarayan12/Logs-analysis | /logs_analysis.py | 1,977 | 3.671875 | 4 | #!/usr/bin/env python3
# using Postgresql
import psycopg2
# query_1 stores most popular three articles of all time
query_1 = """select articles.title, count(*) as num from logs, articles where
log.status='200 OK' and articles.slug = subdtr(log.path,10) group by
articles.title order by num desc limit 3;"""
# query_2 stores most popular article authors of all time
query_2 = """select article.authors, count(*) as num from logs, articles where
log.status='200 OK' and articles.slug = subdtr(log.path,10) group by
articles.name order by num desc;"""
# query_3 stores on which day more than 1% of requests lead to errors
query_3 = """select time, percentagefailed from percentagecount where
percentagefailed > 1;"""
# establishing a connection and fetching data by executing the query send in
argument
def db_query(query):
db = psycopg2.connect(database="name")
cursor = db.cursor()
cursor.execute(query)
data = cursor.fetchall()
db.close()
return data
# prints the top three articles of all time
def top_3_articles():
top_3_articles = db_query(query_1)
print("\n1.Most popular 3 articles of all time\n")
for title, num in top_3_articles:
print(" \"{}\" --> {} views".format(title, num))
# prints most popular article authors of all time
def top_authors():
top_authors = db_query(query_2)
print("\n2.Top authors of all time\n")
for name, num in top_authors:
print(" {} --> {} views".format(name, num))
# prints days on which more than 1% of the requests lead to error
def max_error():
high_error_days = db_query(query_3)
print("\n3.Days with more than 1% of requets leading to error\n")
for day, percentagefailed in high_error_days:
print(
""" {0:%B %d, %Y} --> {1:.1f} % errors""",
format(day, percentagefailed)
)
if __name__ == '__main__':
print("\nOutput of logs_analysis.py\n")
top_3_articles()
top_authors()
max_error()
|
d79927fd530f49188c71e7ae1b08b9d7caf66b46 | datakortet/dklint | /dklint/pfind.py | 834 | 3.65625 | 4 | #!/usr/bin/python
"""`pfind path filename` find the closest ancestor directory conataining
filename (used for finding syncspec.txt and config files).
"""
import os
import sys
def pfind(path, fname):
"""Find fname in the closest ancestor directory.
For the purposes of this function, we are our own closest ancestor.
"""
wd = os.path.abspath(path)
assert os.path.isdir(wd)
def parents():
parent = wd
yield parent
while 1:
parent, dirname = os.path.split(parent)
if not dirname:
return
yield parent
for d in parents():
if fname in os.listdir(d):
return os.path.join(d, fname)
return None
if __name__ == "__main__":
_path, filename = sys.argv[1], sys.argv[2]
print pfind(_path, filename)
|
7c3c888e16db2362ae804b29402d0d67930d2711 | NataliyaPavlova/WordSearch | /word_search.py | 4,428 | 3.875 | 4 | import codecs
import sys
import re
import argparse
class Dict:
def __init__(self, filepath):
self.filepath = filepath
def make_dict(self): #make a dictionary of words; group words by their lengths
with codecs.open(self.filepath, encoding = "utf8") as f:
data_list=list(f)
data_list = list(map(lambda x: x.lower(), data_list)) #all words to lower register
data_list = list(map(lambda x: re.split("[^a-z-']", x), data_list)) #delete all punctuation
self.dict = {}
for line in data_list:
for word in line:
word_length = len(word)
if word_length in self.dict.keys():
self.dict[word_length].append(word)
else:
self.dict[word_length] = [word]
self.dict.pop(0) #delete all empty words
#return self.dict
class Word(Dict):
def __init__(self, filepath, length, letters):
Dict.__init__(self, filepath)
self.length = length
self.letters = letters
def conditions_list(self):
#makes from letters string a dictionary of letter conditions (self.letters_list) like {1:'a', 2:'b', 3:'c'}
if (self.letters is None): #then we can return first met word with given length
return False
self.letters_list={}
self.letters = self.letters[1:-1].split(',')
if (len(self.letters)==1) and (len(self.letters[0])>5): #check if ',' is a separator of letters' conditions
print 'Wrong punctuation in the input.'
raise SystemExit
for condition in self.letters:
condition = condition.split(':')
if (len(condition)==1): #check if ':' is a separator between a letter and a position
print 'Wrong punctuation in the input.'
raise SystemExit
if len(condition[0])!=3: #check if letter input is ok
print 'Wrong input: ',condition[0]
raise SystemExit
letter = condition[0][1]
try: #check if position of the letter is ok
position = int(condition[1])-1
except ValueError:
print 'Wrong input: ',condition[1]
raise SystemExit
#print letter, position
self.letters_list[position]=letter
return True
def fit_parameters(self, word):
#check if the word fits given letter conditions
fit = True
for position in self.letters_list.keys():
try:
if position>len(word): raise IndexError
except IndexError:
print "Wrong input: letter's position is bigger then word's length: ",position+1
raise SystemExit
if not (word[position]==self.letters_list[position]):
fit = False
#print self.letters_list[position], position, word
return fit
return fit
def search_word(self): #look through the words with given length
answer = 'There is no such word...'
if not (self.length in self.dict):
return answer
answers_list = self.dict[self.length]
i = self.conditions_list()
if i==False: #then we can return first met word with given length
return answers_list[0]
for word in answers_list:
if self.fit_parameters(word):
answer = word
break
return answer
'''
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('--length', help='Length of word, obligatory parameter, should be integer', type=int)
parser.add_argument('--letters', help="Known letters, the format is as {'a':1,'b':2}")
args = parser.parse_args()
filepath = "sentences.txt"
answer = Word(filepath, args.length, args.letters)
answer.make_dict()
if args.length:
print answer.search_word()
else:
print('Wrong input: there is no length condition.')
raise SystemExit
if __name__ == "__main__":
_main()
''' |
d8a6583ccf82efcee73aa8b62d21c1b7810159a0 | Vince249/Projet_Python_COVID | /Projet_Python/Projet_Python/methode_JSON/methodes_JSON.py | 4,184 | 3.578125 | 4 | #Mettre ici les méthodes de lecture/écriture JSON
# Python program to update
# JSON
from datetime import datetime
import json
from datetime import date,timedelta
# function to add to JSON
def write_json(data, filename):
with open(filename,'w') as f:
json.dump(data, f, indent=4)
return
def EnregistrerClient(data):
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp = fichier['foyers']
data['Personnes']=[]
today = date.today()
data['Date']=today.strftime("%Y-%m-%d")
temp.append(data)
write_json(fichier,'./JSON/infos_client.json')
return
def EnregistrerPersonnes(data):
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp = fichier['foyers']
temp[len(temp)-1]['Personnes'].append(data)
write_json(fichier,'./JSON/infos_client.json')
return
### Méthode ajoutant la commande passée par un client à la BDD des commandes effectuées ###
def EnregistrerCommande(data, id):
#récupération CP de la personne ayant commandé (utile pour la partie admin)
CP=""
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp = fichier['foyers']
for element in temp:
if (element["id_box"]==id): CP = element["codeP"]
with open('./JSON/commandes_faites.json') as json_file:
fichier = json.load(json_file)
temp = fichier['commandes']
datacleaned={}
for k,v in data.items():
if (v != '0'):
datacleaned[k]=v
datacleaned['id']=id
datacleaned['CP']=CP
datacleaned['Date'] = (datetime.now()).strftime("%Y-%m-%d") #Ajout de la date au format YYYY-mm-dd
temp.append(datacleaned)
write_json(fichier,'./JSON/commandes_faites.json')
return
### Méthode créant la livraison associé à la commande venant d'être passée. Nous avons fixer le jour de livraison à j+1 par rapport à la date de la commande ###
def Remplissage_Livraison(data,id):
#initialisation des données que l'on veut récupérer
tel=""
ville=""
codeP=""
adresse=""
produits_commande={}
#commande à livrer
for k,v in data.items():
if (v != '0'):
produits_commande[k]=v
#on donne la valeur qu'il faut aux données initialisées précédemment
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp = fichier['foyers']
for element in temp:
if (element["id_box"]==id):
tel = element["tel"]
ville=element["ville"]
codeP=element["codeP"]
adresse=element["adresse"]
with open('./JSON/livraisons.json') as json_file:
fichier = json.load(json_file)
temp = fichier['liste_livraisons']
datacleaned={}
datacleaned['id']=id
datacleaned['tel']=tel
datacleaned['ville']=ville
datacleaned['codeP']=codeP
datacleaned['adresse']=adresse
datacleaned['Date_livraison'] = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d") #Ajout de la date au format YYYY-mm-dd -> par défaut on dit que la livraison se fait au jour j+1 par rapport à la date de la commande
datacleaned['produits_commande']=produits_commande
temp.append(datacleaned)
write_json(fichier,'./JSON/livraisons.json')
return
### Méthode vérifiant si l'Id et le password entrés par le client sont dans la base de données clients ###
def VerifClient(id,pwd):
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp=fichier['foyers']
check = False
for element in temp:
if(element['id_box']==id and element['pwd']==pwd):
check=True
break
return check
### Méthode vérifiant si l'Id et le password entrés par l'admin sont dans la base de données admin ###
def VerifAdmin(id,pwd):
with open('./JSON/admin_login.json') as json_file:
fichier = json.load(json_file)
temp=fichier['admin']
check = False
for element in temp:
if(element['id']==id and element['pwd']==pwd): check=True
return check
def VerifUniciteClient(id,latitude,longitude):
with open('./JSON/infos_client.json') as json_file:
fichier = json.load(json_file)
temp=fichier['foyers']
check = True
for element in temp:
if(element['id_box']==id or (element['latitude']==latitude and element['longitude']==longitude)): check=False
return check |
b33cd202f48ae05efcfa8fe1d93f7ae7d41ef690 | OliverIgnetik/tkinter_practice | /python_namespaces.py | 528 | 3.765625 | 4 | # illustration why importing everything from tkinter is a bad idea
# the namespace is absolutely cluttered
################################################
num1 = 5
num2 = 3.142
s = 'hello'
def add_two(num1, num2):
print('function/local namespace')
print(dir())
return num1+num2
sum_of_numbers = add_two(1, 2)
print()
print(f'sum of numbers: {sum_of_numbers}')
print()
print('Check the global namespace')
namespace = dir()
print(namespace)
print()
print(f'__file__: {__file__}')
print(f'__name__: {__name__}')
|
70ad62d28607d8ecfc46ef97b522cc86090629b6 | mayaragualberto/Introducao-CC-com-Python | /Parte1/Semana4/Cartões.py | 435 | 3.921875 | 4 | meuCartão=int(input("Digite o número do seu cartão de crédito: "))
cartãoLido=1
encontreiMeuCartãoNaLista=False
while cartãoLido!=0 and not encontreiMeuCartãoNaLista:
cartãoLido=int(input("Digite o número do próximo cartão de crédito: "))
if cartãoLido==meuCartão:
encontreiMeuCartãoNaLista=True
if encontreiMeuCartãoNaLista:
print("EBA! Meu cartão está lá!")
else:
print("Xi, meu cartão não está lá!")
|
c2b43f193dca6df62b9a5488ebd8d91c963d201d | cedenoparedes/Python-course | /calc/calc.py | 1,275 | 3.9375 | 4 |
def main():
def sumar(a,b):
return a+b
def restar(a,b):
return a-b
def multiplicacion(a,b):
return a*b
def division(a,b):
return a/b
print "Calculadora"
print "Bienvenido"
print "Introdusca el primer numero"
a = int(raw_input())
print "Introdusca el segundo numero"
b = int (raw_input())
print "Seleccione la Operacion Sum:1,rest:2,mult:3,div:4"
seleccion = int (raw_input())
if seleccion == 1:
print (a,"+",b,'=',sumar(a,b))
elif seleccion == 2:
primerrint (a,"-", b, "=",restar(a,b))
elif seleccion == 3:
print (a,"*",b, "=",multiplicacion(a,b))
elif seleccion == 4:
print (a,"/",b, "=",division(a,b))
elif seleccion == 4 and b== 0:
print "Operacion no valida, seleccione un numero mayor a 0"
print "Introdusca el segundo numero"
b = int (raw_input())
print (a,"/",b, "=",division(a,b))
else:
print "Operacion no valida"
def again():
print "precione Y para vorver a inicio N para salir"
calc_again = str(raw_input())
if calc_again.upper() == 'Y':
main()
elif calc_again.upper() == 'N':
print ('Bye.')
else:
again()
main()
|
d68c21bb62a72eb51827fb84a3febb1edaf2450f | hoangdat1807/pycharm_test- | /ex11.py | 502 | 3.828125 | 4 | from datetime import datetime, date
# a= datetime(2017, 11, 28, 23, 55, 59, 34280)
# print("year =", a.year)
# print("month =", a.month)
t1= date(year = 2018, month = 7, day= 12)
t2= date(year = 2017, month = 12, day=23)
t3= t1 - t2
print("t3 =", t3)
t4 = datetime(year = 2018, month=7, day =12, hour =7, minute =9, second =33)
t5=datetime(year = 2019, month =6, day=10, hour =5, minute= 55, second =13)
t6 =t4 - t5
print("t6 =", t6)
print("type of t3 =", type(t3))
print("type of t6 =", type(t6))
|
a506101ac9977d230b7633e80fb59aa2d597aa63 | frankieliu/problems | /leetcode/python/116/sol.py | 736 | 3.921875 | 4 |
7 lines, iterative, real O(1) space
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37484
* Lang: python3
* Author: StefanPochmann
* Votes: 84
Simply do it level by level, using the `next`-pointers of the current level to go through the current level and set the `next`-pointers of the next level.
I say "real" O(1) space because of the many recursive solutions ignoring that recursion management needs space.
def connect(self, root):
while root and root.left:
next = root.left
while root:
root.left.next = root.right
root.right.next = root.next and root.next.left
root = root.next
root = next
|
9ff50b16965da22dd76ebba422753a10d7ef8f09 | jmkd0/ProjetGestionDeStock | /main.py | 663 | 3.578125 | 4 | import re
#Ouverture du fichier en lecture
file = open('file2.txt',"r")
lines = file.readlines()
#initialisation d'une liste vide
liste = []
for line in lines:
#Enlever l'espace et le \n de ma cdc
line = re.split(' |\n',line)
#Supprimer les '' de la liste
if '' in line:
line.remove('')
#Concatenation des deux chaines
liste += line
print(line)
print(liste)
#Initialisation des produits
liste2 = ['Stylo','Crayon','Trousse']
i = 0
while i < len(liste):
if liste[i] in liste2:
print(liste[i]+ " existe dans la liste")
else:
print(liste[i]+ " n'existe pas dans la liste")
i += 2
|
0cf7d21514bdcf1cb6ed07e1dceade7fff4d8e8e | idosilverwater/ai-project | /BackTrackHeuristics/Degree.py | 1,266 | 3.90625 | 4 | from BackTrackHeuristics.VariableHeuristic import *
class Degree(VariableHeuristic):
"""
This class represents Degree Heuristic.
"""
def __init__(self, variables):
"""
Creates a new degree heuristic object.
:param variables: A list of variable objects.
"""
VariableHeuristic.__init__(self, variables)
def init_sorted_variables(self):
"""
Initializes a list of variables according to the heuristic - the
variable with most neighbors is first and so on.
"""
variables_by_neighbors = [] # A list of (var_name, |neighbors|)
for variable in self.var_names:
variables_by_neighbors.append(
(self.variables[variable].get_name(), len(self.variables[variable].get_neighbors())))
# In this part we sort the variables according to the heuristic:
variables_by_neighbors = sorted(variables_by_neighbors, key=lambda tup: tup[1], reverse=True)
# (J) Notice that there can be many variables with same neighbour, thus the order between them isn't determined.
self.sorted_variables = [*map(lambda x: x[0], variables_by_neighbors)]
def select_unassigned_variable(self):
return self.sorted_variables
|
82852b31b7d5a7c41e9ec077779d77b80197490f | abhimanyupandey10/python | /while_loop.py | 176 | 4.09375 | 4 | # This program prints even numbers till the limit entered.
limit = int(input('Enter limit: '))
i = 1
while i <= limit:
if i % 2 == 0:
print(i)
i = i + 1 |
eff7c25fe670111dd807f52eb19c1c816f3586f0 | eduardhogea/Algorithms-and-Datastructures | /montecarlo.py | 2,059 | 3.890625 | 4 | from random import random
class MonteCarlo:
def __init__(self, length, width, rectangles):
"""constructor
:param length - length of the enclosing rectangle
:param width - width of the enclosing rectangle
:param rectangles - array that contains the embedded rectangles
:raises ValueError if any of the paramters is None
"""
self.l = length
self.w = width
self.r = rectangles
if self.l is None or self.w is None or self.r is None:
raise ValueError("The parameters can't be None")
def area(self, num_of_shots):
"""Method "area "to estimate the area of the enclosing rectangle that is not covered by the embedded rectangles
:param num_of_shots - Number (>0) of generated random points whose location (inside/outside) is analyzed
:return float
:raises ValueError if any of the paramters is None
"""
n=num_of_shots
nr=0
i=0
for i in range (0,n):
x = self.l*random()
y = self.w*random()
ok=0
for j in self.r:#testing for each rectangle
if self.inside(x, y, j) == True:
ok=1
break
if ok==0:
nr=nr+1
if n is None:
raise ValueError("The parameters can't be None")
return nr/n*self.l*self.w
def inside(self, x, y, rect):
"""Method "inside" to determine if a given point (x,y) is inside a given rectangle
:param x,y - coordinates of the point to check
:param rect - given rectangle
:return bool
:raises ValueError if any of the paramters is None
"""
if x >= rect.origin_x and y >= rect.origin_y and x <= rect.origin_x+rect.length and y <= rect.origin_y+rect.width:
return True
else:
return False
if x is None or y is None or rect is None:
raise ValueError("The parameters can't be None")
|
3c28abdd0b44d4d03a65b34e4d5cb661e8e7cb5e | mouryay/python | /factorial.py | 455 | 4.34375 | 4 | """
Get user input to find the factorial of the number, given by the user. The output should be on a single line.
"""
user_num = int(input("Enter a number: "))
if user_num < 0:
print("Factorial of a negative number is not defined.")
elif user_num == 0:
print("Factorial of 0 is 1.")
else:
factorial = 1
for i in range (1, user_num + 1):
factorial = factorial * i
print(f"Factorial of {user_num} is {factorial}")
|
e7b39f326cd9db257c45d81bf05393d7d622da83 | brianweber2/project2_battleship | /ship.py | 1,221 | 3.734375 | 4 | from constants import VERTICAL_SHIP, HORIZONTAL_SHIP, SUNK, HIT, MISS
class Ship(object):
"""
Ship with name, size, coordinates, and hits.
Args:
name (str): Name of the ship
size (int): ship size in board spaces
coords (list[str]): list of ship board coords
direction (str): ship direction vertical or horizontal
Attributes:
hits (list[str]): coords "hit" by guess
sunk (boolean): all coords "hit"
char (str): display charater "|" vertical or "-" horizontal
"""
def __init__(self, name, size, coords, orientation):
"""
Initialize Ship with name, size, coordinates and direction.
"""
self.name = name
self.size = size
self.coords = coords
self.orientation = orientation
# List[str]: coordinates of ship that has been "hit"
self.hits = []
# List[str]: coordinates that are a "miss"
self.misses = []
# Boolean: Has this ship sunk (all coords as "hit")
self.sunk = False
# str: display character
if orientation.lower() == 'v':
self.char = VERTICAL_SHIP
else:
self.char = HORIZONTAL_SHIP
|
d3ecd2b94eb361f1fe2c6d235b019c4c10849843 | WangZhengZhi/GoFile | /python/hello.py | 98 | 3.671875 | 4 | import turtle
bob=turtle.Turtle
print(bob)
turtle.mainloop()
for i in range(4):
print("hello") |
84ff97cf3df389ee8521da8e41bb542e7edd6fe4 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/f34e7f6d9be84c8cbf674e37cf512a8b.py | 617 | 4.09375 | 4 | #!/usr/bin/env python
"""
Anagram
Write a program that, given a word and a list of possible anagrams,
selects the correct sublist.
Given `"listen"` and a list of candidates like `"enlists" "google"
"inlets" "banana"` the program should return a list containing `"inlets"`.
"""
class Anagram(object):
def __init__(self, word):
self.word = word
def match(self, anagram_list):
signature = sorted(self.word.lower())
result = filter(lambda item: sorted(item.lower()) == signature, anagram_list)
result = filter(lambda item: item != self.word, result)
return result
|
ebcb89be32b6d81d7659452b6ced7adc3f067ff2 | Carlisle345748/leetcode | /283.移动零.py | 1,652 | 3.515625 | 4 | class Solution1:
def moveZeroes(self, nums: List[int]) -> None:
"""
把遇到的非零数依次放到数组的前面,遍历完一次数组后,所有的非零数组都按原有顺序排列在前面了,最后再把后面的数字都设为0就好
"""
nonzero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[nonzero] = nums[i]
nonzero += 1
for i in range(nonzero, len(nums)):
nums[i] = 0
class Solution2:
"""
遍历数组,每遇到一个非零数字,它应有的位置要不是原有位置,要不是更前的位置(表明该非零数字与上一个非零数字之间有零出现)。
用一个nonzero来记录下一个非零数字出现的数组,每当遇到一个非零数,就把nums[i]和nums[nonzero]交换,共有2种情况:
(1)如果 i == nonzero,说明非零数字保留原始位置,而且该非零数字与上一个非零数字之间没有出现0
(2)如果 nonzeor < i,说明该非零数字与上一个非零数字之间有零出现,而且nums[nonzero]肯定是零,交换后,nums[i]这个非
零数字按顺序放到了数组前面,而nums[nonzero]这个零放到了数组后面。
遍历完数组后,所有非零数字都按顺序放到数组前面,而且中间出现的零都被交换后数组后面,完成目标。
"""
def moveZeroes(self, nums: List[int]) -> None:
nonzero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[nonzero] = nums[nonzero], nums[i]
nonzero += 1 |
709d40ce816b16fc9b764fff094c3c9cf7289e47 | domdew23/Machine-Learning-Algorithms | /supervised_learning/forge.py | 2,524 | 4.03125 | 4 | # Two types of supervised learning:
# Classification - the goal is to predict a class label, which is a choice from a predifined list of possibilites
# Regression - the goal is to predict a continous number, predicted value is an amount
import mglearn
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
def KNeighbors():
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
for n_neighbors, ax in zip([1, 3, 9], axes):
# the fit method dreturns the object self, so we can instantiate and fit in one line
clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X, y)
mglearn.plots.plot_2d_separator(clf, X, fill=True, eps=0.5, ax=ax, alpha=.4)
mglearn.discrete_scatter(X[:, 0], X[:, 1], y, ax=ax)
ax.set_title("{} neighbor(s)".format(n_neighbors))
ax.set_xlabel("Feature 0")
ax.set_ylabel("Feature 1")
axes[0].legend(loc=3)
plt.show()
def show():
# Plot dataset
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
plt.show()
mglearn.plots.plot_knn_classification(n_neighbors=5)
plt.show()
def svm():
X, y = mglearn.tools.make_handcrafted_dataset()
svm = SVC(kernel='rbf', C=10, gamma=0.1).fit(X, y)
mglearn.plots.plot_2d_separator(svm, X, eps=.5)
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
# plot support vectors
sv = svm.support_vectors_
# class labels of support vectors are given by the sign of the dual coeffiecients
sv_labels = svm.dual_coef_.ravel() > 0
mglearn.discrete_scatter(sv[:, 0], sv[:, 1], sv_labels, s=15, markeredgewidth=3)
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.show()
def vary_svm():
fig, axes = plt.subplots(3, 3, figsize=(15, 10))
for ax, C in zip(axes, [-1, 0, 3]):
for a, gamma in zip(ax, range(-1, 2)):
mglearn.plots.plot_svm(log_C=C, log_gamma=gamma, ax=a)
axes[0, 0].legend(["Class 0", "Class 1", "SV Class 0", "SV Class 1"], ncol=4, loc=(.9, 1.2))
plt.show()
# Generate dataset
X, y = mglearn.datasets.make_forge()
print("X.shape: {}".format(X.shape))
print("y: {}".format(y))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = KNeighborsClassifier(n_neighbors=3)
clf.fit(X_train, y_train)
print("Test set predictions: {}".format(clf.predict(X_test)))
print("Test set accuracy: {:.2f}".format(clf.score(X_test, y_test)))
#svm()
vary_svm()
#print("{}".format(mglearn.datasets.make_forge())) |
fa5e284c746230c7aa93de3bc2ec5ca0c1fe4aab | gdh756462786/Leetcode_by_python | /Tree/Construct Binary Tree from Preorder and Inorder Traversal.py | 1,371 | 3.96875 | 4 | # coding: utf-8
'''
Given preorder and inorder traversal of a tree, construct the binary tree.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
if not preorder:
return None
root = TreeNode(preorder[0])
rootPos = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:1+rootPos], inorder[:rootPos])
root.right = self.buildTree(preorder[rootPos+1:], inorder[rootPos+1:])
return root
class Solution2(object):
def buildTree(self, preorder, inorder):
if not preorder:
return None
self.preorder, self.inorder = preorder, inorder
return self.dfs(0, len(preorder) - 1, 0, len(inorder) - 1)
def dfs(self, L1, R1, L2, R2):
if L1 > R1:
return None
if L1 == R1:
return TreeNode(self.preorder[L1])
root = TreeNode(self.preorder[L1])
# rootPos is the index of current root (preorder[L1]) in inorder list
rootPos = self.inorder.index(self.preorder[L1])
root.left = self.dfs(L1 + 1, L1 + rootPos - L2, L2, rootPos - 1)
root.right = self.dfs(L1 + rootPos - L2 + 1, R1, rootPos + 1, R2)
return root |
7272d0efc6ce49b4a779fb71a066a76b0262cd5e | vamsitallapudi/Coderefer-Python-Projects | /programming/dsame/trees/PreOrderTraversal.py | 324 | 3.546875 | 4 | class BinaryTreeNode:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class Tree:
def preOrder(self, root: BinaryTreeNode):
if root:
print(root.data)
self.preOrder(root.left)
self.preOrder(root.right)
|
911674ffd7230a16bfdabfc28806f80b013026dc | groversid/holbertonschool-python-camp2 | /0x02-python_if_else_loops_functions/1-odd_or_even.py~ | 122 | 4.125 | 4 | #!/usr/bin/python3
number = 12
if number % 2 ==0:
print (number + 'is even')
else:
print (number + 'is odd')
|
62fc9ae8322e0fdfc394240eade0e2a2e70da54a | arched1/Hangman | /hangman.py | 4,101 | 4.15625 | 4 | import random
from words import word_list
# Get a random word from the words.py file.
def get_word():
selected_word = (random.choice(word_list))
return selected_word.upper()
# Based on the stage of the game, the correct hangman illustration will be shown.
def display_hangman(tries):
stages = {0: "\
|------\n\
| O\n\
| ---|---\n\
| / \\ \n\
| / \\ \n\
|_____", 1: "\
|------\n\
| O\n\
| ---|---\n\
| / \n\
| / \n\
|_____", 2: "\
|------\n\
| O\n\
| ---|---\n\
| \n\
| \n\
|_____", 3: "\
|------\n\
| O\n\
| ---| \n\
| \n\
| \n\
|_____", 4: "\
|------\n\
| O\n\
| | \n\
| \n\
| \n\
|_____", 5: "\
|------\n\
| O\n\
| \n\
| \n\
| \n\
|_____", 6: "\
|------\n\
| \n\
| \n\
| \n\
| \n\
|_____"}
return stages[tries]
def display_current_progress(tries,word_completion):
print(display_hangman(tries))
print(word_completion)
print("\n")
def play(selected_word):
word_completion = "." * len(selected_word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
# Print out message to the user.
print("Let's play some Hangman!")
display_current_progress(tries,word_completion)
while not guessed and tries > 0:
#Ask user for initial guess.
guess = input("Please guess a letter or word: ").upper()
#Check to see if guess is a single character.
if len(guess) == 1 and guess.isalpha():
#Check to see if this letter has already been guessed.
if guess in guessed_letters:
print("You already guessed this letter")
#If guessed letter is not in word, reduce tries variable by 1 and add it to guessed letters.
elif guess not in selected_word:
print(guess, "is not in the word.")
tries -= 1
guessed_letters.append(guess)
#If the guessed letter is in the word, let the user know and add it to the guessed letters list.
#Fill in word completion with guessed letter.
else:
print("Good job,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list=list(word_completion)
indices= [i for i, letter in enumerate(selected_word) if letter == guess]
for index in indices:
word_as_list[index]=guess
word_completion="".join(word_as_list)
#If they've guessed it correctly, change guessed condition to True.
if "." not in word_completion:
guessed = True
#If they're guessing a whole word and it's not the correct length let them know.
elif len(guess) != len(selected_word) and guess.isalpha():
print("Guess is not the correct length")
#If the guessed word is the correct length.
elif len(guess) == len(selected_word) and guess.isalpha():
#If they've already guessed this word then let them know.
if guess in guessed_words:
print("You already guess the word", guess)
#If they've guessed incorrectly, let them know and add it to guessed words. Also decrease tries variable.
elif guess !=selected_word:
print(guess,"is not the word.")
tries-=1
guessed_words.append(guess)
#If they've guessed it correctly, change guessed variable to True and update word completion.
else:
guessed=True
word_completion=selected_word
#If they haven't entered a valid guess let them know.
else:
print("Not a valid guess.")
display_current_progress(tries,word_completion)
if guessed:
print("Congrats, you did it!")
else:
print("Sorry, you lost. The word was " + selected_word)
# Run the code and ask if the individual would like to run again.
def main():
word=get_word()
play(word)
while input("Play Again? (Y/N) ").upper()=="Y":
word=get_word()
play(word)
if __name__ == "__main__":
main()
|
2a6085a5ccaca023de72b93ca2ae6f1a184b3e4b | PurnaKoteswaraRaoMallepaddi/Design-1 | /HashMap.py | 1,954 | 3.84375 | 4 | """
Time complexity:
Put: O(1)
Get: O(m) where m is the hashmap size we difined
Remove: O(m)
Space complexity:
O(1) for every thing.
"""
class Node:
def __init__(self,tup = [-1,-1],next = None):
self.next = next
self.tup = tup
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.Map = [Node() for i in range(0,1000)]
self.chabi = 1000
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hashkey = key % self.chabi
temp = self.Map[hashkey]
while temp.next is not None:
if temp.next.tup[0] == key:
temp.next.tup[1] = value
return None
temp = temp.next
temp.next = Node(tup = [key,value])
return None
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
hashkey = key % self.chabi
temp = self.Map[hashkey]
while temp.next is not None and temp.next.tup[0] != key:
temp = temp.next
if temp.next is None:
return -1
else:
return temp.next.tup[1]
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
hashkey = key % self.chabi
temp = self.Map[hashkey]
while temp.next is not None and temp.next.tup[0] != key:
temp = temp.next
if temp.next is None:
return None
else:
temp.next = temp.next.next
return None
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key) |
c9d723798eae1de520aa751d82e474fe26109531 | mkodekar/PythonPractice | /Loops.py | 254 | 3.921875 | 4 | condition = 1
while condition <= 20:
print(condition)
condition += 1
while True:
print('doing stuff')
break
exampleList = [1, 2, 3, 4, 5, 6, ]
for eachNumber in exampleList:
print(eachNumber)
for x in range(1, 3):
print(x)
|
5e086b9d944b4c3a54da5ff168dadfb709c7816e | BaoziSwifter/MyPythonLeetCode | /pythonLeetcode/88-合并两个有序数组.py | 1,582 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
cNum1 = nums1[:m]
nums1[:] = []
i,j = 0,0
while i < m and j < n:
if cNum1[i] < nums2[j]:
nums1.append(cNum1[i])
i += 1
else:
nums1.append(nums2[j])
j += 1
while i < m:
nums1.append(cNum1[i])
print("+")
i += 1
while j < n:
nums1.append(nums2[j])
j += 1
print("-")
if __name__ == '__main__':
s = Solution()
n1 = [1]
n2 = []
s.merge(n1,1,n2,0)
[print(">> %d" % i) for i in n1]
|
bdea67f523c17d67fe9d9f889e06cb1c783e2d33 | sugia/leetcode | /search-insert-position.py | 642 | 3.890625 | 4 | class Solution:
#given a list of integers and an integer
#return an integer
def searchInsert(self, A, target):
if len(A) == 0:
return 0
if target <= A[0]:
return 0
if target > A[-1]:
return len(A)
left = 0
right = len(A) - 1
while left + 1 < right:
mid = (left + right) >> 1
if A[mid] < target:
left = mid
elif A[mid] > target:
right = mid
else:
return mid
if A[left] == target:
return left
else:
return right
|
dba42242972435d05cfe70beadb2004aaaada03a | RalapIT/Python- | /Python基础源码/day02/homework/05.猜数字游戏.py | 252 | 3.84375 | 4 | import random
num2 = random.randint(1,999)
for i in range(10,0,-1):
num = int(input("请输入一个数字:"))
if(num < num2):
print("小了")
elif(num > num2):
print("大了")
else:
print("正确")
break |
a1f8ad2ff76084762e464981944419ef9777a68f | anuj-padmawar/Hackerrank_Python_codes | /itertools.product().py | 237 | 3.84375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product
A = raw_input().split()
A = list(map(int, A))
B = raw_input().split()
B = list(map(int, B))
for i in product(A, B):
print (i),
|
5ba9a5ba3be4b78e0c0073205aa13ad7aa0ed946 | qizongjun/Algorithms-1 | /Leetcode/Binary Search/#222-Count Complete Tree Nodes/main.py | 1,512 | 3.9375 | 4 | # coding=utf-8
'''
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last,
is completely filled, and all nodes in the last level are as far left as
possible. It can have between 1 and 2h nodes inclusive at the last level h.
'''
'''
还是靠牛客网看了才做出来...
因为是完全树所以必然是由数个满树组成的
先找到左子树的高,再找到右子树的高
如果两高相等,则必然左子树是满树可以直接计算,右子树继续递归
如果两高不等,则必然右子树是满树可以直接计算,左子树继续递归
最后算出结果
Beat 75.54%
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findLeft(self, root):
if not root:
return 0
return self.findLeft(root.left) + 1
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left = self.findLeft(root.left)
right = self.findLeft(root.right)
zuo, you = 0, 0
if left == right:
zuo = 2 ** left - 1
you = self.countNodes(root.right)
else:
zuo = 2 ** right - 1
you = self.countNodes(root.left)
return zuo + you + 1
|
62babbf6532c5a5fcb41b58b26221c127034c2a9 | rlankin/advent-of-code | /2015/day1.py | 652 | 3.515625 | 4 | def part_1():
floor = 0
with open('input/day1_input.txt', 'r') as f:
while True:
direction = f.read(1)
if not direction:
break
floor += 1 if direction == "(" else -1
print("Part 1: " + str(floor))
def part_2():
floor = 0
count = 0
with open('input/day1_input.txt', 'r') as f:
while True:
direction = f.read(1)
if not direction:
break
count += 1
floor += 1 if direction == "(" else -1
if floor == -1:
break
print("Part 2: " + str(count))
part_1()
part_2()
|
807aee2b956adf7427a93928566a3614406a7bf1 | welchsoft/assignment-5.4.2018 | /bonus/descriptive.py | 1,017 | 4 | 4 | #set up the dictionary
number_names = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen',
19 : 'nineteen', 20 : 'twenty',
30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty',
70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
#take user input
try:
num = int(input("Enter a number between 1 and 100: "))
except ValueError:
print("not a valid number")
#parse through the values and select the right names from the dictionary
if int(num) > 100 or int(num) < 0:
print("you swindled me, now results may not be accurate")
if num<20:
print(number_names[num])
if (num < 100):
if num % 10 == 0:
print(number_names[num])
else:
print( number_names[num // 10 * 10] + ' ' + number_names[num % 10])
|
1502c118ab8e83c65f2a0fb257adad98ba79dfd0 | FrankieZhen/Lookoop | /python/设计模式/适配器模式/adapter.py | 990 | 3.640625 | 4 | # coding:utf-8
# 2019-2-4
"""适配器让两个或多个不兼容的接口兼容"""
class Human(object):
def __init__(self, name):
self.name = name
def speak(self):
print('{} say hello.'.format(self.name))
class Mp3(object):
def __init__(self, name):
self.name = name
def play(self):
print("play song: {}".format(self.name))
class Computer(object):
def __init__(self, name):
self.name = name
def excute(self):
print('{} show message.'.format(self.name))
class Adapter(object):
"""统一接口"""
def __init__(self, obj, extend_method=None):
self.obj = obj
if extend_method:
self.__dict__.update(extend_method)
def main():
objects = []
human = Human('yauno')
mp3 = Mp3('young and beautiful')
computer = Computer('screen')
objects.append(Adapter(human, dict(excute=human.speak)))
objects.append(Adapter(mp3, dict(excute=mp3.play)))
objects.append(computer)
for obj in objects:
# print(obj)
obj.excute()
if __name__ == '__main__':
main() |
696dc7a0a52d9e11019a636f7cb45ef88d4332ff | rafaelperazzo/programacao-web | /moodledata/vpl_data/390/usersdata/313/77354/submittedfiles/ex1.py | 193 | 3.796875 | 4 |
a = int(input( ' digite o valor de a ' ))
print( '%d' % a )
b = int(input(' digite o valor de b ' ))
print( '%d' % b )
c = int(input(' digite o valor de c ' ))
print( '%d' % c ):
|
7653991b2510b90937d12076b42daefa935d4b1c | mwilso17/python_work | /OOP and classes/users.py | 2,142 | 4.3125 | 4 | # Mike Wilson 20 June 2021
# this program simulates the creation of a user profile.
class User:
"""create a user profile"""
def __init__(self, first, last, user_name):
"""initialize self and attributes"""
self.first = first
self.last = last
self.user_name = user_name
self.login_attempts = 0
def describe_user(self):
"""describes the user"""
print(f"\nFirst Name: {self.first.title()}")
print(f"Last Name: {self.last.title()}")
print(f"Username: {self.user_name}")
def greet_user(self):
"""greets the user"""
print(f"Welcome, {self.first.title()}!")
def increment_login_attempts(self):
"""Increases the login_attempts by 1"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets login_attempts to 0"""
self.login_attempts = 0
class Admin(User):
"""Admin class profile with privileges."""
def __init__(self, first, last, user_name):
"""Initializes attributes"""
super().__init__(first, last, user_name)
self.privileges = Privileges()
class Privileges():
"""A class to store an admin's privileges"""
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print(f"- {privilege}")
else:
print("- This user has no privileges.")
my_user = User('mike', 'wilson', 'mikwil99')
my_user.describe_user()
my_user.greet_user()
their_user = User('bill', 'roberts', 'bilrob12')
their_user.describe_user()
their_user.increment_login_attempts()
their_user.increment_login_attempts()
print(f" Login Attempts: {their_user.login_attempts}")
print("Resetting Login Attempts...")
their_user.reset_login_attempts()
print(f" Login Attempts: {their_user.login_attempts}")
their_user.greet_user()
bill = Admin('bill', 'lee', 'billee22')
bill.describe_user()
bill.privileges.show_privileges()
print("\nAdding privileges...")
bill_privileges = [
'can reset passwords',
'can delete user',
'can add new user',
]
bill.privileges.privileges = bill_privileges
bill.privileges.show_privileges() |
62724d4cae2bc9a43f7bf497cd52300c09bcce53 | Web-Control/PythonCourse | /Kurs Pirple/Homeworks/importing/importing_csv.py | 2,061 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 17:43:35 2021
@author: psnma
"""
import csv
#Open and read csv file
#Open and reading csv file as a list
with open('username.csv', 'r') as csvfile:
csvReader = csv.reader(csvfile,dialect='excel', delimiter=';')
# =============================================================================
# #printing rows
# for row in csvReader:
# print(row)
# =============================================================================
for row in csvReader:
for value in row:
print(value,end=" ")
print("\n")
#Open and reading csv file as a dictionary
with open('username.csv','r') as csvfile:
csvReader = csv.DictReader(csvfile, delimiter = ";")
for row in csvReader:
for key in row.keys():
print(key, row[key])
#Save data to csv file:
#Saving line by line
with open('example_file1.csv', 'w', encoding='utf-8', newline='') as csvfile:
# initial "writer"
csvWriter = csv.writer(csvfile)
# seting column names
csvWriter.writerow(['Name', 'Surname', 'Age'])
# rows with values
csvWriter.writerow(['Simon', 'Chomej', '37'])
csvWriter.writerow(['Agnes', 'Bunch', '25'])
csvWriter.writerow(['John', 'Doe', '44'])
#Saving struct
struct = {'Name': 'Simon',
'Surname': 'Chomej',
'Age': '37',
'City': 'Olsztyn'}
struct2 = {'Name': 'Nicole',
'Surname': 'Jordan',
'Age': '29'}
struct3 = {'Name': 'Richard',
'Surname': 'Johnson',
'Age': '54',
'City': 'New York'}
structList = [struct, struct2, struct3]
with open('example_file2.csv', 'w', encoding='utf-8', newline='') as csvfile:
# define and save column names
fieldNames = ['Name', 'Surname', 'Age', 'City']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldNames)
csvwriter.writeheader()
# saving struct
for n in structList:
csvwriter.writerow(n)
|
8c2368dd1e03fa781c9f8fed1becb26ea7679d7b | MollyKate-G/file_managment_MG | /bank.py | 1,284 | 4.09375 | 4 | def bank_assign():
print("Welcome to MollyKate's Bank ATM")
balance = 0
choice = ''
def user_balance():
global balance
print(f'Available funds: $ {balance:,.2f}')
def user_deposit():
global balance
deposit_amount = (int(input("Enter deposit amount: ")))
balance = deposit_amount + balance
print(f'Your new balance is: $ {balance:,.2f}')
def user_withdraw():
global balance
withdrawl_amount = (int(input("Enter withdrawl amount: ")))
if balance <= withdrawl_amount:
print(f'Adequate funding not available. Your current balance is $ {balance:,.2f}.')
else:
balance = balance - withdrawl_amount
print(f'Your new balance is: $ {balance:,.2f}')
while choice.upper() != 'Q':
choice = input(""""Please select from the following menu options: "
(B)alance
(D)eposit
(W)ithdraw
(Q)uit
""")
if choice.upper() == 'B':
user_balance()
if choice.upper() == 'D':
user_deposit()
if choice.upper() == 'W':
user_withdraw()
if choice.upper() == 'Q':
print("Have a nice day! \nGoodbye")
return
|
4680b40d7469b3dbe4b0c02d8d421500220213d6 | Shiuay/Flower-Simlator | /Programme/bin/Meteo.py | 6,027 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 31 20:01:52 2016
@author: Roméo
"""
from random import *
def test_degage(duree):
tirage = random()
if tirage < 0.1 * (1 + (1 / -duree)):
return ["Nuageux3", 1]
if tirage < 0.3 * (1 + (1 / -duree)):
return ["Nuageux2", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Nuageux1", 1]
else:
return ["Dégagé", duree + 1]
def test_nuageux1(duree):
tirage = random()
if tirage < 0.03 * (1 + (1 / -duree)):
return ["Nuageux4", 1]
if tirage < 0.1 * (1 + (1 / -duree)):
return ["Nuageux3", 1]
if tirage < 0.3 * (1 + (1 / -duree)):
return ["Nuageux2", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Dégagé", 1]
else:
return ["Nuageux1", duree + 1]
def test_nuageux2(duree):
tirage = random()
if tirage < 0.03 * (1 + (1 / -duree)):
return ["Nuageux5", 1]
if tirage < 0.1 * (1 + (1 / -duree)):
return ["Nuageux4", 1]
if tirage < 0.3 * (1 + (1 / -duree)):
return ["Nuageux3", 1]
if tirage < 0.53 * (1 + (1 / -duree)):
return ["Dégagé", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Nuageux1", 1]
else:
return ["Nuageux2", duree + 1]
def test_nuageux3(duree):
tirage = random()
if tirage < 0.1 * (1 + (1 / -duree)):
return ["Nuageux5", 1]
if tirage < 0.3 * (1 + (1 / -duree)):
return ["Nuageux4", 1]
if tirage < 0.37 * (1 + (1 / -duree)):
return ["Dégagé", 1]
if tirage < 0.53 * (1 + (1 / -duree)):
return ["Nuageux1", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Nuageux2", 1]
else:
return ["Nuageux3", duree + 1]
def test_nuageux4(duree):
tirage = random()
if tirage < 0.3 * (1 + (1 / -duree)):
return ["Nuageux5", 1]
if tirage < 0.32 * (1 + (1 / -duree)):
return ["Nuageux1", 1]
if tirage < 0.37 * (1 + (1 / -duree)):
return ["Nuageux2", 1]
if tirage < 0.53 * (1 + (1 / -duree)):
return ["Nuageux3", 1]
if tirage < 0.55 * (1 + (1 / -duree)):
return ["Pluvieux2", 1]
if tirage < 0.6 * (1 + (1 / -duree)):
return ["Pluvieux3", 1]
if tirage < 0.9 * (1 + (1 / -duree)):
return ["Pluvieux4", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Pluvieux5", 1]
else:
return ["Nuageux4", duree + 1]
def test_nuageux5(duree):
tirage = random()
if tirage < 0.02 * (1 + (1 / -duree)):
return ["Nuageux2", 1]
if tirage < 0.07 * (1 + (1 / -duree)):
return ["Nuageux3", 1]
if tirage < 0.23 * (1 + (1 / -duree)):
return ["Nuageux4", 1]
if tirage < 0.27 * (1 + (1 / -duree)):
return ["Pluvieux3", 1]
if tirage < 0.35 * (1 + (1 / -duree)):
return ["Pluvieux4", 1]
if tirage < 1 * (1 + (1 / -duree)):
return ["Pluvieux5", 1]
else:
return ["Nuageux5", duree + 1]
def test_pluvieux1(duree):
tirage = random()
if tirage < 0.85 * (1 - (1 + (1 / -duree**1.5))):
return ["Pluvieux2", duree + 1]
if tirage < 1 * (1 - (1 + (1 / -duree**0.52))):
return ["Pluvieux1", duree + 1]
else:
return ["Dégagé", 1]
def test_pluvieux2(duree):
tirage = random()
if tirage < 0.85 * (1 - (1 + (1 / -duree**1.5))):
return ["Pluvieux3", duree + 1]
if tirage < 1 * (1 - (1 + (1 / -duree**0.52))):
return ["Pluvieux2", duree + 1]
else:
return ["Pluvieux1", duree + 1]
def test_pluvieux3(duree):
tirage = random()
if tirage < 0.85 * (1 - (1 + (1 / -duree**1.5))):
return ["Pluvieux4", duree + 1]
if tirage < 1 * (1 - (1 + (1 / -duree**0.52))):
return ["Pluvieux3", duree + 1]
else:
return ["Pluvieux2", duree + 1]
def test_pluvieux4(duree):
tirage = random()
if tirage < 0.85 * (1 - (1 + (1 / -duree**1.5))):
return ["Pluvieux5", duree + 1]
if tirage < 1 * (1 - (1 + (1 / -duree**0.52))):
return ["Pluvieux4", duree + 1]
else:
return ["Pluvieux3", duree + 1]
def test_pluvieux5(duree):
tirage = random()
if tirage < 1 * (1 - (1 + (1 / -duree**0.52))):
return ["Pluvieux5", duree + 1]
else:
return ["Pluvieux4", duree + 1]
def degage(meteo):
if meteo[0] == "Dégagé":
return True
else:
return False
def nuageux(meteo):
if meteo[0].startswith('Nuageux'):
return True
else:
return False
def pluvieux(meteo):
if meteo[0].startswith('Pluvieux'):
return True
else:
return False
def test_temps(meteo):
changement = True
if meteo[0] == "Dégagé" and changement:
meteo = test_degage(meteo[1]+1)
changement = False
if meteo[0] == "Nuageux1" and changement:
meteo = test_nuageux1(meteo[1]+1)
changement = False
if meteo[0] == "Nuageux2" and changement:
meteo = test_nuageux2(meteo[1]+1)
changement = False
if meteo[0] == "Nuageux3" and changement:
meteo = test_nuageux3(meteo[1]+1)
changement = False
if meteo[0] == "Nuageux4" and changement:
meteo = test_nuageux4(meteo[1]+1)
changement = False
if meteo[0] == "Nuageux5" and changement:
meteo = test_nuageux5(meteo[1]+1)
changement = False
if meteo[0] == "Pluvieux1" and changement:
meteo = test_pluvieux1(meteo[1]+1)
changement = False
if meteo[0] == "Pluvieux2" and changement:
meteo = test_pluvieux2(meteo[1]+1)
changement = False
if meteo[0] == "Pluvieux3" and changement:
meteo = test_pluvieux3(meteo[1]+1)
changement = False
if meteo[0] == "Pluvieux4" and changement:
meteo = test_pluvieux4(meteo[1]+1)
changement = False
if meteo[0] == "Pluvieux5" and changement:
meteo = test_pluvieux5(meteo[1]+1)
changement = False
return meteo |
3c3f1c5542c94fdcc8467a916bf625af3e826648 | Agoming/python-note | /3.高级语法/多线程和多进程/多线程案例1-18/15.py | 840 | 3.546875 | 4 | # encoding:utf-8
# 可重入锁,当同一个线程在未释放同一把锁的情况下,可再次申请的操作
import threading
import time
class MyThread(threading.Thread):# 继承多线程写法
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):# 申请超时超过一秒则不申请
num = num+1
msg = self.name +"set num to"+str(num)
print(msg)
mutex.acquire() # 在同一把锁还未释放的时候,再次申请同一把锁
mutex.release() # 不管释放的是否是同一把锁,你申请了多少次就要释放多少次
mutex.release()
num = 0
mutex = threading.RLock()# Rlock = 可重入锁
def testTh():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
testTh() |
9f64a972565f160af0b5af30acaff4a8d5a03e6b | harrisonmk/ListaPython | /src/Lista.py | 4,762 | 3.625 | 4 | from No import No
class Lista:
def __init__(self):
self.primeiroNo = None
self.ultimoNo = None
def isEmpty(self):
return self.primeiroNo is None
def tamanho(self):
atual = self.primeiroNo
cont = 0
while atual is not None:
cont = cont + 1
atual = atual.getProx()
return cont
def insereNoComeco(self, valor):
novoNo = No(valor)
if self.isEmpty():
self.primeiroNo = self.ultimoNo = novoNo
else:
novoNo.setProx(self.primeiroNo)
self.primeiroNo = novoNo
def insereNoFinal(self, valor):
novoNo = No(valor)
if self.isEmpty():
self.primeiroNo = self.ultimoNo = novoNo
else:
self.ultimoNo.setProx(novoNo)
self.ultimoNo = novoNo
def removeComeco(self):
if self.isEmpty():
print("Impossivel Remover Lista Vazia")
primeiroValorNo = self.primeiroNo.getElemento()
if self.primeiroNo == self.ultimoNo:
self.primeiroNo = self.ultimoNo = None
else:
self.primeiroNo = self.primeiroNo.getProx()
return primeiroValorNo
def removeFinal(self):
if self.isEmpty():
print("Impossivel Remover Lista Vazia")
ultimoValorNo = self.ultimoNo.getElemento()
if self.primeiroNo is self.ultimoNo:
self.primeiroNo = self.ultimoNo = None
else:
noAtual = self.primeiroNo
while noAtual.getProx() != self.ultimoNo:
noAtual = noAtual.getProx()
noAtual.setProx(None)
self.ultimoNo = noAtual
return ultimoValorNo
def busca(self, valor):
if self.isEmpty == True:
return None
i = self.primeiroNo
while i != None:
if i.getElemento() == valor:
return i
i = i.getProx()
return None
def listar(self):
if self.primeiroNo == None:
print("Lista Vazia")
else:
temp = self.primeiroNo
while temp != None:
print("Valor: ", temp.getElemento())
temp = temp.getProx()
def __str__(self):
if self.isEmpty():
return "Lista Vazia"
noAtual = self.primeiroNo
palavra = "a lista eh: "
while noAtual is not None:
palavra += str(noAtual.getElemento()) + " "
noAtual = noAtual.getProx()
return palavra
def bubleSortPython(self, arraytoSort):
swapFlag = True
while swapFlag:
swapFlag = False
for i in range(len(arraytoSort) - 1):
if arraytoSort[i] > arraytoSort[i + 1]:
arraytoSort[i], arraytoSort[i + 1] = arraytoSort[i + 1], arraytoSort[i]
print("Swapped: {} with {}".format(arraytoSort[i], arraytoSort[i + 1]))
swapFlag = True
return arraytoSort
def insertion_sort(self, list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i + 1] = list[i]
list[i] = value
i = i - 1
else:
break;
def mergeSorte(self, a, b):
resultado = None;
if (a == None):
return b
if (b == None):
return a;
if (a.elemento <= b.elemento):
resultado = a
resultado.Prox = mergeSorte(a.Prox, b)
else:
resultado = b;
resultado.Prox = mergeSorte(a, b.Prox)
return resultado
def mergeSort(self, h):
if (h == None or h.prox == None):
return h
meio = getMiddle(h)
proxDoMeio = meio.getProx()
meio.Prox = None
esquerda = mergeSort(h)
direita = mergeSort(proxDoMeio)
sortedlist = mergeSorte(esquerda, direita)
return sortedlist
def getMiddle(self, h):
if (h == None):
return h
parteRapida = h.getProx()
parteLenta = h
while (parteRapida != None):
parteRapida = parteRapida.getProx();
if (parteRapida != None):
parteLenta = parteLenta.getProx();
parteRapida = parteRapida.getProx();
return parteLenta;
def sort1(self,array):
for p in range(0, len(array)):
current_element = array[p]
while p > 0 and array[p - 1] > current_element:
array[p] = array[p - 1]
p -= 1
array[p] = current_element |
bb79d4598bd0d766341f0386fcb15bacd98f555f | famaf/Modelos_Simulacion_2016 | /Practico_06/ejercicio04.py | 2,594 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import random
import math
from distribuciones import *
def generarM():
"""
Genera M tq' M = {n : U1 <= U2 <= ... <= Un-1 > Un}
"""
n = 2
U = random.random() # Un-1
Un = random.random() # Un
while U <= Un:
n += 1
U = Un # U pasa a ser Un (nuevo Un-1)
Un = random.random() # Generamos un nuevo valor Un
M = n
return M
def estimacion01():
"""
Ejercicio 4 con la Generacion de M.
"""
n = 1000 # Simulaciones
X = generarM()
M = X # Media Muestral (valor inicial: M(1) = X1)
S_cuadrado = 0 # Varianza Muestral (valor inicial: S_cuadrado(1) = 0)
# Calculamos M(n) y S_cuadrado(n)
for j in xrange(2, n+1):
X = generarM()
A = M
M += (X - M)/float(j)
S_cuadrado = (1 - 1.0/(j-1))*S_cuadrado + j*((M-A)**2)
S = math.sqrt(S_cuadrado) # Desviacion Estandar Muestral (sigma)
IC = (M - 1.96*(S/math.sqrt(n)) , M + 1.96*(S/math.sqrt(n)))
return M, S_cuadrado, IC
# IC = (Xbarra - Z_alfa/2 * (S/sqrt(n)), Xbarra + Z_alfa/2 * (S/sqrt(n)))
# Longitud
# 2 * Z_alfa/2 * S/sqrt(n)
# Longitud de a lo sumo d
# 2 * Z_alfa/2 * S/sqrt(n) <= d
def estimacion02():
"""
Ejercicio 4 con la Poisson.
"""
n = 1000 # Simulaciones
X = math.e * poisson(1)
M = X # Media Muestral (valor inicial: M(1) = X1)
S_cuadrado = 0 # Varianza Muestral (valor inicial: S_cuadrado(1) = 0)
# Calculamos M(n) y S_cuadrado(n)
for j in xrange(2, n+1):
X = math.e * poisson(1)
A = M
M += (X - M)/float(j)
S_cuadrado = (1 - 1.0/(j-1))*S_cuadrado + j*((M-A)**2)
S = math.sqrt(S_cuadrado) # Desviacion Estandar Muestral (sigma)
IC = (M - 1.96*(S/math.sqrt(n)) , M + 1.96*(S/math.sqrt(n)))
return M, S_cuadrado, IC
def puntoC(n):
a = 0
for _ in xrange(n):
a += poisson(1)
return math.e *(a/float(n))
def printEstimacion01():
M, S_cuadrado, IC = estimacion02()
print("ESTIMACION CON LA POISSON(1)")
print("### e =", math.e, "###")
print("Media Muestral =", M)
print("Varianza Muestral =", S_cuadrado)
print("Intervalo de Confianza (IC) =", IC)
print("")
def printEstimacion02():
M, S_cuadrado, IC = estimacion01()
print("\nESTIMACION CON LA GENERACION DE M")
print("### e =", math.e, "###")
print("Media Muestral =", M)
print("Varianza Muestral =", S_cuadrado)
print("Intervalo de Confianza (IC) =", IC)
print("")
printEstimacion01()
printEstimacion02()
print("Con Poisson(1) --> E[M] =", puntoC(1000))
|
2225823a13a994841afcc2491fef853f637eb591 | Shihab-Munna/Learning-Python3- | /namota.py | 108 | 3.71875 | 4 | n = int (input("Please enter a number :"))
c = 1
while (c <= 10):
print( n,'X' ,c ,'=', n*c)
c+=1
|
e889b83948245996339bef194c3a89b2cbe97431 | quockhanhtn/artificial_intelligence_exercise | /ex4_n_queens_with_and_or_search/ex4_main.py | 7,069 | 4.03125 | 4 | #nguồn: code thầy phần class NQueensProblem:
# Solve N-queens problems using AND-OR search algorithm
'''
YOUR TASKS:
1. Read the given code to understand
2. Implement the and_or_graph_search() function
3. (Optinal) Add GUI, animation...
'''
import tkinter as tk
from PIL import ImageTk, Image
import time as t
class NQueensProblem:
"""The problem of placing N queens on an NxN board with none attacking each other.
A state is represented as an N-element array, where a value of r in the c-th entry means there is a queen at column c,
row r, and a value of -1 means that the c-th column has not been filled in yet. We fill in columns left to right.
Sample code: iterative_deepening_search(NQueensProblem(8))
Result: <Node (0, 4, 7, 5, 2, 6, 1, 3)>
"""
def __init__(self, N):
# self.initial = initial
self.initial = tuple([-1] * no_of_queens) # mảng có giá trị là -1
self.N = N #số con hậu
def actions(self, state):
"""In the leftmost empty column, try all non-conflicting rows."""
if state[-1] is not -1:#thêm đủ N con hậu rồi
return [] # All columns filled; no successors
else:
col = state.index(-1)#lấy giá trị cột cầu thêm tiếp theo
# return [(col, row) for row in range(self.N)
return [row for row in range(self.N)#trả về một list các hành động
if not self.conflicted(state, row, col)]
def goal_test(self, state):
"""Check if all columns filled, no conflicts."""
if state[-1] is -1:#chưa là goal state
return False
return not any(self.conflicted(state, state[col], col)#trả về False nếu có ít nhất 1 cặp con hâu tấn công được nhau
for col in range(len(state)))
def result(self, state, row):
"""Place the next queen at the given row."""
col = state.index(-1)#lấy vị trí -1 tìm thấy đầu tiên
new = list(state[:])
new[col] = row#di chuyển con hậu lên hàng được truyền vào
return tuple(new)#trả về state sau khi hành động
def conflicted(self, state, row, col):
"""Would placing a queen at (row, col) conflict with anything?"""
return any(self.conflict(row, col, state[c], c)#xét các con hậu có tấn công được nhau hay không
for c in range(col))#trả về true nếu có một con hậu cái thể tấn công nhau
def conflict(self, row1, col1, row2, col2):
"""Would putting two queens in (row1, col1) and (row2, col2) conflict?"""
return (row1 == row2 or # same row
col1 == col2 or # same column
row1 - col1 == row2 - col2 or # same \ diagonal
row1 + col1 == row2 + col2) # same / diagonal
def value(self, node):
"""Return (-) number of conflicting queens for a given node"""
num_conflicts = 0
for (r1, c1) in enumerate(node.state):
for (r2, c2) in enumerate(node.state):
if (r1, c1) != (r2, c2):
num_conflicts += self.conflict(r1, c1, r2, c2)
return -num_conflicts
''' IMPLEMENT THE FOLLOWING FUNCTION '''
def and_or_graph_search(problem):
"""See [Figure 4.11] for the algorithm"""
global timeN
timeN = t.time()
state = problem.initial
path = []
return (or_search(state, problem, path))
def or_search(state, problem, path):
global clickStop
global cStop
if problem.goal_test(state):
showGoal(state, problem.N, t.time())
if (clickStop == True):
cStop = True
return []
#if state in path: return None
plans = []
for action in problem.actions(state):
#plan = and_search([problem.result(state, action)], problem, [state] + path)
plan = and_search([problem.result(state, action)], problem, path)
if plan is not None:
plans.append([action, plan])
if cStop == True:
break
if len(plans) > 0:
return plans
return None
def and_search(states, problem, path):
plan = {}
for s in states:
plan[s] = or_search(s, problem, path)
if plan[s] is None:
return None
return plan
def showGoal(solution, no, time):
global win
global listlb
global img
global lbtime
global timeN
global timeT
global no_goal
global lbno_goal
no_goal += 1
lbno_goal.config(text=no_goal)
timeT += time - timeN
lbtime.config(text=timeT)
for i in range(len(solution)):
for j in range(len(solution)):
if (i + j) % 2 == 1:
if j == solution[i]:
listlb[i*no + j].config(image=img[2])
else:
listlb[i*no + j].config(image=img[0])
else:
if j == solution[i]:
listlb[i*no + j].config(image=img[3])
else:
listlb[i*no + j].config(image=img[1])
win.update()
t.sleep(0.1)
timeN = t.time()
def loadGui(no):
global win
global listlb
str = no.__str__() + '-Queens'
win.title(str)
img = []
img.append(ImageTk.PhotoImage(Image.open("Photo/1.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/2.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/3.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/4.PNG")))
for i in range(no):
for j in range(no):
if (i + j) % 2 == 1:
listlb.append(tk.Label(win, image=img[0]))
listlb[-1].grid(column=i, row=j)
else:
listlb.append(tk.Label(win, image=img[1]))
listlb[-1].grid(column=i, row=j)
win.update()
def btnStop_click():
#t.sleep(60)
global clickStop
clickStop = True
if __name__ == '__main__':
clickStop = False
cStop = False
listlb = []
win = tk.Tk()
img = []
timeN = t.time()
timeT = 0
no_goal = 0
img.append(ImageTk.PhotoImage(Image.open("Photo/1.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/2.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/3.PNG")))
img.append(ImageTk.PhotoImage(Image.open("Photo/4.PNG")))
no_of_queens =15;
loadGui(no_of_queens)
lbtext = tk.Label(win, text=" Time: ")
lbtext.grid(column=no_of_queens + 1, row=1)
lbtime = tk.Label(win, text="0", width=20)
lbtime.grid(column=no_of_queens + 2, row=1)
lbno_goal_text = tk.Label(win, text=" No_of_goal: ")
lbno_goal_text.grid(column=no_of_queens + 1, row=3)
lbno_goal = tk.Label(win, text="0", width=20)
lbno_goal.grid(column=no_of_queens + 2, row=3)
btnStop = tk.Button(win, command=btnStop_click, text="Break")
btnStop.grid(column=no_of_queens + 2, row=5)
win.update()
problem1 = NQueensProblem(no_of_queens)
result2 = and_or_graph_search(problem1)
print(result2)
win.mainloop() |
d3b3f1a947ca07038d4244ee054da6bade648fae | ghanshyamdhiman/gsdss | /c1.py | 401 | 3.71875 | 4 | import calendar
import datetime
yy = 2020
mm = 12
the_cal = calendar.TextCalendar(calendar.SUNDAY)
cal_display = the_cal.formatmonth(2020,11)
# display the calendar
print(calendar.month(yy, mm))
print(cal_display)
#print(the_cal.today())
week_days = the_cal.iterweekdays()
def print_time(r_time):
return datetime.datetime(r_time)
the_time = [2020,12,29]
print(print_time(the_time)) |
bcc21417bb7b70eb6c177ee3fe4c1f23dba0f353 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/4e221cf14bc743ca9ba7a63e749fcad0.py | 269 | 3.703125 | 4 | def sieve(n):
ints = range(2, n)
count = 0
while count < len(ints):
currentprime = ints[count]
multiple = currentprime
while multiple < n:
multiple = multiple + currentprime
if multiple in ints:
ints.remove(multiple)
count = count + 1
return ints
|
c8f2e4044bdb4db9edcad0e5a4b63a187be724a8 | caiosainvallio/estudos_programacao | /USP_coursera/primalidade.py | 173 | 3.78125 | 4 | num = int(input('Digite um número inteiro: '))
i = 1
div = 0
while i <= num:
if num % i == 0:
div += 1
i += 1
if div == 2:
print('primo')
else:
print('não primo')
|
c0e736f6de3766abfe94b01431e9d34046e53c06 | RyanPretzel/Ch.01_Version_Control | /1.2_turtorial.py | 1,998 | 4.1875 | 4 | '''
Modify the starter code below to create your own cool drawing
and then Pull Request it to your instructor. Make sure you
keep the last two lines of code. Your first and last name must be written on your art.
The last line keeps the window open until you click to close.
Turtle Documentation: https://docs.python.org/3.3/library/turtle.html?highlight=turtle
'''
import turtle
def draw_circle(turtle, color, size, x, y):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x,y)
turtle.begin_fill()
turtle.pendown()
turtle.circle(size)
turtle.penup()
turtle.end_fill()
turtle.pendown()
def draw_rectangle(turtle, color, x1, y1, x2, y2):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x1,y1)
turtle.begin_fill()
turtle.pendown()
turtle.goto(x1,y2)
turtle.goto(x2,y2)
turtle.goto(x2,y1)
turtle.goto(x1,y1)
turtle.penup()
turtle.end_fill()
turtle.pendown()
tom = turtle.Turtle()
tom.shape("turtle")
tom.speed(500)
draw_circle(tom, "yellow", 200, 0, -12) #makes outer circle
draw_circle(tom, "white", 185, 0, 0)
draw_rectangle(tom, "yellow", -200, 180, -30, 190) #makes horizontal line
draw_rectangle(tom, "yellow", -5, 20, 5, 380) #makes vertical line
draw_rectangle(tom, "white", -5, 360, -15, 400) #makes the little space at the top
tom.penup() #making the bottom of the "Q"
tom.color("yellow")
tom.fillcolor("yellow")
tom.goto(10, 0)
tom.begin_fill()
tom.pendown()
tom.goto(150, -51)
tom.goto(225, -61)
tom.goto(201, -68)
tom.goto(152,-70)
tom.goto(100, -60)
tom.goto(30, -30)
tom.goto(0,-25)
tom.goto(-50, -30)
tom.goto(-58, -28)
tom.goto(-55,-20)
tom.goto(-20,0)
tom.goto(10,0)
tom.penup()
tom.end_fill()
tom.penup()
tom.goto(0,-120)
tom.color('black')
tom.write("Ryan Muetzel", align="center", font=(None, 16, "bold"))
tom.goto(420,-400)
tom.write("RIP TOM 2.0", align="center", font=(None, 12)) #hehe
tom.goto(0,-160)
turtle.Screen().exitonclick() |
c295dda94ef5b4fbbb4a35fba9653cb986bf9d65 | Vick1165/downloadMp3Files | /mp3.py | 1,622 | 3.53125 | 4 | import requests,re
from bs4 import BeautifulSoup
'''
URL of the archive web-page which provides link to
all mp3 files. It would have been tiring to
download each video manually.
In this example, we first crawl the webpage to extract
all the links and then download mp3 files.
'''
# specify the URL of the archive here
archive_url = "https://www.soundsmarathi.com/noisy-sounds.html"
def get_video_links():
# create response object
r = requests.get(archive_url)
# create beautiful-soup object
soup = BeautifulSoup(r.content, 'html.parser')
# filter the link sending with .mp3 and save url into linkss
linkss = [a['href'] for a in soup.find_all('a', attrs={'href':re.compile(".mp3$")})]
return linkss
def download_video_series(linkss):
for link in linkss:
'''iterate through all links in video_links
and download them one by one'''
# obtain filename by splitting url and getting
# last string
file_name = link.split('/')[-1]
print("Downloading file:%s" % file_name)
# create response object
r = requests.get(link, stream=True)
# download started
with open('H:\\NS production\\' + file_name, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024 * 1024):
if chunk:
f.write(chunk)
print("%s downloaded!\n" % file_name)
print("All videos downloaded!")
return
if __name__ == "__main__":
# getting all video links
video_links = get_video_links()
# download all videos
download_video_series(video_links)
|
8e03ab8d3b2e2c63aa8782aa26b5940be1ab21c9 | veera2508/AI-Lab | /S-1/191-S1.py | 2,274 | 3.515625 | 4 | '''
Decantation Problem
States - Represented as (a,b,c) where a is water in bucket 1, b is water in bucket 2, c is water in bucket 3
Actions - Transfer water completely from one bucket to another bucket given it has sufficient capacity [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]
Initial State - (8,0,0)
Goal State - 4 in any one of the buckets
'''
from collections import deque
#Data structure to store each state and child
class state:
def __init__(self, val, parent= None):
self.val = val
self.parent = parent
#Constants for the problem
capacity = (8, 5, 3)
actions = [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]
dis = set()
#Func to return list of all successor state for the given state
def next_states(s):
nextstates = []
for action in actions:
ns = [p for p in s.val]
if s.val[action[1]] < capacity[action[1]] and s.val[action[0]] >= 0:
if s.val[action[0]] > (capacity[action[1]] - s.val[action[1]]):
ns[action[0]] -= (capacity[action[1]] - s.val[action[1]])
ns[action[1]] += (capacity[action[1]] - s.val[action[1]])
else:
ns[action[1]] += s.val[action[0]]
ns[action[0]] = 0
if ns != s.val:
nextstates.append(state(ns, s))
return nextstates
#Func to check if goal state is reached
def goal(s):
if 4 in s.val:
return True
else:
return False
#Func to print the path
def printPath(s):
lst = []
while s!= None:
lst.append(s.val)
s = s.parent
lst.reverse()
for i in range(len(lst)-1):
print(lst[i], end = '->')
print(lst[i+1])
print()
#Func for the bfs search
def bfs(s):
q = deque()
dis.add(s)
q.append(s)
while len(q) != 0:
u = q.popleft()
nextstates = next_states(u)
for i in nextstates:
if i not in dis:
dis.add(i)
if goal(i):
printPath(i)
print()
return
q.append(i)
print('Enter the initial state as space seperated integers (Total <= 8 and Individual values <= (8,5,3)):')
st = input().split(' ')
st = [int(i) for i in st]
bfs(state(st))
|
517cff5cb7ad0680de6d860b7dec80f7428c33ed | Varobinson/Projects | /python 102/even-numbers.py | 112 | 3.6875 | 4 | numbers = [2, 5, 9, 4, 1]
even_numbers =[]
for number in numbers:
if number % 2 == 0:
print(number) |
8950a81dc01c7eb0345fcb15d5bc355c3b75aee4 | iStealerSn/codingbat-python-solutions | /List-2.py | 2,648 | 4.3125 | 4 | # List-2 solutions
"""
Medium python list problems -- 1 loop.. Use a[0], a[1], ... to access elements in a list, len(a) is the length.
"""
# count_evens
"""
Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
For example - count_evens([2, 1, 2, 3, 4]) → 3
"""
def count_evens(nums):
count = 0
for i in nums:
if i % 2 == 0:
count += 1
return count
# big_diff
"""
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
For example - big_diff([10, 3, 5, 6]) → 7
"""
def big_diff(nums):
return max(nums)-min(nums)
# centered_average
"""
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value. Use int division to produce the final average.
You may assume that the array is length 3 or more.
For example - centered_average([1, 2, 3, 4, 100]) → 3
"""
def centered_average(nums):
nums.remove(max(nums))
nums.remove(min(nums))
return (sum((nums)) / len(nums))
# sum13
"""
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky,
so it does not count and numbers that come immediately after a 13 also do not count.
For example - sum13([1, 2, 2, 1]) → 6
"""
def sum13(nums):
while 13 in nums:
if nums.index(13) < len(nums) - 1:
nums.pop(nums.index(13) + 1)
nums.pop(nums.index(13))
return sum(nums)
# sum67
"""
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and
extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.
For example - sum67([1, 2, 2]) → 5
"""
def sum67(nums):
sum_ = 0
position = False
for n in nums:
if n == 6:
position = True
continue
if n == 7 and position:
position = False
continue
if not position:
sum_ += n
return sum_
# has22
"""
Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
For example - has22([1, 2, 2]) → True
"""
def has22(nums):
found = False
for i in range(0,len(nums)-1):
if nums[i] == 2 and nums[i+1] == 2:
found = True
return found
# Thank you for looking up my solution |
bb37632b765c09abc8dc6eb142db3384451d83a0 | Burseylj/ProjectEuler | /P14.py | 650 | 3.703125 | 4 | #attempt at project euler problem 14
#for some reason the dynamic programming parts aren't helping
import time
start = time.time()
def collatzLength(x):
initialValue = x
length = 0
while x != 1:
x = collatzSequence(x)
length+= 1
return length +1
def collatzSequence(x):
if x & 1:
return (3*x +1)
else:
return (x/2)
biggest = 0
for i in range(1,1000000):
clt = collatzLength(i)
if clt > biggest:
biggest = clt
starting = i
elapsed = (time.time() - start)
print "found starting number %s with length %s in %s seconds" % (starting,biggest,elapsed)
|
55d84f25ae764f5aeb9fa18ec4e91ea761b8c053 | omarsinan/hackerrank | /submissions/time_conversion.py | 649 | 3.984375 | 4 | # author: Omar Sinan
# date: 26/08/2017
# description: HackerRank's "Time Conversion" Coding Challenge
#!/bin/python
import sys
def timeConversion(s):
t = 0
arr = s.split(':')
if "PM" in arr[len(arr) - 1]:
t = 1
arr[len(arr) - 1] = arr[len(arr) - 1].replace('PM', '')
else:
arr[len(arr) - 1] = arr[len(arr) - 1].replace('AM', '')
if t:
if not int(arr[0]) == 12:
arr[0] = str(int(arr[0]) + 12)
else:
if int(arr[0]) == 12:
arr[0] = "00"
return ":".join(str(item) for item in arr)
s = raw_input().strip()
result = timeConversion(s)
print(result)
|
1f278a96e70d21c27f09aea018dba6de1f74c311 | Adasumizox/ProgrammingChallenges | /codewars/Python/7 kyu/SquareEveryDigit/square_digits.py | 109 | 3.75 | 4 | def square_digits(num):
ret = ""
for x in str(num):
ret += str(int(x)**2)
return int(ret) |
f6002044c2b165fa4cc774811767f97d1c38606d | raveena17/workout_problems | /basic_python/primeSieve.py | 365 | 3.5 | 4 | def primeSieve(numberList):
if numberList == []:
return []
else:
prime = numberList[0]
return [prime] + primeSieve(sift(prime, numberList[1:]))
#call------- primeSieve(range(2, 100))
# output:------[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.