blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7c73a88b1896480031f1572c3994afcb1e2e9a00 | stekodyne/python-class | /exercises/solution_ex08_concurrency/subprocesses/encrypt.py | 2,903 | 3.515625 | 4 | """
encrypt.py - uses the subprocess module to encrypt multiple files in parallel.
"""
import getpass
import os
import sys
# TODO: import the subprocess module
import subprocess
# TODO: note the definition of the run_openssl() function. This function will
# be the target of the processes that you create.
# (no code change required)
def run_openssl(file, pw):
try:
# TODO: note how the input and output files are opened as
# `in_file` and `out_file`
# (no code change required)
with open(file, 'r') as in_file:
with open(file + '.aes', 'w') as out_file:
environ = os.environ.copy()
environ['secret'] = pw # store password in env variable
# TODO: call subprocess.Popen() to launch a process running
# openssl to encrypt the input file.
# For the `stdin` argument, pass in_file
# For the `stdout` argument, pass out_file
# Assign the returned Popen instance to a local variable.
# HINT: see slide 8-10
cmd = ['openssl', 'enc', '-e', '-aes256', '-pass', 'env:secret']
proc = subprocess.Popen(cmd, env=environ,
stdin=in_file, stdout=out_file)
# TODO: note that you don't need to write to or flush the
# Popen instance's standard input because openssl is reading
# from a file instead of a pipe.
# (no code change required)
# TODO: return the Popen instance
return proc
except Exception as e:
print('Problem encrypting', file, e)
raise
def main():
if len(sys.argv) == 1:
print('Usage: {} file...'.format(sys.argv[0]))
sys.exit(1)
pw = getpass.getpass() # prompts and reads without echoing input
# TODO: initialize a local variable named `procs` with an empty list
procs = []
# TODO: note the following loop over the command line arguments
# (no code changes required)
for file in sys.argv[1:]:
# TODO: Call run_openssl(), passing arguments file and password
# Save the returned Popen instance in a local variable.
# HINT: see slide 8-11
proc = run_openssl(file, pw)
# TODO: append the Popen instance to the `procs` list
procs.append(proc)
# TODO: loop over all the Popen instances in the `procs` list
for proc in procs:
# TODO: for each Popen instance, call the communicate() method to wait
# for the process to complete.
# HINT: you don't need to save the return values of communicate()
# because the processes are reading and writing directly to files.
proc.communicate()
print('Done encrypting', ' '.join(sys.argv[1:]))
if __name__ == '__main__':
main()
|
26aec7ce43dcc700806987187f196b5d546b2dc8 | 99zraymond/python-lesson-2 | /python_2_4.py | 543 | 4.625 | 5 | # Zackary Raymond chapter 2 lesson 2. excersise-2 2-8-2018
#Exercise 4: Please copy the link to your program and attach it for turn in. Assume that we execute the following assignment statements:
#width = 17
#height = 12.0
#For each of the following expressions, write the value of the expression and the type (of the value of the expression).
#width//2
#width/2.0
#height/3
#1 + 2 \* 5
#Use the Python interpreter to check your answers.
width = 17
height = 12
print (width//2)
print (width/2.0)
print (height/3)
print (1+2*5)
|
78dd33951ab6deec901dc2dcbc50a9745aef0938 | chadmccully/training | /beginner_lessons.py | 623 | 3.875 | 4 | #tuples and indexses
# numbers = [1,4,6,3,4]
# # for index, number in enumerate(numbers):
# # print(f'{index} - {number}')
# #
# # values = list('aeiou')
# #
# # ['a', 'e', 'i', 'o', 'u']
# # for index, vowel in enumerate(values):
# # ... print(f'{index} - {vowel}')
# number = 5
# if(number%2==0):
# isEven = True
# else:
# isEven = False
# #or
# isEven = True if number%2==0 else False
# #or
# isEven = number%2==0
# sum([12,34,56])
#
# number1 = 10
# number2 = 20
# sum = number1 + number2 <== this creates shadowing of the function sum(). You can do this better by including an underscore (sum_)
|
27eded1b392e124ba3abdcaff0fdd37563215185 | vipin26/python | /PYTHON/New folder/not practised/list75/1 list.py | 92 | 3.609375 | 4 | lis1=[23,34,45,56,67]
print lis1
print"printing list elements"
for i in lis1:
print i
|
9f667e7b8153624f51119d6d040502a366fe858d | AshishMaheshwari5959/Projects | /CH26_check_tic_tac_toe.py | 2,135 | 3.828125 | 4 | #import CH24_gameboards
import random
print("PLAYER 1 : X")
print("PLAYER 2 : O")
row1=[]
row2=[]
row3=[]
gameover=False
a=['X','O','_']
a1=random.choice(a)
row1.append(a1)
a2=random.choice(a)
row1.append(a2)
a3=random.choice(a)
row1.append(a3)
b1=random.choice(a)
row2.append(b1)
b2=random.choice(a)
row2.append(b2)
b3=random.choice(a)
row2.append(b3)
c1=random.choice(a)
row3.append(c1)
c2=random.choice(a)
row3.append(c2)
c3=random.choice(a)
row3.append(c3)
join1=" ".join(row1)
join2=" ".join(row2)
join3=" ".join(row3)
def displayBoard():
print(join1)
print("\n")
print(join2)
print("\n")
print(join3)
print("\n")
displayBoard()
def condition():
if a1==a2 and a1==a3 :
if a1=='X':
print("PLAYER 1 IS WINNER")
elif a1=='O':
print("PLAYER 2 IS WINNER")
elif a1==b1 and a1==c1:
if b1=='X':
print("PLAYER 1 IS WINNER")
elif b1=='O':
print("PLAYER 2 IS WINNER")
elif a1==b2 and a1==c3:
if b2=='X':
print("PLAYER 1 IS WINNER")
elif b2=='O':
print("PLAYER 2 IS WINNER")
elif b1==b2 and b1==b3:
if b1=='X':
print("PLAYER 1 IS WINNER")
elif b1=='O':
print("PLAYER 2 IS WINNER")
elif c1==c2 and c1==c3:
if c1=='X':
print("PLAYER 1 IS WINNER")
elif c1=='O':
print("PLAYER 2 IS WINNER")
elif b2==a2 and b2==c2:
if b2=='X':
print("PLAYER 1 IS WINNER")
elif b2=='O':
print("PLAYER 2 IS WINNER")
elif a3==b3 and a3==c3:
if c3=='X':
print("PLAYER 1 IS WINNER")
elif c3=='O':
print("PLAYER 2 IS WINNER")
elif c1==b2 and c1==a3:
if c1=='X':
print("PLAYER 1 IS WINNER")
elif c1=='O':
print("PLAYER 2 IS WINNER")
else:
print("GAME IS EITHER DRAW OR INCOMPLETE")
condition()
|
a743cdf9b3d1137829d1e85ae14c212808d6ba16 | ammfat/KotaKode-Challange | /case-03.py | 1,388 | 3.609375 | 4 | #!/usr/bin/env python
def subsetTerbesar(inputList):
'''
Mengembalikan subset dari elemen tak bersebalahan
yang jika ditotal memiliki jumlah terbesar. Bila semua
elemen bernilai negatif, maka akan dikembalikan nilai 0
'''
subset = []
maksTotal = 0
for i in range(len(inputList)):
## Bagian 1
for j in inputList[i+2:]:
subset.append([inputList[i], j])
## Bagian 2
tempList = [inputList[i]]
sisiKanan = inputList[i+2:]
if len(sisiKanan) == 0:
continue
for t in range(0, len(sisiKanan), 2):
tempList.append(sisiKanan[t])
if tempList not in subset:
subset.append(tempList)
## Menemukan subset dengan total nilai antar elemen terbesar
for total in subset:
maksTotal = sum(total) if sum(total) > maksTotal else maksTotal
return maksTotal
def main():
testCase = [
[1, 2, 300, -400, 5], # 306
[3, 7, 4, 6, 5], # 13
[2, 1, 5, 8, 4], # 11
[3, 5, -7, 8, 10], # 15
[-1, -2, -3, -4, -22], # 0
[-2, 1, 2, 10, 22, 0], # 24
[0, 0, 0, 0, 0, 0] # 0
]
for t in testCase:
hasil = subsetTerbesar(t)
print(f'--> {hasil}')
# DRIVER CODE
if __name__ == "__main__":
main() |
7b1966ee824f64f14d51202886e24cafcd981566 | kausthub/Python-Sessions | /Day2/derived.py | 330 | 3.859375 | 4 | #How to created a derived class
#Here drclass() is derived from myclass defined in the classes.py example
#Same rules apply here as well
#Eg. of usage - a=drclass()
from classes import myclass
class drclass(myclass):
def surname(self,name):
global sur
sur=str(name)
def printsur(self):
print sur
|
b6c8ebac38345d119461ca2801a211c015b65e7b | Sofia-Ortega/mathDiscordBot | /math_game/generator.py | 2,456 | 3.953125 | 4 | """
Contains Generators for the equations
"""
from random import randint
def add_gen(rangeArray):
"""Takes array of min and max values. Returns str of unique 2 num equation and their sum"""
num1 = randint(rangeArray[0], rangeArray[1])
num2 = randint(rangeArray[0], rangeArray[1])
sum = num1 + num2
equation = str(num1) + " + " + str(num2) + " = "
return equation, sum
def subtract_gen(rangeArray):
"""Takes array of min and max values. Returns str of unique 2 num equation and their difference"""
num1 = randint(rangeArray[0], rangeArray[1])
num2 = randint(rangeArray[0], rangeArray[1])
diff = num1 - num2
equation = str(num1) + " - " + str(num2) + " = "
return equation, diff
def multiply_gen(rangeArray):
"""Takes array of min and max values. Returns str of unique 2 num equation and their product"""
num1 = randint(rangeArray[0], rangeArray[1])
num2 = randint(rangeArray[2], rangeArray[3])
product = num1 * num2
equation = str(num1) + " * " + str(num2) + " = "
return equation, product
def division_gen(rangeArray):
"""Takes array of min and max values. Returns str of unique 2 num equation and their quotient"""
quotient = randint(rangeArray[0], rangeArray[1])
num2 = randint(rangeArray[2], rangeArray[3])
num1 = quotient * num2
equation = str(num1) + " / " + str(num2) + " = "
return equation, quotient
# Level: [[add min and max], [subtract min and max], [multiply min and max], [divide min and max]]
levels = {
"easy": [[1, 10], [1, 10], [1, 10, 1, 10], [1, 10, 1, 10]],
"medium": [[1, 100], [1, 100], [1, 100, 1, 10], [1, 100, 1, 10]],
"hard": [[1, 1000], [1, 1000], [1, 100, 1, 100], [1, 100, 1, 100]]
}
#FIXME: in main, add eq_gen(difficulty) with difficulty gotten from user
def eq_gen(difficulty):
"""Takes in difficulty. Randomly returns sum_gen, subtract_gen, multiply_gen, or division_gen"""
options = {
1: add_gen(levels[difficulty][0]),
2: subtract_gen(levels[difficulty][1]),
3: multiply_gen(levels[difficulty][2]),
4: division_gen(levels[difficulty][3])
}
# randomly picks a generator from options
return options[randint(1, len(options))]
# # difficulty = input("easy, medium, hard")
# difficulty = "hard"
# for i in range(20):
#
# # print(add_gen(levels[difficulty][0]))
# eq, ans = eq_gen(difficulty)
# print(eq + " " + str(ans).ljust(20))
|
5e7f96cf94fa805e98ee0431f533096900e25cbd | ozanozd/Firestation-DSS | /utilities.py | 12,553 | 3.59375 | 4 | """
This module contains general utility functions for the entire program
"""
#Open close debugging , testing
IS_DEBUG = False
IS_TEST = False
#General constants initialization
NUMBER_OF_DISTRICT = 867 #Number of district for solvers
VIS_NUMBER_OF_DISTRICT = 975 #Number of district for visualization
#General library imports
import os
from math import radians, cos, sin, asin, sqrt
import random
import string
def get_current_directory():
"""
This function returns the current directory of the utilities.py
number_of_arguments = 0
num_of_return = 1
return_type = string , current directory
"""
dirpath = os.getcwd()
if IS_DEBUG == True:
print("current directory is : " + dirpath)
return dirpath
def generate_appropriate_pairs(from_district , to_district , distance , threshold):
"""
This function returns the pair of districts such that the distance between them is less than threshold returns it.
If dist(district_a , district_b ) < threshold and district_a < district_b the list only contains (district_a , district_b).
It takes 4 arguments:
i) from_district(list) : It contains all from_district id's
ii) to_district(list) : It contains all to_district id's
iii) distances(list) : It contains all the distances(m)
iv) threshold(integer) : If the distance between two district is greater than threshold distance , do not ask the query.
It returns 1 variable:
i) pair_array : A list , consisting of all the appropriate pairs
"""
pair_array = []
#Iterate over all enties
for i in range(len(distance)) :
district_1 = from_district[i]
district_2 = to_district[i]
#We found an appropriate pair if the following if statement is satisfied
if distance[i] <= threshold and district_1 < district_2 :
pair_array.append([district_1 , district_2])
return pair_array
def get_appropriate_pairs_da(from_district , to_district , distance , threshold):
"""
This function returns the pair of districts such that the distance between them is less than threshold returns it.
If dist(district_a , district_b ) < threshold and district_a < district_b the list only contains (district_a , district_b).
It takes 4 arguments:
i) from_district(list) : It contains all from_district id's
ii) to_district(list) : It contains all to_district id's
iii) distances(list) : It contains all the distances(m)
iv) threshold(integer) : If the distance between two district is greater than threshold distance , do not ask the query.
It returns 1 variable:
i) pair_array : A list , consisting of all the appropriate pairs
"""
pair_array = []
#Iterate over all enties
for i in range(len(distance)) :
district_1 = from_district[i]
district_2 = to_district[i]
#We found an appropriate pair if the following if statement is satisfied
if distance[i] <= threshold :
pair_array.append([district_1 , district_2])
return pair_array
def clean_query(duration):
"""
This takes duration list which consists of durations such as 8 mins etc. then it converts them to float(8)
"""
#Initialize variables
new_duration = []
#Clean each duration in the duration list
for i in range(len(duration)):
new_data = ""
for element in duration[i]:
if 48 <= ord(element) and ord(element) <= 57:
new_data += element
new_duration.append(float(new_data))
return new_duration
def seperate_appropriate_pairs(appropriate_pairs):
"""
This function seperates appropriate_pairs list into 2 lists : from_district , to_district
It takes 1 argument:
i) appropriate_pairs : A list , whose elements are list of length 2
It returns 2 variables:
i) from_district : A list , whose elements are ids of from_district
ii) to_district : A list , whose elements are ids of to_district
"""
#Initialize variables
from_district = []
to_district = []
for element in appropriate_pairs:
from_district.append(element[0])
to_district.append(element[1])
return from_district , to_district
def generate_availability_matrix(from_district , to_district , distance , threshold):
"""
This function creates availability matrix and returns it.
It takes 4 arguments:
i) from_district : A list , which consists of ids of from_districts
ii) to_district : A list , which consists of ids of to_districts
iii) distance : A list , which consists of distances between from_district and to_district
iv) threshold : An integer , which is the number that represents the maximum distances between two districts to call them appropriate
It returns 1 variable:
i) availability_matrix : A list of lists , which represents whether the distance between two districts within the threshold or not.It contains binary values
"""
# Initialize the availability_matrix
availability_matrix = []
temp_array = []
for i in range(NUMBER_OF_DISTRICT) :
temp_array.append(0)
for i in range(NUMBER_OF_DISTRICT) :
availability_matrix.append(list(temp_array))
if IS_DEBUG == True :
print("The number of rows in availability_matrix is " , len(availability_matrix))
print("The number of columns in availability_matrix is " , len(availability_matrix[0]))
pair_array = get_appropriate_pairs_da(from_district , to_district , distance , threshold)
if IS_DEBUG == True:
print("The number of availabile pairs is" , len(pair_array))
# Write the appropriate binary values in availability_matrix
for element in pair_array :
availability_matrix[element[0] - 1][element[1] - 1] = 1
return availability_matrix
def generate_risk_availability_matrix(from_districts , to_districts , distances , risks , threshold):
"""
This function generates availability_matrix with respect to risks.
This function takes 5 arguments:
i) from_districts : A list , which consists of ids of from_districts
ii) to_districts : A list , which consists of ids of to_districts
iii) distances : A list , which consists of distances between from_districts and to_districts
iv) risks : A list , which consists of fire risks of districts
v ) threshold : An integer , which is the number that represents whethet two districts are appropriate or not.
It return 1 variable:
i) availability_matrix_risk : A list of list of list : A list , which contains direct values
"""
risk_dict = { 'A' : 0 , 'B' : 1 , 'C' : 2 , 'D' : 3}
risk_availability_matrix = []
temp_array = []
for i in range(NUMBER_OF_DISTRICT) :
temp_array.append([0,0,0,0])
for i in range(NUMBER_OF_DISTRICT):
risk_availability_matrix.append(temp_array)
pair_array = get_appropriate_pairs_da(from_districts , to_districts , distances , threshold)
for element in pair_array :
from_district = element[0] - 1
to_district = element[1] - 1
risk = risks[to_district]
risk_number = risk_dict[risk]
risk_availability_matrix[from_district][to_district][risk_number] = 1
return risk_availability_matrix
def generate_stochastic_sparse_matrix(random_numbers , appropriate_pairs , min_threshold):
assign = []
for k in range(len(random_numbers)):
from_district = appropriate_pairs[k][0]
to_district = appropriate_pairs[k][1]
for i in range(len(random_numbers[k])):
if random_numbers[k][i] <= min_threshold :
assign.append([from_district , to_district , i + 1])
assign.append([to_district , from_district , i + 1])
for i in range(867):
for k in range(100):
assign.append([ i + 1 , i + 1 , k + 1])
return assign
def generate_risk_indicator(risks):
"""
This function is a function
"""
risk_dict = { 'A' : 0 , 'B' : 1 , 'C' : 2 , 'D' : 3}
risk_indicator = []
for i in range(NUMBER_OF_DISTRICT):
risk_indicator.append([0,0,0,0])
for i in range(NUMBER_OF_DISTRICT):
risk = risks[i]
risk_index = risk_dict[risk]
risk_indicator[i][risk_index] = 1
return risk_indicator
def generate_risk_array():
"""
This function is a function
"""
return [2,2,1,1]
def generate_fixed_cost_array():
"""
This function generates a fixed_cost array with number of district elements
It takes no arguments.
It returns 1 variable:
fixed_cost_array : A list , whose length is NUMBER_OF_DISTRICT and it contains only 1(dummy) as an element
"""
fixed_cost_array = []
for i in range(NUMBER_OF_DISTRICT) :
fixed_cost_array.append(1)
return fixed_cost_array
def calculate_centers_new_districts(lats , longs):
"""
This function calculates centers of new districts using polygon coordinates
It takes 2 arguments:
i) lats : A list of list , which has 975 element and each element consists of lats of polygon coordinates of a particular district
i) longs : A list of list , which has 975 element and each element consists of longs of polygon coordinates of a particular district
"""
x_coordinates = []
y_coordinates = []
for i in range(len(lats)):
temp_x = 0
temp_y = 0
for k in range(len(lats[i])):
temp_x += longs[i][k]
temp_y += lats[i][k]
center_x = temp_x / len(lats[i])
center_y = temp_y / len(longs[i])
x_coordinates.append(center_x)
y_coordinates.append(center_y)
return x_coordinates , y_coordinates
def calculate_distance_between_two_district(x_coord1 , y_coord1 , x_coord2 , y_coord2):
"""
This function calculates the distances between (x1 , y1) and (x2 , y2) with unit meter.
"""
# convert decimal degrees to radians
x_coord1 , y_coord1 , x_coord2 , y_coord2 = map(radians, [x_coord1, y_coord1, x_coord2, y_coord2])
# haversine formula
dlon = abs(x_coord2 - x_coord1)
dlat = abs(y_coord2 - y_coord1)
a = sin(dlat/2)**2 + cos(y_coord1) * cos(y_coord2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers is 6371
meter = 6371* c * 1000
return meter
def find_minimum_distance_cover(solution_array , old_x_coordinates , old_y_coordinates , new_x_coordinates , new_y_coordinates , threshold):
"""
This function finds the minimum distance fire station that covers 975 districts.
It takes arguments:
i) solution_array : A list , whose length is NUMBER_OF_DISTRICT it contains binary values if ith element of it is 1 then we will open a fire station at ith district
ii) old_x_coordinates : A list , which contains x_coordinates of old districts
iii) old_y_coordinates : A list , which contains y_coordinates of old districts
iv) new_x_coordinates : A list , which contains x_coordinates of new districts
v) new_y_coordinates : A list , which contains y_coordinates of new districts
"""
covering_array = []
for i in range(975):
covering_array.append([])
for i in range(len(solution_array)):
if solution_array[i] == 1:
for k in range(975):
old_x = old_x_coordinates[i]
old_y = old_y_coordinates[i]
new_x = new_x_coordinates[k]
new_y = new_y_coordinates[k]
distance = calculate_distance_between_two_district(old_x , old_y , new_x , new_y)
if distance < threshold :
covering_array[k].append([i , distance])
min_cover_array = []
for i in range(975):
min_distance = float("inf")
min_index = -1
for element in covering_array[i]:
index = element[0]
dist = element[1]
if dist < min_distance :
min_distance = dist
min_index = index
min_cover_array.append(min_index)
return min_cover_array
def generate_map_name():
"""
This function generates random map name
"""
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
|
96fa62527da2066a2b80127206c92bc00d2213b2 | harshbakori/classic_py_repo | /p1.py | 426 | 3.890625 | 4 | def main():
a=10
print(a,type(a))
a,b,c=3,4,5
print("%d %d %d"%(a,b,c))
a,b = b,a
print("%d %d "%(a,b))
print ("array....")
arr1 =[1,45,3,54,3] # if we use () brakets we cannot alter data with [] we caan ater data...
print(type(arr1),arr1)
arr1.append(8)
arr1.insert(0,23) #insert (pisition , thing to insert) ...
arr1.insert(-1,99)
print(type(arr1),arr1)
main()
|
369b3d3989879abf26b8a5f1d035e7dbcd4fd29d | snaveen1856/Python_Revised_notes | /Core_python/_24_DB_Connection_Python/_05_storing_image.py | 211 | 3.5 | 4 | import sqlite3
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
m = cursor.execute("""
SELECT * FROM mark_employee
""")
for x in m:
print(x[0], x[0])
conn.commit()
cursor.close()
conn.close()
|
e472d504cefb1803c4a4dd454d329f51fafddb5f | leticiamchd/Curso-Em-Video---Python | /Desafio035.py | 384 | 4.125 | 4 | lado1 = float(input('Digite o tamanho do primeiro lado do triângulo: '))
lado2 = float(input('Digite o tamanho do segundo lado do triângulo: '))
lado3 = float(input('Digite o tamanho do terceiro lado do triângulo: '))
if lado1 < (lado2+lado3) and lado1 > (lado2-lado3):
print('Essas medidas formam um triangulo')
else:
print('Essas medidas não formam um triângulo') |
00fee21bf78dc452a548213e5ead8f6051cc7a11 | zhaoqyu/DeepLearningForTSF | /5.预测用电量(多变量,多步骤)/2.传统机器学习的多步时间序列预测/02.将分钟级别数据合并成日级别.py | 626 | 3.90625 | 4 | # 将分钟级别的数据合并成不同级别,确实的日期中间补零
from pandas import read_csv
# 加载数据
dataset = read_csv('household_power_consumption2.csv', header=0, infer_datetime_format=True, parse_dates=['datetime'], index_col=['datetime'])
# 根据年级别合并数据
#daily_groups = dataset.resample('Y')
# 根据月级别合并数据
#daily_groups = dataset.resample('M')
# 根据日级别合并数据
daily_groups = dataset.resample('D')
daily_data = daily_groups.sum()
# 展示
print(daily_data.shape)
print(daily_data.head())
# 保存
daily_data.to_csv('household_power_consumption_days.csv') |
830ebd341b15e3dbaa7df5c931969fadbaecb2f6 | C-CCM-TC1028-111-2113/homework-3-MAngelFM | /assignments/07VolumenPrismaRectangular/src/exercise.py | 409 | 3.71875 | 4 |
def main():
#escribe tu código abajo de esta línea
def volumen(r,h,p):
v = r * h * p
print("Volumen del Prisma: ",v)
def area(r,h):
a = r * h
return area
base = float(input("Dame la base "))
altura = float(input("Dame la Altura "))
profundidad = float(input("Dame la Profundidad "))
volumen(base,altura,profundidad)
area(base,altura)
pass
if __name__=='__main__':
main()
|
95383291e15173d9347c028e2d15607f4b40ce18 | fanainaalves/Mundo-1-2-e-3-de-Python-Curso-em-Video- | /exe091.py | 631 | 3.6875 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogo = {'Jogador 1': randint(1, 6),
'Jogador 2': randint(1, 6),
'Jogador 3': randint(1, 6),
'Jogador 4': randint(1, 6)}
ranking = list()
print('Valores Sorteados: ')
for keys, valores in jogo.items():
print(f'{keys} tirou {valores} Pontos no dado.')
sleep(1)
ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
print('-='*30)
print(' == RANKING DOS JOGADORES ==')
for indice, valores in enumerate(ranking):
print(f' {indice+1}º Lugar: {valores[0]} com {valores[1]}.')
sleep(1)
|
a4a6c4d07ebdbd892eff33800676de9063d208ca | binzamu/geeksforgeeks | /arrays/basic/find_number_of_numbers.py | 442 | 3.890625 | 4 | # https://practice.geeksforgeeks.org/problems/find-number-of-numbers/1
def num(arr, n, k):
arr_separated = []
for i in arr:
arr_separated += list(str(i))
return arr_separated.count(str(k))
if __name__=='__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
k = int(input())
print(num(arr, n, k))
# Contributed By: Harshit Sidhwa |
8dd3f81f8bff59379c7b5278d978b6cff1cad814 | harishsakamuri/python-files | /basic python/codecata.py | 108 | 3.5 | 4 | a = int(input())
s = 0
b = 1
while (b>0):
if (a==b):
s = s+b
b=b+1
print(s)
|
9046217f42f7d15e84611241cc7bbaf590412ab9 | fallaciousreasoning/study | /pair_that_sum.py | 1,741 | 3.703125 | 4 | def naive_pair_that_sum(numbers, sum):
for i in range(len(numbers)):
for j in range(i, len(numbers)):
if i == j: continue
if numbers[i] + numbers[j] == sum:
return True
return False
def bs_pair_that_sum(numbers, sum):
sorted_numbers = sorted(numbers)
for i in range(len(sorted_numbers)):
current = sorted_numbers[i]
left = i + 1
right = len(sorted_numbers)
while True:
guess_index = (left + right) // 2
if left == right: break
result = current + sorted_numbers[guess_index]
if result == sum:
return True
if result < sum:
left = guess_index + 1
if result > sum:
right = guess_index - 1
return False
def hash_pair_that_sum(numbers, sum):
s = {}
for number in numbers:
if not number in s:
s[number] = 0
s[number] += 1
for number in numbers:
complement = sum - number
if complement in s and (complement != number or s[number] != 1):
return True
return False
def linear_pair_that_sum(numbers, sum):
i = 0
j = len(numbers) - 1
while i < j:
current = numbers[i] + numbers[j]
if current == sum: return True
if current < sum: i += 1
if current > sum: j -= 1
return False
def better_hash_pair_that_sum(numbers, sum):
seen = set()
for number in numbers:
complement = sum - number
if complement in seen:
return True
seen.add(number)
return False
print(better_hash_pair_that_sum([1,2,3,4], 8))
print(better_hash_pair_that_sum([1,2,3,4,4], 8))
|
cc21cf06ffa25086aa34c765230bfe93581ce7e6 | CollegeBoreal/INF1042-202-20H-02 | /4.QuickSort/b300117806.py | 461 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 15:20:15 2020
@author: User
"""
def quicksort(array):
# base case
if len(array) < 2 :
return array
else:
# recursive case
pivot = array [0]
less = [i for i in array [1:] if i <= pivot]
greater = [i for i in array[1:] if i <= pivot]
return quicksort(less) + [pivot] + quicksort(greater)
print(quicksort([24, 50, 200, 800, 10, 45, 13, 70]))
|
3209947bf5e2e8f33dd65561744ecc8380faf4ab | aziaziazi/Euler | /problem 2.py | 235 | 3.765625 | 4 | def sum_fibonacci_not_even():
fib = [1,1]
total = 0
while fib[-1]<4000000:
to_add = fib[-1]+fib[-2]
fib.append(to_add)
if not fib[-1] % 2:
total+=to_add
fib[-1] = 0
print fib
return total
print sum_fibonacci_not_even()w |
930ccd4f4320719c96b15e6c84a9397f40587ec8 | alex19451/us-states-game | /main.py | 1,006 | 3.84375 | 4 | import turtle
import pandas
data = pandas.read_csv("50_states.csv")
all_states = data.state.to_list()
screen = turtle.Screen()
title = screen.title("Find USA states Games")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
guessed_states = []
while len(guessed_states)< 50:
answer = screen.textinput(title=f"{len(guessed_states)}/50 States Correct", prompt="What's another state's name?").title()
if answer_state == "Exit":
missing_states = []
for state in all_states:
if state not in guessed_states:
missing_states.append(state)
new_data = pandas.DataFrame(missing_states)
new_data.to_csv("states_to_learn.csv")
if answer in all_states:
guessed_states.append(answer)
t=turtle.Turtle()
t.penup()
t.hideturtle()
data_state = data[data["state"]==answer]
t.goto(int(data_state.x),int(data_state.y))
t.write(answer)
screen.exitonclick() |
775c2ea9d60a9b7e92462c04ae97016cd6f8d909 | Helton-Rubens/Python-3 | /exercicios/exercicio080.py | 666 | 4.0625 | 4 | #colocar os valores em ordem sem a função .sort()
digito = []
for c in range(1, 6):
user = int(input('Digite um número: '))
if c == 1:
print('Número adicionado no começo da lista')
digito.append(user)
elif user > digito[-1]:
digito.append(user)
print('Número adicionado no final da lista')
else:
pos = 0
while pos < len(digito):
if user < digito[pos]:
digito.insert(pos, user)
print(f'Número adicionado na posição {pos+1} da lista')
break
pos += 1
print('-='*30)
print('Você digitou os números: ',end='')
print(digito)
|
b66a310d6aa0fe4497bfa529fa7382f396a74f03 | 1141938529/ClassExercises | /week01/day04/demo07.py | 716 | 3.671875 | 4 | # 猜数字游戏
# 规则:随机产生一个0-1000 的数字 用户进行输入数字
import random
answer = random.randint(1, 1000)
myAnswer = None
while myAnswer!=answer :
myAnswer= eval( input("请猜一个数字(0-1000):"))
if myAnswer==-1 :
print("老子不想玩了 gun")
break
else:
if (myAnswer>1000 or myAnswer<0):
print("骚年,睁大眼睛看看条件"
",请重新输入吧")
continue
else:
if myAnswer>answer :
print("太大了")
elif myAnswer<answer:
print("太小了")
pass
else:
print("猜对了")
pass
print("game over")
|
75cd6c3220bab095fbc663393017db84989b68fb | yura20/logos_python | /hw_01/hw.py | 561 | 4.34375 | 4 | name = input("enter your name: ")
surname= input("enter your surname: ")
group_name = input("enter your group name: ")
university = input("enter your university: ")
mark = int(input("enter your average mark: "))
name = name[0].upper()+name[1:].lower()
surname = surname[0].upper()+surname[1:].lower()
university = university.upper()
text = "I am {name} {surname}, I am studying at the {university} with {group_name}, my average mark is {mark}.".format(name = name, surname = surname, university = university, group_name = group_name, mark = mark)
print(text) |
d43057b2e7a28cabbbb28e3ee40618a03580bab5 | ihavegerms/pythonpractice | /primefactorpe3.py | 422 | 3.546875 | 4 | #!/usr/bin/env python
# comment your code better... can't explain why you did something 1 or 2 days later
def primefactor(a):
b = 2
while (a > b):
if (a % b == 0):
# i'm a derp i did this cause x,y
a = a / b;
# this causes x to happen cause y is dumb
b = 2;
else:
b += 1;
print(str(b))
primefactor(600851475143000000000000000000000) |
5cc5514ddce6cc4a8216ddd77513d85aae52fe95 | MengleJhon/python_1 | /python1.0/python_study1/little_game1.0.py | 2,029 | 4.1875 | 4 | # Lin Xin
import random
def roll_dice(numbers = 3,points = None): # numbers:骰子个数 points:预置骰子点数列表
print('<<<<< ROLL THE DICE ! >>>>>')
if points is None:
points = []
while numbers > 0:
point = random.randrange(1,7)
points.append(point)
numbers = numbers - 1
return points
def roll_result(total):
isBig = 11 <= total <= 18
isSmall = 3 <= total <= 10
if isBig:
return 'Big'
elif isSmall:
return 'Small'
def start_game(initial_money = 1000):
choices = ['Big','Small']
flag = 1
while flag:
print('<<<<<<<<< GAME STARTS ! >>>>>>>>>')
your_choice = input('Big or Small :')
if your_choice.lower().title() in choices:
bet_money = input('How much you wanna bet ? - ')
while not bet_money.isdigit():
print('Please input a positive number !')
bet_money = input('How much you wanna bet ? - ')
points = roll_dice()
total = sum(points)
youWin = your_choice.lower().title() == roll_result(total)
if youWin:
initial_money = initial_money + int(bet_money)
print('The points are',points,'You win !')
print('You gained ' + bet_money + ', you have ' + str(initial_money) + ' now !')
flag = 1
else:
initial_money = initial_money - int(bet_money)
print('The points are', points, 'You lose ! But, come on !')
print('You lose ' + bet_money + ', you have ' + str(initial_money) + ' now !')
if initial_money > 0:
flag = 1
else:
print('GAME OVER !')
flag = 0
# start_game()
elif your_choice.lower().title() == 'Stop':
print('Let\'s play next time !\nBye !')
flag = 0
else:
print('Invalid Words')
flag = 1
start_game() |
a249d02c6806b5aceaf068fad44606132275cf2c | kungbob/Leetcode_solution | /python/6_ZigZag_Conversion.py | 1,484 | 3.515625 | 4 | ################################################################################
# Question : 6. ZigZag Conversion
# Difficulty : Medium
# Author : Kung Tsz Ho
# Last Modified Date : 2018/8/3
# Number of Method : 1
# Fastest Runtime : 84 ms
################################################################################
################################################################################
# Method : 1 -
# Runtime : 84 ms
# Beats : 86.90 % of submissions
# Remark :
################################################################################
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length = len(s)
result = ''
if numRows == 1:
return s
for i in range(numRows):
line_start = i
while line_start < length:
result += s[line_start]
# Handle the first line and middle line
if not (i == numRows - 1):
line_start += (numRows-1-i) * 2
else:
# Handle the last line
line_start += i * 2
# Handle the middle line
if (line_start >= length) or (i == 0) :
continue
else:
result += s[line_start]
line_start += i * 2
return result
|
a5e115eff881231ef49dba9c28148c3a27ed59ca | flematthias/exo-python | /exo-14/myClass.py | 356 | 3.59375 | 4 | class myClass:
"""classe pour agrandir
"""
@staticmethod
def staticmethod(up):
"""methode pour agrandir
Arguments:
a {str} -- le string en minuscule
Returns:
str -- le resultat en capitale
"""
return up.upper()
print(myClass.staticmethod('stringtoupper'))
|
13c80a7a4131419370c73c7bcd3c415608f99585 | allyrob/parsing | /stringparsing.py | 1,699 | 4.34375 | 4 | # grocery_string = "item:apples,quantity:4,price:1.50\n"
# split_item = grocery_string.split(",")
# print split_item
# item_data = split_item[0]
# print item_data
# item = item_data.split(":")
# print item[1]
# my_name = "Sonia"
# print list(my_name)
# numbers = "1,2,3,4,5"
# numberslist = numbers.split(",")
# print numberslist
# for numbers in numberslist:
# int(numbers)
# print numbers
# suess = "one fish two fish red fish blue fish"
# print suess.split("fish")
grocery_string = "item:apples,quantity:4,price:1.50\n"
def string_split(grocery_string):
#this function splits the items in the string grocery_string
split_item = grocery_string.split(",")
quantity_data = split_item[1]
quantity = quantity_data.split(":")
real_quantity = int(quantity[1])
price_data = split_item[2]
price = price_data.split(":")
real_price = float(price[1].strip())
return (real_quantity, real_price)
def bill(quantity, real_price):
#this function will get the bill total for each item * quantity
total_bill = real_quantity * real_price
return total_bill
grocery_list = ["item:apples,quantity:4,price:1.50\n",
"item:pears,quantity:5,price:2.00\n",
"item:cereal,quantity:1,price:4.49\n"]
total_bill = 0 #must be named outside of the for loop
for item in grocery_list:
#turns the list into several strings, applies the function string_split
#and applies the bill function
real_quantity, real_price = string_split(item)
my_bill = bill(real_quantity, real_price)
print my_bill
total_bill += my_bill #adds total_bill to each total in my_bill
print total_bill #prints the total for all of the items
|
60954f75a9c3fd0f1c285c38a80c30cb85e057dd | EmersonBraun/python-excercices | /cursoemvideo/ex052.py | 431 | 4 | 4 | # Faça um programa que leia um número inteiro
# e diga se ele é ou não um número primo
num = int(input('Digite um número para ver ser é primo: '))
cont = 0
print('{} é divisível por: '.format(num),end='')
for c in range(1, num + 1):
if num % c == 0:
print('{} ,'.format(c) ,end='')
cont+=1
if cont <= 2:
print('\nentão É um número primo!')
else:
print('\nentão NÃO é um número primo!') |
feddef1c18fd87ddd77a50f188dd9b408ff6f8de | rakaar/OOP-Python-Notes | /6-decorators-get-set-deleters.py | 1,177 | 4.125 | 4 | '''
@property
a decorator used to access the methods as attributes
setters
allows us to set the attributes
deleter
runs when something is deleted
'''
class Employee:
bonus = 100
def __init__(self, firstName, lastName, salary):
self.firstName = firstName
self.lastName = lastName
self.salary = salary
# this decorator allows us to access the below function as an attribute
@property
def fullname(self):
return self.firstName + ' ' + self.lastName
# basically the syntax is funcname(or attribute name to be set).setter and define a function with same name
@fullname.setter
def fullname(self, new):
first, last = new.split(' ')
self.firstName = first
self.lastName = last
@fullname.deleter
def fullname(self):
print('deleted')
emp_1 = Employee("jan", "doe", 100)
# Before @property
# print(emp_1.fullname())
#After @property
print(emp_1.fullname)
# BEOFRE USING SETTER
# suppose
emp_1.fullname = "new name"
# error : says can't set an attribute, LETS USE A SETTER THEN !
print(emp_1.fullname)
# AFTER, using setters this will print new name
del emp_1.fullname
|
e1db6fc30efc4468dbac2529a0450f12a7ad9aa6 | gennis2008/python_workspace | /CrazyPythonTalkLiGang/part03/section3.3/update_test.py | 355 | 3.546875 | 4 | a_list = [2,4,-3.4,'crazyit',23]
a_list[2] = 'fkit'
print(a_list)
a_list[-2] = 9527
print(a_list)
b_list = list(range(1,5))
print(b_list)
b_list[1:3] = ['a','b']
print(b_list)
b_list[2:5] = []
print(b_list)
b_list[2:2] = ['x','y']
print(b_list)
b_list[1:3]='charlie'
print(b_list)
c_list = list(range(1,10))
c_list[2:9:2]=['a','b','c','d']
print(c_list) |
9bc662d868ae4a8428428732f26e71227fb0d151 | andresparrab/Python_Learning | /SQLite/05. UPDATE and DELETE.py | 1,711 | 3.859375 | 4 | import sqlite3
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
conn = sqlite3.connect('tutorial.db')
cursor = conn.cursor()
def graph_data():
cursor.execute('SELECT unix, value FROM stuffToPlot')
dates = []
values = []
data = cursor.fetchall()
for row in data:
# print(row[0])
# print(datetime.datetime.fromtimestamp(row[0]))
dates.append(datetime.datetime.fromtimestamp(row[0]))
values.append(row[1])
plt.plot_date(dates,values, ':')
plt.show()
def del_and_update():
cursor.execute('SELECT * FROM stuffToPlot')
data = cursor.fetchall()
[print(row) for row in data]
print(50*'//')
# Set the value 99 everywhere where de value is2, OBS this is permanent
cursor.execute('UPDATE stuffToPlot SET value = 99 WHERE value =2')
# conn.commit() save the changes
conn.commit()
# Select the table again and showthen new values
cursor.execute('SELECT * FROM stuffToPlot')
data = cursor.fetchall()
[print(row) for row in data]
# this will delete the first 3 rows where the value is 99, witout LIMIT it will delete all rows value=99
cursor.execute('DELETE FROM stuffToPlot WHERE value = 99')
conn.commit()
print(50*'#')
cursor.execute('SELECT * FROM stuffToPlot')
data = cursor.fetchall()
[print(row) for row in data]
# fetch how many rows has value of 0,is good to know before delete or update
cursor.execute('SELECT * FROM stuffToPlot WHERE value = 0')
data = cursor.fetchall()
print(50*'...')
[print(row) for row in data]
print(len(data))
del_and_update()
cursor.close()
conn.close()
|
61833c2b811a23fb4429b640ba42015720a4c5ed | harababurel/homework | /sem1/fop/practical-simulation/models/route.py | 1,671 | 4.1875 | 4 | class Route:
"""
Class models a bus route as a real world object.
A bus route is defined by:
self.__ID (int): the unique ID of the route.
self.__code (str): the unique code of the route (<= 3 characters).
self.__usage (int): the percentage that indicates the route's usage.
self.__busCount (int): the number of buses that run on the route.
"""
def __init__(self, ID, code, usage, busCount):
try:
ID = int(ID)
assert 0 < len(code) and len(code) <= 3
usage = int(usage)
assert 0 <= usage and usage <= 100
busCount = int(busCount)
except:
raise Exception("Could not create Route. Check the parameters.")
self.__ID = ID
self.__code = code
self.__usage = usage
self.__busCount = busCount
def __repr__(self):
return("ID: %i, code: %s, usage: %i, busCount: %i" % (self.getID(), self.getCode(), self.getUsage(), self.getBusCount()))
def getID(self):
return self.__ID
def setID(self, newID):
self.__ID = newID
def getCode(self):
return self.__code
def setCode(self, newCode):
self.__code = newCode
def getUsage(self):
return self.__usage
def setUsage(self, newUsage):
self.__usage = newUsage
def getBusCount(self):
return self.__busCount
def setBusCount(self, newBusCount):
self.__busCount = newBusCount
def increaseBusCount(self):
"""
Method increments the bus count for the current route.
"""
self.setBusCount(self.getBusCount() + 1)
|
4d9629aae3d871e063a896c4ded416afcb8577e2 | SamuelDovgin/INFO490Assets | /src/dmap/lessons/color/lib/LessonUtil.py | 854 | 3.8125 | 4 | #
# common code given to the students
# only edit the source, this gets copied into distribution
#
import random as r
import numpy as np
class RandomData(object):
def __init__(self, n=50, cat_count=3):
r.seed(101)
np.random.seed(101)
self.x = np.random.randn(n) # norm dist, mean 0; var: 1
self.y = np.random.randn(n)
self.c = np.random.choice(cat_count, n)
self.n = np.array([x for x in range(0, n)])
self.xy = np.array([self.x, self.y])
1
class RandomPetData(object):
def __init__(self, n=50):
r.seed(101)
np.random.seed(101)
self.x = np.random.randn(n) # norm dist, mean 0; var: 1
self.y = np.random.randn(n)
self.pet = np.random.choice([ 'dog', 'cat', 'fish', 'n/a'], size=n,
p=[0.35, 0.25, 0.10, 0.30])
|
f1b62a292a1c02362501f2c30beb58abc3a5b593 | ZihengZZH/LeetCode | /py/MaximumProductSubarray.py | 2,052 | 4.15625 | 4 | '''
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
'''
class Solution:
# inspired by the integral image concept
# but apparently, many constrictions exist
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
nums_mul = [1] * (len(nums)+1)
for i in range(1, len(nums)+1):
nums_mul[i] = nums_mul[i-1] * nums[i-1]
max_num_index, min_num_index = nums_mul.index(max(nums_mul)), nums_mul.index(min(nums_mul))
if max(nums_mul) * min(nums_mul) < 0:
min_num_index = nums_mul.index(min(j for j in nums_mul if j > 0))
if max_num_index > min_num_index:
return int(nums_mul[max_num_index] / nums_mul[min_num_index])
else:
return 0
# complexity: O(n); beats 19.7%
def maxProduct_online(self, nums):
# always keep imax > imin and possibly (imax > 0 and imin < 0)
imin = imax = max_v = nums[0]
for i in range(1, len(nums)):
n = nums[i]
# swap if negative
if n < 0:
imin, imax = imax, imin
imax = max(n, imax*n) # perhaps > 0
imin = min(n, imin*n) # perhaps < 0
max_v = max(max_v, imax) # update largest values
return max_v
if __name__ == "__main__":
solu = Solution()
input_1 = [2, 3, -2, 4]
input_2 = [-2, 0, -1]
input_3 = [0, 0, 0]
input_4 = [-2]
input_5 = [-1, -1]
assert solu.maxProduct_online(input_1) == 6
assert solu.maxProduct_online(input_2) == 0
assert solu.maxProduct_online(input_3) == 0
assert solu.maxProduct_online(input_4) == -2
assert solu.maxProduct_online(input_5) == 1 |
519b4e21e5bb85d752b17993b65893df053fc69e | mattjax16/pitching_video_analysis | /kmeansGPU.py | 38,279 | 3.578125 | 4 | '''kmeans.py
Performs K-Means clustering
YOUR NAME HERE
CS 251 Data Analysis Visualization, Spring 2021
'''
import numpy as np
import matplotlib.pyplot as plt
from palettable import cartocolors
import palettable
import concurrent.futures
import pandas as pd
import cupy as cp
class KMeansGPU():
def __init__(self, data=None, use_gpu=True, data_type = 'float64'):
'''KMeans constructor
(Should not require any changes)
Parameters:
-----------
data: ndarray. shape=(num_samps, num_features)
'''
# k: int. Number of clusters
self.k = None
# centroids: ndarray. shape=(k, self.num_features)
# k cluster centers
self.centroids = None
# data_centroid_labels: ndarray of ints. shape=(self.num_samps,)
# Holds index of the assigned cluster of each data sample
self.data_centroid_labels = None
# inertia: float.
# Mean squared distance between each data sample and its assigned (nearest) centroid
self.inertia = None
# data: ndarray. shape=(num_samps, num_features)
self.data = data
# num_samps: int. Number of samples in the dataset
self.num_samps = None
# num_features: int. Number of features (variables) in the dataset
self.num_features = None
#each datas distance from the centroid
self.data_dist_from_centroid = None
#holds wether gpu is being used or not
self.use_gpu = use_gpu
# holds whether the array in a numpy or cumpy array
if use_gpu:
self.xp = cp
else:
self.xp = np
if data is not None:
data = self.checkArrayType(data)
#get the original data type of the data matrix
self.original_data_type = data.dtype
#make data passed in data type
# self.set_data_type = data_type
# make data passed in data type
self.set_data_type = data.dtype
self.set_data(data)
self.num_samps, self.num_features = data.shape
else:
self.set_data_type = data_type
# Making Cuda Kernal Functions for increased speed on gpu
# learned how to thanks to Cupy documentation!
# https://readthedocs.org/projects/cupy/downloads/pdf/stable/
#making kernal functions for different l Norms (distances)
#L2 (euclidien distance kernal)
self.euclidean_dist_kernel = cp.ReductionKernel(
in_params = 'T x', out_params = 'T y', map_expr='x * x', reduce_expr='a + b',
post_map_expr= 'y = sqrt(a)', identity='0', name='euclidean'
)
# L1 (manhattan distance kernal)
self.manhattan_dist_kernel = cp.ReductionKernel(
in_params='T x', out_params='T y', map_expr='abs(x)', reduce_expr='a + b',
post_map_expr='y = a', identity='0', name='manhattan'
)
# these next 2 kerneals are used to get the mean of a cluster of data
# (update the centroids)
# gets the sum of a matrix based off of one hot encoding
self.sum_kernal = cp.ReductionKernel(
in_params = 'T x, S oneHotCode', out_params ='T result',
map_expr= 'oneHotCode ? x : 0.0' , reduce_expr='a + b',post_map_expr= 'result = a' ,identity='0', name= 'sum_kernal'
)
# gets the count of a matrix from one hot encoding (by booleans)
#TODO make a class variable to hold data type of data set
self.count_kernal = cp.ReductionKernel(
in_params='T oneHotCode', out_params='float32 result',
map_expr='oneHotCode ? 1.0 : 0.0', reduce_expr='a + b', post_map_expr='result = a' ,identity='0', name='count_kernal'
)
#TODO ASK MY NOT MAKE A self.dataframe object
def checkArrayType(self, data):
if self.use_gpu:
if cp.get_array_module(data) == np:
data = cp.array(data)
else:
if cp.get_array_module(data) == cp:
data = np.array(data)
return data
# helper function to get things as numpy
def getAsNumpy(self, data):
if cp.get_array_module(data) == cp:
data = data.get()
return data
# helper function to get things as numpy
def getAsCupy(self, data):
if cp.get_array_module(data) == np:
data = cp.array(data)
return data
def set_data(self, data):
'''Replaces data instance variable with `data`.
Reminder: Make sure to update the number of data samples and features!
Parameters:
-----------
data: ndarray. shape=(num_samps, num_features)
'''
#make sure the data is 2 dimensions
assert data.ndim == 2
self.data = data.astype(self.set_data_type)
self.num_samps = data.shape[0]
self.num_features = data.shape[1]
self.xp = cp.get_array_module(data)
def get_data(self):
'''Get a COPY of the data
Returns:
-----------
ndarray. shape=(num_samps, num_features). COPY of the data
'''
return self.xp.copy(self.data)
def get_inertia(self):
return self.inertia
def get_centroids(self):
'''Get the K-means centroids
(Should not require any changes)
Returns:
-----------
ndarray. shape=(k, self.num_features).
'''
return self.centroids
def get_data_centroid_labels(self):
'''Get the data-to-cluster assignments
(Should not require any changes)
Returns:
-----------
ndarray of ints. shape=(self.num_samps,)
'''
return self.data_centroid_labels
def dist_pt_to_pt(self, pt_1, pt_2, method = 'L2'):
'''Compute the Euclidean distance between data samples `pt_1` and `pt_2`
Parameters:
-----------
pt_1: ndarray. shape=(num_features,)
pt_2: ndarray. shape=(num_features,)
method: string. L2 or L1 for eculidiean or manhattan distance
Returns:
-----------
float. Euclidean distance between `pt_1` and `pt_2`.
NOTE: Implement without any for loops (you will thank yourself later since you will wait
only a small fraction of the time for your code to stop running)
'''
if method == 'L2':
pt_1 = pt_1.reshape(1,pt_1.size)
pt_2 = pt_2.reshape(1, pt_2.size)
euclid_dist = self.xp.sqrt(self.xp.sum((pt_1-pt_2)*(pt_1-pt_2),axis=1))
return euclid_dist[0]
elif method == 'L1':
pt_1 = pt_1.reshape(1, pt_1.size)
pt_2 = pt_2.reshape(1, pt_2.size)
manhat_dist = self.xp.sum(self.xp.abs(pt_1-pt_2))
return manhat_dist
def dist_pt_to_centroids(self, pt, centroids = None, method = 'L2'):
'''Compute the Euclidean distance between data sample `pt` and and all the cluster centroids
self.centroids
Parameters:
-----------
pt: ndarray. shape=(num_features,)
centroids: ndarray. shape=(C, num_features)
C centroids, where C is an int.
method: string. L2 or L1 for eculidiean or manhattan distance
Returns:
-----------
ndarray. shape=(C,).
distance between pt and each of the C centroids in `centroids`.
NOTE: Implement without any for loops (you will thank yourself later since you will wait
only a small fraction of the time for your code to stop running)
'''
if isinstance(centroids,type(None)):
if method == 'L2':
centroid_dist_array = self.xp.sqrt(self.xp.sum((pt - self.centroids) * (pt - self.centroids), axis=1))
elif method == 'L1':
centroid_dist_array = self.xp.sum(self.xp.abs(pt-self.centroids),axis=1)
else:
if method == 'L2':
centroid_dist_array = self.xp.sqrt(self.xp.sum((pt - centroids) * (pt - centroids), axis=1))
elif method == 'L1':
centroid_dist_array = pt-centroids
centroid_dist_array = self.xp.sum( centroid_dist_array,axis=1)
return centroid_dist_array
def initialize(self, k, init_method = 'points',distance_calc_method = 'L2',matix_mult_dist_calc = True):
'''Initializes K-means by setting the initial centroids (means) to K unique randomly
selected data samples
Parameters:
-----------
k: int. Number of clusters
Returns:
-----------
ndarray. shape=(k, self.num_features). Initial centroids for the k clusters.
NOTE: Can be implemented without any for loops
'''
self.k = k
if init_method == 'range':
maxs = self.xp.max(self.data,axis = 0)
mins = self.xp.min(self.data,axis = 0)
starting_centroids = self.xp.random.uniform(mins,maxs, size = (k,mins.size))
elif init_method == 'points':
data_as_np = cp.asnumpy(self.data)
unique_data_samples = np.unique(data_as_np,axis = 0)
unique_data_samples_shape = unique_data_samples.shape[0]
range_of_samples_array = np.arange(unique_data_samples_shape)
# assert range_of_samples_array.ndim == 2
starting_centroid_point_indicies = np.random.choice(range_of_samples_array, replace = False,size = k)
starting_centroid_point_indicies = starting_centroid_point_indicies.astype('int')
starting_centroids = unique_data_samples[starting_centroid_point_indicies,:]
if self.xp == cp:
starting_centroids = cp.asarray(starting_centroids)
#TODO maybe check if there are not enough unique colors for ammount of centroids
if unique_data_samples.shape[0] < k:
print(f'Warning!!!!!!!! \nNot enough unique samples for number of clusters (point initialization)')
elif init_method == '++':
starting_centroids = self.xp.zeros((k, self.num_features), dtype=self.set_data_type)
np_data = self.data
#get unique data-samples
if self.use_gpu:
np_data = np_data.get()
unique_data_samples = np.unique(np_data, axis=0)
unique_data_samples_shape = unique_data_samples.shape[0]
range_of_samples_array = np.arange(unique_data_samples_shape)
if self.use_gpu:
# make cupy version
unique_data_samples = cp.array(unique_data_samples)
if unique_data_samples.shape[0] < k:
print(f'Warning!!!!!!!! \nNot enough unique samples for number of clusters (point initialization)')
for i in range(k):
if i == 0:
starting_centroids[i, :] = unique_data_samples[np.random.choice(range_of_samples_array)]
# starting_centroids[i, :] = unique_data_samples[np.random.choice(range_of_samples_array)]
else:
if distance_calc_method == 'L2':
if self.xp == np:
if matix_mult_dist_calc:
data_distance_from_centroids = -2 * unique_data_samples @ starting_centroids[:i,:].T + (unique_data_samples * unique_data_samples).sum(axis=-1)[:, None] + \
(starting_centroids[:i,:] * starting_centroids[:i,:]).sum(axis=-1)[None]
data_distance_from_centroids = self.xp.sqrt(self.xp.abs(data_distance_from_centroids))
else:
data_distance_from_centroids = self.xp.apply_along_axis(func1d=self.dist_pt_to_centroids,
axis=1, arr=unique_data_samples, centroids=starting_centroids[:i,:],
method='L2')
else:
# To much Memory when all on gpu
# data_distance_from_centroids = self.xp.zeros((unique_data_samples_shape, i), dtype = self.set_data_type)
# data_matrix_points = unique_data_samples[:, None, :]
# centroids_so_far_0 = starting_centroids[:i,:]
# centroids_so_far_1 = centroids_so_far_0 * self.xp.ones((unique_data_samples_shape,i), dtype = self.set_data_type)
# centroids_matrix = centroids_so_far_1[None,:,:]
# dist_calc_input = data_matrix_points - centroids_matrix
# data_distance_from_centroids = self.euclidean_dist_kernel(dist_calc_input, axis = 1)
data_distance_from_centroids = self.xp.zeros((unique_data_samples_shape, i),
dtype=self.set_data_type)
data_matrix_points = unique_data_samples[:, None, :]
centroids_chosen = np.arange(i)
centroids_matrix = starting_centroids[centroids_chosen, :]
centroids_matrix = centroids_matrix * self.xp.ones((i, self.num_features),
dtype=self.set_data_type)
centroids_matrix = centroids_matrix[None, :, :]
dist_calc_input = data_matrix_points - centroids_matrix
data_distance_from_centroids = self.euclidean_dist_kernel(dist_calc_input, axis=1)
if distance_calc_method == 'L1':
if self.xp == np:
data_distance_from_centroids = self.xp.apply_along_axis(
func1d=self.dist_pt_to_centroids,
axis=1, arr=self.data, centroids=starting_centroids[:i, :],
method='L2')
else:
data_distance_from_centroids = self.xp.zeros((self.num_samps, self.k), dtype = self.set_data_type)
data_matrix_points = self.data[:, None, :]
centroids_matrix = starting_centroids[None, :, :]
dist_calc_input = data_matrix_points - centroids_matrix
data_distance_from_centroids = self.manhattan_dist_kernel(dist_calc_input)
dist_sums = data_distance_from_centroids.sum()
probs = data_distance_from_centroids.sum(axis=1) / dist_sums
# s_centroids = unique_data_samples[np.random.choice(range_of_samples_array, p=probs),:]
if self.use_gpu:
random_choice = np.random.choice(range_of_samples_array, p=probs.get())
starting_centroids[i,:] = unique_data_samples[random_choice,:]
else:
starting_centroids[i,:] = unique_data_samples[np.random.choice(range_of_samples_array, p=probs),:]
else:
print(f'Error Method needs to be "range" or "points" currently it is {init_method}')
raise Exception
exit()
return starting_centroids
def cluster(self, k=2, tol=1e-2, max_iter=100, verbose=False, init_method = 'points' ,distance_calc_method = 'L2'):
'''Performs K-means clustering on the data
Parameters:
-----------
k: int. Number of clusters
tol: float. Terminate K-means if the difference between all the centroid values from the
previous and current time step < `tol`.
max_iter: int. Make sure that K-means does not run more than `max_iter` iterations.
verbose: boolean. Print out debug information if set to True.
Returns:
-----------
self.inertia. float. Mean squared distance between each data sample and its cluster mean
int. Number of iterations that K-means was run for
TODO:
- Initialize K-means variables
- Do K-means as long as the max number of iterations is not met AND the difference
between every previous and current centroid value is > `tol`
- Set instance variables based on computed values.
(All instance variables defined in constructor should be populated with meaningful values)
- Print out total number of iterations K-means ran for
'''
self.k = k
# - Initialize K-means variables
self.centroids = self.initialize(k ,init_method)
#do K-means untils distance less than thresh-hold or max ittters reached
i = 0
max_centroid_diff = self.xp.inf
#TODO add a way to store values from update labels so inertia is easier to calculate
while i < max_iter and max_centroid_diff > tol:
#combine
self.data_centroid_labels = self.update_labels(self.centroids,distance_calc_method = distance_calc_method)
self.inertia = self.compute_inertia(distance_calc_method=distance_calc_method)
#TODO add place fot finding farthest data point from biggest centroid
new_centroids, centroid_diff = self.update_centroids(k=k, data_centroid_labels=self.data_centroid_labels,
prev_centroids=self.centroids,distance_calc_method = distance_calc_method)
self.centroids = new_centroids
#check that centroids are more than 1 feature
if centroid_diff.size == self.k:
max_centroid_diff = self.xp.max(centroid_diff)
else:
max_centroid_diff = self.xp.max(self.xp.sum(centroid_diff,axis=1))
# increment i
i += 1
return self.inertia, i
# #TODO maybe update self.dataframe here
#
# return self.inertia, max_iter
def cluster_batch(self, k=2, n_iter=5, tol=1e-2, max_iter=100, verbose=False, init_method = 'points',distance_calc_method = 'L2'):
'''Run K-means multiple times, each time with different initial conditions.
Keeps track of K-means instance that generates lowest inertia. Sets the following instance
variables based on the best K-mean run:
- self.centroids
- self.data_centroid_labels
- self.inertia
Parameters:
-----------
k: int. Number of clusters
n_iter: int. Number of times to run K-means with the designated `k` value.
verbose: boolean. Print out debug information if set to True.
'''
# initialize best distance value to a large value
best_intertia = self.xp.inf
has_found_better_centroids = False
for i in range(n_iter):
intertia_kmeans, number_of_iters = self.cluster(k,tol=tol, max_iter=max_iter,verbose=verbose,
init_method=init_method,distance_calc_method=distance_calc_method)
if intertia_kmeans < best_intertia:
best_intertia = intertia_kmeans
best_centroids = self.centroids
best_data_labels = self.data_centroid_labels
has_found_better_centroids = True
if has_found_better_centroids:
self.inertia = best_intertia
self.centroids = best_centroids
self.data_centroid_labels = best_data_labels
def update_labels(self, centroids, multiProcess = False, matix_mult_dist_calc = True, distance_calc_method = 'L2'):
'''Assigns each data sample to the nearest centroid
Parameters:
-----------
centroids: ndarray. shape=(k, self.num_features). Current centroids for the k clusters.
Returns:
-----------
ndarray of ints. shape=(self.num_samps,). Holds index of the assigned cluster of each data
sample. These should be ints (pay attention to/cast your dtypes accordingly).
Example: If we have 3 clusters and we compute distances to data sample i: [0.1, 0.5, 0.05]
labels[i] is 2. The entire labels array may look something like this: [0, 2, 1, 1, 0, ...]
'''
data_distance_from_centroids = []
centroids = self.checkArrayType(centroids)
#make sure cntroids is 2 dimensions
# if centroids.shape[1] == 1:
# centroids = centroids[None,:]
if multiProcess:
pass
else:
# Credit to this paper for the idea of the matrix method
# https://www.robots.ox.ac.uk/~albanie/notes/Euclidean_distance_trick.pdf
# and https://medium.com/@souravdey/l2-distance-matrix-vectorization-trick-26aa3247ac6c
if distance_calc_method == 'L2':
if self.xp == np:
if centroids.size == self.k:
data_distance_from_centroids = self.xp.sqrt((self.data - centroids.T)*(self.data - centroids.T))
else:
data_distance_from_centroids = -2 * self.data @ centroids.T + (self.data * self.data).sum(axis=-1)[:, None] + (centroids * centroids).sum(axis=-1)[None]
data_distance_from_centroids = np.sqrt(np.abs(data_distance_from_centroids))
#else if it is Cupy Gpu bases
else:
data_distance_from_centroids = self.xp.zeros((self.num_samps,self.k), dtype = self.set_data_type)
data_matrix_points = self.data[:,None,:]
centroids_matrix = centroids[None,:,:]
dist_calc_input = data_matrix_points - centroids_matrix
data_distance_from_centroids = self.euclidean_dist_kernel(dist_calc_input, axis = 2)
data_distance_from_centroids = data_distance_from_centroids.reshape(data_distance_from_centroids.shape[0], centroids.shape[0])
labels = self.xp.argmin(data_distance_from_centroids, axis=1)
self.data_dist_from_centroid = self.xp.min(data_distance_from_centroids, axis=1)
return labels
elif distance_calc_method == 'L1':
if self.xp == np:
data_distance_from_centroids = self.xp.apply_along_axis(func1d=self.dist_pt_to_centroids,
axis=1, arr=self.data, centroids=centroids,
method='L1')
data_distance_from_centroids = self.xp.abs(data_distance_from_centroids)
else:
data_distance_from_centroids = self.xp.zeros((self.num_samps, self.k), dtype = self.set_data_type)
data_matrix_points = self.data[:, None, :]
centroids_matrix = centroids[None, :, :]
dist_calc_input = data_matrix_points - centroids_matrix
data_distance_from_centroids = self.manhattan_dist_kernel(dist_calc_input)
data_distance_from_centroids = data_distance_from_centroids.reshape(data_distance_from_centroids.shape[0], centroids.shape[0])
labels = self.xp.argmin(data_distance_from_centroids, axis=1)
self.data_dist_from_centroid = self.xp.min(data_distance_from_centroids, axis=1)
return labels
def update_centroids(self, k, data_centroid_labels, prev_centroids, distance_calc_method = 'L2'):
'''Computes each of the K centroids (means) based on the data assigned to each cluster
Parameters:
-----------
k: int. Number of clusters
data_centroid_labels. ndarray of ints. shape=(self.num_samps,)
Holds index of the assigned cluster of each data sample
prev_centroids. ndarray. shape=(k, self.num_features)
Holds centroids for each cluster computed on the PREVIOUS time step
Returns:
-----------
new_centroids. ndarray. shape=(k, self.num_features).
Centroids for each cluster computed on the CURRENT time step
centroid_diff. ndarray. shape=(k, self.num_features).
Difference between current and previous centroid values
'''
self.k = k
data_centroid_labels = self.checkArrayType(data_centroid_labels)
prev_centroids = self.checkArrayType(prev_centroids)
if self.xp == np:
new_centroids = []
centroid_diff = []
for centroid_label, prev_centroid in enumerate(prev_centroids):
data_group_indicies = self.xp.where(data_centroid_labels == centroid_label)
data_with_label = self.xp.squeeze(self.data[data_group_indicies,:])
#TODO not sure if thius is proper way to handle when a centroid has not data label
# if some cluster appeared to be empty then:
# 1. find the biggest cluster
# 2. find the farthest from the center point in the biggest cluster
# 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster.
if data_with_label.size == 0:
new_centroid = self.find_farthest_data_point(centroid_label,distance_calc_method)
elif data_with_label.size == self.num_features:
new_centroid = data_with_label
else:
new_centroid = data_with_label.mean(axis=0)
new_centroids.append(new_centroid)
#TODO maybe no abs for better speed since it is very computationaly intensive
centroid_diff.append(abs(new_centroid - prev_centroid))
new_centroids = self.xp.array(new_centroids, dtype= self.xp.float64 )
centroid_diff = self.xp.array(centroid_diff, dtype= self.xp.float64)
return new_centroids, centroid_diff
else:
label_range_array = self.xp.arange(self.k)
label_matrix = data_centroid_labels == label_range_array[:, None]
sum_data_mask = label_matrix[:,:,None]
data_sums = self.sum_kernal(self.data,sum_data_mask, axis = 1)
counts_of_centroids = self.count_kernal(label_matrix, axis = 1).reshape((self.k,1))
new_centroids = data_sums/counts_of_centroids
centroid_diff = self.xp.abs(prev_centroids-new_centroids)
return new_centroids, centroid_diff
def compute_inertia(self ,distance_calc_method = 'L2',get_mean_dist_per_centroid = False,calc_dist_again = True):
'''Mean squared distance between every data sample and its assigned (nearest) centroid
Parameters:
-----------
None
Returns:
-----------
float. The average squared distance between every data sample and its assigned cluster centroid.
'''
# if isinstance(self.data_dist_from_centroid, type(None)):
if calc_dist_again:
#commented out code trying to make cleaner
centroid_mean_dist_array = self.xp.zeros(len(self.centroids))
centroid_mean_squared_dist_array= self.xp.zeros(len(self.centroids))
centroid_mean_squared_dist_list = []
for index, centroid in enumerate(self.centroids):
if distance_calc_method == 'L2':
data_in_centroid = self.data[self.data_centroid_labels == index]
centroid_square_dist_part_1 = (data_in_centroid - centroid) * (data_in_centroid - centroid)
if centroid_square_dist_part_1.shape[0] == 1:
centroid_square_dist_array = self.xp.sum(centroid_square_dist_part_1)
else:
centroid_square_dist_array = self.xp.sum(centroid_square_dist_part_1, axis=1)
if get_mean_dist_per_centroid:
centroid_dist_array = self.xp.sqrt(centroid_square_dist_array)
#if there is only one centroid witht he distance
if centroid_square_dist_part_1.shape[0] == 1:
centroid_mean_dist = centroid_dist_array
else:
centroid_mean_dist = self.xp.mean(centroid_dist_array)
centroid_mean_dist_array[index] = centroid_mean_dist
if centroid_square_dist_array.size == 1:
centroid_mean_squared = centroid_square_dist_array.max()
else:
centroid_mean_squared = self.xp.mean(centroid_square_dist_array)
#TODO fix calculation for squared dist not normal dist
elif distance_calc_method == 'L1':
data_in_centroid = self.data[np.where(self.data_centroid_labels == index),:]
if data_in_centroid.size == 0:
centroid_mean = 0
else:
data_in_centroid = data_in_centroid.reshape(int(data_in_centroid.size/self.num_features),self.num_features)
if data_in_centroid.size > self.num_features:
centroid_mean_squared = np.apply_along_axis(func1d = self.dist_pt_to_pt
,axis=1, arr=data_in_centroid,
pt_2=centroid, method=distance_calc_method)
else:
centroid_mean_squared = np.array(self.dist_pt_to_pt(data_in_centroid,centroid,distance_calc_method))
centroid_mean_squared_dist_array[index] = centroid_mean_squared
#TODO maybe add option for kernal use
sum_of_dists = self.xp.sum(self.xp.array(centroid_mean_squared_dist_array))
intertia = sum_of_dists/centroid_mean_squared_dist_array.size
if get_mean_dist_per_centroid:
return intertia, centroid_mean_dist_array
else:
return intertia
# if self.xp == cp:
#
# if get_mean_dist_per_centroid:
# return intertia, centroid_mean_dist_array
# else:
# return intertia
#
# if get_mean_dist_per_centroid:
# return intertia, centroid_mean_dist_array
# else:
# return intertia
#if the k means obj has been used atleast once
else:
# data_dist_from_centroids_squared = self.data_dist_from_centroid**2
intertia = self.xp.mean(self.data_dist_from_centroid)
if get_mean_dist_per_centroid:
num_classes_array = self.xp.arange(self.k)
label_one_hot = self.data_centroid_labels == num_classes_array[:, None]
# make booleans 0s and 1s to be multiplied
label_one_hot = label_one_hot.astype('int')
# sum_mask = label_one_hot[:, None, :]
if self.use_gpu:
#TODO add kernal operators
# grouped_data = label_one_hot * data_dist_from_centroids_squared[:, None].T
grouped_data = self.data_dist_from_centroid * label_one_hot
sum_grouped_data = grouped_data.sum(axis=1)
group_samp_counts = label_one_hot.sum(axis=1)
centroid_means = sum_grouped_data / group_samp_counts
return intertia, centroid_means
else:
# grouped_data = label_one_hot * data_dist_from_centroids_squared[:, None].T
grouped_data = self.data_dist_from_centroid * label_one_hot
sum_grouped_data = grouped_data.sum(axis=1)
group_samp_counts = label_one_hot.sum(axis=1)
centroid_means = sum_grouped_data/group_samp_counts
return intertia, centroid_means
return intertia
def plot_clusters(self, cmap = palettable.colorbrewer.qualitative.Paired_12.mpl_colormap, title = '' ,x_axis = 0, y_axis = 1, fig_sz = (8,8), legend_font_size = 10):
'''Creates a scatter plot of the data color-coded by cluster assignment.
cmap = palettable.colorbrewer.qualitative.Paired_12.mpl_colors
TODO: FIX THE LEGEND ALSO IF I WAS USING A DATA FRAME COULD USE
- Plot samples belonging to a cluster with the same color.
- Plot the centroids in black with a different plot marker.
- The default scatter plot color palette produces colors that may be difficult to discern
(especially for those who are colorblind). Make sure you change your colors to be clearly
differentiable.
You should use a palette Colorbrewer2 palette. Pick one with a generous
number of colors so that you don't run out if k is large (e.g. 10).
'''
fig, axes = plt.subplots(1,1,figsize = fig_sz)
#TODO maybe set up data frame based of of label
# Set the color map (cmap) to the colorbrewer one
scat = axes.scatter(self.data[:,x_axis], self.data[:,y_axis], c=self.data_centroid_labels, cmap=cmap)
# # Show the colorbar
# cbar = fig.colorbar(scat)
#
# # set labels
# cbar.ax.set_ylabel(c_var, fontsize=20)
# colors_legend_size = unique_c_vals.size
color_legend = axes.legend(*scat.legend_elements(), title = 'Groups:', loc = 'best',fontsize = legend_font_size,
title_fontsize = legend_font_size)
# color_legend = axes.legend(*scat.legend_elements(), bbox_to_anchor=(1.2, 1),
# loc="upper left")
# frameon = True
axes.add_artist(color_legend)
# axes.set_color_cycle(cmap)
# for group in np.unique(self.data_centroid_labels):
#
# x_data = self.data[self.data_centroid_labels == group,x_axis]
# y_data = self.data[self.data_centroid_labels == group, y_axis]
# axes.scatter(x_data,y_data,label = f'Group {group}')
# axes.set_title(title)
# axes.legend([f'Group {i+1}' for i in np.arange(np.unique(self.data_centroid_labels).size)])
return fig, axes
def elbow_plot(self, max_k, title = '',fig_sz = (8,8), font_size = 10, cluster_method = 'single', batch_iters = 20, distance_calc_method = 'L2', max_iter = 100, init_method = 'points'):
'''Makes an elbow plot: cluster number (k) on x axis, inertia on y axis.
Parameters:
-----------
max_k: int. Run k-means with k=1,2,...,max_k.
TODO:
- Run k-means with k=1,2,...,max_k, record the inertia.
- Make the plot with appropriate x label, and y label, x tick marks.
'''
#set up plot
fig, axes = plt.subplots(1,1,figsize =fig_sz)
k_s = np.arange(max_k) + 1
#do all the k-means
cluster_results = []
for i in k_s:
if cluster_method == 'single':
self.cluster(k=i, distance_calc_method=distance_calc_method, max_iter=max_iter, init_method=init_method)
cluster_results.append(self.get_inertia())
elif cluster_method == 'batch':
self.cluster_batch(k = i,n_iter=batch_iters,distance_calc_method=distance_calc_method,max_iter=max_iter, init_method = init_method)
cluster_results.append(self.get_inertia())
else:
print(f'Error! cluster_method needs to be single or batch\nCurrently it is {cluster_method}')
raise ValueError
k_means_interia = np.array(cluster_results)
axes.plot(k_s,k_means_interia)
axes.set_xticks(k_s)
axes.set_xlabel('Cluster(s)',fontsize = font_size)
axes.set_ylabel('Inertia')
axes.set_title(title)
return fig,axes
def replace_color_with_centroid(self):
'''Replace each RGB pixel in self.data (flattened image) with the closest centroid value.
Used with image compression after K-means is run on the image vector.
Parameters:
-----------
None
Returns:
-----------
None
'''
self.data = self.xp.array([self.centroids[label] for label in self.data_centroid_labels]).astype('int')
def find_farthest_data_point(self, label, distance_calc_method = 'L2'):
label = self.checkArrayType(label)
# one hot encode all the labels for the data
label_range_array = self.xp.arange(self.k)
label_matrix = self.data_centroid_labels == label_range_array[:, None]
if self.xp == np:
counts_of_centroids = label_matrix.astype('float64')
counts_of_centroids = self.xp.sum(counts_of_centroids,axis=1)
else:
counts_of_centroids = self.count_kernal(label_matrix, axis=1).reshape((self.k, 1))
largest_label = self.xp.argmax(counts_of_centroids)
data_in_largest_centroid = self.data[(self.data_centroid_labels == largest_label),:]
largest_centroid = self.centroids[largest_label]
pre_dist_calc_matrix = data_in_largest_centroid - largest_centroid
if distance_calc_method == 'L2':
if self.xp == np:
sum_part = self.xp.sum(pre_dist_calc_matrix, axis=1)
data_dists = self.xp.sqrt(sum_part * sum_part)
else:
data_dists = self.xp.zeros((data_in_largest_centroid.size,self.k), dtype = self.set_data_type)
data_dists = self.euclidean_dist_kernel(pre_dist_calc_matrix)
largest_data_point = data_in_largest_centroid[self.xp.argmax(data_dists)]
label_change_index = self.xp.where(self.xp.all(self.data==largest_data_point,axis=1))
self.data_centroid_labels[label_change_index] = label
return largest_data_point
|
966df10a557099162bebf95b42c79042a5f3d57a | Zen-Master-SoSo/legame | /examples/board-game.py | 4,283 | 3.546875 | 4 | """
Demonstrates board game moves, jumps, state changes, and animations
"""
import random
from pygame.locals import K_ESCAPE, K_q
from pygame import Rect
from pygame.sprite import Sprite
from legame.game import *
from legame.board_game import *
from legame.flipper import *
from legame.exit_states import *
class TestGame(BoardGame):
def __init__(self, options=None):
self.set_resource_dir_from_file(__file__)
BoardGame.__init__(self, options)
self.my_color = random.choice(["r", "g", "b"])
def initial_state(self):
return GSSelect(cell=None)
# Game states:
class GSBase(BoardGameState):
"""
Used as the base class of all game states defined in this module.
ESCAPE or Q button quits game.
"""
def keydown(self, event):
"""
Exit game immediately if K_ESCAPE key pressed
"""
if event.key == K_ESCAPE or event.key == K_q:
GSQuit()
class GSSelect(BoardGameState):
"""
Game state entered when the user must choose an empty space to fill, or their own block to move.
attributes used:
cell: the position that the last piece moved to, used as a reminder
Example of changing state to this:
GSSelect(cell=(x, y))
"""
may_click = True # May click on any block
cell = None
def enter_state(self):
Game.current.statusbar.write("GSSelect")
self.reminder_timer = None if self.cell is None else Game.current.set_timeout(self.timeout, 4000)
def click(self, cell, evt):
if self.reminder_timer is not None:
Game.current.clear_timeout(self.reminder_timer)
if cell.is_mine():
GSSelectMoveTarget(cell=cell)
else:
Block(cell, Game.current.my_color)
self.cell = cell # Used to jiggle the last piece moved
self.reminder_timer = Game.current.set_timeout(self.timeout, 4000)
def timeout(self, args):
self.cell.piece().jiggle()
def keydown(self, event):
"""
Exit game immediately if K_ESCAPE or "q" keys pressed
"""
if event.key == K_ESCAPE or event.key == K_q:
GSQuit()
def exit_state(self, next_state):
if self.reminder_timer is not None:
Game.current.clear_timeout(self.reminder_timer)
class GSSelectMoveTarget(BoardGameState):
"""
Game state entered after the user choses their own block, setting up for a move.
attributes used:
cell: the position of the block to move
Example of changing state to this:
GSSelectMoveTarget(cell=(x, y))
"""
may_click = True # May click on any block
cell = None
def enter_state(self):
self.selected_piece = self.cell.piece().glow()
Game.current.statusbar.write("GSSelectMoveTarget")
def click(self, cell, evt):
self.selected_piece.unglow()
if cell.is_mine():
self.selected_piece = cell.piece().glow()
else:
Game.current.play("jump.wav")
self.selected_piece.move_to(cell, lambda: GSSelect(cell=cell))
def keydown(self, event):
"""
Exit game immediately if K_ESCAPE key pressed
"""
if event.key == K_ESCAPE or event.key == K_q:
GSQuit()
# Sprites:
class Block(GamePiece, Flipper):
def __init__(self, cell, color):
self.image_base = "Block/" + color
GamePiece.__init__(self, cell, color)
Flipper.__init__(self, FlipThrough("enter", fps=25), FlipNone())
Game.current.play("enter.wav")
self.__glow = None
def update(self):
GamePiece.update(self)
Flipper.update(self)
def jiggle(self):
self.flip(FlipBetween("jiggle", loops=11, fps=30), FlipNone())
return self
def glow(self):
self.__glow = Glow(self.cell)
return self
def unglow(self):
if self.__glow:
self.__glow.kill()
self.__glow = None
return self
def kill(self):
Game.current.play("bust.wav")
Sprite.kill(self)
class Glow(Flipper, Sprite):
def __init__(self, cell, frame=0):
self.cell = cell
self.rect = self.cell.rect()
Sprite.__init__(self, Game.current.sprites)
Game.current.sprites.change_layer(self, Game.LAYER_BELOW_PLAYER)
Flipper.__init__(self, FlipBetween(loop_forever=True, frame=frame, fps=30))
if __name__ == '__main__':
import argparse, sys
p = argparse.ArgumentParser()
p.epilog = "Demonstrates board game moves, jumps, state changes, and animations"
p.add_argument("--quiet", "-q", action="store_true", help="Don't make sound")
p.add_argument("--verbose", "-v", action="store_true", help="Show more detailed debug information")
sys.exit(TestGame(p.parse_args()).run())
|
e8939e901f55d02c0a520a80b493cdb4ec9fd5a4 | amishramuz/attendance_management_system | /db.py | 786 | 3.796875 | 4 | import sqlite3
class Database:
def __init__(self,db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS STUDENT (id integer primary key,name text,regi INTEGER ,branch text)")
self.conn.commit()
def fetch(self):
self.cur.execute("select * from STUDENT")
rows=self.cur.fetchall()
return rows
def insert(self,name,regi,branch):
self.cur.execute("INSERT into STUDENT values (null,?,?,?)",(name,regi,branch))
self.conn.commit()
def remove(self,regi):
self.cur.execute("delete from STUDENT where regi=(?)",(regi))
self.conn.commit()
def __del__(self):
self.conn.close()
|
aae22cc73f327d9a128c0c313de0369ae6923e1f | caoxp930/MyPythonCode | /49class/7.01/7.01/lesson13/two_内置装饰器.py | 1,579 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:fei time:2019/7/1 20:35
# 类的定义和使用
class Cat:
"""这是一个猫类"""
name = '猫'
def __init__(self, color, eat):
self.color = color
self.eat = eat
@property
def print_cat(self):
print("{}-{}".format(self.color, self.eat))
@staticmethod # 方法变静态方法,没有参数绑定
def func():
print("我来测试静态方法")
print("我不需要self参数也能运行")
print("我不需要实例化也能运行")
@classmethod # 类方法
def func1(cls): # cls代表类本身
# def func1(self, cls): # cls代表类本身
print("="*50)
print("我是来测试类方法的")
print(cls)
print(cls.name)
Cat.func() # 解绑,不用实例化就可以调用方法。执行效率高
kitty = Cat('white', 'food')
print(kitty.color)
kitty.color = "hua"
print(kitty.color)
# kitty.print_cat() # 调用类内方法的方式
# 1.property装饰器:方法变属性
# class、instance、property
# 使用起来方便,但是又不能随意去修改
kitty.print_cat
# 2.staticmethod装饰器:方法变静态方法,没有参数绑定
# 只在类本身生效
kitty.func()
Cat.func()
# 3.classmethod装饰器:方法变类方法
kitty.func1()
print("以下是类名.类方法")
Cat.func1()
# 属性:实例是可以调用实例属性、类属性,类只能调用类属性
# 方法:实例是可以调用类内方法、类方法,类只能调用类方法
# Cat.func1(kitty)
|
4bb63801ee4d89f2812a86cce4815cd0d465f718 | gogomillan/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 4,646 | 3.59375 | 4 | #!/usr/bin/python3
"""
Module for class Base
"""
import json
import csv
class Base:
"""
Class Base
"""
""" Private class attribute """
__nb_objects = 0
def __init__(self, id=None):
"""
Class constructor method
Args:
id (int): The id for the Base class
"""
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
@staticmethod
def to_json_string(list_dictionaries):
"""
Return the JSON serialization of a list of dicts.
Args:
list_dictionaries (list): A list of dictionaries.
"""
if list_dictionaries is None or list_dictionaries == []:
return "[]"
return json.dumps(list_dictionaries)
@classmethod
def save_to_file(cls, list_objs):
"""
Write the JSON serialization of a list of objects to a file.
Args:
list_objs (list): A list of inherited Base instances.
"""
filename = cls.__name__ + ".json"
with open(filename, "w") as jsonfile:
if list_objs is None:
jsonfile.write("[]")
else:
list_dicts = [o.to_dictionary() for o in list_objs]
jsonfile.write(Base.to_json_string(list_dicts))
@staticmethod
def from_json_string(json_string):
"""
Return the deserialization of a JSON string.
Args:
json_string (str): A JSON str representation of a list of dicts.
Returns:
If json_string is None or empty - an empty list.
Otherwise - the Python list represented by json_string.
"""
if json_string is None or json_string == "[]":
return []
return json.loads(json_string)
@classmethod
def create(cls, **dictionary):
"""
Return a class instantied from a dictionary of attributes.
Args:
**dictionary (dict): Key/value pairs of attributes to initialize.
"""
if dictionary and dictionary != {}:
if cls.__name__ == "Rectangle":
new = cls(1, 1)
else:
new = cls(1)
new.update(**dictionary)
return new
@classmethod
def load_from_file(cls):
"""
Return a list of classes instantiated from a file of JSON strings.
Reads from `<cls.__name__>.json`.
Returns:
If the file does not exist - an empty list.
Otherwise - a list of instantiated classes.
"""
filename = str(cls.__name__) + ".json"
try:
with open(filename, "r") as jsonfile:
list_dicts = Base.from_json_string(jsonfile.read())
return [cls.create(**d) for d in list_dicts]
except IOError:
return []
@classmethod
def save_to_file_csv(cls, list_objs):
"""
Write the CSV serialization of a list of objects to a file.
Args:
list_objs (list): A list of inherited Base instances.
"""
filename = cls.__name__ + ".csv"
with open(filename, "w", newline="") as csvfile:
if list_objs is None or list_objs == []:
csvfile.write("[]")
else:
if cls.__name__ == "Rectangle":
fieldnames = ["id", "width", "height", "x", "y"]
else:
fieldnames = ["id", "size", "x", "y"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
for obj in list_objs:
writer.writerow(obj.to_dictionary())
@classmethod
def load_from_file_csv(cls):
"""
Return a list of classes instantiated from a CSV file.
Reads from `<cls.__name__>.csv`.
Returns:
If the file does not exist - an empty list.
Otherwise - a list of instantiated classes.
"""
filename = cls.__name__ + ".csv"
try:
with open(filename, "r", newline="") as csvfile:
if cls.__name__ == "Rectangle":
fieldnames = ["id", "width", "height", "x", "y"]
else:
fieldnames = ["id", "size", "x", "y"]
list_dicts = csv.DictReader(csvfile, fieldnames=fieldnames)
list_dicts = [dict([k, int(v)] for k, v in d.items())
for d in list_dicts]
return [cls.create(**d) for d in list_dicts]
except IOError:
return []
|
e034787a22486272a59e5e4abb0d8bde0cfb31a4 | messersm/sudokutools | /sudokutools/solvers.py | 20,083 | 4.125 | 4 | """High level solving of sudokus.
This module provides classes which represent typical sudoku solving
steps used by humans. Steps can be found and applied to a given
sudoku. But steps can also be printed without applying them, e.g. to inform
a user, what steps can be taken to solve the sudoku.
A single solve step may consist of multiple actions, e.g.
* Setting a number at a given field.
* Setting the candidates at a given field.
* Removing some of the candidates at a given field.
Solve steps defined here:
* CalcCandidates
* NakedSingle
* NakedPair
* NakedTriple
* NakedQuad
* NakedQuint
* HiddenSingle
* HiddenPair
* HiddenTriple
* HiddenQuad
* HiddenQuint
* PointingPair
* PointingTriple
* XWing
* Swordfish
* Jellyfish
* Bruteforce
"""
from collections import defaultdict, namedtuple
from functools import total_ordering
from itertools import combinations, product
from sudokutools.solve import init_candidates, calc_candidates, dlx
from sudokutools.sudoku import Sudoku
class Action(namedtuple("ActionTuple", ["func", "row", "col", "value"])):
"""Named tuple, that represents a single change operation on a sudoku.
Create with: Action(func, row, col, value)
Args:
func (callable): One of Sudoku.set_number, Sudoku.set_candidates and
Sudoku.remove_candidates
row (int): The row of the field, which will be changed.
col (int): The column of the field, which will be changed.
value (int or iterable): The number or candidates to set/remove.
"""
@total_ordering
class SolveStep(object):
def __init__(self, clues=(), affected=(), values=()):
"""Create a new solve step.
Args:
clues (iterable of (int, int)): An iterable of (row, col) pairs
which cause this step.
affected (iterable of (int, int)): An iterable of (row, col)
pairs which are affected by
this step.
values (iterable of int) : A list of values to apply to the
affected fields.
"""
self.clues = tuple(sorted(clues))
self.affected = tuple(sorted(affected))
self.values = tuple(sorted(values))
self.actions = []
def __eq__(self, other):
return (self.clues, self.affected, self.values) == (
other.clues, other.affected, other.values)
def __lt__(self, other):
return (self.clues, self.affected, self.values) < (
other.clues, other.affected, other.values)
def __repr__(self):
return "%s(%s, %s, %s)" % (
self.__class__.__name__, self.clues, self.affected, self.values)
def __str__(self):
return "%s at %s: %s" % (
self.__class__.__name__, self.clues, self.values)
@classmethod
def find(cls, sudoku):
"""Iterates through all possible solve steps of this class.
Args:
sudoku (Sudoku): The sudoku to solve.
Yields:
SolveStep: The next solve step.
"""
raise NotImplementedError("%s.find() not implemented." % cls.__name__)
def build_actions(self, sudoku):
raise NotImplementedError(
"%s.build_actions() not implemented." % self.__class__.__name__)
def apply(self, sudoku):
"""Apply this solve step to the sudoku."""
if not self.actions:
self.build_actions(sudoku)
for action in self.actions:
action.func(sudoku, action.row, action.col, action.value)
@classmethod
def apply_all(cls, sudoku):
"""Apply all possible steps of this class to the sudoku."""
for step in cls.find(sudoku):
step.apply(sudoku)
class CalculateCandidates(SolveStep):
"""Calculates the candidates of fields."""
@classmethod
def find(cls, sudoku):
for row, col in sudoku:
# ignore fields with defined candidates
if sudoku.get_candidates(row, col):
continue
values = calc_candidates(sudoku, row, col)
yield cls(((row, col),), ((row, col),), values)
def build_actions(self, sudoku):
row, col = self.clues[0]
self.actions.append(
Action(Sudoku.set_candidates, row, col, self.values))
class _SingleFieldStep(SolveStep):
"""Represents a solve method, which sets a single field."""
def __init__(self, row, col, value):
super(_SingleFieldStep, self).__init__(
((row, col),), ((row, col),), (value, ))
def __repr__(self):
row, col = self.clues[0]
value = self.values[0]
return "%s(%d, %d, %d)" % (self.__class__.__name__, row, col, value)
def __str__(self):
return "%s at %s: %s" % (
self.__class__.__name__, self.clues[0], self.values[0])
@classmethod
def find(cls, sudoku):
raise NotImplementedError("%s.find() not implemented." % cls.__name__)
def build_actions(self, sudoku):
row, col = self.affected[0]
value = self.values[0]
self.actions.append(
Action(Sudoku.set_number, row, col, value))
self.actions.append(
Action(Sudoku.set_candidates, row, col, {value}))
for i, j in sudoku.surrounding_of(row, col, include=False):
if value in sudoku.get_candidates(i, j):
self.actions.append(
Action(Sudoku.remove_candidates, i, j, {value}))
class NakedSingle(_SingleFieldStep):
"""Finds naked singles in a sudoku.
A naked single is a field with only one candidate.
The field can be set to this candidate and this candidate
can be removed from all fields in the same row, column and box.
"""
@classmethod
def find(cls, sudoku):
for row, col in sudoku.empty():
candidates = sudoku.get_candidates(row, col)
if len(candidates) == 1:
for value in candidates:
break
yield cls(row, col, value)
class HiddenSingle(_SingleFieldStep):
"""Finds hidden singles in a sudoku.
A hidden single is a field containing a candidate which
exists in no other fields in the same row, column or box.
The field can be set to this candidate and this candidate
can be removed from all fields in the same row, column and box.
"""
@classmethod
def find(cls, sudoku):
yielded_coords = []
for row, col in sudoku.empty():
for f in sudoku.column_of, sudoku.row_of, sudoku.box_of:
found_hidden_single = False
candidates = set(sudoku.numbers)
for i, j in f(row, col, include=False):
candidates -= sudoku.get_candidates(i, j)
for value in candidates:
if (row, col) not in yielded_coords:
yielded_coords.append((row, col))
yield cls(row, col, value)
found_hidden_single = True
# skip the other functions
if found_hidden_single:
break
class Bruteforce(_SingleFieldStep):
"""Solve the sudoku using brute force.
Bruteforce simply works by trial and error testing each
combination of valid candidates in a field until a
solution has been found.
"""
@classmethod
def find(cls, sudoku):
try:
solution = next(dlx(sudoku))
except StopIteration:
return
for row, col in sudoku.diff(solution):
yield cls(row, col, solution[row, col])
class NakedTuple(SolveStep):
"""Finds naked tuples in a sudoku.
A naked tuple is a set of n fields in a row, column or box,
which (in unison) contain a set of at most n candidates.
These candidates can be removed from all fields in the
same row, column or box.
"""
n = 2
def build_actions(self, sudoku):
for (i, j) in self.affected:
to_remove = set(self.values) & sudoku.get_candidates(i, j)
self.actions.append(
Action(Sudoku.remove_candidates, i, j, to_remove)
)
@classmethod
def find(cls, sudoku):
# keep track of yielded steps
yielded_coords = []
# we work through rows, cols and quads in 3 steps, since the
# empty fields can changed in-between
for func in sudoku.row_of, sudoku.column_of, sudoku.box_of:
clist = []
for (row, col) in sudoku.empty():
coords = func(row, col)
if coords not in clist:
clist.append(coords)
for coords in clist:
for step in cls.__find_at(sudoku, coords):
if step.clues not in yielded_coords:
yielded_coords.append(step.clues)
yield step
@classmethod
def __find_at(cls, sudoku, coords):
# Create a list of fields with at least 2 and at most n candidates.
# (We ignore naked singles here, because combinations() would
# return a very long list otherwise.)
n_candidates = [(row, col) for (row, col) in coords if 1 < len(
sudoku.get_candidates(row, col)) <= cls.n]
for fields in combinations(n_candidates, cls.n):
all_candidates = set()
for (row, col) in fields:
all_candidates |= sudoku.get_candidates(row, col)
if len(all_candidates) <= cls.n:
# Naked Tuple found - only yield, if actions can be applied.
affected = [(r, c) for r, c in coords if (r, c) not in fields
and set(all_candidates)& sudoku.get_candidates(r, c)]
if affected:
step = cls(
clues=fields, affected=affected, values=all_candidates)
yield step
NakedPair = type("NakedPair", (NakedTuple,), dict(n=2))
NakedTriple = type("NakedTriple", (NakedTuple,), dict(n=3))
NakedQuad = type("NakedQuad", (NakedTuple,), dict(n=4))
NakedQuint = type("NakedQuint", (NakedTuple,), dict(n=5))
class HiddenTuple(SolveStep):
"""Finds hidden tuples in a sudoku.
A hidden tuple is a set of n fields in a row, column or box,
which (in unison) contain a set of at most n candidates, which
are present in no other fields of the same row, column or box.
All other candidates can be removed from these fields.
"""
n = 2
def build_actions(self, sudoku):
for row, col in self.affected:
to_remove = sudoku.get_candidates(row, col) - set(self.values)
self.actions.append(
Action(Sudoku.remove_candidates, row, col, to_remove))
@classmethod
def find(cls, sudoku):
# keep track of yielded steps
yielded_coords = []
# we work through rows, cols and quads in 3 steps, since the
# empty fields can changed in-between
for func in sudoku.row_of, sudoku.column_of, sudoku.box_of:
clist = []
for (i, j) in sudoku.empty():
coords = func(i, j)
if coords not in clist:
clist.append(coords)
for coords in clist:
for step in cls.__find_at(sudoku, coords):
yield step
@classmethod
def __find_at(cls, sudoku, coords):
cand_coords = defaultdict(lambda: set())
# build coordinate list for each candidate
for cand in sudoku.numbers:
for (row, col) in coords:
if cand in sudoku.get_candidates(row, col):
cand_coords[cand].add((row, col))
# create a list of numbers with at most n occurrences
n_times = [c for c in sudoku.numbers if 1 < len(cand_coords[c]) <= cls.n]
# select n numbers from the n_times list
for numbers in combinations(n_times, cls.n):
max_set = set()
for num in numbers:
max_set |= cand_coords[num]
if len(max_set) <= cls.n:
# hidden tuple found - only yield, if there are actions to apply
for (row, col) in max_set:
affected = [(r, c) for r, c in max_set
if sudoku.get_candidates(r, c) - set(numbers)]
if affected:
yield cls(clues=coords, affected=affected, values=numbers)
HiddenPair = type("HiddenPair", (HiddenTuple,), dict(n=2))
HiddenTriple = type("HiddenTriple", (HiddenTuple,), dict(n=3))
HiddenQuad = type("HiddenQuad", (HiddenTuple,), dict(n=4))
HiddenQuint = type("HiddenQuint", (HiddenTuple,), dict(n=5))
class PointingTuple(SolveStep):
n = 2
@classmethod
def find(cls, sudoku):
# reducing row or column candidates
for box in sudoku.indices:
for step in cls.__find_in_box(sudoku, box):
yield step
# reducing box candidates
for x in sudoku.indices:
for step in cls.__find_in_row_and_column(sudoku, x):
yield step
@classmethod
def __find_in_row_and_column(cls, sudoku, x):
for f in sudoku.row_of, sudoku.column_of:
coords = f(x, x)
for candidate in sudoku.numbers:
clues = [(r, c) for r, c in coords
if candidate in sudoku.get_candidates(r, c)]
# skip, if this doesn't have the correct number of fields
# (e.g. we have a pair, but want a triple)
if len(clues) != cls.n:
continue
# if all fields with this candidate lie in the same
# box, remove this candidate from all other fields
# in the box
if len(set([sudoku.box_at(r, c) for r, c in clues])) == 1:
affected = [(r, c) for r, c in sudoku.box_of(*clues[0])
if (r, c) not in clues
and candidate in sudoku.get_candidates(r, c)]
if affected:
yield cls(
clues=clues, affected=affected, values=(candidate,))
@classmethod
def __find_in_box(cls, sudoku, box):
row = (box // sudoku.box_height) * sudoku.box_height
col = (box % sudoku.box_height) * sudoku.box_width
box_coords = sudoku.box_of(row, col)
for candidate in sudoku.numbers:
clues = [(r, c) for r, c in box_coords
if candidate in sudoku.get_candidates(r, c)]
# skip, if this doesn't have the correct number of fields
# (e.g. we have a pair, but want a triple)
if len(clues) != cls.n:
continue
# if all fields with this candidate lie in the same row
# remove this candidate from all other fields in the same row
if len(set([r for r, c in clues])) == 1:
affected = [(r, c) for r, c in sudoku.row_of(*clues[0])
if (r, c) not in clues
and candidate in sudoku.get_candidates(r, c)]
# if all fields with this candidate lie in the same column
# remove this candidate from all other fields in the same column
elif len(set([c for r, c in clues])) == 1:
affected = [(r, c) for r, c in sudoku.column_of(*clues[0])
if (r, c) not in clues
and candidate in sudoku.get_candidates(r, c)]
else:
affected = []
if affected:
yield cls(
clues=clues, affected=affected, values=(candidate,))
def build_actions(self, sudoku):
val = self.values[0]
for r, c in self.affected:
self.actions.append(
Action(Sudoku.remove_candidates, r, c, self.values))
PointingPair = type("PointingPair", (PointingTuple,), dict(n=2))
PointingTriple = type("PointingTriple", (PointingTuple,), dict(n=3))
class BasicFish(SolveStep):
n = 2
@classmethod
def find(cls, sudoku):
variants = ((0, sudoku.row_of, sudoku.column_of),
(1, sudoku.column_of, sudoku.row_of))
for item, candidate in product(variants, sudoku.numbers):
for step in cls.__find_for_candidate(sudoku, candidate, *item):
yield step
@classmethod
def __find_for_candidate(
cls, sudoku, candidate, offset, base_func, cover_func):
# fields with this candidate, keyed by their index.
fields = {}
for i in sudoku.indices:
fields[i] = [(r, c) for r, c in base_func(i, i)
if candidate in sudoku.get_candidates(r, c)]
valid_indices = [i for i in fields if 2 <= len(fields[i]) <= cls.n]
for indices in combinations(valid_indices, cls.n):
base_fields = []
for i in indices:
base_fields.extend(fields[i])
other_counts = defaultdict(lambda: 0)
other_offset = (offset + 1) % 2
for coord in base_fields:
other_counts[coord[other_offset]] += 1
# The other coordinate only appears once,
# so this is not a valid fish
if min(other_counts.values()) < 2:
continue
# There are more than cls.n other coordinates,
# so this is not a valid fish
if len(other_counts) > cls.n:
continue
covered = []
for val in other_counts:
covered.extend(cover_func(val, val))
affected = [(r, c) for r, c in covered
if (r, c) not in base_fields
and candidate in sudoku.get_candidates(r, c)]
if affected:
yield cls(
clues=base_fields,
affected=affected,
values=(candidate,)
)
def build_actions(self, sudoku):
for r, c in self.affected:
self.actions.append(
Action(Sudoku.remove_candidates, r, c, self.values))
XWing = type("XWing", (BasicFish,), dict(n=2))
Swordfish = type("Swordfish", (BasicFish,), dict(n=3))
Jellyfish = type("Jellyfish", (BasicFish,), dict(n=4))
# A list of available solve methods (in the order, they're used by solve())
SOLVERS = [
CalculateCandidates,
NakedSingle,
HiddenSingle,
NakedPair,
HiddenPair,
NakedTriple,
HiddenTriple,
NakedQuad,
HiddenQuad,
NakedQuint,
HiddenQuint,
PointingPair,
PointingTriple,
XWing,
Swordfish,
Jellyfish,
Bruteforce,
]
def solve(sudoku, report=lambda step: None):
"""Solve the sudoku and return the solution.
Args:
sudoku (Sudoku): The sudoku to solve.
report (callable): A function taking a single argument (the current
step), which can be used as a callback.
Returns:
Sudoku: The solution of the sudoku.
"""
solution = sudoku.copy()
init_candidates(solution, filled_only=True)
while True:
for cls in SOLVERS:
count = 0
for step in cls.find(solution):
report(step)
step.apply(solution)
count += 1
if count > 0:
break
else:
break
return solution
def hints(sudoku):
"""Yield all available solve steps for the current state of a sudoku.
Args:
sudoku (Sudoku): The sudoku to get hints for.
Yields:
SolveStep: A step available for the given sudoku in the current state.
"""
for solver in SOLVERS:
if solver == Bruteforce:
continue
for step in solver.find(sudoku):
yield step
|
4d25f9383bf7b596ebd89aa88930cd821be41d82 | masterkanch/Comproproject | /login.py | 1,899 | 3.8125 | 4 | def begin():
global option
print("Welcome to Game")
option = input("Login or Register or LeaderBoard(login,reg,score): ")
if(option!="login" and option != "reg" and option != "score"):
begin()
def login(name,password):
success = False
file = open("user.txt","r")
for i in file:
a,b = i.split(",")
a = a.strip()
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Successful!!!")
import ComPro_Project_Keng
else:
print("wrong username or password")
def register(name,password):
file = open('user.txt','a')
file.write(f'{name},{password}\n')
file.close
import ComPro_Project_Keng
def begin():
global option
print("Welcome to Game")
option = input("Login or Register or LeaderBoard(login,reg,score): ")
if(option!="login" and option != "reg" and option != "score"):
begin()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("Enter your password: ")
login(name,password)
elif option == "reg":
print("Enter your name and password to register")
name = input("Enter your name: ")
password = input("Enter your password: ")
register(name,password)
elif option == "score":
LeaderBoard()
def LeaderBoard():
print("=======================LeaderBoard====================")
print("Username Totalscore ")
file = open("score.txt","r")
for i in file:
Username,chompoo,namkhing,totalscore = i.split(",")
Username = Username.strip()
totalscore = totalscore.strip()
print(f"{Username} {totalscore}")
file.close()
begin()
access(option)
|
e4244518438e52cd1f3b9859f3b039e4ef86a700 | ankitt8/mahawiki | /Python Challenge/Solution3/solution_three_PradnyaB - Pradnya Borkar.py | 239 | 3.8125 | 4 | String1=input("Enter String")
list1=list(String1)
set1=set(list1)
maximum=0
val=""
for i in set1:
if maximum<list1.count(i):
maximum=list1.count(i)
val=i
print(val)
"""
Enter String aaaaaaaaaaaaaaaaaabbbbcddddeeeeee
a
""" |
0992ddaa2d28a61131abe027bc16ce71f094417f | mcgowent/Python-Adventure-Game | /src/room.py | 569 | 3.828125 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
# base class for rooms
def __init__(self, name, description, itemArr=[]):
self.name = name
self.description = description
self.itemArr = itemArr
def showItems(self):
if(len(self.itemArr) > 0):
for i in self.itemArr:
print(i)
else:
print("There are no items in the room")
def __repr__(self):
return f"Room({self.name, self.description, self.itemArr})"
|
38580d205b5c2fea47b7841b932043433047d93e | mbakin/py-samples | /biggestNumber.py | 541 | 4.3125 | 4 | """
Traning: Which number is the biggest
"""
number1 = float(input("First Number = " ))
number2 = float(input("Second Number = "))
number3 = float(input("Third Number = "))
a = [number1, number2, number3]
a.sort()
print("Sorted Values = " + str(a))
print("************************")
if number1>number2 and number1>number3:
print("Number 1 biggest than values")
elif number2>number3 and number3>number1:
print("Number 2 biggest in values")
else:
print("Number 3 biggest than values")
|
d9d381b1ecbc86e933c63274a9945fa8ba4e1914 | shivasitharaman/python | /py3.py | 116 | 3.890625 | 4 | num1 = 50
num2 = 3
div = int(num1) / int(num2)
print('The div of {0} and {1} is {2}'.format(num1, num2, div)) |
c53793bb40c36b89481c06266eab87da9b372ade | lohitha02/task1 | /task1.py | 1,330 | 4.1875 | 4 | import random
computer=["rock","paper","scissors"]
userscore=0
computerscore=0
for i in range(0,5):
user=input()
while(user!="rock" and user!="paper" and user!="scissors"):
print("enter either rock or paper or scissors")
user=input()
choice=random.choice(computer)
if(user==choice):
print("tie,scores are equal")
elif(user=="rock"):
if(choice=="scissors"):
print("rock blunts scissors,you won")
userscore=userscore+5
else:
print("computer wins")
computerscore=computerscore+5
elif(user=="scissors"):
if(choice=="paper"):
print("scissors cut paper,you won")
userscore=userscore+5
else:
print("computer wins")
computerscore=computerscore+5
elif(user=="paper"):
if(choice=="rock"):
print("paper covers rock,you won")
userscore=userscore+5
else:
print("computer wins")
computerscore=computerscore+5
else:
print("something is wrong,please check the input")
print("userscore="+str(userscore))
print("computerscore="+str(computerscore))
if(userscore>computerscore):
print("yayyy you won")
elif(computerscore==userscore):
print("match tied")
else:
print("computer won")
|
cfbc419f57f21ae71877a00208876e7d1b8cd407 | wesleyjr01/rest_api_flask | /2_python_refresher/52-mutable_default_params.py | 629 | 3.90625 | 4 | """
Mutable Default Parameters (and why they're a bad Idea.)
Never make a parameter equal to a mutable value by default.
__init__(self, List[int] = []) # Bad
__init__(self, List[int] = None) # Good
"""
from typing import List
class Student:
def __init__(self, name: str, grades: List[int] = []): # This is bad!
self.name = name
self.grades = grades
def take_exam(self, result):
self.grades.append(result)
# Check the problem here, both bob and rolf are sharing the same list
bob = Student("Bob")
rolf = Student("Rolf")
bob.take_exam(90)
print(bob.grades)
print(rolf.grades)
|
245852d73edba80c8a39bb7336452489d127a85d | yunnong770/EE-247-HW | /HW5-codes/nndl/conv_layers.py | 11,881 | 3.875 | 4 | import numpy as np
from nndl.layers import *
import pdb
"""
This code was originally written for CS 231n at Stanford University
(cs231n.stanford.edu). It has been modified in various areas for use in the
ECE 239AS class at UCLA. This includes the descriptions of what code to
implement as well as some slight potential changes in variable names to be
consistent with class nomenclature. We thank Justin Johnson & Serena Yeung for
permission to use this code. To see the original version, please visit
cs231n.stanford.edu.
"""
def conv_forward_naive(x, w, b, conv_param):
"""
A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and width
W. We convolve each input with F different filters, where each filter spans
all C channels and has height HH and width HH.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
out = None
pad = conv_param['pad']
stride = conv_param['stride']
# ================================================================ #
# YOUR CODE HERE:
# Implement the forward pass of a convolutional neural network.
# Store the output as 'out'.
# Hint: to pad the array, you can use the function np.pad.
# ================================================================ #
N, C, H, W = x.shape
F, C, HH, WW = w.shape
H_out = int(1 + (H + 2*pad - HH)/stride)
W_out = int(1 + (W + 2*pad - WW)/stride)
out = np.zeros((N, F, H_out, W_out))
x_padded = np.pad(x, ((0, 0), (0, 0), (pad, pad),(pad, pad)), constant_values = 0)
for n in range(N):
for f in range(F):
for i in range(H_out):
for j in range(W_out):
out[n, f, i, j] = np.sum(x_padded[n, :, i*stride:i*stride+HH, j*stride:j*stride+WW]*w[f, :, :, :]) + b[f]
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
cache = (x, w, b, conv_param)
return out, cache
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
N, F, out_height, out_width = dout.shape
x, w, b, conv_param = cache
stride, pad = [conv_param['stride'], conv_param['pad']]
xpad = np.pad(x, ((0,0), (0,0), (pad,pad), (pad,pad)), mode='constant')
num_filts, _, f_height, f_width = w.shape
# ================================================================ #
# YOUR CODE HERE:
# Implement the backward pass of a convolutional neural network.
# Calculate the gradients: dx, dw, and db.
# ================================================================ #
dx = np.zeros_like(x)
dw = np.zeros_like(w)
db = np.sum(dout, axis = (0, 2, 3))
n, c, hh, ww = dout.shape
# x_dilated = np.zeros((n, c, stride*hh - stride + 1, stride*ww - stride + 1), dtype = x.dtype)
# x_dilated[:, :, ::stride, ::stride] = x
dout_dilated = np.zeros((n, c, stride*hh, stride*ww), dtype = x.dtype)
dout_dilated[:, :, ::stride, ::stride] = dout
x_padded = np.pad(x, ((0, 0), (0, 0), (pad, pad+1),(pad, pad+1)), constant_values = 0)
N, C, H, W = x_padded.shape
for n in range(N):
for f in range(F):
for d in range(C):
for i in range(W - out_width*stride + stride - 1):
for j in range(H - out_height*stride + stride - 1):
dw[f, d, i, j] += np.sum(dout_dilated[n, f, :, :]*x_padded[n, d, i:i+out_width*stride, j:j+out_height*stride])
_, _, H, W = x.shape
_, _, H_w, W_w = w.shape
w_rotated = np.rot90(w, axes = (2, 3))
w_rotated = np.rot90(w_rotated, axes = (2, 3))
dout_padded = np.pad(dout_dilated, ((0, 0), (0, 0), (pad, pad),(pad, pad)), constant_values = 0)
N, C, H, W = x.shape
for n in range(N):
for f in range(F):
for d in range(C):
for i in range(W):
for j in range(H):
dx[n, d, i, j] += np.sum(dout_padded[n, f, i:i+W_w, j:j+H_w]*w_rotated[f, d, :, :])
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx, dw, db
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
Returns a tuple of:
- out: Output data
- cache: (x, pool_param)
"""
out = None
# ================================================================ #
# YOUR CODE HERE:
# Implement the max pooling forward pass.
# ================================================================ #
pool_width, pool_height, stride = pool_param['pool_width'], pool_param['pool_height'], pool_param['stride']
N, C, H, W = x.shape
out_height = int((H-pool_height)/stride + 1)
out_width = int((W-pool_width)/stride + 1)
out = np.zeros((N, C, out_height, out_width))
x_temp = x
for n in range(N):
for c in range(C):
for i in range(out_height):
for j in range(out_width):
out[n, c, i, j] = np.max(x_temp[n, c, i*stride:i*stride+pool_height, j*stride:j*stride+pool_width])
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a max pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
dx = None
x, pool_param = cache
pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride']
# ================================================================ #
# YOUR CODE HERE:
# Implement the max pooling backward pass.
# ================================================================ #
pool_width, pool_height, stride = pool_param['pool_width'], pool_param['pool_height'], pool_param['stride']
N, C, H, W = x.shape
N, C, H_dout, W_dout = dout.shape
dx = x
dout_temp = dout
for n in range(N):
for c in range(C):
for i in range(H_dout):
for j in range(W_dout):
local_max = np.max(dx[n, c, i*stride:i*stride+pool_height, j*stride:j*stride+pool_width])
dx_local = dx[n, c, i*stride:i*stride+pool_height, j*stride:j*stride+pool_width]
dx_local[dx_local<local_max] = 0
dx_local[dx_local != 0] = 1
dx_local = dx_local*dout_temp[n, c, i, j]
dx[n, c, i*stride:i*stride+pool_height, j*stride:j*stride+pool_width] = dx_local
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx
def spatial_batchnorm_forward(x, gamma, beta, bn_param):
"""
Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance. momentum=0 means that
old information is discarded completely at every time step, while
momentum=1 means that new information is never incorporated. The
default of momentum=0.9 should work well in most situations.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
# ================================================================ #
# YOUR CODE HERE:
# Implement the spatial batchnorm forward pass.
#
# You may find it useful to use the batchnorm forward pass you
# implemented in HW #4.
# ================================================================ #
N, C, H, W = x.shape
x_temp = np.zeros((N*H*W, C))
for c in range(C):
x_temp[:, c] = np.reshape(x[:,c,:,:], (N*H*W))
out_temp, cache = batchnorm_forward(x_temp, gamma, beta, bn_param)
out = np.zeros((N, C, H, W))
for c in range(C):
out[:,c,:,:] = np.reshape(out_temp[:,c], (N, H, W))
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return out, cache
def spatial_batchnorm_backward(dout, cache):
"""
Computes the backward pass for spatial batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Gradient with respect to shift parameter, of shape (C,)
"""
dx, dgamma, dbeta = None, None, None
# ================================================================ #
# YOUR CODE HERE:
# Implement the spatial batchnorm backward pass.
#
# You may find it useful to use the batchnorm forward pass you
# implemented in HW #4.
# ================================================================ #
N, C, H, W = dout.shape
x, gamma, var, mu, eps, mode, momentum = cache
x_temp = x
dout_temp = np.zeros((N*H*W, C))
for c in range(C):
dout_temp[:, c] = np.reshape(dout[:,c,:,:], (N*H*W))
cache_temp = x_temp, gamma, var, mu, eps, mode, momentum
dx_temp, dgamma, dbeta = batchnorm_backward(dout_temp, cache_temp)
dx = np.zeros((N, C, H, W))
for c in range(C):
dx[:,c,:,:] = np.reshape(dx_temp[:,c], (N, H, W))
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return dx, dgamma, dbeta |
9719a907ede711f73d75f5ea03df9223c19f1e13 | Aasthaengg/IBMdataset | /Python_codes/p03080/s548707550.py | 64 | 3.609375 | 4 | N=int(input())
print("Yes" if input().count('R')>N//2 else "No") |
c87486bfb55a0668a2b57859a24bfb332fc9445c | JaymesKat/Prime-Number-Generator | /src/app.py | 498 | 4.09375 | 4 | # this python function returns a list containing sequence of prime numbers below the given argument
def prime_num_generator(end):
noprimeNums = set(j for i in range(2, 8) for j in range(i*2, end, i))
primeNums = [x for x in range(2, end) if x not in noprimeNums]
return primeNums
def is_prime(num):
#Return true if *num* is prime.
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
|
f63902d53439d6264484239ad5c1569d59a2a5de | Mandella-thi/Exercicios-Massanori-py | /exercícios-massanori-py/exercicios/pontas lista 11.py | 305 | 3.921875 | 4 | # B. pontas
# Dada uma string s, retorna uma string com as duas primeiras e as duas
# últimas letras da string original s
# Assim 'palmeiras' retorna 'paas'
# No entanto, se a string tiver menos que 2 letras, retorna uma string vazia
def pontas(s):
return s[0]+s[1]+s[-2]+s[-1]
print(pontas('thiago')) |
c54c8be82457e37117717d23c50ede328e6bcc56 | firework-eternity/Personal-Python-Repository | /basics_test/csv_file.py | 547 | 3.53125 | 4 | import csv
import os
def csv_read(csv_name):
# csv_path = "../test_data/" + csv_name
dir_path = os.path.dirname(__file__)
csv_path = dir_path.replace("basics_test", "test_data/" + csv_name)
re_table = []
# file = open(csv_path)
with open(csv_path) as file: # 文件自动关闭
table = csv.reader(file)
initial_variable = True
for row in table:
if initial_variable:
initial_variable = False
else:
re_table.append(row)
return re_table
|
66a30dca87d42c916422a13db170716bf6dba583 | tangentstorm/pirate | /pirate/test/python/microthreads_more.py | 152 | 3.53125 | 4 | from __future__ import generators #@TODO: 2.3
def count():
x = 0
while 1:
yield x
x = x + 1
g = count()
for i in [1,2,3]:
print g.next(),
|
9834c38ffda66a0a37b9046b89f8fb304e5d8e0e | guilleCM/Programacion_Python | /POO/Cuenta corriente/CuentaCorriente.py | 3,603 | 3.53125 | 4 | # Autor: guilleCM
# coding=utf-8
# Enunciado:
##Construye una clase de nombre CuentaCorriente que permita almacenar
##los datos asociados a la cuenta bancaria de un cliente, e interactuar con ellos.
#Propiedades privadas (de momento, en Python nos da igual que sean privadas):
####nombre, apellidos, dirección, teléfono: todas de tipo string.
####NIF: objeto instancia de la clase DNI que resolvimos en clase**. Se trata de una relación “Has-A” o “Tiene-una”.
####saldo: de tipo double.
#Constructores (inicializador en Python):
####Constructor que por defecto inicializa las propiedades de la clase (programación defensiva).
####Constructor al que se le pasen como argumentos todas las propiedades que tiene la clase.
#Métodos públicos:
####set() y get() para todas las propiedades de la clase [Abstracción y encapsulamiento].
####retirarDinero(): resta al saldo una cantidad de dinero pasada como argumento.
####ingresarDinero(): añade al saldo una cantidad de dinero.
####consultarCuenta(): visualizará los datos de la cuenta.
####saldoNegativo(): devolverá un valor lógico indicando si la cuenta está o no en números rojos.
class CuentaCorriente:
def __init__(self, nombre, apellidos, direccion, telefono, nif, saldo):
self.__nombre = nombre
self.__apellidos = apellidos
self.__direccion = direccion
self.__telefono = telefono
self.__nif = nif
self.__saldo = saldo
# SETTERS
def setNombre(self, nombre):
self.__nombre = nombre
def setApellidos(self, apellidos):
self.__apellidos = apellidos
def setDireccion(self, direccion):
self.__direccion = direccion
def setTelefono(self, telefono):
self.__telefono = telefono
def setNif(self, nif):
self.__nif = nif
def setSaldo(self, saldo):
self.__saldo = saldo
# GETTERS
def getNombre(self):
return self.__nombre
def getApellidos(self):
return self.__apellidos
def getDireccion(self):
return self.__direccion
def getTelefono(self):
return self.__telefono
def getNif(self):
return self.__nif
def getSaldo(self):
return self.__saldo
def __str__(self):
return '[Propietario: %s %s, Direccion: %s, Telefono: %s, NIF: %s, Saldo Disponible: %s]' % (self.__nombre, self.__apellidos, self.__direccion, self.__telefono, self.__nif, self.__saldo)
def saldoNegativo(self):
if self.__saldo < 0:
return True
else:
return False
def consultarCuenta(self):
print(self)
def ingresarDinero(self, cantidad):
self.__saldo += cantidad
def retirarDinero(self, cantidad):
if cantidad > self.__saldo:
print("No dispone de tal cantidad para retirar")
print("Su saldo disponible es de", self.saldo)
else:
self.__saldo = self.__saldo-cantidad
print("Ha retirado %s€, su saldo disponible es de %s€" %
(cantidad, self.__saldo))
if __name__=='__main__':
guilleCM = CuentaCorriente("Guillermo", "Cirer Martorell", "C/ Tenor Bou Roig", 717114964, "43223381X", 60)
guilleCM.ingresarDinero(40) #saldo pasa a ser 100
guilleCM.retirarDinero(100) #saldo pasa a ser 0
guilleCM.setNombre("Pedro") #nombre pasa a ser Pedro
guilleCM.consultarCuenta() #comprueba que lo anterior se ha cumplido
cuentaGuille = CuentaCorriente("Guillermo", "Cirer Martorell", "C/ Tenor Bou Roig", 717114964, "43223381X", 60)
print(cuentaGuille.getNombre())
print(cuentaGuille.setNif("re"))
print(cuentaGuille.getNif()) |
59fa9a61a24a02406e42e9d7e8b35360338ae3a3 | cjdhein/Random-Word-Generator | /Random-Word-Constructor.py | 3,204 | 3.828125 | 4 | import random
"""A Random Word Generator that uses a built-in algorithm that follows the syllable rules
in the English language. Useful for finding a creative name for a business or app."""
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
consensnts = [x for x in alphabet if x not in vowels]
starting_letters = ['c', 'd', 'g', 'h', 'i', 'j', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'y', 'z' ]
class Random_Word_Constructor (object):
def __init__(self, maxlength):
self.maxlength = maxlength
self.dictionary = {}
self.start = [x for x in alphabet if x != 'x' and x != 'u']
self.word = ''
self.word += self.start[random.randrange(len(self.start))]
self.preceed_Vowel_letters = ['b', 'd', 'j', 'w', 'z', 'q']
self.a = [x for x in alphabet if x != 'a' and x != 'h' and x != 'u']
self.e = [x for x in alphabet if x != 'h']
self.i = [x for x in alphabet if x != 'i' and x != 'h' and x != 'u' and x != 'y']
self.o = [x for x in alphabet if x != 'a' and x != 'e' and x != 'i' and x != 'y']
self.u = [x for x in consensnts if x != 'y' and x != 'u']
self.y = ['o', 'a', 'e', 'u']
self.cons_next = ['a', 'i', 'e', 'o', 'u', 't', 'r']
def construct_word(self):
while len(self.word) < self.maxlength:
if len(self.word) >= 2:
if self.word[-2] and self.word[-1] in vowels:
self.word += consensnts[random.randrange(len(consensnts))]
if self.word[-2] and self.word[-1] in consensnts:
self.word += vowels[random.randrange(len(vowels))]
if self.word[-1] in vowels:
if self.word[-1] == 'a':
self.word += self.a[random.randrange(len(self.a))]
if self.word[-1] == 'e':
self.word += self.e[random.randrange(len(self.e))]
if self.word[-1] == 'i':
self.word += self.i[random.randrange(len(self.i))]
if self.word[-1] == 'o':
self.word += self.o[random.randrange(len(self.o))]
if self.word[-1] == 'u':
self.word += self.u[random.randrange(len(self.u))]
if self.word[-1] in consensnts:
if self.word[-1] in self.preceed_Vowel_letters:
self.word += vowels[random.randrange(len(vowels))]
if self.word[-1] == 'y':
self.word += self.y[random.randrange(len(self.y))]
else:
self.word += self.cons_next[random.randrange(len(self.cons_next))]
self.word = self.word[0:self.maxlength]
return self.word
def add_to_dictionary(self):
if self.word[0] in self.dictionary.keys():
self.dictionary[self.word[0]].append(self.word)
self.word = '' + self.start[random.randrange(len(self.start))]
else:
self.dictionary.update({self.word[0]:[self.word]})
self.word = '' + self.start[random.randrange(len(self.start))]
def Random_Word(maxlength): #returns a single random word
word = Random_Word_Constructor(maxlength)
return word.construct_word()
def Random_Dictionary(entries, maxlength): #returns a dictionary of specificed number of entries, and prints them.
word, count = Random_Word_Constructor(maxlength), 0
while count < entries:
word.construct_word()
word.add_to_dictionary()
count += 1
for k, v in word.dictionary.items():
print k, v
|
1382183bfe6b698816e1a5031f7640f1f3d9276b | bmviniciuss/ufpb-so | /project1/SJF.py | 3,723 | 3.5 | 4 | class SJF:
"""Implements an SJF scheduler (Shortest Job First) """
def __init__(self, processes):
self.processes = processes.copy()
self.done = []
self.ready_queue = []
self.cpu_active = False
self.on = False
self.timer = 0
def get_processes(self):
"""Get a list of processes by the time of the timer"""
processes_copy = self.processes.copy()
filtered = list(filter(lambda p: self.timer >=
p.t_arrival, processes_copy))
self.processes = [p for p in self.processes if p not in filtered]
return filtered
def increment_waiting_time(self):
"""Increments the waiting time of all processes in the Ready Queue"""
for p in self.ready_queue:
p.wait()
def print_process(self, ps, message):
"""Function that print a list of processes"""
print(message)
for p in ps:
print(p)
def tick(self):
"""Ticks the timer by 1 unit of time"""
self.timer += 1
def update_ready_queue(self):
"""Updates the ready queue with the latest processes"""
# Get proccess by time
ps = self.get_processes()
# Append processes in ready queue
self.ready_queue += ps
def sortP(p):
"""Sort functions that returns the cpu peak of a process"""
return p.cpu_peak
self.ready_queue.sort(key=sortP)
def run(self):
"""Runs the FCFS algorithm"""
self.timer = 0
self.on = True
self.cpu_active = False
# self.print_process(self.processes, "SJF Original: ")
while self.on:
self.update_ready_queue() # Update Ready Queue
# scheduling
if len(self.ready_queue) > 0:
if self.cpu_active == False: # if cpu does not has a process
# process already arrive
if self.timer >= self.ready_queue[0].t_arrival:
self.cpu_active = True # make cpu active
# pop process first process from ready_queue
p = self.ready_queue.pop(0)
p.init_process(self.timer) # Starts process
# do some cpu work
while not p.is_done():
self.update_ready_queue() # update ready queue
p.run() # run single interation of process
self.tick() # incremet the timer
self.increment_waiting_time() # icrement waiting process in ready_queue
p.end_process(self.timer) # finish process
self.cpu_active = False # cpu is not working at the time
# append finished process to the done list
self.done.append(p)
else: # cpu has a process
self.tick() # increment timer until has a process
self.update_ready_queue() # update ready queue
self.increment_waiting_time() # increment waiting time
else:
break
# self.print_process(self.done, "Done: ")
result = self.compute_stats()
return result
def compute_stats(self):
"""Compute the scheduler's peformance stats"""
n = len(self.done)
# t_return, t_response, t_waiting
sums = [0, 0, 0]
for p in self.done:
sums[0] += p.t_return
sums[1] += p.t_response
sums[2] += p.t_waiting
avgs = list(map(lambda x: x / n, sums))
return avgs
|
41c7c0204d01fb2f3a891cd7b641a8452cd831f1 | zwcoop/guttag_intro_comp_ed3 | /ch2/fig2-7.py | 322 | 4.03125 | 4 | # Figure 2-7 Squaring an integer the hard way
# The abs(x) is essential for the code not to enter an infinite loop
x = int(input('Enter a positive or negative integer: '))
ans = 0
num_iterations = 0
while (num_iterations < abs(x)):
ans = ans + abs(x)
num_iterations = num_iterations + 1
print(f'{x}*{x} = {ans}')
|
2e5764db0d1f898fb04850b04621bd646bf6ac75 | akshitgupta29/Competitive_Programming | /LeetCode & GFG & IB/P2 - Happy Number.py | 718 | 3.859375 | 4 | '''
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
'''
def isHappy(n: int) -> bool:
visited = set([n])
while n!=1:
num = n
n = 0
while num:
num, rem = num//10, num %10
n += rem ** 2
break
visited.add(n)
return n == 1
if __name__ == "__main__":
print (isHappy(19)) |
9bd70354f1fc810336177c846a20ab6738db9d5a | hsartoris/python | /Lab 5/read_file.py | 250 | 3.515625 | 4 | '''
Created on Sep 23, 2013
@author: hsartoris
'''
in_file = 0
if (raw_input("Short or long file? (S/L)") == "S"):
in_file = open("yelp-short.txt", 'r')
else:
in_file = open("yelp.txt", 'r')
for line in in_file:
print line, len(line) |
b59587c38765e23a5d821cc6d9560284ca88a71e | Jitha-menon/jithapythonfiles | /PycharmProject/fundamental_programming/Swapping/flow_of_controls/Looping_For Loop.py | 372 | 4.21875 | 4 | # For i in range (5):
# print('hello')
for a in range (2,8):
print (a)
# for in range with initial value final value and increment value
for i in range (1,10,2):
print (i)
#problem to find numbers between min and max range
min= int(input('enter the min num'))
max=int(input('enter the max num'))
for i in range(min,max):
print(i)
break |
740ae7e5efdb1b428fcf131e70e9012a87e455ce | rnaster/Today-I-Learned | /2018/1811/181101.py | 791 | 3.625 | 4 | # BOJ - 2504
from collections import deque
s = tuple(input())
stack = deque()
for i in s:
if i == ']' or i == ')':
num = 0
while len(stack):
val = stack.pop()
if isinstance(val, int): num += val
else:
if i == ']' and val == '[':
if num: stack.append(num*3)
else: stack.append(3)
break
elif i == ')' and val == '(':
if num: stack.append(num*2)
else: stack.append(2)
break
else: print(0);exit()
else:
stack.append(i)
ans = 0
while len(stack):
a = stack.pop()
if isinstance(a, int): ans += a
else: print(0); exit()
print(ans)
"""
(()[[]])([])
""" |
70d105c4d4e13e8d42bfde1b9ebeed141b8a9eec | Valavala24/Rock-paper-scissors- | /RockPaperScissors.py | 2,864 | 4.03125 | 4 | # RockPaperScissors
import getpass
x = 0 # Keeps track of player X's current selection
y = 0 # Keeps track of player Y's current selection
x_wins = 0 # Keeps track of player X's overall wins
y_wins = 0 # Keeps track of player Y's overall wins
num_games = 2 # Player X will first choose and then player Y according to the following keys
keep_playing = True # Will get set to false when there is a winner
valid_input = False # Checks to make sure the user input a 1, 2, or 3 as well as if the num games needed is valid
while (valid_input == False):
num_games = str(raw_input("Choose number of games (1-9) needed in order to win: "))
if (num_games != "1" and num_games != "2" and num_games != "3" and num_games != "4" and num_games != "5"
and num_games != "6" and num_games != "7" and num_games != "8" and num_games != "9"):
print("Incorrect selection, please select 1-9 games to win")
else:
valid_input = True
num_games = int(num_games)
print ("\nPlayer X will first choose and then player Y according to the following keys")
print(" 1 = Rock")
print(" 2 = Paper")
print(" 3 = Scissors")
while (keep_playing == True):
valid_input = False
while (valid_input == False):
x = str(getpass.getpass("Player X, choose your item: "))
if (x != "1" and x != "2" and x != "3"):
print("You did not enter a valid input, please use 1, 2, or 3")
else:
valid_input = True
valid_input = False
while (valid_input == False):
y = str(getpass.getpass("Player Y, choose your item: "))
if (y != "1" and y != "2" and y != "3"):
print("You did not enter a valid input, please use 1, 2, or 3")
else:
valid_input = True
x = int(x)
y = int(y)
if (x == y):
print("\nBoth players chose the same item, please choose again")
elif (x == 1 and y == 2):
print("\nPlayer X chose Rock and Player Y chose Paper. Player Y wins this round")
y_wins = y_wins + 1
elif (x == 1 and y == 3):
print("\nPlayer X chose Rock and Player Y chose Scissors. Player X wins this round")
x_wins = x_wins + 1
elif (x == 2 and y == 3):
print("\nPlayer X chose Paper and Player Y chose Scissors. Player Y wins this round")
y_wins = y_wins + 1
elif (x == 2 and y == 1):
print("\nPlayer X chose Paper and Player Y chose Rock. Player X wins this round")
x_wins = x_wins + 1
elif (x == 3 and y == 1):
print("\nPlayer X chose Scissors and Player Y chose Rock. Player Y wins this round")
y_wins = y_wins + 1
elif (x == 3 and y == 2):
print("\nPlayer X chose Scissors and Player Y chose Papaer. Player X wins this round")
x_wins = x_wins + 1
print("")
print("Wins:")
print(" Player X: " + str(x_wins))
print(" Player Y: " + str(y_wins))
print("")
if (x_wins == num_games):
print("Player X Wins!")
print("")
keep_playing = False
if (y_wins == num_games):
print("Player Y Wins!")
print("")
keep_playing = False |
26c845769a9608e625c87d0fd20c58efd155f762 | heartyhardy/data-structs-python | /phaseII/data_structs/deque_test.py | 343 | 3.75 | 4 | from deque import Element, LinkedList, Deque
el1 = Element("Apple")
el2 = Element("Peach")
el3 = Element("Orange")
el4 = Element("Pear")
el5 = Element("Kiwi")
dq = Deque()
dq.enqueue(el3)
dq.push(el2)
dq.enqueue(el1)
dq.push(el4)
dq.enqueue(el5)
print(dq.ll.toArray())
dq.pop()
dq.dequeue()
dq.dequeue()
dq.pop()
print(dq.ll.toArray())
|
4a8674127013d05ff067051061d65f81c362f0dd | thesmigol/python | /1015.py | 565 | 3.6875 | 4 | import math
enrtada = None
entrada = None
jfghjhgjhg = None
kkkkkkkkkkk = None
x1 = None
x2 = None
y1 = None
y2 = None
def read_line():
try:
# read for Python 2.x
return raw_input()
except NameError:
# read for Python 3.x
return input()
enrtada = read_line().split(" ")
x1 = float((enrtada[0]))
y1 = float((enrtada[1]))
entrada = read_line().split(" ")
x2 = float((entrada[0]))
y2 = float((entrada[1]))
jfghjhgjhg = x2 - x1
kkkkkkkkkkk = y2 - y1
print("{:0.4f}".format((math.sqrt(((math.pow(jfghjhgjhg, 2)) + (math.pow(kkkkkkkkkkk, 2)))))))
|
81d206d3695e472459b642296717a5fd83bd6ee4 | javahongxi/pylab | /lang/misc/enum_demo.py | 336 | 3.671875 | 4 | # from enum import Enum
from enum import IntEnum,unique
@unique
class VIP(IntEnum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
print(VIP.YELLOW)
print(VIP.YELLOW.name)
print(VIP.YELLOW.value)
print(VIP['YELLOW'])
for v in VIP:
print(v)
print(VIP.YELLOW == VIP.YELLOW)
print(VIP.YELLOW is VIP.YELLOW)
print(VIP(1))
|
d57c69aa459c52c3eb578ace97b827becbec8645 | kalmalang/BMES-T580-2019 | /Module06/wizard_battle.py | 2,556 | 3.53125 | 4 | import wizard_code as wc
from random import choice
if __name__ == '__main__':
#creature = wc.Creature('small animal', 1)
creatures_to_fight = [wc.Creature('bear', 5),
wc.Creature('bird', 3),
wc.Creature('wolf', 8),
wc.Wizard('Evil Guy', 9)]
possible_events = [wc.Event('Snowstorm', -2),
wc.Event('Thunder', 1),
wc.Event('Sunshine', 2),
wc.Event('Rain', -1)]
me = wc.IceWizard('Joe', 10)
while True:
turn_creature = choice(creatures_to_fight)
print('-------------------------------')
print('From the forest emerges {}'.format(turn_creature.name))
if turn_creature.level < me.level:
print('Should be easy. Its only level {}'.format(turn_creature.level))
else:
print('Watch out! Its level {}'.format(turn_creature.level))
turn_event = choice(possible_events)
if turn_event.type == 'Snowstorm':
print('There is a snowstorm coming, your level will be reduced by 2')
me.level_down()
me.level_down()
elif turn_event.type == 'Thunder':
print('A Thunderstorm comes through. The {} is scared and you feel empowered (+1 level)'.format(turn_creature.name))
me.level_up()
elif turn_event.type == 'Sunshine':
print('The sun comes out and you feel in best fighting spirit. Your level is raised by 2')
me.level_up()
me.level_up()
else:
print('It is starting to rain. The grass becomes slippery and you lose a level')
me.level_down()
print('What do you want to do?')
action = input('[A]ttack, [R]un, [Q]uit')
if action == 'Q':
print('Bye')
raise SystemExit
elif action == 'A':
my_roll = me.attack_roll()
creature_roll = turn_creature.defense_roll()
print('You got: ', my_roll, 'and the creature got', creature_roll)
if my_roll > creature_roll:
me.level_up()
print('Yay! You won! Your level is now %i' % me.level)
else:
me.level_down()
print('You lost! Your level is now %i' % me.level)
if me.level == 0:
print('Oop, you died')
raise SystemExit
elif action == 'R':
print('Coward! Your level remains %i' % me.level)
|
609c1cd4d9270abe2379ae59abbc32541d1a095e | doweyab/Personal_projects | /Piglatin_Translator.py | 1,033 | 4.125 | 4 | print("This code doesn't handle upper-case letters or punctuation.")
vowels = "eaoui"
consonants = "bcdfghjklmnpqrstvwxyz"
def get_consonant_prefix(word):
consonants = "bcdfghjklmnpqrstvwxyz"
i = 0
consonant_prefix = ""
while (consonants.find(word[i]) > -1):
consonant_prefix += word[i]
i += 1
return consonant_prefix
def get_tail(word):
consonants = "bcdfghjklmnpqrstvwxyz"
i = 0
consonant_prefix = ""
while (consonants.find(word[i]) > -1):
consonant_prefix += word[i]
i += 1
tail = word[i:]
return tail
#Enter a sentence here for it to be converted to pig-latin.
print('''
it could be something like "all this pig latin is making me hungry"
''')
sentence = input("Give me a msg to translate: ")
pig_sentence = ""
for word in sentence.split(" "):
if(vowels.find(word[0]) > -1):
pig_sentence = pig_sentence + word + "yay "
else:
pig_sentence = pig_sentence + get_tail(word) + get_consonant_prefix(word) + "ay "
print(pig_sentence) |
51280fef7365a1f453e657fa8e4edf12599f01c6 | StefanDimitrovDimitrov/Python_Basic | /03.Conditional_Statement_Ex/08_Schoolarship.py | 656 | 3.625 | 4 | from math import floor
income = float(input())
average_score = float(input())
min_salary = float(input())
soc_scholarship = 0
scholareship_hight_score = 0
if income < min_salary:
if average_score > 4.5:
soc_scholarship = min_salary * 0.35
if average_score >= 5.50:
scholareship_hight_score = average_score * 25
if soc_scholarship > scholareship_hight_score:
print(f'You get a Social scholarship {floor(soc_scholarship)} BGN')
elif scholareship_hight_score > soc_scholarship:
print(f'You get a scholarship for excellent results {floor(scholareship_hight_score)} BGN')
else:
print('You cannot get a scholarship!')
|
9482600b6cd586262e84abbfa31f79f5d2bb5ffd | suraj-singh12/python-revision-track | /06-conditionals/64_ten_chars.py | 172 | 3.859375 | 4 | username = input("Enter username: ")
if (len(username) < 10):
print("Error!!",username,"is less than 10 characters long.")
else:
print(username,"meets conditions.") |
21fddbf80ad8c0faabfdff76fe8cf1a0b31b56bf | solzhen/tarea1nn | /activation_functions.py | 1,010 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Activation functions
Created on Fri Aug 30 23:55:11 2019
@author: Cristobal
"""
import numpy as np
class ActivationFunction:
def apply(x):
'''
Applies function to input X
'''
pass
def derivative(z):
'''
Calculates derivative in terms of the function itself as input z.
Assume z = apply(x)
'''
pass
class Step(ActivationFunction):
def apply(x):
return np.where(x >= 0, 1, 0)
def derivative(z):
return 0
class Sigmoid(ActivationFunction):
def apply(x):
return 1 / (1 + np.exp(-x))
def derivative(z):
return z * (1 - z)
class Tanh(ActivationFunction):
def apply(x):
p = np.exp(x)
n = np.exp(-x)
return (p - n) / (p + n)
def derivative(z):
return 1 - np.power(z, 2)
class Relu(ActivationFunction):
def apply(x):
return np.maximum.reduce([x, np.zeros(x.shape)])
def derivative(z):
return -np.maximum.reduce([-z, -np.ones(z.shape)]) |
ca669658a7918b14db2a3d0b1249c70a040bbe1f | mauro-20/The_python_workbook | /chap1/ex04.py | 264 | 4.09375 | 4 | # Area of a field
width = float(input('type the width of the field in feet\n'))
length = float(input('type the length of the field in feet\n'))
# computing the area in acres
area = width * length / 43560
print('the area of the field is %.2f acres' % area)
|
cdacf80f2d8b772ba1d45a93d15abfeea9065f17 | paulopradella/Introducao-a-Python-DIO | /Aula_8/Aula8_1.py | 1,832 | 4.03125 | 4 | #Lidando com módulos, importação de classes, métodos e
# construção de funções anônimas (lambda)
#Ex1.:
# >>> import Aula7_3(tirar os prints
# >>> televisao = Aula7_3.Televisao()
# >>> televisao.ligada
# False
# >>> televisao.power()
# >>> televisao.ligada
# True
# Ex2.:Outras forma de acessar um módulo:
# >>> from Aula8_1 import Televisão
# #Está falando que lá da Aula8_1 morte Televisao
# >>> televisao = Televisao()
# >>> televisao.ligada
# False
# >>> televisao.power()
# >>> televisao.ligada
# True
class Televisao:
def __init__(self):
self.ligada = False
self.canal = 5
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
if self.ligada:
self.canal += 1
def diminui_canal(self):
if self.ligada:
self.canal -= 1
if __name__ == '__main__':
#Qundo quem está chamando, se for o mesmo arquivo eu faço isso
#se não, não faz nada, sempre que tiver que fazer testes, vai usar isso.
#ou seja se estiver sendo executado o própria aquivo,
# ele vai executar, caso contrário não
televisao = Televisao()
print('Televisão está ligada: {}' .format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}' .format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}' .format(televisao.ligada))
print('Canal: {}' .format(televisao.canal))
televisao.power()
print('Televisão está ligada: {}' .format(televisao.ligada))
print('Canal: {}' .format(televisao.canal))
televisao.aumenta_canal()
televisao.aumenta_canal()
print('Canal: {}' .format(televisao.canal))
televisao.diminui_canal()
print('Canal: {}' .format(televisao.canal))
|
c4c0a9e34f2ca6a59bbff71bdfde67c743f45b58 | evenchen0321/testmac | /rework/3级菜单.py | 847 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Even
menu = {
'北京':{
"昌平":{
"沙河":["oldboy","test"],
"天通苑":["链家地产","我爱我家"]
},
"朝阳":{
"望京":["奔驰","陌陌"],
"国贸":{"CICC","HP"},
"东直门":{"Advent","飞信"},
},
"海淀":{},
},
'山东':{
"德州":{},
"青岛":{},
"济南":{}
},
'广东':{
"东莞":{},
"常熟":{},
"佛山":{},
},
}
level = []
while True:
for key in menu:
print(key)
choose = input("choose:").strip()
if choose == "b":
if len(level) == 0:break
menu = level[-1]
level.pop()
if choose not in menu:continue
level.append(menu)
menu = menu[choose] |
8236a429cf28322d7a826063478626777c8e9b27 | iac-nyc/Python | /Python2.7/ichowdhury_3.1.py | 778 | 3.5625 | 4 | #Name: Iftekhar Chowdhury
#Date: Nov 10, 2015
#HW : 3.1
while True:
input = raw_input("Please enter 4 digit number: ")
if input.isdigit() and len(input) == 4:
break
else:
print "Sorry, '{}' is not a valid number.".format(input)
this_sum = 0
count = 0
filename = 'c:\users\Iftekhar Chowdhury\Desktop\FF_abbreviated.txt'
fh = open(filename)
for line in fh:
year = line[0:4]
if year == input:
elements = line.split()
new_value = float(elements[1])
this_sum = float(this_sum + new_value)
count = count + 1
average = this_sum / count
print 'Counter: {} Sum : {} Average: {}'.format(count,this_sum ,average)
|
3f1d6d0aa11836b78ce6361f60a3c027568dc4fd | mick-d/python_lecture | /vs_tut/exam1.py | 853 | 4.1875 | 4 | import teaching
def print_student_feedback(student_info: dict, feedback_mode="normal") -> None:
'''Print students feedback according to their grades
Parameters
----------
student_info
A dictionary with student name as key and student grade as value
feedback_mode
The feedback mode, either "normal" (default) or "positive_reinforcement"
Returns
-------
None
'''
for s_name, s_grade in student_info.items():
s_feedback = teaching.comment_grade(s_grade, mode=feedback_mode)
print('Feedback for {}: {}'.format(s_name, s_feedback))
if __name__ == '__main__':
print(__name__)
student_results = {
'John': 3,
'Mary': 9,
'Peter': 5
}
print_student_feedback(student_results)
|
e3f06d27b15cbcec0484632c1c8506988961c006 | JonLevin25/coding-problems | /daily-coding-problems/old/problem008/tests.py | 1,366 | 3.6875 | 4 | import unittest
from solution.solution import *
from queue import Queue
def left_setter(parent_node):
def assign(node):
parent_node.left = node
return assign
def right_setter(parent_node):
def assign(node):
parent_node.right = node
return assign
def create_tree(*args):
open_spots = Queue()
root = None
for n in args:
if not isinstance(n, int) and n is not None:
raise TypeError("All args should be int or None!")
if root == None:
root = TreeNode(n)
open_spots.put(left_setter(root))
open_spots.put(right_setter(root))
continue
if open_spots.qsize == 0:
raise ValueError
next_node_setter = open_spots.get()
if n is None:
continue
new_node = TreeNode(n)
next_node_setter(new_node)
open_spots.put(left_setter(new_node))
open_spots.put(right_setter(new_node))
return root
class TestCreateTree(unittest.TestCase):
def test(self):
tree = create_tree(3, 4, 5)
assert tree.value == 3
assert tree.left is not None
assert tree.left == 4
assert tree.right is not None
assert tree.right == 5
if __name__ == '__main__':
unittest.main() |
7727d174598ea2150e9faec0e9640bbf69d1ab46 | FerisZura/RPG-Game | /Equip.py | 7,353 | 3.875 | 4 | from Functions import *
# prints a gem if it is owned. prints (E) after if it is equipped
def print_gem(gemCount, equipped, string):
if equipped == 0:
if gemCount > 0 and gemCount < 3:
print(string)
elif gemCount >= 3 and gemCount < 6:
print(string + " LV2")
elif gemCount >= 6:
print(string + " LV3")
if equipped > 0:
if gemCount > 0 and gemCount < 3:
print(string + " (E)")
elif gemCount >= 3 and gemCount < 6:
print(string + " LV2 (E)")
elif gemCount >= 6:
print(string + " LV3 (E)")
# flips a gem between equipped and non equipped. Only when the number of gems equipped is 6 or less
def select_gem(gemCount, equipped, gemName, numberEquipped):
if equipped == 0:
if numberEquipped >= 6:
input("You have the max number of gems equipped!")
return equipped, numberEquipped
else:
if gemCount > 0 and gemCount < 3:
input("You have equipped the {} gem".format(gemName))
return 1, numberEquipped + 1
elif gemCount >= 3 and gemCount < 6:
input("You have equipped the {} gem (LV2)".format(gemName))
return 2, numberEquipped + 1
elif gemCount >= 6:
input("You have equipped the {} gem (LV3)".format(gemName))
return 3, numberEquipped + 1
elif equipped > 0:
input("You have unequipped the {} gem".format(gemName))
return 0, numberEquipped - 1
def equip(player):
equipRun = True
equipMenu = ["View stats", "Equip gems", "About gems", "Main Menu"]
numberEquipped = 0
# ^^pay attention to this pls
################################################################################
# make initialize function where it runs through all gems and sees if equipped #
################################################################################
while equipRun == True:
print("Equip Menu")
print_list(equipMenu)
menuInput = integer_input(len(equipMenu))
if menuInput == 1:
print("{}'s Stats".format(player.name))
print("Weapon level: {}".format(player.weaponTier))
print("Helmet level: {}".format(player.hatTier))
print("Armour level: {}".format(player.armourTier))
print("Max health: {}".format(player.maxHealth))
print("Min attack: {}".format(player.minAttack))
print("Max attack: {}".format(player.maxAttack))
print("Health potions: {}" .format(player.healthPotion))
print("Super health potions: {}" .format(player.maxHealthPotion))
input("Equipped Gems: Can be viewed from [Equip gems]")
print()
elif menuInput == 2:
gemLoop = True
print("Type input to equip/unequip gem. Can equip up to six")
while gemLoop == True:
# display owned and unequipped gems hmm spaghetti
print_gem(player.rabbit, player.rabbitEquip, "(r) Rabbit Gem")
print_gem(player.tank, player.tankEquip, "(t) Tank Gem")
print_gem(player.gorilla, player.gorillaEquip, "(go) Gorilla Gem")
print_gem(player.diamond, player.diamondEquip, "(di) Diamond Gem")
print_gem(player.hawk, player.hawkEquip, "(h) Hawk Gem")
print_gem(player.gatling, player.gatlingEquip, "(ga) Gatling Gem")
print_gem(player.ninja, player.ninjaEquip, "(n) Ninja Gem")
print_gem(player.comic, player.comicEquip, "(c) Comic Gem")
print_gem(player.dragon, player.dragonEquip, "(dr) Dragon Gem")
print_gem(player.lock, player.lockEquip, "(l) Lock Gem")
print("(q)(4) Quit")
gemInput = input()
gemInput = gemInput.lower()
# equip/unequips gem
if gemInput == "r":
player.rabbitEquip, numberEquipped = select_gem(player.rabbit, player.rabbitEquip, "rabbit",
numberEquipped)
elif gemInput == "t":
player.tankEquip, numberEquipped = select_gem(player.tank, player.tankEquip, "tank", numberEquipped)
elif gemInput == "go":
player.gorillaEquip, numberEquipped = select_gem(player.gorilla, player.gorillaEquip, "gorilla",
numberEquipped)
elif gemInput == "di":
player.diamondEquip, numberEquipped = select_gem(player.diamond, player.diamondEquip, "diamond",
numberEquipped)
elif gemInput == "h":
player.hawkEquip, numberEquipped = select_gem(player.hawk, player.hawkEquip, "hawk", numberEquipped)
elif gemInput == "ga":
player.gatlingEquip, numberEquipped = select_gem(player.gatling, player.gatlingEquip, "gatling",
numberEquipped)
elif gemInput == "n":
player.ninjaEquip, numberEquipped = select_gem(player.ninja, player.ninjaEquip, "ninja",
numberEquipped)
elif gemInput == "c":
player.comicEquip, numberEquipped = select_gem(player.comic, player.comicEquip, "comic",
numberEquipped)
elif gemInput == "dr":
player.dragonEquip, numberEquipped = select_gem(player.dragon, player.dragonEquip, "dragon",
numberEquipped)
elif gemInput == "l":
player.lockEquip, numberEquipped = select_gem(player.lock, player.lockEquip, "lock", numberEquipped)
elif gemInput == "q" or gemInput == "4":
gemLoop = False
else:
input("Invalid input")
elif menuInput == 3:
gemDescription = [
"Gems contain special powers that can be used in battle",
"Get gems from the gacha using gold or gacha tokens",
"When you gain 3 of the same gem, it will level up to LV2"
"When you gain 6 of the same gem, it will level up to LV3"
"View and equip up to six gems from the [Equip gems] menu",
"Select an equipped gem to unequip it",
"In battle, activate gems from the [gems] menu",
"Two gems must be activated at a time",
"Each gem has an effect when activated, lasting until a different gem is selected",
"If your two gems are a [best match], a bonus effect is applied"
]
for string in gemDescription:
print(string)
input()
elif menuInput == 4:
equipRun = False
|
4350eae23b841f537ee8c7dc630855eb3ba509bb | profnssorg/henriqueJoner1 | /exercicio43.py | 1,055 | 4.46875 | 4 | """
Descrição: Este programa verifica os maiores e menores números apresentados pelo usuário
Autor:Henrique Joner
Versão:0.0.1
Data:25/11/2018
"""
#Inicialização de variáveis
a = 0
b = 0
c = 0
maior = 0
menor = 0
#Entrada de dados
primeiro = int(input("Digite um número: "))
segundo = int(input("Ok! Agora digite mais um número: "))
terceiro = int(input("Ótimo, precisamos de apenas mais um! Digite um número: "))
#Processamento de dados
if primeiro > segundo and primeiro > terceiro:
maior = primeiro
if segundo > primeiro and segundo > terceiro:
maior = segundo
if terceiro > primeiro and terceiro > segundo:
maior = terceiro
if primeiro < segundo and primeiro < terceiro:
menor = primeiro
if segundo < primeiro and segundo < terceiro:
menor = segundo
if terceiro < primeiro and terceiro < segundo:
menor = terceiro
if primeiro == segundo and primeiro == terceiro:
print("Todos os números são iguais!")
#Saída de dados
print("O maior número digitado foi %d, e o menor foi %d !" % (maior, menor))
|
93eaa61623894e98372e5f371a91fcc1484dfa26 | lilukai1/Coding-Challenges | /guessing_game.py | 1,988 | 4.03125 | 4 | ## A simple 'guess the number' game! ##
import random
## maybe add extra functionality? Like displaying what the old scores were, or how many times the game has been played ##
scores = [100000,]
def game_on():
solved = False
answer = random.randrange(1,11)
guesses = 1
if len(scores) == 1:
print("No current high score.")
else:
print(f"The high score is {min(scores)}, good luck!!")
while solved == False:
try:
guess = int(input("Guess a number between 1 and 10.\n"))
if guess > 10 or guess < 1:
raise
except:
print("That's not a valid option!\n")
continue
if guess > answer:
print("Your guess was too high!")
guesses += 1
elif guess < answer:
print("Your guess was too low!")
guesses += 1
elif guess == answer:
solved = True
game_winner(guesses)
def game_winner(guesses):
high_score = min(scores)
play_count = len(scores)
if high_score == 100000:
print(f"You won game {play_count} and set the high score of {guesses}!")
elif high_score > guesses:
print(f"You won game {play_count} AND beat the old high score!! New high score is {guesses} guesses.")
elif high_score == guesses:
print(f"You won game {play_count} AND tied the high score!! High score is {guesses} guesses.")
else:
print(f"You won game {play_count}!! It took you {guesses} guesses. The current high score is {high_score} guesses.")
play_again = ""
scores.append(guesses)
while play_again.lower() not in ("y", "n"):
play_again = input("Would you like to play again? Y/N \n")
if play_again.lower() == "y":
game_on()
elif play_again.lower() == "n":
print("Thank you for playing!")
print("Hello, and welcome to....\n")
print("GUESS THAT NUMBER!!\n")
game_on() |
5013d4b87e26d5cc38c90fc23b948912f267b4b4 | KingsleyDeng/CoolPython | /国旗/国旗.py | 565 | 3.90625 | 4 | import turtle
# 定义一个函数,可以画五角星
def picture(x1,y1,x,y):
turtle.up()
turtle.goto(x1, y1)
turtle.down()
#用于填充颜色
turtle.begin_fill()
turtle.fillcolor("yellow")
for i in range(5):
turtle.forward(x)
turtle.left(y)
turtle.end_fill()
# 速度为3
turtle.speed(3)
# 背景红色
turtle.bgcolor("red")
# 画笔颜色
turtle.color("yellow")
picture(-250,230,100,144)
picture(-31,290,60,144)
picture(-30,181,60,144)
picture(-100,81,60,144)
picture(-210,65,60,144)
turtle.hideturtle()
turtle.done() |
7ab4f08ce17a7323d55092c76d22ad088b899ff8 | MartinMa28/Algorithms_review | /linked_list/0206_reverse_linked_list.py | 652 | 3.96875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
next_node = head.next
head.next = None
while next_node:
further = next_node.next
next_node.next = head
head = next_node
next_node = further
return head
if __name__ == "__main__":
h = ListNode(1)
h.next = ListNode(2)
h.next.next = ListNode(3)
h.next.next.next = ListNode(4)
solu = Solution()
solu.reverseList(h)
|
ff243e6110546cd9f316131e1eb951a77e383704 | Guan-Ling/20210125 | /3-L.py | 431 | 4.03125 | 4 | # Write a program that solves a linear equation ax = b in integers.
# Given two integers a and b (a may be zero), print a single integer root if it exists and print "no solution" or "many solutions" otherwise.
a=int(input("a:"))
b=int(input("b:"))
if a!=0:
c=b/a
c=c*10
if c%10!=0:
print("no solution")
elif c%10==0:
print(int(c/10))
elif a==0 and b==0:
print("many solutions")
else:
print("no solution")
|
12d10d3fefa15500836bc535bbe4209eebbc8b29 | BlakeBagwell/week_one | /list_exercises/smallest.py | 322 | 4.09375 | 4 | numbers = [1, 2, 3, 3, 2, 5, 2, 3, 1, 3, 2]
lowest = 0
#for i in range(len(numbers)):
# for j in range(len(numbers)):
# if numbers[i] < numbers[j]:
# lowest = numbers[i]
#print lowest
a = [1, 2, 3, 2]
minimum = a[0]
for number in a:
if minimum > number:
minimum = number
print minimum
|
ea44a6bca42f1180ea54e392716322068f357d14 | pretom97/Day5 | /day5/lesson5B.py | 835 | 3.828125 | 4 | ''''
if text expression:
statment
'''
players = ['Torun','Sourov','Asik','Rajib','Pritom']
for name in players :
if name == 'Sourov':
print(name.upper())
else:
print(name.lower())
age = 21
if age >= 18:
print('your old enough to vote')
print('have you register for vote yet')
else:
print('sorry you are to too young')
print('sorry')
print ('\n')
month = 1
#month = int(input('plase enter month 1-3 : '))
if month == 1:
print('jan')
elif month == 2:
print('feb')
elif month == 3:
print('mar')
else:
print ('invalit month')
print ('\n')
print("\n\nThe odd numbers are : \n")
for n in range(50):
if n%2 == 1:
print(n,end='\t')
print ('\n')
sum = 0
print("\n\nThe sum of number are : ",end='')
for n in range(0,11):
sum = sum + n
print(sum, end='\t') |
4a33b07178ac0c0673e600b36eef6ef357bd1563 | DeepNoceans/PythonPrograms | /Pygame!/L2/L2_C1_MadLib.py | 2,363 | 3.796875 | 4 | print("Mad Lib Game")
print("Enter answers to the following prompts\n")
guy = input("Name of a brave knight: ")
girl = input("Name of princess: ")
clan = input("Cool/Heroic animal (plural): ")
enemy = input("Evil animal (plural): ")
hours = input("Number from 2-5: ")
weapon = input("Medival weapon (singular)(close combat): ")
horse = input("Name of horse: ")
metal = input("Type of metal: ")
adjective = input("Weird adjective: ")
story = "\nGUY the brave knight was playing cards with the\n" +\
"local weaponsmith when we was suddenly called to the duty of\n" +\
"saving princess GIRL. Princess GIRL was captured by\n" +\
"the evil kingdom of ENEMY only HOURS hours ago. In honor\n"+\
"of his kingdom, the kingdom of CLAN, GUY the knight grabbed\n"+\
"his WEAPON and headed off towards the kingdom of ENEMY\n" +\
"on his trusty steed, HORSE. With his shiny WEAPON and his\n"+\
"gleaming armor made of METAL, GUY barged into the evil\n"+\
"kingdom's castle. He glared at his ADJ enemies with absolute \n"+\
"hatred. He saw princess GIRL tied up next to the fat king of \n"+\
"the kingdom of ENEMY. The knight raised his WEAPON and charged\n"+\
"at the king on the throne. He plowed through the crowds of ADJ people\n"+\
"effortlessly with his armor made of METAL. Before the king could escape\n"+\
"from his throne, the knight leaped into the air with his sharp WEAPON held up \n"+\
"above his head, pointing downwards with uncontrollable rage. The knight slowly\n"+\
"soured above the helpless crowd as if he were in slow motion. The king, too\n"+\
"large to escape his throne in time, could only say his last prayers. As the brave\n"+\
"Descended with no other wish than the eradication of the man behind the imprisonment\n"+\
"of the beautiful princess GIRL. The final blow was about the commence, when suddenly, \n"+\
"the story ended."
story = story.replace("GUY", guy)
story = story.replace("GIRL", girl)
story = story.replace("CLAN",clan)
story = story.replace("ENEMY", enemy)
story = story.replace("HOURS", hours)
story = story.replace("WEAPON",weapon)
story = story.replace("HORSE", horse)
story = story.replace("METAL", metal)
story = story.replace("ADJ", adjective)
print(story)
|
31ad5daff1576d5257d8fd2e170067db43836f3b | NourDT/Sudoku | /solution.py | 7,377 | 3.96875 | 4 | assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
pass
rows = 'ABCDEFGHI'
cols = '123456789'
diagonal_1 = zip
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
diagonal_units = [ [rows[i]+cols[i] for i in range(len(rows))], [rows[i]+cols[::-1][i] for i in range(len(rows))] ]
unitlist = row_units + column_units + square_units + diagonal_units
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
for unit in unitlist:
possible_twins = [(box, values[box]) for box in unit if len(values[box]) == 2]
#put all boxes that has a 2 digit value in this list,
if len(possible_twins) >= 2:
#if this unit has at least 2 or more boxes with 2 digits, we may have naked twins
for i in range (len(possible_twins) - 1):
if possible_twins[i][1] == possible_twins [i+1][1]: #if the 2 boxes have the same value, means they are naked twins, and we need to remove the values of naked twincs from the all other unsolved boxes
value_to_remove = possible_twins[i][1]
boxes_to_update = [box for box in unit if len(values[box]) > 1 if box != possible_twins[i][0] and box != possible_twins[i+1][0]]
#get a list of all unsolved boxes in the unit, not including the naked twins
unit_with_values_before = {box: values[box] for box in unit}
for box in boxes_to_update:
for val in value_to_remove:
#values[box] = values[box].replace(val, '')
assign_value(values, box, values[box].replace(val, '')) #remove the value of naked twins from the list of unsolved boxes.
unit_with_values_after = {box: values[box] for box in unit}
return values
# Find all instances of naked twins
# Eliminate the naked twins as possibilities for their peers
def grid_values(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid(string) - A grid in string form.
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
"""
chars = []
digits = '123456789'
for c in grid:
if c in digits:
chars.append(c)
if c == '.':
chars.append(digits)
assert len(chars) == 81
return dict(zip(boxes, chars))
def display(values):
"""
Display the values as a 2-D grid.
Args:
values(dict): The sudoku in dictionary form
"""
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
for c in cols))
if r in 'CF': print(line)
return
def eliminate(values):
"""
This is the implemtnation of the elimnate method, this function will go through all the solved boxes, which are boxes containing 1 digit valye only.
Args:
values(dict): The sudoku in dictionary form
"""
solved_values = [box for box in values.keys() if len(values[box]) == 1]
for box in solved_values:
digit = values[box]
for peer in peers[box]:
#values[peer] = values[peer].replace(digit, '')
assign_value(values, peer, values[peer].replace(digit, ''))
return values
def only_choice(values):
for unit in unitlist:
for digit in '123456789':
dplaces = [box for box in unit if digit in values[box]]
if len(dplaces) == 1:
#values[dplaces[0]] = digit
assign_value(values, dplaces[0], digit)
return values
def reduce_puzzle(values):
"""
values(dict): The sudoku in dictionary form
:return:
the sudoko puzzle after applying all possible methods to try and narrow down the possible solution space.
"""
solved_values = [box for box in values.keys() if len(values[box]) == 1]
stalled = False
while not stalled:
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
values = eliminate(values) #apply elimnate
values = only_choice(values) #apply only choice
values = naked_twins(values) #apply naked twins
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
stalled = solved_values_before == solved_values_after
if len([box for box in values.keys() if len(values[box]) == 0]): #if one of the boxes doesn't have a value anymore, it means the solution can't be found or something had been done wrong so we stop.
return False
return values
def search(values):
"Using depth-first search and propagation, try all possible values."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
if values is False:
return False ## Failed earlier
if all(len(values[s]) == 1 for s in boxes):
return values ## Solved!
# Choose one of the unfilled squares with the fewest possibilities
n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
# Now use recurrence to solve each one of the resulting sudokus, and
for value in values[s]:
new_sudoku = values.copy()
new_sudoku[s] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
values = grid_values(grid)
return search(values)
if __name__ == '__main__':
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
display(solve(diag_sudoku_grid))
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except SystemExit:
pass
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
|
aefc93b1c86e35ce1cdb7f285fa27e8dbc52cf1d | DriveMyScream/Python | /03_Strings/05_Escape_Sequence_character.py | 328 | 3.96875 | 4 | str = "Shubham is Good Boy"
# For New Tab in String
str = "Shubham \nis a Good Boy"
print(str)
# For New Tab in String
str = "Shubham \t is a Good Boy"
print(str)
# Want a single coat in string
str = "Shubham\' is a Good boy"
print(str)
# Want a Slash or in String
str = "Shubham \\ is Good Boy"
print(str) |
dc4f8e19d515d4e81109b86454c759b3623e55ae | qfaizan401/OpenCV | /chapter1.py | 914 | 3.609375 | 4 | #Chapter 1: Read- Images, Videos, Webcam
import cv2
import numpy as np
print('Package Imported', cv2.__version__)
#Part 1: Read Images
img_path = 'Resources/lena.jpg'
img = cv2.imread(img_path)
cv2.imshow('Lena', img)
cv2.waitKey(0)
#Part 2: Read Video
video_path = 'Resources/IMG_0275.MOV.mp4'
cap = cv2.VideoCapture(video_path)
#As we know that video is a squence of images(frames) so we need to loop through it.
while True:
sucess, img = cap.read()
print(np.shape(img))
cv2.imshow('Video', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#Part 3: Access the WebCam (Very much similar to Read Video)
WebCam_cap = cv2.VideoCapture(0)
#As we know that video is a squence of images(frames) so we need to loop through it.
while True:
sucess, img = WebCam_cap.read()
print(np.shape(img))
cv2.imshow('Video', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break |
5404390248ec7b0409a22df6ba2ab8019e83f1e5 | MJHutchinson/PytorchPrivacy | /pytorch_privacy/analysis/online_accountant.py | 2,118 | 3.671875 | 4 | class OnlineAccountant(object):
""" A class to perform accounting in an
online manner to speed up experiments. requires
an accountancy method to have an online method. """
def __init__(self,
accountancy_update_method,
ledger=None,
accountancy_parameters=None):
"""
:param accountancy_update_method: A method to compute the desired accountancy in and
online fashion. Should take as parameters some list of new privacy queries to update the
privacy for, and some tracking variable specific to the method (E.g. log moments for the
moment accountant). This method should fuction if the tracking variable are None.
:param ledger: Some initial ledger. May be None
:param accountancy_parameters: Some parameters to pass to the accountancy update method.
E.g. the target epsilon or delta, maximum log moment...
"""
self._accountancy_update_method = accountancy_update_method
self._accountancy_parameters = accountancy_parameters
self._ledger = []
self._tracking_parameters = None
self._position = 0
if ledger is None:
ledger = []
self._privacy_bound = self.update_privacy(ledger)
def update_privacy(self, incremented_ledger):
""" Update the current privacy bound using new additions to the ledger.
:param incremented_ledger: The new ledger. Assumes that the only differences
from previously seen ledger is the new entries. This should be of the formatted
ledger type.
:return: The new privacy bound.
"""
self._ledger = incremented_ledger
new_entries = self._ledger[self._position:]
self._privacy_bound, self._tracking_parameters = self._accountancy_update_method(
new_entries,
self._tracking_parameters,
**self._accountancy_parameters
)
self._position = len(self._ledger)
return self._privacy_bound
@property
def privacy_bound(self):
return self._privacy_bound
|
0cef636afac5369a7b0d672335fd745535505303 | zhengchaoxuan/Lesson-Code | /Python/Python基础/day 7/exercise_5计算指定的年月日是这一年的第几天.py | 1,208 | 4.71875 | 5 | """
exercise5:计算指定的年月日是这一年的第几天
设计逻辑:年判断是否为闰年,月的话每月的日期都不同,用元组表示
Version : 0.1
Author : 郑超轩
Date : 2020/02/11
"""
"""
param:
year :年
month:月
day :日
return:
date:该年第几天
"""
def get_date(year,month,day):
if year%4 ==0 and year%100!=0 or year%400==0 :
months =(31,28,31,30,31,30,31,31,30,31,30,31) #每月的天数
else:
months =(31,29,31,30,31,30,31,31,30,31,30,31) #每月的天数
date = day
for i in range(month-1):
date+=months[i]
return date
def main():
print(get_date(2016,1,8))
print(get_date(2018,12,3))
if __name__ =='__main__':
main()
"""
参考答案:
判断闰年
def is_leap_year(year):
return year%4==0 and year%100!=0 or year%400==0:
计算日期
def which_day(year,month,date):
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
][is_leap_year(year)]
total = 0
for index in range(month - 1):
total += days_of_month[index]
return total + date
""" |
e491168fad60c24e43e4c2f5f0e3687495ef39b2 | cruigo93/leetcode | /easy/709.py | 417 | 3.734375 | 4 | from typing import List
class Solution:
def toLowerCase(self, str: str) -> str:
new_str = ""
for i in range(len(str)):
c = str[i]
if ord("Z") >= ord(c) >= ord("A"):
c = chr(ord(c) + 32)
new_str += c
return new_str
def main():
sol = Solution()
s = input()
print(sol.toLowerCase(s))
if __name__ == "__main__":
main() |
8c0806adbd691d6e7db5e25da631da0c7e54a63d | KaShing96/hackerrank-challenges | /easy/sherlock_and_array/functions.py | 3,009 | 3.75 | 4 | # === Imports ===
import math
import os
import random
import re
import sys
# === Function ===
def balancedSums(arr):
"""
Your code goes here.
"""
# Left and right sums
left = 0
right = sum(arr)
# Loop through each element, adding the previous element to left, and removing the current element from right where possible
for ix, i in enumerate(arr):
# We ensure that ix - 1 >= 0 before we add the previous to left
if ix >= 1:
left += arr[ix-1]
# Subtract from right
right -= arr[ix]
# Check for equality
if left == right:
return "YES"
return "NO"
# === Main ===
# Function to be called
def main(args):
"""
This is the main function to be called in test_functions.py.
This should emulate the logic in HackerRank's if __name__ == '__main__' logic block and process #args# accordingly.
Params
======
args: str
A single line string
"""
T = int(input().strip())
for T_itr in range(T):
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = balancedSums(arr)
fptr.write(result + '\n')
fptr.close()
# === Debug ===
def DEBUG(*args, **kwargs):
"""
If this function is not run directly, i.e. it is under test, this will take on the print statement. Otherwise, nothing happens.
"""
if __name__ != "__main__":
print(*args, **kwargs)
# === Mock ===
# Mock fptr.write()
class Writer():
def __init__(self):
"""Initialises the list of answers."""
self.answers = []
def write(self, string):
"""Appends the string to a list, which is then accessed by the parent test function to check for equality of arguments.
Params
======
string: str
The string to be appended to the list of answers.
"""
# Process the string to be appended, to remove the final newline character as added in main()
li = string.rsplit('\n', 1)
self.answers.append(''.join(li))
def get_answers(self):
"""
Returns the answers and resets it.
Returns
=======
result: list of strings
The answers to be returned.
"""
result = self.answers
self.answers = []
return result
def close(self):
pass
fptr = Writer()
# List of inputs
list_of_inputs = []
# Sets inputs
def set_inputs(string):
"""
This function sets the inputs to be mocked by the input() function.
The #string# passed is split by the newline character. Each element then makes up the argument called sequentially by input().
"""
global list_of_inputs
list_of_inputs = string.split("\n")
# Mocks the inputs
def input():
"""
Mocks the 'input()' function.
If arguments is not None, it resets the arguments used.
"""
return list_of_inputs.pop(0) |
1a2d2826db7c0848f99e1a1d65bb4db2d8b3b32c | sunjilong-tony/python1 | /test.py | 273 | 3.984375 | 4 | #coding=utf-8
print("hello,world")
number=int(input("please input your number:"))
if number < 18 :
print("you are young")
elif number >=18 :
print("hello ,骚年")
elif number >60 :
print("haha")
input("enter 退出")
for number in range(100):
print(numer)
|
105df97eb4c77c1098c818a825ebced65bb8cd50 | mathans1695/Python-Practice | /codeforces problem/WayTooLongWords.py | 227 | 3.65625 | 4 | n = int(input())
result = []
for i in range(n):
word = input()
if len(word) <= 10:
result.append(word)
else:
result.append(word[0] + '{}'.format(len(word[1:len(word)-1])) + word[len(word)-1])
for i in result:
print(i) |
738dcee30452cdf0f170339df27d88064069c845 | jocelo/rice_intro_python | /practice_excercises/week_0b/11_herons_formula.py | 528 | 3.75 | 4 | #x0, y0 = 0, 0
#x1, y1 = 3, 4
#x2, y2 = 1, 1
#x0, y0 = -2, 4
#x1, y1 = 1, 6
#x2, y2 = 2, 1
x0, y0 = 10, 0
x1, y1 = 0, 0
x2, y2 = 0, 10
a = ((x0-x1)**2+(y0-y1)**2) ** (1.0/2.0)
b = ((x1-x2)**2+(y1-y2)**2) ** (1.0/2.0)
c = ((x0-x2)**2+(y0-y2)**2) ** (1.0/2.0)
semi = (a+b+c)/2.0
area = (semi*(semi-a)*(semi-b)*(semi-c)) ** (1.0/2.0)
print "A triangle with vertices (" + str(x0) + "," + str(y0) + "),",
print "(" + str(x1) + "," + str(y1) + "), and",
print "(" + str(x2) + "," + str(y2) + ") has an area of " + str(area) + "." |
fb30a2e639653d9a98a9440be797384c0de87278 | tsumo/solutions | /project_euler/003-largest_prime_factor.py | 1,747 | 3.984375 | 4 | #!/usr/bin/env python3
"""
Largest prime factor
Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
import pe_utils
def lpf_naive(n):
largest_prime = 0
current_prime = 0
while current_prime < n:
current_prime = next_prime(current_prime)
if n % current_prime == 0:
n /= current_prime
largest_prime = current_prime
return largest_prime
def is_prime(n):
"""
Checks if the number is a prime.
"""
if n == 0 or n == 1:
return False
for i in range(n - 1, 1, -1):
if n % i == 0:
return False
return True
def next_prime(n):
"""
Returns next prime number n + x.
"""
while True:
n += 1
if is_prime(n):
return n
def lpf_fast(n):
i = 1
while n > 1:
i += 1
while n % i == 0:
n /= i
return i
def lpf_faster(n):
"""
Since 2 is the only even prime we can treat
it separately and increase i by 2.
"""
while n % 2 == 0:
n /= 2
i = 1
while n > 1:
i += 2
while n % i == 0:
n /= i
return i
pe_utils.test(lpf_naive, [13195], 29)
# pe_utils.test(lpf_naive, [600851475143], 6857)
# pe_utils.test(lpf_naive, [600851475142], 22567)
print("-----")
pe_utils.test(lpf_fast, [600851475143], 6857)
pe_utils.test(lpf_fast, [600851475142], 22567)
pe_utils.test(lpf_fast, [234783486], 1863361)
pe_utils.test(lpf_fast, [876426], 79)
print("-----")
pe_utils.test(lpf_faster, [600851475143], 6857)
pe_utils.test(lpf_faster, [600851475142], 22567)
pe_utils.test(lpf_faster, [234783486], 1863361)
pe_utils.test(lpf_faster, [876426], 79)
|
cad38b889cf060f59298ecd216d914f3435fb155 | Staggier/Kattis | /Python/leftbeehind.py | 299 | 3.921875 | 4 | def leftbeehind():
while True:
n, k = [int(x) for x in input().split()]
if n == 0 and k == 0:
return
if n + k == 13:
print("Never speak again.")
elif n == k:
print("Undecided.")
elif n > k:
print("To the convention.")
else:
print("Left beehind.")
leftbeehind()
|
542e58c6e54d714b60944bbbeb08b6cd1ea9b103 | lokeshagg13/Path-Finder | /Helper/Geometry.py | 726 | 3.78125 | 4 | class Vector2:
def __init__(self, _x=0, _y=0):
self.x = _x
self.y = _y
@staticmethod
def zero():
v = Vector2(0,0)
return v
@staticmethod
def one():
v = Vector2(1,1)
return v
def __str__(self):
return '({0},{1})'.format(self.x,self.y)
class Vector3(Vector2):
def __init__(self, _x=0, _y=0, _z=0):
super().__init__(_x,_y)
self.z = _z
@staticmethod
def zero():
v = Vector3(0,0,0)
return v
@staticmethod
def one():
v = Vector3(1,1,1)
return v
def __str__(self):
return '({0},{1},{2})'.format(self.x,self.y,self.z)
v = Vector3(2,8,6)
print(v)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.