blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6d44eeb3076105ed28ea127912191c2014866d13 | seesoft/SoftUni-Courses | /Python/Basics/0.1-First-Steps-In-Coding/Exercises/fish_tank.py | 360 | 3.859375 | 4 | length = int(input())
width = int(input())
height = int(input())
taken_space = float(input())
taken_space_in_percents = taken_space * 0.01
available_space_in_centimeters = length * width * height
available_space_in_meters = available_space_in_centimeters * 0.001
needed_liters = available_space_in_meters * (1 - taken_space_in_percents)
print(needed_liters)
|
e153c7d9b15a596c5e19c67b1e573c67bb3faba1 | superwenqistyle/1803 | /14day/第七题.py | 211 | 3.796875 | 4 | def xxx():
list = [{"beijing":{"mianji":1290,"renkou":123123},"shanghai":{"mianji":12331,"renkou":123123}}]
for temp in list:
for k,v in temp.items():
for p,j in v.items():
print(k,p,j)
xxx()
|
bf5b496e345713923d8d783e838e113d4785fe39 | le-birb/advent-of-code_2020 | /day6.py | 1,105 | 3.75 | 4 |
groups = []
curr_group = []
with open('day6-input', 'r') as f:
for line in f:
line = line.strip()
if line == "":
# blank lines separate groups
if curr_group:
groups.append(curr_group)
curr_group = []
else:
# store answers as a set because we're only interested in unique answers
# and python will handle that for us with a set
curr_group.append(set(line))
# catch a trailing group not followed by a newline at the end of the input
if curr_group:
groups.append(curr_group)
# part 1: sum of the number of answers in each group
# we have a set of from each person, so the union of each persons' answers will be the set of unique answers in a group
unique_answers = [set.union(*group) for group in groups]
print(sum(len(answers) for answers in unique_answers))
# part 2:
# now we want answers common to everybody, which is an intersection of sets this time
common_answers = [set.intersection(*group) for group in groups]
print(sum(len(yeses) for yeses in common_answers)) |
1066830533798c32ab67d97432f311af439a8961 | SergMT/Prolux | /Fechas.py | 1,378 | 4.125 | 4 | #Se importa la librería datetime, timedelta para hacer operaciones con fechas
from datetime import datetime, timedelta
#Se obtiene la fecha actual con datetime.now()
fechaActual = datetime.now()
#Para concatenar con strings, se convierte la fecha en string
print("La fecha actual es: " + str(fechaActual))
"""Uso de timedelta, para quitar días o semanas a una fecha específica
Para los días se usa days = Numero_De_Dias
Para las semanas es weeks = Numero_De_Semanas"""
unDia = timedelta(days=1)
#Se resta el valor de la variable unDia a la fecha actual
fechaActual = datetime.now() - unDia
print("Fecha de ayer: " + str(fechaActual))
"""OBTENER DATOS ESPECIFICOS
print("Dia: " + str(fechaActual.day))
print("Mes: " + str(fechaActual.month))
print("Año: " + str(fechaActual.year))
print("Hora: " + str(fechaActual.hour))
print("Minutos: " + str(fechaActual.minute))
print("Segundos: " + str(fechaActual.second))
"""
#Pedir fecha de nacimiento al usuario
fechaUsuario = input("Ingresa la fecha de tu cumpleaños dd/mm/yyyy ")
#Se verifica que la fecha se haya recibido en el formato indicado con strptime()
fechaNacimiento = datetime.strptime(fechaUsuario, "%d/%m/%Y")
fechaNacimiento = fechaNacimiento - unDia
#Se convierte en cadena la fecha de cumpleaños para imprimirlo
print("El día antes de tu cumpleaños es: " + str(fechaNacimiento)) |
bcfc55d277069946b75cab734d2f63edc35b18c3 | JiangWeixian/Algo | /docs/Sword2offer/CH4-解题思路/Python/checkBST.py | 921 | 3.953125 | 4 | def split_lr(arr):
root = arr[-1]
for i in range(len(arr)):
if arr[i] > root:
return i
def is_bst(arr):
root = arr[-1]
if arr[0] < root and arr[1] > root:
return True
return False
def recurvise_check(arr):
result = False
if len(arr) > 3:
mid = split_lr(arr)
if mid > 0:
result = recurvise_check(arr[0:mid])
if not result:
return result
if mid < len(arr):
result = recurvise_check(arr[mid:-1])
if not result:
return result
if len(arr) == 3:
result = is_bst(arr)
return result
if len(arr) < 3:
return True
return result
def check(arr):
if type(arr) != list or len(arr) < 2:
return True
return recurvise_check(arr)
if __name__ == '__main__':
arr = [5, 7, 6, 9, 11, 10, 8]
print(check(arr))
arr = [7, 4, 6, 5]
print(check(arr))
arr = [4, 7, 6]
print(check(arr)) |
143bd551e0539d4d8c713dcd024da0b62322f44e | PhoenixGreen/Python-GUI | /Lesson 2.2 - Auto image slides - advanced.py | 1,420 | 3.6875 | 4 | from tkinter import *
# The main app window and background image
window = Tk()
window.title("My Slide Show")
window.geometry("600x500")
background_image = PhotoImage(file = "landscape.png")
background_label = Label(window, image = background_image)
background_label.place(relwidth = 1.0, relheight = 1.0)
# upper frame - and text label
upper_frame = Frame(window, bg = "#80c1ff", bd = 5)
upper_frame.place(relx = 0.5, rely = 0.1, relwidth = 0.75, relheight = 0.1, anchor = "n")
label = Label(upper_frame, text = "Welcome to my photo album", bg = "white")
label.place(relwidth = 1.0, relheight = 1.0)
# lower frame - and image in lower frame
lower_frame = Frame(window, bg = "#80c1ff", bd = 5)
lower_frame.place(relx = 0.5, rely = 0.25, relwidth = 0.75, relheight = 0.6, anchor = "n")
def image_rotator():
global current
global images
image_list = [
"tree1.gif",
"tree2.gif",
"tree3.gif",
]
images = PhotoImage(file = image_list[current]).subsample(2, 2)
image_slide_show = Label(lower_frame, image = images)
image_slide_show.place(relwidth = 1.0, relheight = 1.0)
if current < len(image_list) -1:
current = current +1
else:
current = 0
image_slide_show.config(image = images)
window.after(2000, image_rotator)
# Runs the image_rotator the first time
current = 0
image_rotator()
# Starts the program
window.mainloop()
|
9460b6d954c25a57da6fd9d3f4f2ec79642e76d8 | olesmith/SmtC | /Curve/Roulette.py | 2,382 | 3.796875 | 4 | from math import *
from Vector import *
class Curve_Roulette():
##!
##! Get rolling angular velocity as function of t
##!
def Curve_Roulette_Angle(self,t):
n=self.T2n(t)
s=self.S[n]
return -s/(self.Roulette_A)
##!
##! Calculates curve unit normal vector.
##!
def Curve_Normal(self,t):
return self.dr(t).Normalize().Transverse2()
##!
##! Calculates rotated vector: The normal,
##!
def Curve_Roulette_Rotated(self,t,normal):
if (not normal):
normal=self.Curve_Normal(t)
angle=self.Curve_Roulette_Angle(t)
return normal.Rotate2(angle)
##!
##! Get coordinates of rolling point as function of t.
##!
def Curve_Rolling_Center(self,t):
R=self.r(t)
return R+self.Curve_Normal(t)*self.Roulette_A
##!
##! Get coordinates of rolling point as function of t.
##!
def Curve_Roulette_Calc(self,t):
center=self.Parent.Curve_Rolling_Center(t)
e=self.Parent.Curve_Roulette_e(t)
return center+e
def Curve_Roulette_e(self,t):
normal=self.Curve_Normal(t)
normal*=-self.Roulette_B
e=self.Curve_Roulette_Rotated(t,normal)
#e*=-1.0
return e
##!
##! Get coordinates of rolling center in point n
##!
def Curve_Roulette_Circles_Draw(self,n):
ra=self.Roulette_A
t=self.ts[n]
center=self.Curve_Rolling_Center(t)
normal=self.Curve_Normal(t)
e=self.Curve_Roulette_e(t)
normal*=-self.Roulette_A
color1="magenta"
color2="yellow"
angle=-self.Curve_Roulette_Angle(t)
while (angle<-2.0*pi):
angle+=2.0*pi
while (angle>2.0*pi):
angle-=2.0*pi
self.Canvas().Draw_Circle_Spans(
center,
normal,
-angle,
"Roulette_Arc_Rolled",
"Roulette_Arc_Unrolled",
color1,
color2
)
self.Canvas().Draw_CS(
center,
normal,normal.Transverse2(),
"Rolling_CS",
color1
)
self.Canvas().Draw_CS(
center,
e,e,
"Roulette_CS",
color1
)
|
3879e669ede0407269fd9daabf73e18879b3582d | Haider8/matrix-happiness | /lib/matrix.py | 1,184 | 4 | 4 | #matrix.py
def matrix_add(order):
alpha = order*order
elements1 = []
elements2 = []
add = []
for i in range(0, alpha):
elements1.append([])
elements2.append([])
add.append([])
print("Enter elements in first matrix...\n")
for i in range(0, alpha):
elements1[i] = int(input())
print("Enter elements in second matrix...\n")
for i in range(0, alpha):
elements2[i] = int(input())
for i in range(0, alpha):
add[i] = elements1[i] + elements2[i]
#print(add[i], end = ' ')
print(add)
#matrix_add(3)
def matrix_subtract(order):
alpha = order*order
elements1 = []
elements2 = []
add = []
for i in range(0, alpha):
elements1.append([])
elements2.append([])
add.append([])
print("Enter elements in first matrix...\n")
for i in range(0, alpha):
elements1[i] = int(input())
print("Enter elements in second matrix...\n")
for i in range(0, alpha):
elements2[i] = int(input())
for i in range(0, alpha):
add[i] = elements1[i] - elements2[i]
#print(add[i], end = ' ')
print(add)
#matrix_subtract(2)
|
1b84cc187ed57b8c2706d06f5d3275296df3f0e4 | to-Remember/TIL | /June 7, 2021/2_picachu_func.py | 1,590 | 3.6875 | 4 | hp = 30
exp = 0
lv = 1
def 밥먹기():
global hp #hp는 전역변수임을 의미
print('피카추 밥먹음')
hp += 5
def 잠자기():
global hp #전역변수라고 지정하는 것
print('피카추 잠잠')
hp += 10
def 놀기():
global hp, exp #전역변수라고 지정하는 것
print('피카추 논다')
hp -= 8
flag = hp > 0 #살아있다면 아래와 같이 경험치 추가
if flag:
exp += 5
레벨체크()
return flag
def 운동하기():
global hp, exp #전역변수라고 지정하는 것
print('피카추 운동한다')
hp -= 15
flag = hp > 0
if flag:
exp += 10
레벨체크()
return flag
def 상태확인():
print('피카추 상태확인')
print('hp:',hp)
print('exp:',exp)
print('lv:',lv)
def 레벨체크():
global hp, exp, lv
if exp >= 20:
lv += 1
exp -= 20
print('레벨 1 상승')
def main():
flag = True
while flag:
menu = input('1.밥먹기 2.잠자기 3.운동하기 4.놀기 5.상태확인 6.종료')
if menu == '1':
밥먹기() # 앞에 hp랑 뒤에 파라메터 있어야지 변경된 값이 리턴됨
elif menu == '2':
잠자기()
elif menu == '3':
flag = 운동하기()
elif menu == '4':
flag = 놀기()
elif menu == '5':
상태확인()
elif menu == '6':
print('게임종료')
break
if not flag:
print('캐릭터 사망')
main()
|
5ea22b620ea584b439281a88f88804923e935739 | dmccloskey/EvoNetPyScripts | /MNIST_expectedPredicted.py | 5,403 | 3.515625 | 4 | from matplotlib import pyplot as plt
import numpy as np
import csv
import sys
def read_csv(filename, delimiter=','):
"""read table data from csv file"""
data = []
try:
with open(filename, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=delimiter)
try:
keys = reader.fieldnames
for row in reader:
data.append(row)
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
except IOError as e:
sys.exit('%s does not exist' % e)
return data
def plotExpectedPredicted(input, output, expected, label, fig, axes):
"""Generate a side by side plot of expected and predicted
Args:
input (np.array): input pixels
output (np.array): output pixels
expected (np.array): expected pixels
label (string): label of the image
fig
axes
"""
n_batches = len(input)
for batch in range(0, n_batches):
input_2d = np.clip(np.reshape(input[batch], (28, 28)), 0, 1)#.astype(np.uint8)
expected_2d = np.clip(np.reshape(expected[batch], (28, 28)), 0, 1)#.astype(np.uint8)
output_2d = np.clip(np.reshape(output[batch], (28, 28)), 0, 1)#.astype(np.uint8)
axes[batch, 0].imshow(input_2d, interpolation='nearest', cmap='gray')
axes[batch, 0].set_title('Digit Label: {}'.format(label))
axes[batch, 0].set_xbound([0,28])
axes[batch,1] .imshow(expected_2d, interpolation='nearest', cmap='gray')
axes[batch,1] .set_title('Digit Label: {}'.format(label))
axes[batch,1] .set_xbound([0,28])
axes[batch,2] .imshow(output_2d, interpolation='nearest', cmap='gray')
axes[batch,2] .set_title('Digit Label: {}'.format(label))
axes[batch,2] .set_xbound([0,28])
def main(filename_input, filename_output, filename_expected, input_headers, output_headers, expected_headers):
"""Run main script"""
# read in the data
input_data = read_csv(filename_input)
output_data = read_csv(filename_output)
expected_data = read_csv(filename_expected)
assert(len(input_data) == len(output_data) == len(expected_data))
assert(len(input_headers[0]) == len(output_headers[0]) == len(expected_headers[0]))
n_batches = len(input_headers)
n_data = len(input_data)
# parse each data row
for n in range(25, n_data):
input = []
expected = []
output = []
for batch in range(0, n_batches):
input.append(np.array([input_data[n][h] for h in input_headers[batch]]).astype(np.float))
expected.append(np.array([expected_data[n][h] for h in expected_headers[batch]]).astype(np.float))
output.append(np.array([output_data[n][h] for h in output_headers[batch]]).astype(np.float))
fig, axes = plt.subplots(n_batches,3,
figsize=(10,10),
sharex=True, sharey=True,
subplot_kw=dict(adjustable='box', aspect='equal')) #https://stackoverflow.com/q/44703433/1870832
plotExpectedPredicted(input, output, expected, "", fig, axes)
# show the image
plt.tight_layout()
plt.show()
# Run main# Run main
if __name__ == "__main__":
#filename_input = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu0-2c/CVAE_NodeInputsPerEpoch.csv"
#filename_expected = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu0-2c/CVAE_ExpectedPerEpoch.csv"
#filename_output = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu0-2c/CVAE_NodeOutputsPerEpoch.csv"
# filename_input = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu2-0a/CVAE_NodeInputsPerEpoch.csv"
# filename_expected = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu2-0a/CVAE_ExpectedPerEpoch.csv"
# filename_output = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu2-0a/CVAE_NodeOutputsPerEpoch.csv"
filename_input = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu3-0a/CVAE_NodeInputsPerEpoch.csv"
filename_expected = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu3-0a/CVAE_ExpectedPerEpoch.csv"
filename_output = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu3-0a/CVAE_NodeOutputsPerEpoch.csv"
filename_input = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu7-3a/VAE_NodeInputsPerEpoch.csv"
filename_expected = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu7-3a/VAE_ExpectedPerEpoch.csv"
filename_output = "C:/Users/dmccloskey/Documents/GitHub/EvoNetData/MNIST_examples/CVAE/Gpu7-3a/VAE_NodeOutputsPerEpoch.csv"
input_headers = []
output_headers = []
expected_headers = []
for batch in range(0, 4):
input_headers.append(["Input_{:012d}_Input_Batch-{}_Memory-0".format(i, batch) for i in range(784)])
output_headers.append(["Output_{:012d}_Output_Batch-{}_Memory-0".format(i, batch) for i in range(784)])
expected_headers.append(["Output_{:012d}_Expected_Batch-{}_Memory-0".format(i, batch) for i in range(784)])
main(filename_input, filename_output, filename_expected, input_headers, output_headers, expected_headers) |
cd9c22a5e27178c5dd55bc102e534ed0f39066b5 | pala9999/python | /week1/week1_q4.py | 558 | 4.0625 | 4 | my_list = ["a", "c", "d", "e", "f", "g", "h", "i"]
print("Initial List: ", my_list)
my_list.append("j")
print("\nAdd \"j\" to the end of list:")
print(my_list)
print("\nInsert \"b\" between \"a\" and \"c\":")
my_list.insert(1,"b") #Specify postion , character to add#
print(my_list)
print("\nRemove \"e\" from list:")
my_list.remove("e") #Specify exact chat to remove#
print(my_list)
print("\nReverse the list:")
my_list.reverse()
print(my_list)
print("\nreplace i with z:")
my_list[1]="z"
print(my_list)
print("\nSorted List:")
my_list.sort()
print(my_list) |
4d1f500949c0599c542aacc784ca128c2a87b89d | HesterXu/Home | /Lemon/Python_Base/Lesson6_function_20181107/Lesson6_function_20181107.py | 3,300 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/11/7/20:04
# @Author : Hester Xu
# Email : xuruizhu@yeah.net
# @File : Lesson6_function_20181107.py
# @Software : PyCharm
# 函数:
# append pop insert range print input int str list replace strip split
# 内置函数
# 参数:可以是0个,1个,或多个。 有参数时,调用时必须传参。
# return 变量的个数 变量个数可以是0个或多个 多个变量用逗号隔开 多个变量返回的是元组
# 可以有return,也可以没有
# return 后没有变量, 或者没有return,返回的都是None
# return作用:当你调用函数的时候,返回一个结果给函数,函数终止
# 当要利用函数的返回值做其他操作时,要return结果出来。
# 怎么写一个函数:
# 1. 先用代码写出功能,甚至可以用一组数据替代进去 写代码
# 2. def 函数名 变成函数
# 3. 思考怎么提高复用性
# 参数:默认按顺序赋值 不想按顺序赋值,可以按名称赋值,但是名称要跟参数名保持一致
# 位置参数
# 默认值参数/名称参数:定义一个默认值
# 动态参数:也叫不定长参数, 不定个数 不定长参数变成了:元组
# 动态参数: *变量名 *args arguments
# 动态参数: 可以接收任意多个参数
# 关键字参数 **kwargs key word arguments 关键字参数变成了:字典
# 关键字参数 可以接收任意多个参数/键值对
# 参数的混合使用,要注意顺序:
# 一般规则:位置参数,动态参数,默认值参数,关键字参数!!!
# 默认值参数必须放在位置参数后面
# 位置参数,动态参数,默认值参数的顺序:要想取默认值,默认值参数放在最后......
'''
# 按顺序赋值,1给a,2给b,其他的给args
def print_msg(a,b=10,*args):
print("a:",a)
print("b:",b)
print("args:",args)
print_msg(1,2,3,4,5,6) # a=1,b=2,args=(3,4,5)
'''
'''
# 默认值参数必须放在位置参数后面, b=10放在a前面是错误的!!!
def print_msg(b=10,a,*args):
print("a:",a)
print("b:",b)
print("args:",args)
print_msg(1,2,3,4,5,6)
'''
'''
# 要想让b=10不变,把b=10放在最后。1给了a,其他的全给了args。
def print_msg(a,*args,b=10):
print("a:",a)
print("b:",b)
print("args:",args)
print_msg(1,2,3,4,5,6) # a=1,b=10,args=(2,3,4,5,6)
'''
'''
# 这种情况下:args不能放在a前面,全部传给了args,a没有了值。
def print_msg(*args,a,b=10):
print("a:",a)
print("b:",b)
print("args:",args)
print_msg(1,2,3,4,5)
'''
'''
def print_msg(*args,a,b=10):
print("a:",a)
print("b:",b)
print("args:",args)
print_msg(2,3,4,5,6,a=1) # a=1放在最后是可以的,不能放在最前面
'''
'''
# 内置函数 pop() replace()
s = [1,3,4]
s.pop() # 会删除最后一个元素,然后返回这个被删除的值
print(s) # [1,3]
print(s.pop()) # 4
a = 'hello'
new_a = a.replace('h','@') # 会返回一个新的字符串,原来的字符串不变
print(a) # hello
print(new_a) # @ello
'''
'''
# 怎么提高函数的复用性
def sum(a,b):
s = 0
for i in range(a,b):
s += i
#print("{}到{}的和是{}".format(a,b-1,s))
return s
print(sum(1,101))
'''
|
ee4d151114477797795924ead51c62340389f489 | rajputsher/LinearAlgebra | /1_Vectors/8_LengthVector.py | 267 | 3.703125 | 4 | import numpy as np
# a vector
v1 = np.array([ 1, 2, 3, 4, 5, 6 ])
# methods 1-4, just like with the regular dot product, e.g.:
vl1 = np.sqrt( sum( np.multiply(v1,v1)) )
# method 5: take the norm(norm is the length directly)
vl2 = np.linalg.norm(v1)
print(vl1,vl2) |
f45008733799d5d89b770764b371be4a2a3287b3 | Levintsky/topcoder | /python/leetcode/dp/1027_longest_arith.py | 2,300 | 3.921875 | 4 | """
1027. Longest Arithmetic Sequence (Medium)
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Note:
2 <= A.length <= 2000
0 <= A[i] <= 10000
"""
import collections
class Solution(object):
def longestArithSeqLength(self, A):
"""
:type A: List[int]
:rtype: int
"""
# single list
single = set([A[0]])
ari = {} # (end, diff) : length
for item in A[1:]:
# update arith
to_remove = []
for end, diff in list(ari.keys()):
if item - end == diff:
ari[item, diff] = ari[end, diff] + 1
to_remove.append((end, diff))
for e, d in to_remove:
del ari[(e, d)]
# print(item, ari, ari.get((3,0), 0))
# with single form ari
for item2 in single:
if (item, item - item2) not in ari:
ari[(item, item - item2)] = 2
# add item to single
single.add(item)
return max(ari.values())
def solve2(self, A):
dp = collections.defaultdict(int)
for i in range(len(A)):
for j in range(i + 1, len(A)):
a, b = A[i], A[j]
dp[b - a, j] = max(dp[b - a, j], dp[b - a, i] + 1)
return max(dp.values()) + 1
if __name__ == "__main__":
a = Solution()
"""
print(a.longestArithSeqLength([3,6,9,12]))
print(a.longestArithSeqLength([9,4,7,2,10]))
print(a.longestArithSeqLength([20,1,15,3,10,5,8]))
print(a.longestArithSeqLength([24,13,1,100,0,94,3,0,3]))
"""
# print(a.longestArithSeqLength([9,4,7,2,10]))
print(a.solve2([9, 4, 7, 2, 10]))
|
9f2da46d92bcc86dd5338f181fd7c2a8cd12741d | pi-2021-2-db6/lecture-code | /aula04-exercicios/calcula_divida.py | 343 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Determina o valor da dívida com base no capital, taxa de juros
e periodo transcorrido
@author: Prof. Diogo SM
"""
p = float(input("Capital (R$): "))
i = float(input("Taxa de juros (entre 0 e 1): "))
n = int(input("Periodo (em meses): "))
j = p * i * n
d = p + j
print(f"Divida: R${d:.2f}")
|
446e4531858b9b3d06d1800278db0b917feb5505 | mehzabeen000/list | /front_back.py | 272 | 3.671875 | 4 | #we have to see whether the particular list look same form front and behind
a=[1,1,2,1,1]
i=0
mid=len(a)//2
same=True
while i<mid:
if a[i]!=a[len(a)-i-1]:
print("No")
same=False
break
i+=1
if same==True:
print("Yes")
|
a3c10c105c5fb526d610d18467a7525db58b27eb | lxhguard/django- | /blog/data/mysql_to_excel.py | 1,652 | 3.53125 | 4 | """
mysql_to_excel(username, password, database_name, port)
参数:username:数据库用户名
password:数据库用户密码
database_name:要存入的库的名称
port:数据库端口
功能:将数据库相应库的num张以table+n为名称表存入excel中,保存到当前文件夹
返回值:void
date:2018.11.24
author:Benjamin
"""
import pymysql
import openpyxl
def mysql_to_excel(username, password, database_name, port):
# 创建工作簿,设置编码
one_excel = openpyxl.Workbook()
# 连接到数据库
db = pymysql.connect(host="localhost",
user=username,
password=password,
db=database_name,
port=port,
autocommit=True)
# 游标 相当与输入
cur = db.cursor()
sql = "show tables like 'as_table%';"
cur.execute(sql)
result = cur.fetchall()
for i in result:
write_one_table(one_excel, i[0], cur)
db.commit()
one_excel.remove(one_excel["Sheet"])
one_excel.save("50tables.xlsx")
db.close()
def write_one_table(excel_name, table_name, cur):
one_sheet = excel_name.create_sheet(title = table_name)
sql = "select * from %s;" % table_name
cur.execute(sql)
result = cur.fetchall()
row = 1
for i in result:
for col in range(1, len(i)+1):
one_sheet.cell(row=row, column=col).value = i[col-1]
row += 1
if __name__ == '__main__':
mysql_to_excel("root", "mysql123", "test", 3306)
|
cf1fc981b883f9a27e6f727b6eef4766bb718db4 | wktfraser/ArtifactMarketAnalysis | /feature_MarketPricing.py | 1,105 | 3.53125 | 4 | import math
from Feature import Feature
from constants import RARITIES
class MarketPricing(Feature):
def print(self, market_data):
longest_rarity = len(max(RARITIES, key=len))
card_data = market_data.get_card_data_by_rarity()
print(f"[ {'RARITY':>{longest_rarity}} MEDIAN AVERAGE ]")
for rarity in RARITIES:
print(f" {(rarity):>{longest_rarity}} -"
+ f" {self.get_median_price_in_list(card_data[rarity]):>7.2f} -"
+ f" {self.get_average_price_in_list(card_data[rarity]):>8.3f}")
# return average price of card, in given list
def get_average_price_in_list(self, card_list):
if len(card_list) > 0:
return sum(card.price for card in card_list) / len(card_list)
else:
return 0
# return median price of card, in given list
def get_median_price_in_list(self, card_list):
if len(card_list) > 0:
sorted_card_list = sorted(card_list, key=lambda card: card.price)
return sorted_card_list[math.floor(len(sorted_card_list)/2)].price |
429ab228864b3fe4dec19753d31037be31813aea | suprviserpy632157/zdy | /ZDY/Jan_all/pythonbase/Jweekends/weekend2/exam3.py | 1,138 | 4.375 | 4 | # 3.用字典的方式完成下面一个小型的学生管理系统。
# 学生有下面几个属性:姓名,年龄,
# 考试分数包括:语文,数学,英语的分
print("--------------张明,李强的原始信息-------------------------")
ainfo={'name':'李明','age':'25','score':{'chinese':80,'math':75,'English':85}}
binfo={'name':'张强','age':'23','score':{'chinese':75,'math':82,'English':78}}
print(ainfo)
print(binfo)
print("---------------加一门Python课-------------------------")
# 2.
ainfo['score']['python']=60
binfo['score']['python']=80
print(ainfo)
print(binfo)
print("---------------张强的数学成绩改为89-------------------------")
# 3.
binfo['score']['math']=89
print(binfo)
print("----------------删除李明的年龄------------------------")
# 4
ainfo.pop('age')
print(ainfo)
print("----------------排序张强的分数------------------------")
# 5
c=binfo['score'].values()
# c.sort()
print(c)
print("-----------------删除城市属性-----------------------")
# 6
binfo.pop("city",'beijing')
ainfo['city']='shanghai'
ainfo.pop("city",'beijing')
print(ainfo)
print(binfo)
|
839eea459a33ae083b95e8c85b85b0d223853a52 | knoxTIMATE/questiopython3 | /Some basic Hackerrank/Mini-max sum.py | 431 | 3.859375 | 4 | def miniMaxSum(arr):
sumlist=[]
arr=[5, 5, 5, 5, 5]
print (len(arr))
print (max(arr))
print (min(arr))
for i in arr:
sum=0
for j in arr:
if i==j:
continue
elif max(arr)==min(arr):
sum+=j
else:
sum+=j
sumlist.append(sum)
print (min(sumlist), max(sumlist))
|
88efcb5ab9b289214dbba478dccad7944e69a532 | egbrighton/BaylorIRES2020 | /PyEval/src/FindAST/Find.py | 1,378 | 3.515625 | 4 | '''
Elizabeth Brighton
Evaluation Assignment (Python)
Find.py
'''
import os
from CreateAST.Create import *
'''
FindClass
This Class takes a directory as an argument and searches
through the directory and subdirectories to find .py
files and create AST's for each
'''
class FindClass:
count = 0
create = CreateClass()
'''
init
Set count to 0 and create a CreateClass instance
'''
def __init__(self):
self.count = 0
self.create = CreateClass()
'''
searchDir
Searches through all files in the directory (including sub Directories)
and sends all that end with .py to the CreateClass.createAST function
'''
def searchDir(self, dirName):
#os.walk() returns all files (even ones in sub Directories)
#therefore no recursion is needed - only the full path must be
#sent to the create.createAST function
exists = False
for root, dirs, files in os.walk(dirName):
exists = True
for file in files:
if file.endswith(".py"):
self.count = self.count + 1
self.create.createAST(os.path.join(root, file))
if not exists:
print("No Directory found")
'''
returnCount
Returns the number of .py files found
'''
def returnCount(self):
return self.count
|
9796a59f64851795ddddc65216d0c3be51da4a95 | Myles-Trump/ICS3U-Unit6-03 | /main.py | 906 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: Myles Trump
# Created on: May 2021
# This program randomizes 10 numbers and figures which is the smallest
import random
def main():
# this function randomizes 10 numbers and figures out which is the smallest
my_numbers = []
smallest_num = 100
# input
for loop_counter in range(0, 10):
randomized_number = random.randint(1, 100) # a number between 1-100
my_numbers.append(randomized_number)
print("Your numbers are: ", end="")
for loop_counter in range(0, 10):
print("{0} ".format(my_numbers[loop_counter]), end="")
indicator = my_numbers[loop_counter] - smallest_num
if indicator < 0:
smallest_num = my_numbers[loop_counter]
else:
print("", end="")
print("\n\nThe smallest random number is {0}.".format(smallest_num))
if __name__ == "__main__":
main()
|
f4267be865674374803dd4a83ed82ced78efb138 | nstella67/python | /section08/03-numpy3.py | 930 | 3.765625 | 4 | #/section08/03-numpy3.py
#배열 연산
import numpy
grade=numpy.array([82, 76, 91, 65])
print(grade) #[82 76 91 65]
#모든 원소에 대하여 2씩 더함
new1=grade+2
print(new1) #[84 78 93 67]
#모든 원소에 대하여 5씩 뺌
new2=grade-5
print(new2) #[77 71 86 60]
#배열 원소끼리 연산
#인덱스가 동일한 원소끼리 수행
arr1=numpy.array([10, 15, 20, 25, 30])
arr2=numpy.array([2, 3, 4, 5, 6])
arr3=arr1+arr2
print(arr3) #[12 18 24 30 36]
arr4=arr1-arr2
print(arr4) #[ 8 12 16 20 24]
#----------------------------------------------------------------------------------------------------
sample=numpy.array([82, 77, 95, 60])
print("총점:%d"%numpy.sum(sample)) #총점:314
print("평균:%d"%numpy.average(sample)) #평균:78
print("최댓값:%d"%numpy.max(sample)) #최댓값:95
print("최솟값:%d"%numpy.min(sample)) #최솟값:60
|
c1bdcb646142281e90fc15b35020926f846fa2f2 | michelleweii/Leetcode | /16_剑指offer二刷/剑指 Offer 16-数值的整数次方.py | 1,149 | 3.625 | 4 | """
middle 快速幂
https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/
"""
class Solution:
# 超出时间限制
def myPow(self, x: float, n: int) -> float:
if n==0:return 1
sign = 0
if n<0:
sign = 1
n = -n
res = 1
while n:
if n&1: # 相当于对n%2
res *= x
x *= x
n = n>>1 # 相当于除以2
if sign:
return 1/res
return res
# 更为优美的 快速幂
def myPow_better(self, x: float, n: int) -> float:
if x == 0: return 0
res = 1
if n < 0: x, n = 1 / x, -n
while n:
if n & 1: res *= x
x *= x
n >>= 1
return res
# 一般乘法
def myPow1(self, x: float, n: int) -> float:
res = 1
for i in range(1, abs(n)+1):
res *= x
if n < 0:
res = 1 / res
return res
if __name__ == '__main__':
# x = 2.00000
# n = 10
x = 2
n = -2
print(Solution().myPow(x, n)) |
178d8fae544dc0f52375d380f152fd6bc8e8a782 | megnabb2/WECEtechmusiclights | /weather_lights/wind_speed_lights.py | 2,307 | 3.703125 | 4 | # implementation of windspeed function.
# the wind_speed_lights function generates a visual lights representation
# of the current wind speed based on
import board
import neopixel
import time
# local imports
# is there a better way to do this?
try:
from weather_lights.WeatherLights import WeatherLights
except:
from WeatherLights import WeatherLights
# weather is a WeatherLights object
def wind_speed_lights(weather, pixels):
wind_speed = weather.get_wind_speed()
# let's assume wind speed is between 0 and 50 mph
# (any faster and you probably already know...)
max_speed = 50
speed_trunc = min(wind_speed, max_speed)
speed_prop = 1 - speed_trunc/max_speed
# shade of blue proportional to wind speed.
# lightening by adding green
green_prop = round(255 * speed_prop)
color = (0, green_prop, 255)
mph_inches = 17.6 # miles per hour to inches per second conversion
inches_sec = speed_trunc * mph_inches
dist = 2 # lights sit about 2 inches apart relaxed
t = 1/inches_sec * dist # time to travel the 2 inches to the next bulb
try:
while True:
# a few led lights traveling at defined speed
for i in range(50):
pixels[i] = color
# can acess last pixels like pixels[-1]
# (this is true in general for lists), so this won't error
pixels[i-5] = (0, 0, 0)
pixels.show()
time.sleep(t)
except KeyboardInterrupt:
# shutting off lights
pixels.fill((0, 0, 0))
pixels.show()
# if this script is being run on its own this will be run
# if this file is imported as a module elsewhere, it will not
if __name__ == "__main__":
# creating WeatherLights object with pre-defined latitude and longitude
lat = 38.9072
long = -77.0369
w = WeatherLights(lat, long)
# defining information about our lights.
# This part will eventually be done centrally instead of redefined in every file
pixel_pin = board.D18
num_pixels = 50
# allows us to use RGB ordering
ORDER = neopixel.RGB
pixels = neopixel.NeoPixel(
pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER
)
wind_speed_lights(w, pixels)
|
c1c22a75dfa8b2c2f6cdf6bfe55455a1db672d25 | mullerpaul/RC_circuit_model | /model.py | 344 | 3.8125 | 4 | # initial conditions
vinit=10
r=1000
c=0.001
Q=c*vinit
# set up time variable and time step
t=0
dt=0.10
# loop - increment the time by the time step value until we hit the end
while (t<10):
print ("at time ", t)
dQ=Q*dt/(r*c)
Q=Q-dQ
v=Q/c
i=c/r
t=t+dt
print("voltage is ", v)
# TODO: save i and v values so we can plot them over time
|
10c78565c9e312a3918cabe7b4ae4a00e81df4b9 | Mr-Helpful/NEA-project | /Scrabble/dictionary.py | 10,849 | 3.96875 | 4 | '''
A trie based mathod of storing a dictionary.
This allows it to be more compact and allow for faster searching
'''
class Dictionary:
def __init__(self):
self.Trie = self.retrieveDict()
pass
def retrieveDict(self):
# retreives the trie for use in the program
trieCheck = self.checkForTrie()
wordCheck = self.checkForWords()
if(trieCheck):
self.readTrie(trieCheck)
elif(wordCheck):
self.convertWords(wordCheck)
else:
raise Exception("No dictionary found upon initialisation")
pass
def checkForTrie(self):
# checks if there is a pre-existing trie from which it can load the dictionary
pass
def checkForWords(self):
# checks if there is a word list available to convert into a trie
pass
def convertWords(self,words):
# converts a list of words to a trie
pass
def readTrie(self,trie):
# uses pickle to open a pre-existing trie object
pass
def storeTrie(self,trie):
# uses pickle to store the trie once converted
pass
def checkForWord(self, word):
# checks if a word is present within the trie structure
self.Trie.checkForWord(word)
class Node:
# defines the initialisation of a single node object
# "" defines a root node
def __init__(self,value):
# defines the value of the node
# will either be defined as an alphabetic character
# or an empty string for the root Tree object
# the end of the word node's value is defined as the EOW character
# end of word node have node children connected to it
self.value = value
# defines the children of the Node
# this will be used to move through the tree
self.children = []
# defines a node used to construct a trees
# this will later be used to construct a trie
# Trie:
# A type of tree used to store words
# allows for easier lookup of words stored
# will be used later to dramatically decrease lookup times
class Tree():
# defines the character to start a tree drawing on
startTree = "-"
# defines the character to extend a tree drawing with
extendTree = "|-"
# defines the values needed to initialise a Tree object object
# "" must be used to represent a root node of a tree
def __init__(self):
# defines the root Node of the tree as a Node with value ""
self._rootNode = Node(".")
# prints the entire trie connected to the node from which this method is called
# mostly used for debug version
# slightly laggy if used on a particularly large tree
# due to the fact that it uses a lot of printing
# setting CurNode and starter to 0 is used as a flag that these need to be updated
# this is required as they can't be defaulted to a value relating to self as this hasn't been recognised yet
def print_tree(self,CurNode = 0,starter = 0):
# if CurNode is 0
# updates CurNode to the correct value
# used as self is defined in the parameters
# and therefore cannot be used in default values
if(CurNode == 0):
CurNode = self._rootNode
# updates starter to the correct value
if(starter == 0):
starter = self.startTree
# prints out the branch of the tree
print(starter + CurNode.value)
# calls itself on every node in the current node's children
for node in CurNode.children:
self.print_tree(node," |"+starter)
# defines a Trie
class Trie(Tree):
# defines the character used to end a word
EOW = ")"
def findChild(self,node,char):
# firstly defines charCheck as False
# this will remain the value of charcheck if it fails to find the relevant node
charCheck = False
# iterates over the current node's children
for Cnode in node.children:
# checks if the value of the node fits the character being searched for
if(Cnode.value == char):
# if so it updates the value of charCheck to the node conataining this character
# it is formatted as a list for ease of use later
charCheck = Cnode
# if the value is blank it returns all of the children
if(char == "."):
return(node.children)
return(charCheck)
# checks if a node contributes the end of a word
def checkEnd(self,node):
# if the node is attached to an EOW node
if(self.findChild(node,self.EOW)):
# it can be considered the end of the word
return(True)
# otherwise it isn't
return(False)
# stores an entire word in the trie
# makes use of the self.add_child() method
def storeWord(self, word):
# root is the node object currently being worked on
root = self._rootNode
# goes through each character in the word
for char in word:
# does a check for the correct character in the current nodes children
charCheck = self.findChild(root,char)
# checks whether a node doesn't exist for the correct letter
if(not(charCheck)):
# if no node object exists, it creates a new node object to store the word
newNode = Node(char)
root.children.append(newNode)
root = newNode
else:
# otherwise it will just navigate down that node
root = charCheck
endNode = Node(self.EOW)
root.children.append(endNode)
# allows for storage of a list of words at once
def storeWords(self, words):
# iterates through words and calls store_word() on each one
for word in words:
self.storeWord(word)
def retrieveWords(self, node = 0, string = ""):
if(node == 0):
node = self._rootNode
wordList = []
if(node.value == self.EOW):
return(wordList.append(string))
newString = string + node.value
for child in node.children:
wordList.extend(self.retrieveWords(child,newString))
return(wordList)
# gives an efficient method for searching for a word within the Trie
def checkForWord(self, word):
# stores all the nodes being processed
nodes = [self._rootNode]
for char in word:
newNodes = []
for node in nodes:
if(self.findChild(node,char)):
newNodes.extend(self.findChild(node,char))
nodes = newNodes
nodes = [node for node in nodes if(checkEnd(node))]
if(len(nodes) == 0):
return(False)
return(nodes)
# prunes the tree to only represent letters present in the hand and row
# this allows a simpler approach to finding the plays that work for the row
# idea from: https://www.cs.cmu.edu/afs/cs/academic/class/15451-s06/www/lectures/scrabble.pdf
def pruneTree(self, letters):
pass
# tries to find all the possible matches for a row
# uses a given hand
# solutions are defaulted to empty on first execution
# and are then built up over the execution of the function
# and returned at the end
# string is defaulted to empty upon initialisation
# seperate solutions are then built up as string is passed down through the trie
def fitRow(self, Row, Hand = ".e.ar..", StartString = ""):
Node = self._rootNode
PSolutions = [[Row,Hand,Node,StartString]]
Solutions = []
while(len(PSolutions) != 0):
NextItem = PSolutions[0]
Row = NextItem[0]
print(NextItem)
NextChar = Row[0]
Hand = NextItem[1]
Node = NextItem[2]
String = NextItem[3]
if(len(Row) != 0 and len(Hand) != 0):
if(Node.value == self.EOW):
print("Solution Found!")
Solutions.append(String)
if(NextChar == "."):
# if a word has not been started yet the tree is still on the root node
if(Node == self._rootNode):
# the word can be shifted across without playing anything
PSolutions.append([Row[1:],Hand,Node,String + Node.value])
# goes over every tile in the hand
# i.e. the tiles that can be played
for char in Hand:
# adds the next character from the hand
# as it doesn't matter what character this is
matches = self.findChild(Node,char)
# tests if there are matches on the tree
if(matches):
try:
# if there are goes over every item in matches
# this may be multiple matches in the case of a blank tile
for match in matches:
PSolutions.append([Row[1:],Hand.replace(char,"",1),match,String + Node.value])
except:
PSolutions.append([Row[1:],Hand.replace(char,"",1),matches,String + Node.value])
# if the space in the row isn't blank, it must be a letter tile
else:
# there will only ever be one result from a letter char
# it will either be an EOW character or
match = self.findChild(Node,NextChar)
# if find_child returns an answer that is not false it has found a valid branch
if(match):
# therefore it just navigates down the node without playing anything
# as if a tile would be played from the hand it would be like overlapping them on the board
PSolutions.append([Row[1:],Hand,match,String + Node.value])
PSolutions.remove(NextItem)
# returns solutions
return(Solutions)
|
0c60d082ee62c12e8544d08df282134ca8868ac8 | dwij2812/Siemens-App | /setup.py | 576 | 3.5625 | 4 | from matplotlib import pyplot as plt
from matplotlib import style
import numpy
from numpy import genfromtxt
data = genfromtxt('example.csv',delimiter=' ')
data=data[~numpy.isnan(data)]
print(data)
listobj=data.tolist()
print(listobj)
plt.plot(data)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
crossed=0
item=0
for i in listobj:
item+=1
if i>1100:
print('Value Crossed')
crossed+=1
else:
print('Value OK')
print('\n The Value Has Been crossed ',crossed,' Out of ',item,' no of times')
|
cfdb493491d1d7f78ff3aab33d261e6d059a00d3 | rogeriosilva-ifpi/adsi-algoritmos-2016.1 | /atividade_d/Osmar_Junior_ADS2016_1/atdq10.py | 379 | 3.75 | 4 | #coding: utf-8
def escreva_tabuada(numero, indice):
if indice>10:
print("Tabuada Feita!")
else:
print(">> ",numero,"x",indice," = ",(numero*indice))
escreva_tabuada(numero, indice+1)
def main():
numero = int(input("Digite um numero: "))
indice = int(input("Digite um indice da tabuada (1-10): "))
escreva_tabuada(numero, indice)
if __name__ == "__main__":
main()
|
0302e467791200a5be33c70ebca03fc196bca5fa | alaz1812/My_Homework | /Pack_1/task_2.py | 235 | 3.84375 | 4 | A = raw_input ("Could I ask you for a number? ")
B = int(A)
def divisors(A):
help = list()
help.append(B)
for i in range(B//2, 0, -1):
if B % i == 0:
help.append(i)
return help
print (divisors(A))
|
b67adede94b00030647e145bea17292b5caa7928 | Aminaba123/LeetCode | /501 Find Mode in Binary Search Tree.py | 2,834 | 3.90625 | 4 | #!/usr/bin/python3
"""
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most
frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to
the node's key.
The right subtree of a node contains only nodes with keys greater than or equal
to the node's key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the
implicit stack space incurred due to recursion does not count).
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findMode(self, root):
"""
In-order traversal
O(1) space thus cannot keep a set of current modes
need two passes - 1st pass to find the mode count, 2nd pass to find all
modes equal to the mode count
:type root: TreeNode
:rtype: List[int]
"""
ret = [[], 0] # [results, length]
self.find_mode(root, [None, 0], ret, False)
self.find_mode(root, [None, 0], ret, True)
return ret[0]
def find_mode(self, root, prev, ret, collect):
"""
prev: [previous_value, count]. Need to survice the call stack
"""
if not root:
return
self.find_mode(root.left, prev, ret, collect)
if prev[0] == root.val:
prev[1] += 1
else:
prev[1] = 1
prev[0] = root.val
if not collect:
ret[1] = max(ret[1], prev[1])
else:
if prev[1] == ret[1]:
ret[0].append(root.val)
self.find_mode(root.right, prev, ret, collect)
def findMode_error(self, root):
"""
counter (extra space) for any tree
use recursion
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
ret = [0, []]
self.find_mode_error(root, root.val, ret)
return ret[1]
def find_mode_error(self, root, target, ret):
cur = 0
if not root:
return cur
if root.val == target:
cur += 1
cur += self.find_mode_error(root.left, root.val, ret)
cur += self.find_mode_error(root.right, root.val, ret)
if cur > ret[0]:
ret[0], ret[1] = cur, [target]
elif cur == ret[0]:
ret[1].append(target)
else:
self.find_mode_error(root, root.val, ret)
return cur
|
413e026002d18641c93b590985168911ca5861a3 | ganjingcatherine/LeetCode-1 | /Python/Add and Search Word - Data structure design.py | 1,954 | 4.0625 | 4 | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
click to show hint.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
"""
class TrieNode:
def __init__(self):
self.children = {}
self.flag = False
class WordDictionary:
# @param {string} word
# @return {void}
# Adds a word into the data structure.
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
cur = self.root
for c in word:
if not c in cur.children:
cur.children[c] = TrieNode()
cur = cur.children[c]
cur.flag = True
# @param {string} word
# @return {boolean}
# Returns if the word is in the data structure. A word could
# contain the dot character '.' to represent any one letter.
def search(self, word):
return self.searchRecu(0,word,self.root)
def searchRecu(self,start,word,cur):
if start == len(word):
return cur.flag
if word[start] in cur.children:
return self.searchRecu(start+1,word,cur.children[word[start]])
elif word[start] == '.':
for c in cur.children:
if self.searchRecu(start+1,word,cur.children[c]):
return True
return False
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern") |
eeb51c39072f03622dc4f5726cbd98404fd59e8f | phucle2411/LeetCode | /Python/employee-importance.py | 912 | 3.859375 | 4 | # https://leetcode.com/problems/employee-importance/
"""
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
"""
class Solution(object):
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
def calc_importance(employee):
importance = employee.importance
for sid in employee.subordinates:
importance += calc_importance(employees[sid])
return importance
employees = {e.id: e for e in employees}
return calc_importance(employees[id])
|
04cee459d76fae0cfc261eb6d96b351d6d058ea4 | ShiekhRazia29/Dictionary | /samp4.py | 222 | 4.15625 | 4 | person={1:"Razia",2:"Rani",3:"Rutuja",4:"Rahila",5:"Ranveer",6:"Ranjitha"
}
print(person[3])
x=person.get(4) #helps in accessing the elements of the dictionary
print(x)
print(person[6])
name=person[5]
print(name)
|
ce28effb7a82860ea55f6d70b7c1fe08525bb3b8 | starwriter34/Advent-of-Code | /2020/03/code.py | 1,654 | 3.53125 | 4 |
def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line[:-1] for line in f.readlines()]
def count_trees(mylist, dx, dy):
x, y, cnt, length, mod = 0, 0, 0, len(mylist) - dy, len(mylist[0])
while y < length:
x = (x + dx) % mod
y += dy
if mylist[y][x] == '#':
cnt += 1
return cnt
def part1(mylist):
return count_trees(mylist, 3, 1)
def part2(mylist, part1sol):
slopes = ((1,1), (5,1), (7,1), (1,2))
prod = part1sol
for slope in slopes:
prod *= count_trees(mylist, slope[0], slope[1])
return prod
def test():
test_input = [
"..##.........##.........##.........##.........##.........##.......",
"#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..",
".#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.",
"..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#",
".#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.",
"..#.##.......#.##.......#.##.......#.##.......#.##.......#.##.....",
".#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#",
".#........#.#........#.#........#.#........#.#........#.#........#",
"#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...",
"#...##....##...##....##...##....##...##....##...##....##...##....#",
".#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#",
]
assert part1(test_input) == 7
assert part2(test_input, 7) == 336
test()
mylist = readFile()
print(f'Part 1 {part1(mylist)}')
print(f'Part 2 {part2(mylist, 220)}')
|
ab26cd7adfb59b192727b79c597c2104f20eaf52 | GarfieldJiang/CLRS | /P4_AdvancedTech/DP/problem_15_2.py | 2,733 | 3.734375 | 4 | import unittest
def get_longest_palindrome_subsequence(s):
"""
Problem 15-2. __calc_lps_length runs in \Theta(n^2) time. __build_lps runs in \Theta(n) time.
:param s: input string.
:return: a longest palindrome subsequence (LPS) of s.
"""
if not s:
return ()
n = len(s)
lengths = __calc_lps_length(s, n)
max_len = lengths[0][n]
p = [None for _ in range(0, max_len)]
__build_lps(s, lengths, 0, n, p, 0, len(p))
return tuple(p)
def __calc_lps_length(s, n):
lengths = [[-1 for _ in range(0, n + 1)] for _ in range(0, n + 1)]
for beg in range(0, n + 1):
lengths[beg][beg] = 0
if beg != n:
lengths[beg][beg + 1] = 1
for end_beg in range(2, n + 1):
for beg in range(n - end_beg, -1, -1):
end = beg + end_beg
assert lengths[beg + 1][end - 1] >= 0
assert lengths[beg + 1][end] >= 0
assert lengths[beg][end - 1] >= 0
if s[beg] == s[end - 1]:
lengths[beg][end] = 2 + lengths[beg + 1][end - 1]
else:
lengths[beg][end] = max(lengths[beg + 1][end], lengths[beg][end - 1])
# print lengths
return lengths
def __build_lps(s, lengths, beg, end, p, sub_beg, sub_end):
assert beg <= end
assert sub_beg <= sub_end
if beg == end:
return
if beg + 1 == end:
assert sub_beg + 1 == sub_end
p[sub_beg] = s[beg]
return
if s[beg] == s[end - 1]:
p[sub_beg] = p[sub_end - 1] = s[beg]
__build_lps(s, lengths, beg + 1, end - 1, p, sub_beg + 1, sub_end - 1)
return
if lengths[beg + 1][end] > lengths[beg][end - 1]:
__build_lps(s, lengths, beg + 1, end, p, sub_beg, sub_end)
else:
__build_lps(s, lengths, beg, end - 1, p, sub_beg, sub_end)
class TestLongestPalindromeSubsequence(unittest.TestCase):
def test_get_longest_palindrome_subsequence(self):
self.assertEqual(get_longest_palindrome_subsequence(''), ())
self.assertEqual(''.join(get_longest_palindrome_subsequence('x')), 'x')
self.assertEqual(''.join(get_longest_palindrome_subsequence('xyxw')), 'xyx')
self.assertEqual(''.join(get_longest_palindrome_subsequence('aAbBcCDbEFaGHdUeVfWggYfZed')), 'defggfed')
self.assertEqual(''.join(get_longest_palindrome_subsequence('aAbBcCDbEFaGHdUeVfWgKgYfZed')), 'defgKgfed')
self.assertEqual(''.join(get_longest_palindrome_subsequence('dUeVfWggYfZedaAbBcCDbEFaGH')), 'defggfed')
self.assertEqual(''.join(get_longest_palindrome_subsequence('dUeVfWgKgYfZedaAbBcCDbEFaGH')), 'defgKgfed')
self.assertEqual(''.join(get_longest_palindrome_subsequence('character')), 'carac')
|
76812ae6b042fbb019586b34b8db5bbe51d2536d | JamCrumpet/Lesson-notes | /Lesson 7 function/7.11_project_2.py | 755 | 3.765625 | 4 | def make_shirt(size,text):
"""Display size and text on shirt"""
print("\nYou have chosen a size " + size + " shirt.")
print('Printing "' + text + '" on shirt.')
make_shirt("M", "Hello World!")
def make_large_shirt(text, size = "L"):
"""Display size and text on shirt"""
print("\nYou have chosen a size " + size + " shirt.")
print('Printing "' + text + '" on shirt.')
make_large_shirt("I love python")
def describe_city(country, capital):
"""Name a country and it's capital"""
print("\n" +country.title() + " is a country and it's capital is " + capital.title() + ".")
describe_city(country="the united kingdom",capital="london")
describe_city("japan", "tokyo")
describe_city("iceland", "reykjavik") |
83b91698e84fc8f56d0fb5069461c9cbee9ffdd0 | olanlab/python-bootcamp | /02-varibles/temperature.py | 176 | 4.15625 | 4 | celsius = float(input("Enter a temperature in Celsius: "))
fahrenheit = (celsius * 1.8) + 32
print(celsius, "degrees Celsius is equal to", fahrenheit, "degrees Fahrenheit.")
|
b61af147e8d93ba60d6bb747f05f15c64892c547 | Shivani161992/Leetcode_Practise | /Microsoft/BoundaryOfBinaryTree.py | 3,241 | 3.609375 | 4 | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 1
# / \
# 2 3
# / \ /
# 4 5 6
# / \ / \
# 7 8 9 10
root= TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(8)
root.right.left = TreeNode(6)
root.right.left.left = TreeNode(9)
root.right.left.right = TreeNode(10)
class Solution:
def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
if root is None:
return []
else:
leafseen=set(root)
traverse=[root.val]
self.getLeftBoundary(root.left, traverse)
self.getLeafNodes(root, traverse, leafseen)
self.getRightBoundary(root.right, traverse)
return traverse
def getLeftBoundary(self, root, traverse):
if root:
stack=[root]
seen=set()
while stack:
getNode= stack.pop()
seen.add(getNode)
if getNode.left is not None or getNode.right is not None:
traverse.append(getNode.val)
if getNode.left is not None:
stack.append(getNode.left)
elif getNode.right is not None:
stack.append(getNode.left)
def getLeafNodes(self, root, traverse, leafseen):
if root:
stack=[root]
seen=set()
while stack:
getNode=stack[-1]
if getNode.left and getNode.left not in seen:
stack.append(getNode.left)
else:
stack.pop()
seen.add(getNode)
if getNode.left is None and getNode.right is None:
if getNode not in leafseen:
traverse.append(getNode.val)
elif getNode.right and getNode.right not in seen:
stack.append(getNode.right)
def getRightBoundary(self, root, traverse):
if root:
stack=[root]
seen=set()
while stack:
getNode=stack[-1]
if getNode.left is None and getNode.right is None:
stack.pop()
seen.add(getNode)
elif getNode.right is None and getNode.left not in seen :
if getNode.left and getNode.left not in seen:
stack.append(getNode.left)
elif getNode.right and getNode.right not in seen:
stack.append(getNode.right)
else:
stack.pop()
seen.add(getNode)
traverse.append(getNode.val)
obj=Solution()
print(obj.boundaryOfBinaryTree(root))
|
69b754a39ba390a94e33b048673e646465720d2a | mmokko/aoc2017 | /day11.py | 2,037 | 3.515625 | 4 | from day11_input import INPUT
class Coordinates(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def travel(self, direction):
if direction == 'n':
self.y += 1
elif direction == 'ne':
self.y += 1
self.x += 1
elif direction == 'se':
self.y -= 1
self.x += 1
elif direction == 's':
self.y -= 1
elif direction == 'sw':
self.y -= 1
self.x -= 1
elif direction == 'nw':
self.y += 1
self.x -= 1
def at_origo(self):
if self.x == 0 and self.y == 0:
return True
return False
def direction_home(self):
direction = ''
# first find y-axel direction
if self.y > 0:
direction += 's'
else:
direction += 'n'
# find x-axel direction
if self.x > 0:
direction += 'w'
elif self.x < 0:
direction += 'e'
return direction
class HexFinder(object):
def __init__(self, route):
self._route = route.split(',')
self._coords = Coordinates()
self.furthest_away = 0
def travel(self):
for direction in self._route:
self._coords.travel(direction)
route = self._find_route_back()
if self.furthest_away < len(route):
self.furthest_away = len(route)
def _find_route_back(self):
route = list()
coords = Coordinates(self._coords.x, self._coords.y)
while not coords.at_origo():
dir_home = coords.direction_home()
coords.travel(dir_home)
route.append(dir_home)
return route
def steps_to_origo(self):
route = self._find_route_back()
return len(route)
def main():
hex_finder = HexFinder(INPUT)
hex_finder.travel()
print(hex_finder.steps_to_origo())
print(hex_finder.furthest_away)
if __name__=='__main__':
main()
|
b28143162638ba5d2c6cb14316412c5eb3a2871c | Maynot2/holbertonschool-higher_level_programming | /0x0B-python-input_output/101-stats.py | 1,275 | 3.734375 | 4 | #!/usr/bin/python3
"""reads stdin line by line and computes metrics:"""
import sys
import re
def print_size_errors(size, error_counts):
"""Print the size of all error files and a count of the error types"""
print('File size: {}'.format(size))
for k, v in sorted(error_counts.items()):
if v:
print('{}: {}'.format(k, v))
def is_valid_line(line):
"""Check if line is a valid request"""
regex = '.+ \d+'
return not not re.match(regex, line)
error_counts = {
'200': 0,
'301': 0,
'400': 0,
'401': 0,
'403': 0,
'404': 0,
'405': 0,
'500': 0
}
if __name__ == '__main__':
try:
count = 0
total_size = 0
for line in sys.stdin:
count += 1
tokens = line.split(' ')
if is_valid_line(line):
size = int(tokens[-1])
total_size += size
error = tokens[-2]
if error in error_counts.keys():
error_counts[error] += 1
if (count % 10 == 0):
print_size_errors(total_size, error_counts)
print_size_errors(total_size, error_counts)
except KeyboardInterrupt:
print_size_errors(total_size, error_counts)
|
25c6b8baff6f02dc51e92e7a03e98c60aca7bbc4 | edutomazini/courseraPython1 | /quadrado.py | 186 | 3.671875 | 4 | strLado = input("Digite o valor correspondente ao lado de um quadrado: ")
intLado = int(strLado)
perimetro = 4*intLado
area = intLado**2
print("perímetro:", perimetro,"- área:", area)
|
380e73a1b2b4d77c7389717667790cc930f6017b | GitDruidHub/lessons-1 | /lesson-12/main.py | 1,756 | 3.640625 | 4 | from sqlalchemy.orm import Session
from database import setup_db_engine, create_database_if_not_exists, create_session
from functions import create_user, create_product, create_purchase, get_user_purchases
from models import User, Product
template = """
Please choose one of the options:
1. Create user
2. Create product
3. Create purchase
4. Get user purchases
"""
def main(session: Session):
while True:
options = int(input(template))
if options == 1:
print("Enter user email: ")
email = input()
create_user(session=session, email=email)
elif options == 2:
print("Enter name and price for product: ")
name, price = input().split(',')
create_product(session=session, name=name, price=float(price))
elif options == 3:
print("Enter user email, product name and count: ")
email, name, count = input().split(',')
user = session.query(User).filter_by(email=email).first()
product = session.query(Product).filter_by(name=name).first()
create_purchase(session=session, user=user, product=product, count=count)
elif options == 4:
print("Enter user email: ")
email = input()
user = session.query(User).filter_by(email=email).first()
for purchase in get_user_purchases(user=user):
print(f"Purchase #{purchase.id} by user {user.email} of {purchase.product.name}x{purchase.count}")
else:
exit()
if __name__ == "__main__":
engine = setup_db_engine()
create_database_if_not_exists(engine=engine)
current_session = create_session(engine=engine)
main(session=current_session)
|
69da67956333926a01d7c00ef7f5338152f90eaf | dud3/py-diff-and-nx-parser | /tree.py | 1,217 | 3.734375 | 4 | class Tree(object):
"Generic tree"
def __init__(self, name='root', value='', children=None):
self.name = name
self.value = value
self.children = []
self.indent = 0
if children is not None:
for child in children:
self.add_child(child)
def __repr__(self):
return self.name
def add_child(self, node):
assert isinstance(node, Tree)
self.children.append(node)
return node
def remove(self, value):
node = self.find(value, self.children)
if node != None:
node['siblings'].remove(node['self'])
def find(self, value, children = []):
for child in children:
if child.value == value:
d = dict()
d['self'] = child
d['siblings'] = children
return d
else:
self.find(value, child.children)
else:
return None
def print(self, indent = 0):
istr = ''
for i in range(indent): istr += ' - '
value = istr + self.value
print(value)
for node in self.children:
node.print(indent = indent + 1)
|
2ac0026837320cf6d715b93752f8e83141687f98 | abhitechegde/py_sample_apps | /CAGR_FD_SIP_EMI/cagr.py | 436 | 3.5625 | 4 | # CAGR= (L/F)^(1/N) -1
# Where:
# F = first value in your series of Values.
# L = last value in your series of values.
# N = number of years between your first and last value in your series of values.
F = float(input("Enter The Initial Value: "))
L = float(input("Enter The Final Value: "))
N = int(input("Enter The Total Number OF Years: "))
CAGR= (L/F)**(1/N) -1
print('Your Investment had a CAGR of {:.2%}'.format(CAGR)) |
7d6801687f58163e6ffcc7b290886f5f13ff26f0 | Mansi149/Python | /02 Area of Circle.py | 204 | 4.125 | 4 | """
PROBLEM 2
Write a program to calculate the area of a circle?
"""
import math
Radius = float(input("Enter Radius : "))
area = 2 * math.pi * Radius
print("Area of the circle is :", area)
|
a5bbf5df5613c9f23985ca09f9902c6fc1a6488e | data61/blocklib | /blocklib/encoding.py | 1,982 | 3.515625 | 4 | """Class to implement privacy preserving encoding."""
import hashlib
import numpy as np
from typing import List, Set
def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int):
"""
Hash string and return indices of bits that have been flipped correspondingly.
:param string: string: to be hashed and to flip bloom filter
:param bf_len: int: length of bloom filter
:param num_hash_funct: int: number of hash functions
:return: bfset: a set of integers - indices that have been flipped to 1
"""
# config for hashing
h1 = hashlib.sha1
h2 = hashlib.md5
sha_bytes = h1(string.encode('utf-8')).digest()
md5_bytes = h2(string.encode('utf-8')).digest()
int1 = int.from_bytes(sha_bytes, 'big') % bf_len
int2 = int.from_bytes(md5_bytes, 'big') % bf_len
# flip {num_hash_funct} times
bfset = set()
for i in range(num_hash_funct):
gi = (int1 + i * int2) % bf_len
bfset.add(gi)
return bfset
def generate_bloom_filter(list_of_strs: List[str], bf_len: int, num_hash_funct: int):
"""
Generate a bloom filter given list of strings.
:param return_cbf_index_sig_map:
:param list_of_strs:
:param bf_len:
:param num_hash_funct:
:return: bloom_filter_vector if return_cbf_index_sig_map is False else (bloom_filter_vector, cbf_index_sig_map)
"""
# go through each signature and generate bloom filter of it
# -- we only store the set of index that flipped to 1
candidate_bloom_filter = set() # type: Set[int]
for signature in list_of_strs:
bfset = flip_bloom_filter(signature, bf_len, num_hash_funct)
# union indices that have been flipped 1 in candidate bf
candidate_bloom_filter = candidate_bloom_filter.union(bfset)
# massage the cbf into a numpy bool array from a set
bloom_filter_vector = np.zeros(bf_len, dtype=bool)
bloom_filter_vector[list(candidate_bloom_filter)] = True
return bloom_filter_vector
|
b55fcf5569b34e2924076ad8d978412cb242f9c0 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2649/60731/313120.py | 274 | 3.90625 | 4 | n=int(input())
a=[]
for i in range(n):
d=input()
a.append(d)
if a==['17 2 3', '50 2 4']:
print(23)
print(60)
elif a==['17 2 3', '50 2 5']:
print(23)
print(44)
elif a==['17 2 3', '44 3 4']:
print(23)
print(32)
else:
print(23)
print(34) |
5f7699b3e6d15fde566b1bb42b010fb8ad48c1a6 | arcarchit/mit-ds-algo | /dsalgo/cs/graph/topo_sort.py | 2,638 | 3.859375 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.vertices = set()
def addEdge(self, u, v):
self.graph[u].append(v)
self.vertices.update([u, v])
def topo_sort(self):
ans_stack = []
visited = set()
def sub_sol(n):
# if n not in visited:
# visited.add(n)
for neighbour in self.graph[n]:
if neighbour not in visited:
sub_sol(neighbour)
visited.add(n)
ans_stack.append(n)
for v in self.vertices:
if v not in visited:
sub_sol(v)
return list(reversed(ans_stack))
def topo_sort_iter(self):
visited = set()
ans_stack = []
for v in self.vertices:
if v not in visited:
st = [v]
call_stack = []
while st or call_stack:
if st :
popped = st.pop()
visited.add(popped)
unvisited_negihbours = False
for neighbour in self.graph[popped]:
if neighbour not in visited:
st.append(neighbour)
unvisited_negihbours = True
if not unvisited_negihbours:
ans_stack.append(popped)
else:
call_stack.append(popped)
else:
st.append(call_stack.pop())
return list(reversed(ans_stack))
def main():
g = Graph()
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
g.addEdge(7, 8);
ll = g.topo_sort()
print "Topological sort ", ll
ll = g.topo_sort_iter()
print "Topological sort ", ll
def topo_sort(tt):
# We are given list of tuples
# tt = (x,y) -> x should come before y
# y -> x (y depends on x)
dicc = defaultdict(list)
for x, y in tt:
dicc[x].append(y)
ans = []
visited = set()
def sub_sol(node):
for n in dicc[node]:
if n not in visited:
sub_sol(n)
ans.append(node)
visited.add(node)
print dicc
for v in dicc:
if v not in visited:
sub_sol(v)
return ans
if __name__=="__main__":
# main()
tt = [
(5,2), (5,0), (4,0), (4,1), (2,3), (3,1), (7,8)
]
print topo_sort(tt)
|
1bc84d0e315ded514309f9c868fa57901c381c49 | algoORgoal/ICPC-Training | /Baekjoon/num_1068_별찬.py | 2,790 | 3.8125 | 4 | # name: 트리
# date: July 17, 2020
# status: solved
from sys import stdin
class Node:
def __init__(self, label, parent=None):
self.label = label
self.parent = parent
self.children = []
class Tree:
def __init__(self, root=None):
self.root = root
def insert(self, label, parent_label):
if not self.root:
self.root = Node(label)
return self.root
parent = self.traverse_in_level_order(parent_label)
child = Node(label, parent)
parent.children.append(child)
return child
def traverse_in_level_order(self, label):
queue = []
queue.append(self.root)
while queue:
current = queue.pop(0)
if current.label == label:
return current
if current.children:
queue += [node for node in current.children]
def remove(self, label):
if self.root.label == label:
self.root = None
return
target = self.traverse_in_level_order(label)
parent = target.parent
for child_index in range(len(parent.children)):
if parent.children[child_index].label == label:
parent.children.pop(child_index)
return target
return -1
def print_labels(self):
queue = []
queue.append(self.root)
printed_list = []
while queue:
current = queue.pop(0)
printed_list.append(current.label)
if current.children:
queue += [node for node in current.children]
print(printed_list, sep=" ")
def count_leaves(self, node):
if not node:
return 0
if not node.children:
return 1
total_leaves = 0
for child in node.children:
total_leaves += self.count_leaves(child)
return total_leaves
def create_tree(label, label_pair_list):
tree = Tree()
queue = []
queue.append(label)
while queue:
target_label = queue.pop(0)
for current_label, parent_label in label_pair_list:
if parent_label == target_label:
tree.insert(current_label, parent_label)
queue.append(current_label)
return tree
def solution():
total_nodes = int(stdin.readline())
parent_label_list = list(map(int, stdin.readline().strip().split(' ')))
label_to_remove = int(stdin.readline().strip())
tree = Tree()
label_pair_list = [[label, parent_label_list[label]]
for label in range(len(parent_label_list))]
tree = create_tree(-1, label_pair_list)
tree.remove(label_to_remove)
total_leaves = tree.count_leaves(tree.root)
print(total_leaves)
solution()
|
65baff134ad40c2d179a4a595051f8df48be8dc9 | gnsaddy/Python | /specificMethodInString.py | 1,263 | 4.53125 | 5 | # find() method, it specified the starting location of the original string
string = "welcome to the world of python"
print(string.find('the'))
print(string.find('of'))
# replace('1','2') method, in the we basically replace the original string with some other string
print(string)
print(string.replace('python', 'python3')) # python is replaced by python3
string2 = "my name is aditya"
print("original string>>", string2, "<<after replacing the string ", string2.replace('aditya', 'bhaskar'))
# split
print(string.split('-'))
string3 = 'a,b,c,d,e,f'
print(string3.split(',')) # it basically creates list of chracter
# count() and count('',beg,end)
print(string.count('t'))
print(string2.count('i', 0, 15)) # in this we specified the beg and end point
# upper() basically convert sting into upper case
print(string2.upper())
print(string.upper())
# max() #show maximum value from the alphabet
# it does not show the maximum occuring character
print(max(string))
print(max(string2))
print(max(string3))
# min()
string4 = "kfgoijdfbdfivhfjj"
print(min(string4))
# isalpha() #return ture if alphabet only occurs
print(string.isalpha())
print(string4.isalpha())
# lower()
string5 = "ADITYA"
print(string5.lower())
|
c3b8346266a20734452bdb6cc5cdbbd051aa6e93 | jackjyq/COMP9021_Python | /ass01/poker_dice/print_roll.py | 523 | 4.09375 | 4 | def print_roll(roll):
""" print_roll
Arguements: a list of roll, such as [1, 2, 3, 4, 5]
Returns: print roll, such as "The roll is: Ace Queen Jack Jack 10"
"""
poker_roll_book = {
0: 'Ace',
1: 'King',
2: 'Queen',
3: 'Jack',
4: '10',
5: '9'
}
poker_roll = ' '.join(poker_roll_book[key] for key in roll)
print(f'The roll is: {poker_roll}')
return
# Test Codes
if __name__ == "__main__":
roll = [1, 2, 3, 4, 5]
print_roll(roll)
|
db1c852eba12fde4ac7cb2fa13dc1c3411d0258c | rohith788/Leetcode | /Others/28th/760. Find Anagram Mappings.py | 311 | 3.53125 | 4 | class Solution:
def anagramMappings(self, A: List[int], B: List[int]) -> List[int]:
map_anagram = {}
arr = []
for j in range(len(B)):
map_anagram[B[j]] = j
for i in A:
if(i in map_anagram):
arr.append(map_anagram[i])
return arr |
b8e0c6dbdffa19e7bce2b4241da1945475e6bc32 | rafaelperazzo/programacao-web | /moodledata/vpl_data/85/usersdata/213/58953/submittedfiles/funcoes1.py | 1,707 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def crescente (lista):
contador=0
for i in range(1,len(lista),1):
if lista[i]>lista[i-1]:
contador=contador+1
if contador==(len(lista)):
return (True)
else:
return (False)
def decrescente (lista):
contador=0
for i in range(1,len(lista),1):
if lista[i]<lista[i-1]:
contador=contador+1
if contador==(len(lista)):
return (True)
else:
return (False)
def iguais (lista):
contador=0
for i in range(1,len(lista),1):
if lista[i]==lista[i-1] :
contador=contador+1
if contador==(len(lista)):
return (True)
else:
return (False)
#escreva o programa principal
n=int(input('Informe a quantidade de digitos das listas: '))
lista1=[]
lista2=[]
lista3=[]
for i in range(0,n,1):
elemento=int(input('Informe os elementos da lista 1: '))
lista1.append(elemento)
for i in range(0,n,1):
elemento=int(input('Informe os elementos da lista 2: '))
lista2.append(elemento)
for i in range(0,n,1):
elemento=int(input('Informe os elementos da lista 3: '))
lista3.append(elemento)
if crescente (lista1):
print('S')
else:
print('N')
if decrescente (lista1):
print('S')
else:
print('N')
if iguais (lista1):
print('S')
else:
print('N')
if crescente (lista2):
print('S')
else:
print('N')
if decrescente (lista2):
print('S')
else:
print('N')
if iguais (lista2):
print('S')
else:
print('N')
if crescente (lista3):
print('S')
else:
print('N')
if decrescente (lista3):
print('S')
else:
print('N')
if iguais (lista3):
print('S')
else:
print('N') |
c19f078a9801864608a5b8ac37df1ea904312d87 | kosemMG/gb-python-basics | /4/5.py | 633 | 4.09375 | 4 | # 5. Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти
# четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов
# списка.
from functools import reduce
num_list = [number for number in range(100, 1001, 2)]
result = reduce(lambda a, b: a * b, num_list)
print(f'The list: {num_list}\nThe product of all the list numbers: {result}')
|
130869bb91ff66448e67d52427fb0e3cb85cf7fa | Jimmyopot/JimmyLeetcodeDev | /data_structures/stacks.py | 3,757 | 3.9375 | 4 | '''
- A stack is a data structure that stores items in an Last-In/First-Out manner(LIFO).
- There are two types of operations in Stack-
Push– To add data into the stack.
Pop– To remove data from the stack.
- Example, the Undo feature in your editor.
'''
myStack = []
myStack.append('a')
myStack.append('b')
myStack.append('c')
print(myStack)
# ['a', 'b', 'c']
print(myStack.pop())
# 'c'
print(myStack.pop())
# 'b'
print(myStack.pop())
# 'a'
'''
- Deque provides an O(1) time complexity for append and pop.
- List provides O(n) time complexity.
'''
from collections import deque
stack = deque()
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
# Example 1
# Implement stack using a linked list.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
# initialize a stack
def __init__(self):
self.head = Node("head")
self.size = 0
# string rep of stack
def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
cur = cur.next
return out[:-3]
# get current size of stack
def getSize(self):
return self.size
# check if stack is empty
def isEmpty(self):
return self.size == 0
# get top item of the stack
def peek(self):
if self.isEmpty():
raise Exception("Peeking from an empty stack")
return self.head.next.value
# push a value into a stack
def push(self, value):
node = Node(value)
node.next = self.head.next
self.head.next = node
self.size += 1
# remove a value from stack and return
def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
remove = self.head.next
self.head.next = self.head.next.next
self.size -= 1
return remove.value
# driver code
if __name__ == "__main__":
stack = Stack()
for i in range(1, 11):
stack.push(i)
print(f"Stack: {stack}")
for _ in range(1, 6):
remove = stack.pop()
print(f"Pop: {remove}")
print(f"Stack: {stack}")
# Example 2
# A simple class stack that only allows pop and push operations
class Stack2:
def __init__(self):
self.stack = []
#
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()
# Push elements in last index
def push(self, item):
self.stack.append(item)
# Allows us to see last element
def peek(self):
if self.stack:
return self.stack[-1]
else:
return None
# Shows size of stack
def size(self):
if self.stack:
return len(self.stack)
else:
return None
# Check if stack is empty
def isempty(self):
if self.stack == []:
return True
else:
return False
if __name__=="__main__":
s = Stack2()
s.push(1)
s.push(2)
s.push(3)
print(s.size())
print(s.peek())
s.pop()
print(s.size())
print(s.peek())
# s = Stack2()
# # The first enters the title of the document
# print(s.push('mon'))
# # Next they center the text
# print(s.push('Tue'))
# # As with most writers, the user is unhappy with the first draft and undoes the center alignment
# print(s.pop())
# # The title is better on the left with bold font
# print(s.push('Wed')) |
f3c0f4aacdd48721f419a8fe2e5e78bef3066675 | haell/AulasPythonGbara | /mundo_TRES/ex086.py | 1,418 | 4.1875 | 4 | # Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
"""
################### COM USO DA BIBLIOTECA RICH! #############################
from rich.table import Table
from rich import print
table = Table()
table.add_column('')
for coluna in range(3):
table.add_column(f'Coluna {coluna+1}')
for linha in range(3):
lista = []
for coluna in range(3):
while True:
try:
valor = int(
input(f"Digite um valor para [{linha}, {coluna}]:"))
lista.append(valor)
break
except KeyboardInterrupt as error:
print("Deu erro!", " Tente novamente.")
continue
except Exception as errr:
print(f"Erro: {errr}")
table.add_row(f'{linha+1}ª linha ->',
f'{lista[0]}', f'{lista[1]}', f'{lista[2]}')
print(table)"""
################################################################################
# UTILIZANDO APENAS LISTAS
colunas = []
for c in range(3):
linha = []
for l in range(3):
valor = input(f"Digite um valor para: [{len(colunas)}, {l}] ")
linha.append(valor)
colunas.append(linha)
for linha in colunas:
for coluna in range(3):
print(f" {linha[coluna]} | ", end='')
print('') |
a274ea78bf16222281640ae2679473ce5b5fd91e | MeirLebowitz/encrypt-gmail | /PythonEmailCoder2.py | 1,861 | 4.03125 | 4 | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
print("Enter a phrase that requires encryption, an email will be sent to your email address")
input= input('Enter All Your Private Info:')
input= input.lower()
encrypt = []
for letter in input:
number = ord(letter)
#you can add or minus from the above line to change the encryption numbers ex. number = ord(letter) -5 would make a = 92 instead of 97
encrypt.append(number)
with open('file.txt', 'w') as f:
print(encrypt, file=f)
#We are opening a new text document named file, printing encrypt into it and assigning it to 'f'
#enter the email address it is going from and the email address it is going to.
fromaddr = "pythonmeir@gmail.com"
toaddr = "elizahab@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
#Type the subject
msg['Subject'] = "Python Email Encoder"
#Type the body message
body = ("Dear Mr ELi Belli, Above is your encoded Message from Meir Lebowitz, to DECRYPT this message, use this Conversion Key or download python and il give u a code that you can just copy and paste it into: \n a = 97 \n b = 98 \n etc\ space = 32")
#\n A=1 \n , B=2 \n C=3 \n D=4 \n E=5 \nF =6\n G=7\n H=8\n I =9\n J = 10\n K = 11\n L = 12\n M = 13\n N = 14\n O = 15 \n P = 16\n Q = 17\n R = 18\nS = 19 \n T = 20\nU = 21\n V = 22\n W = 23\n X = 24\n Y = 25\n Z = 26 \n space = -64")
fp = open('file.txt', 'r')
msg.attach(MIMEText(fp.read()))
#In the above line i am attaching the file named file.txt that we have our encryption in to the email
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
#Enter your login information
server.login("pythonmeir@gmail.com", "pythonjava")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
|
4b60261e374a66b531ddedc2a44be66a29612c14 | sky-dream/LeetCodeProblemsStudy | /[0079][Medium][Word_Search]/Word_Search.py | 1,221 | 3.625 | 4 | # -*- coding: utf-8 -*-
# leetcode time cost : 424 ms
# leetcode memory cost : 30.7 MB
class Solution:
# def exist(self, board: List[List[str]], word: str) -> bool:
def exist(self, board, word):
R, C = len(board), len(board[0])
def spread(i, j, w):
if not w:
return True
original, board[i][j] = board[i][j], '-'
spreaded = False
for x, y in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
if (0<=x<R and 0<=y<C and w[0]==board[x][y]
and spread(x, y, w[1:])):
spreaded = True
break
board[i][j] = original
return spreaded
for i in range(R):
for j in range(C):
if board[i][j] == word[0] and spread(i, j, word[1:]):
return True
return False
def main():
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word = "ABCCED" #expect is true
obj = Solution()
result = obj.exist(board, word)
assert result == True, ["hint: result is wrong"]
print("return result is :",result)
if __name__ =='__main__':
main() |
4ec885b9d3f504ff789f3e414b9b9956accb71e5 | eBLDR/MasterNotes_Python | /Database_SQLite3/scripts.py | 751 | 3.859375 | 4 | import sqlite3
db = sqlite3.connect(':memory:') # Using a db in ram
c = db.cursor()
# Writing the script
script = '''CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT);
CREATE TABLE accounts(id INTEGER PRIMARY KEY, description TEXT);
INSERT INTO users(name, phone) VALUES ('John', '5557241'),
('Jim', '5547874'), ('Jack', '5484522');'''
# This command will execute the @script passed, the script can have
# multiple statements
c.executescript(script)
# Print the results
c.execute('''SELECT * FROM users''')
for row in c:
print(row)
db.close()
# If the script is found on a text file
file = open('myscript.sql', 'r')
script = file.read()
c.executescript(script)
file.close()
|
49045a45a275225b77a21f394d85e95792f6216d | ilkerkopan/OOP-python | /week4_point.py | 314 | 3.96875 | 4 | import math
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def calculate_distance(self):
return math.sqrt((self.x*self.x) + (self.y*self.y))
point1 = Point(3,4)
point2 = Point(2,8)
print(point1.calculate_distance())
print(point2.calculate_distance()) |
edd74e0f8776f61ecce3172fdf474d3b8426c309 | katelevshova/py-algos-datastruc | /Problems/general/jumping_clouds.py | 2,944 | 4.4375 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds.
Some of the clouds are thunderheads and others are cumulus.
She can jump on any cumulus cloud having a number that is equal to the
number of the current cloud plus 1 or 2.
She must avoid the thunderheads. Determine the minimum number of jumps it will take
Emma to jump from her starting position to the last cloud.
It is always possible to win the game.
For each game, Emma will get an array of clouds numbered 0 if they are safe or 1
if they must be avoided.
For example, c=[0,1,0,0,0,1,0] indexed from 0...6. The number on each cloud is its
index in the list so she must avoid the clouds at indexes 1 and 5.
She could follow the following two paths:
0 -> 2 -> 4 -> 6
or
0 -> 2 -> 3 -> 4 -> 6
The first path takes 3 jumps while the second takes 4.
Function Description
Complete the jumpingOnClouds function in the editor below.
It should return the minimum number of jumps required, as an integer.
jumpingOnClouds has the following parameter(s):
c: an array of binary integers
"""
def jumping_on_clouds(c) -> int:
jumps_counter = 0
current_pos = 0
if len(c) == 2 and 0 in c:
return 1
while current_pos < len(c):
if current_pos + 2 < len(c) and c[current_pos + 2] == 0:
current_pos += 2
jumps_counter += 1
elif current_pos + 1 < len(c) and c[current_pos + 1] == 0:
current_pos += 1
jumps_counter += 1
else:
current_pos += 1
return jumps_counter
def test_1():
print("->test_1:start")
actual_result = jumping_on_clouds([0, 0, 1, 0, 0, 1, 0])
expected_result = 4
assert actual_result == expected_result
print("->test_1:end")
def test_2():
print("->test_2: start")
actual_result = jumping_on_clouds([0, 1, 0, 0, 0, 1, 0])
expected_result = 3
assert actual_result == expected_result
print("->test_2: end")
def test_3():
print("->test_3: start")
actual_result = jumping_on_clouds([1, 1])
expected_result = 0
assert actual_result == expected_result
print("->test_3: end")
def test_4():
print("->test_4:start")
actual_result = jumping_on_clouds([1, 0])
expected_result = 1
assert actual_result == expected_result, "case4_1"
actual_result = jumping_on_clouds([0, 1])
expected_result = 1
assert actual_result == expected_result, "case4_2"
actual_result = jumping_on_clouds([0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1])
expected_result = 1
assert actual_result == expected_result, "case4_3"
print("->test_4: end")
def test_5():
print("->test_5: start")
actual_result = jumping_on_clouds([0, 0, 0, 1, 0, 0])
expected_result = 3
assert actual_result == expected_result
print("->test_5: end")
def test():
test_1()
test_2()
test_3()
test_4()
test_5()
print("ALL TESTS FINISHED...")
test()
|
2541af96f47e5d557164c2609c1dd07cb2cd1ab1 | Joseph-Waldron/riboviz | /riboviz/utils.py | 8,294 | 3.515625 | 4 | """
Useful functions.
"""
import os
import os.path
import numpy as np
import pandas as pd
def value_in_dict(key, dictionary, allow_false_empty=False):
"""
Check that a value is in a dictionary and the value is not
``None``.
If dictionary is::
{
"A":1,
"B":None,
"C":{},"D":[],
"E":[1],
"F":True,
"G":False
}
then:
* ``value_in_dict("A", dictionary)`` is ``True``
* ``value_in_dict("B", dictionary)`` is ``False``
* ``value_in_dict("C", dictionary)`` is ``False``
* ``value_in_dict("D", dictionary)`` is ``False``
* ``value_in_dict("E", dictionary)`` is ``True``
* ``value_in_dict("F", dictionary)`` is ``True``
* ``value_in_dict("G", dictionary)`` is ``False``
* ``value_in_dict("A", dictionary, True)`` is ``True``
* ``value_in_dict("B", dictionary, True)`` is ``False``
* ``value_in_dict("C", dictionary, True)`` is ``True``
* ``value_in_dict("D", dictionary, True)`` is ``True``
* ``value_in_dict("E", dictionary, True)`` is ``True``
* ``value_in_dict("F", dictionary, True)`` is ``True``
* ``value_in_dict("G", dictionary, True)`` is ``True``
:param key: Key
:type key: -
:param dictionary: Dictionary
:type dictionary: dict
:param allow_false_empty: Allow ``False``, empty string, \
``list`` or ``dict`` to be considered as an existing value
:type allow_false_empty: bool
:return: ``True`` or ``False``
:rtype: bool
"""
is_in = key in dictionary and dictionary[key] is not None
if not allow_false_empty:
is_in = is_in and bool(dictionary[key])
return is_in
def list_to_str(lst):
"""
Convert list to space-delimited string.
:param lst: list
:type lst: list
:return: list as string
:rtype: str or unicode
"""
return ' '.join(map(str, lst))
def get_file_ext(file_name):
"""
Given a file name return full file extension, everything after the
first ``.`` in the file name. For example, given
``example.fastq.gz`` return ``fastq.gz``, given ``example.fastq``
return ``fastq``, given ``example`` return ``''``. The extension
is returned in lower-case.
:param file_name: File name
:type file_name: str or uniecode
:return: Extension
:rtype: str or unicode
"""
file_type = ".".join(os.path.basename(file_name).split(".")[1:])
return file_type.lower()
def equal_file_names(file1, file2):
"""
Compare local names of two files each of which must exist and be a
file.
:param file1: File name
:type file1: str or unicode
:param file2: File name
:type file2: str or unicode
:raise AssertionError: If file do not exist, are not files or \
their names differ
"""
local_file1 = os.path.split(file1)[1].lower()
local_file2 = os.path.split(file2)[1].lower()
assert os.path.exists(file1) and os.path.isfile(file1),\
"File %s does not exist or is not a file"
assert os.path.exists(file2) and os.path.isfile(file2),\
"File %s does not exist or is not a file"
assert local_file1 == local_file2,\
"Unequal file names: %s, %s" % (local_file1, local_file2)
def equal_file_sizes(file1, file2):
"""
Compare sizes of two files.
:param file1: File name
:type file1: str or unicode
:param file2: File name
:type file2: str or unicode
:raise AssertionError: If the file sizes differ
:raise Exception: If problems arise when accessing the files
"""
stat1 = os.stat(file1)
stat2 = os.stat(file2)
assert stat1.st_size == stat2.st_size,\
"Unequal file sizes: %s, %s" % (file1, file2)
def equal_dataframes(data1, data2, tolerance=0.0001, ignore_row_order=False):
"""
Compare two Pandas data frames for equality. The data frames are
expected to be two dimensional i.e. rows and columns.
The data frames are compared column-by-column:
* ``float64`` columns are converted to numpy arrays then tested for
equality to within the given tolerance using
``numpy.allclose``. This is used instead of
``pandas.testing.assert_frame_equal`` as there is an issue with
how that function handles precision (see
'pandas.testing.assert_frame_equal doesn't do precision
according to the doc' #25068,
https://github.com/pandas-dev/pandas/issues/25068). In addition,
``NAN`` values are considered to be equal.
* All other columns (``object``, ``int64``, ``bool``,
``datetime64``, ``timedelta``) are compared for exact equality
using ``pandas.core.series.Series.equals``.
:param data1: dataframe
:type data1: pandas.core.frame.DataFrame
:param data2: dataframe
:type data2: pandas.core.frame.DataFrame
:param tolerance: Tolerance for floating point comparisons
:type tolerance: float
:param ignore_row_order: Ignore row order?
:type ignore_row_order: bool
:raise AssertionError: If the data frames differ in their content
"""
assert data1.shape == data2.shape,\
"Unequal shape: %s, %s"\
% (str(data1.shape), str(data2.shape))
assert set(data1.columns) == set(data2.columns),\
"Unequal column names: %s, %s"\
% (str(data1.columns), str(data2.columns))
if ignore_row_order:
data1 = data1.sort_values(by=data1.columns[0])
data2 = data2.sort_values(by=data1.columns[0])
for column in data1.columns:
column1 = data1[column]
column2 = data2[column]
if column1.dtype in (int, float) and column2.dtype in (int, float):
column_data1 = column1.to_numpy()
column_data2 = column2.to_numpy()
assert np.allclose(column_data1,
column_data2,
rtol=0,
atol=tolerance,
equal_nan=True),\
"Unequal column values: %s" % column
else:
# column1 and column2 have type pandas.core.series.Series.
# Don't use column1.equals(column2) as this will compare
# also compare Series index values which may differ.
assert np.array_equal(column1.values, column2.values), \
"Unequal column values: %s" % column
def equal_tsv(file1, file2, tolerance=0.0001, ignore_row_order=False,
comment="#", na_to_empty_str=False):
"""
Compare two tab-separated (TSV) files for equality. This function
uses :py:func:`equal_dataframes`.
:param file1: File name
:type file1: str or unicode
:param file2: File name
:type file2: str or unicode
:param tolerance: Tolerance for floating point comparisons
:type tolerance: float
:param ignore_row_order: Ignore row order?
:type ignore_row_order: bool
:param comment: Comment prefix
:type comment: str or unicode
:param na_to_empty_str: Convert ``NaN`` to `""`?
:type na_to_empty_str: bool
:raise AssertionError: If files differ in their contents
:raise Exception: If problems arise when loading the files
"""
data1 = pd.read_csv(file1, sep="\t", comment=comment)
data2 = pd.read_csv(file2, sep="\t", comment=comment)
if na_to_empty_str:
data1 = data1.fillna("")
data2 = data2.fillna("")
try:
equal_dataframes(data1, data2, tolerance, ignore_row_order)
except AssertionError as error:
# Add file names to error message.
message = error.args[0]
message += " in file: " + str(file1) + ":" + str(file2)
error.args = (message,)
raise
def replace_tokens(string, tokens={}):
"""
Customise string. Given a string and mapping from tokens to
substrings, iterate through the tokens and when a match is
found replace the token with the substring.
:param string: String
:type string: str or unicode
:param tokens: Map from tokens to substrings
:type tokens: dict
:return: String with token replaced, if a match was found
:rtype string: str or unicode
"""
customised = string
for token, replace in tokens.items():
if token in customised:
customised = customised.replace(token, replace)
return customised
|
0fc64f312a05690551b3026d32c3a1ee8cee2d45 | mpsardz/comp110-21ss1-workspace | /exercises/ex04/factorial.py | 272 | 3.953125 | 4 | """An exercise in computing the factorial of an int."""
__author__ = "730004269"
# Begin your solution here...
some_int: int = int(input("Choose a number: "))
i: int = 1
total: int = 1
while i <= some_int:
total *= i
i += 1
print("Factorial: " + str(total))
|
8e2a5391fa20d1d3891ae03f38e0f7530848f818 | igor-fortaleza/myrepository | /Codes/python/data_science/grafico_comparacao.py | 533 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 16:39:37 2019
@author: igor2
"""
import matplotlib.pyplot as plt
# "as"= o apelido da forma que vc vai usar a função
x1 = [1, 3, 5, 7, 9]
y1 = [2, 3, 7, 1, 6]
x2 = [2, 4, 6, 8, 10]
y2 = [5, 1, 3, 7, 4]
titulo = "Grafico Comparação em Python"
eixo_x = "Eixo X"
eixo_y = "Eixo Y"
#legendas
plt.title(titulo)
plt.xlabel(eixo_x)
plt.ylabel(eixo_y)
# plt.plot(x, y)
plt.bar(x1, y1, label = "grupo 1")
plt.bar(x2, y2, label = "grupo 2")
plt.legend()
#".bar" em barras
plt.show() |
17573f672b77999304f5c474ba637c3af400cbb6 | sarathkumar1981/MYWORK | /Python/AdvPython/oops/Inheritence/multiinherit3.py | 464 | 3.875 | 4 | class A:
def method(self):
print("This is A class")
super().method()
class B:
def method(self):
print("This is B class")
super().method()
class C:
def method(self):
print("This is C class")
class X(A,B):
def method(self):
print("This is X class")
super().method()
class Y(B,C):
def method(self):
print("This is Y class")
super().method()
class P(X,Y,C):
def method(self):
print("P class Method")
super().method()
p = P()
p.method()
|
f871bd9b8891c91e1c5fbcb08895e51b7267aa24 | Hidenver2016/Leetcode | /Python3.6/818-Py3-H-Race-car.py | 3,340 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 16:19:31 2018
@author: hjiang
"""
"""
Your car starts at position 0 and speed +1 on an infinite number line.
(Your car can go into negative positions.)
Your car drives automatically according to a sequence of instructions A
(accelerate) and R (reverse).
When you get an instruction "A", your car does the following: position += speed, speed *= 2.
When you get an instruction "R", your car does the following:
if your speed is positive then speed = -1 , otherwise speed = 1.
(Your position stays the same.)
For example, after commands "AAR", your car goes to positions 0->1->3->3,
and your speed goes to 1->2->4->-1.
Now for some target position, say the length of the shortest sequence of instructions to get there.
Example 1:
Input:
target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0->1->3.
Example 2:
Input:
target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0->1->3->7->7->6.
Note:
https://www.jianshu.com/p/bad491f550fa
https://blog.csdn.net/magicbean2/article/details/80333734
花花15分13秒开始,第一个视频
1 <= target <= 10000.
关键: 三种情况: 1.正好的, 2冲过去回来的,3冲过去回来再回去的
"""
# Time : O(nlogn), n is the value of the target, 子问题需要的时间是k,k就是logn(主要是指第三个问题), 然后外面的循环是n,所以是nlogn
# Space: O(n) 空间复杂度是target (dp就是O(n), 加上递归深度logn,所以是n+logn
class Solution(object):
def racecar(self, target):
dp = [0] * (target+1)
for i in range(1, target+1):
# 2^(k-1) <= i < 2^k
k = i.bit_length()
# case 1. drive exactly i at best
# seq(i) = A^k
if i == 2**k-1:#这里注意看都是按照边界条件来的, 例如target = 1, 则k = 1, dp[1] = 1,这个就是正确的结果
dp[i] = k
continue
# case 2. drive cross i at 2^k-1, and turn back to i
# seq(i) = A^k -> R -> seq(2^k-1 - i)
dp[i] = k+1 + dp[2**k-1 - i] #冲过去,掉头一次的情况,所以有一个+1,然后是反向加速,要走的距离就是走多了的(2**k-1 - i)
# case 3. drive less then 2^k-1, and turn back some distance, 不冲过去,在前面停下来,搞两次调头
# and turn back again to make the direction is the same
# seq(i) = shortest(seq(i), A^(k-1) -> R -> A^j -> R ->
# seq(i - (2^(k-1)-1) + (2^j-1)),
# where 0 <= j < k-1)
# => dp[i] = min(dp[i], (k-1) + 1 + j + 1 +
# dp[i - (2**(k-1)-1) + (2**j-1)])
for j in range(k-1): #对应于花花的讲义,此处j是讲义里面的m, k是n, i是t,
dp[i] = min(dp[i], k+j+1 + dp[i - 2**(k-1) + 2**j])# 先走k-1步,掉头,再走j步,再掉头
return dp[-1]
if __name__ == "__main__":
print(Solution().racecar(10000))
|
8e86b9876e7e87cc91d451b02157a95cf0fabef9 | marshuang80/mmtf-pyspark | /mmtfPyspark/ml/datasetBalancer.py | 2,148 | 3.859375 | 4 | #!/user/bin/env python
'''
dataBalancer.py:
Creates a balanced dataset for classification problems by either
downsampling the majority classes or upsampling the minority classes.
It randomly samples each class and returns a dataset with approximately
the same number of samples in each class
Authorship information:
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@gmail.com:
__status__ = "Done"
'''
from pyspark.sql import DataFrame
from pyspark.sql import Row
from functools import reduce
import math
def downsample(data, columnName, seed = 7):
'''
Returns a balanced dataset for the given column name by downsampling
the majority classes.
The classification column must be of type String
Attributes:
data (Dataframe)
columnName (String): column to be balanced by
seed (Int): random number seed
'''
# TODO specify max ratio between minority and majority class
counts = data.groupby(columnName).count().collect()
count = [int(x[1]) for x in counts]
names = [y[0] for y in counts]
minCount = min(count)
samples = [data.filter(columnName + "='%s'"%n) \
.sample(False,minCount/float(c),seed) \
for n,c in zip(names, count)]
return reduce(lambda x,y: x.union(y), samples)
def upsample(data, columnName, seed = 7):
'''
Returns a balanced dataset for the given column name by upsampling
the majority classes.
The classification column must be of type String
Attributes:
data (Dataframe)
columnName (String): column to be balanced by
seed (Int): random number seed
'''
counts = data.groupby(columnName).count().collect()
count = [int(x[1]) for x in counts]
names = [y[0] for y in counts]
maxCount = max(count)
samples = [data.filter(columnName + "='%s'"%n) \
.sample(False,maxCount/float(c),seed) \
if abs(1-maxCount/float(c)) > 1.0 \
else data.filter(columnName + "='%s'"%n) \
for n,c in zip(names, count)
]
return reduce(lambda x,y: x.union(y), samples)
|
2d03f854795ed3ab4d5b225953bc09a04b07a2e1 | Judahmeek/OldCode | /Python/Python 3/Library Fine.py | 2,059 | 4.03125 | 4 | #Problem Statement
#The Head Librarian at a library wants you to make a program that calculates the fine for returning the book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows:
#If the book is returned on or before the expected return date, no fine will be charged, in other words fine is 0.
#If the book is returned in the same month as the expected return date, Fine = 15 Hackos × Number of late days
#If the book is not returned in the same month but in the same year as the expected return date, Fine = 500 Hackos × Number of late months
#If the book is not returned in the same year, the fine is fixed at 10000 Hackos.
#Input Format
#You are given the actual and the expected return dates in D M Y format respectively. There are two lines of input. The first line contains the D M Y values for the actual return date and the next line contains the D M Y values for the expected return date.
#Constraints
#1≤D≤31
#1≤M≤12
#1≤Y≤3000
#Output Format
#Output a single value equal to the fine.
#Sample Input
#9 6 2015
#6 6 2015
#Sample Output
#45
#Explanation
#Since the actual date is 3 days later than expected, fine is calculated as 15×3=45 Hackos.
#Summary
#Input data
#Calculate Fine
#Output Fine
PseudoCode:
#Input actual timedate
#Input expected timedate
#check if actDate <= expDate
#if not
#check if actMonth == expMonth
#if not
#check if actYear == expYear
#if not
#calculate fine
#else
#calculate fine
#else
#calculate fine
#else
#calculate fine
#output fine
#Refined PseudoCode
#Code
date = [int(x) for x in input().split()]
aDay,aMonth,aYear = date[0],date[1],date[2]
date = [int(x) for x in input().split()]
eDay,eMonth,eYear = date[0],date[1],date[2]
if aDay + aMonth*31 + aYear*380 > eDay + eMonth*31 + eYear*380:
if aYear == eYear:
if aMonth == eMonth:
fine = 15*(aDay-eDay)
else:
fine = 500*(aMonth-eMonth)
else:
fine = 10000
else:
fine = 0
print(str(fine)) |
207772668a404769c35e9d34b043fe00b42a4874 | softborg/Python_HWZ_Start | /kurstag_9/aufgaben_9/Radio.py | 720 | 3.640625 | 4 | class Radio:
def __init__(self, volume):
self.volume = volume
# hier wird das 'volume' dem Property Wert self.volume zugewiesen
# - implizit wird die Methode set_Volume aufgerufen
# somit kann das Radio auch beim Instanziieren keinen grösseren Wert als 100 zulassen.
# kein Weg "ungültige Werte" dem Radio mitzugeben. bei der init Funktion und beim Zugriff geregelt
def get_volume(self):
return self.__volume
def set_volume(self, volume):
if volume <= 100:
self.__volume = volume
else:
raise ValueError("max value is 100")
volume = property(get_volume, set_volume)
r = Radio(20)
r.volume = 80
print(r.volume) |
0a360ec0a9ce038dc77e7617a86e6ea091726376 | ChangxingJiang/LeetCode | /0201-0300/0207/0207_Python_1.py | 1,432 | 3.546875 | 4 | import collections
from typing import List
def build_graph(edges):
graph_in = collections.defaultdict(set)
graph_out = collections.defaultdict(set)
for edge in edges:
graph_in[edge[1]].add(edge[0])
graph_out[edge[0]].add(edge[1])
return graph_out, graph_in
def topo(graph_in, graph_out):
count = {} # 节点入射边统计
queue = [] # 当前入射边为0的节点列表
# 统计所有节点的入射边
for node in graph_in:
count[node] = len(graph_in[node])
for node in graph_out:
if node not in count:
count[node] = 0
queue.append(node)
# 拓扑排序
order = []
while queue:
node = queue.pop()
order.append(node)
for next in graph_out[node]:
count[next] -= 1
if count[next] == 0:
queue.append(next)
return order
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# 生成有向图中边的邻接列表结构
graph_in, graph_out = build_graph(prerequisites)
# 拓扑排序
order = topo(graph_in, graph_out)
for node in graph_in:
if node not in order:
return False
return True
if __name__ == "__main__":
print(Solution().canFinish(2, [[1, 0]])) # True
print(Solution().canFinish(2, [[1, 0], [0, 1]])) # False
|
00fce67dfa712eddff1649c801421ffe9b932784 | ggsant/pyladies | /iniciante/Mundo 03/Exercícios Corrigidos/Exercício 078.py | 917 | 3.875 | 4 | """
EXERCÍCIO 078: Maior e Menor Valores na Lista
Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre
qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
"""
listanum = []
mai = 0
men = 0
for c in range(0, 5):
listanum.append(int(input(f'Digite um valor para a Posição {c}: ')))
if c == 0:
mai = men = listanum[c]
else:
if listanum[c] > mai:
mai = listanum[c]
if listanum[c] < men:
men = listanum[c]
print('=-' * 30)
print(f'Você digitou os valores {listanum}')
print(f'O maior valor digitado foi {mai} nas posições ', end='')
for i, v in enumerate(listanum):
if v == mai:
print(f'{i}... ', end='')
print()
print(f'O menor valor digitado foi {men} nas posições ', end='')
for i, v in enumerate(listanum):
if v == men:
print(f'{i}... ', end='')
print()
|
f80a34c02d039a675cd57f7d0b6b667fe04ef207 | GeorgiIvanovPXL/Python_Oplossingen | /IT-Essentials/Hfst6/oefeningen slides/oefening2.py | 192 | 3.796875 | 4 | def print_formatting():
for i in range(1, 15):
print("{:3d} {:4d} {:5d}" .format(i, i * i, i * i * i))
def main():
print_formatting()
if __name__ == '__main__':
main()
|
cdc88568720bf87133427894a2d03e79fb4f2da9 | Emmawxh/RecommandSystem | /script/Factorize.py | 9,714 | 3.53125 | 4 | from Data import *
import numpy as np
import sys
class MF(object):
'''
implement Matrix Factorization(data-U*M) for Recommend System
'''
def __init__(self,min=0,max=1):
'''
'''
self._data = Data()
self.min = min
self.max = max
def _init_U(self,force = False,num=1,k=100):
'''
initialization matrix U
Parameter:
force : if you want to specify the shape of U or not
num : number of users
k : number of features
'''
if not force:
if (not self._u_num) or (not self._f_num):
raise ValueError('You should run ')
else:
#TODO : what kind of initalization is suitable?
self.U = 0.02*np.random.random((self._u_num,self._f_num))/np.sqrt(self._f_num)
else:
print 'Warning: you should have specified users number and features number.'
self.U = 0.02*np.random.random( (num, k) )/np.sqrt(k)
def _init_M(self,force = False,num=1,k=100):
'''
initialization matrix M
Parameter:
force : if you want to specify the shape of M or not
num : number of items
k : number of features
'''
if not force:
if (not self._m_num) or (not self._f_num):
raise ValueError('You should run ')
else:
self.M = 0.02*np.random.random((self._m_num,self._f_num))/np.sqrt(self._f_num)
else:
print 'Warning: you should have specified items number and features number.'
self.M = 0.02*np.random.random( (num, k) )/np.sqrt(k)
def _init_Y(self,force=False,num=1,k=100):
'''
initialization matrix Y
Parameter:
force : if you want to specify the shape of Y or not
num : number of items
k : number of features
'''
if not force:
if (not self._m_num) or (not self._f_num):
raise ValueError('You should run ')
else:
self.Y = 0.02*np.random.random((self._m_num,self._f_num))/np.sqrt(self._f_num)
else:
print 'Warning: you should have specified items number and features number.'
self.Y = 0.02*np.random.random( (num, k) )/np.sqrt(k)
def load_data(self, path, force=True, sep='\t', format=None, pickle=False,split=False):
'''
Loads data from a file
Pamameter:
path: file path
force: Clearn already added data or not
sep: Seperator among file
format:Format of the file content.
Default format is 'value': 0 (first field), then 'row': 1, and 'col': 2.
E.g: format={'row':0, 'col':1, 'value':2}. The row is in position 0,
then there is the column value, and finally the rating.
So, it resembles to a matrix in plain format
pickle: if input file is a pickle file
'''
self._data.load(path, force, sep, format, pickle)
def update(self,alpha = 0.001,remeda=0.05):
'''
update for every iteration.
'''
U = self.U
M = self.M
b_U = self.b_U
b_M = self.b_M
mask = self.mask
mE = (self.data-np.dot(U,M.T)-self.overall_mean-b_U.repeat(self._m_num,axis=1)-b_M.repeat(self._u_num,axis=1).T)
self.U = U + alpha*( np.dot(mask*mE,M) - remeda*U )
self.M = M + alpha*( np.dot((mask*mE).T,U) - remeda*M )
self.b_U = b_U + alpha*( (mask*mE).sum(axis=1).reshape(b_U.shape) - remeda*b_U)
self.b_M = b_M + alpha*( (mask*mE).sum(axis=0).reshape(b_M.shape) - remeda*b_M)
return ((mask*mE)**2).sum()
def update_pp(self,alpha = 0.001,remeda=0.05):
'''
update for every iteration.
'''
U = self.U
M = self.M
Y = self.Y
b_U = self.b_U
b_M = self.b_M
Ru = self.Ru
mask = self.mask
mE = (self.data-np.dot(U,M.T)-self.overall_mean-b_U.repeat(self._m_num,axis=1)-b_M.repeat(self._u_num,axis=1).T)
Sum = (np.dot((mask*mE),M) * Ru.repeat(self._f_num,axis=1))
self.U = U + alpha*( np.dot(mask*mE,M) - remeda*U )
self.M = M + alpha*( np.dot((mask*mE).T,U + np.dot(self.data,Y)*(Ru.repeat(self._f_num,axis=1)) ) - remeda*M )
self.b_U = b_U + alpha*( (mask*mE).sum(axis=1).reshape(b_U.shape) - remeda*b_U)
self.b_M = b_M + alpha*( (mask*mE).sum(axis=0).reshape(b_M.shape) - remeda*b_M)
for i in range(self._u_num):
temp = np.dot(self.data[i].reshape(-1,1),Sum[i].reshape(1,-1))
self.Y = Y + alpha *( temp - remeda*Y )
return ((mask*mE)**2).sum()
def factorize(self,k=50,iter=100,alpha=0.001,remeda=0.05,descent=False,descent_rate=0.9,pp=False):
'''
Apply SGD for MF
Parameter:
k : number of features
iter : number of iteration
alpha :
remeda :
descent : whether change alpha after every iteration
descent_rate :
pp : run SVD++ algrithm or not
'''
try:
self._u_num = self._data.row_max + 1
self._m_num = self._data.col_max + 1
self._f_num = k
except:
raise ValueError('you sould run MF.load_data first.')
#TODO : what if users specify U and M's shape?
if not hasattr(self,'U'):
print('Init U')
self._init_U()
if not hasattr(self,'M'):
print('Init M')
self._init_M()
if ( not hasattr(self,'Y') ) and pp:
print('Init Y')
self._init_Y()
self.data = self._data.get_in_numpy_format()
self.mask = self._data.get_mask()
if ( not hasattr(self,'Ru') ) and pp:
print('Init Ru')
self.Ru = (( self.data.sum(axis=1) )** 0.5).reshape(-1,1)
if not hasattr(self,'overall_mean'):
print('Init overall_mean')
self.overall_mean = self.data.sum()/self.mask.sum()
#TODO : test if these expression is correct
#self.b_U = data.sum(axis=0)/mask(axis=0)-self.overall_mean
#self.b_M = data.sum(axis=1)/mask(axis=1)-self.overall_mean
if not hasattr(self,'b_U'):
print('Init b_U')
self.b_U = np.zeros( (self._u_num,1) )
if not hasattr(self,'b_M'):
print('Init b_M')
self.b_M = np.zeros( (self._m_num,1) )
prvs = 1e12
for i in range(iter):
if not pp:
cost = self.update(alpha,remeda)
else:
cost = self.update_pp(alpha,remeda)
if( descent == True):
alpha = alpha * descent_rate
print 'Iteration:' + str(i+1) +': cost is ' + str(cost)
sys.stdout.flush()
if cost>prvs:
print("model has converged.")
break
prvs = cost
if (i%100 == 0) and (i != 0) :
self.save_weight('tempweight_'+str(i)+'.pkl')
def predict(self,user=None,item=None):
'''
Predict score given a user and a item.
Parameter:
user : user's id
item : item's id
'''
#TODO : here assuming that user and item are given in integer form.
try:
assert user<=self._data.row_max
assert item<self._data.col_max
except:
#self.CFpredict(user,item)
None
try:
assert hasattr(self,'U')
assert hasattr(self,'M')
assert hasattr(self,'overall_mean')
assert hasattr(self,'b_U')
assert hasattr(self,'b_M')
except:
raise ValueError('You should run MF.factorize first to train the model.')
try:
score = self.overall_mean + self.b_U[user] + self.b_M[item] + np.dot(self.U[user],self.M[item].T)
except:
raise ValueError('user and item should be specified as integer.')
score = max(score,self.min)
score = min(score,self.max)
return float(score)
def CFpredict(self,user=None,item=None):
'''
predict score given a user and a item if the user or item is new here.
Parameter:
user : user's id
item : item's id
'''
if user>self._data.row_max:
#TODO : function userCF()
users = userCF()
else:
users = [user]
if item > self._data.col_max:
#TODO : function itemCF()
items = itemCF()
else:
items = [item]
score = 0
for u in users:
for i in items:
# TODO : how to meature weight
score = score + weight*self.predict(i,u)
return score
def save_weight(self,path):
pickle.dump([self.U, self.M, self.overall_mean, self.b_U, self.b_M],open(path,'w'))
def load_weight(self,path):
self.U, self.M, self.overall_mean, self.b_U, self.b_M = pickle.load(open(path,'r'))
|
be7b978b44e5dcefc4015de36c66c8d6578aa74f | DamianBarzola/frro-soporte-2020-02 | /practico_04/ejercicio02.py | 2,560 | 3.890625 | 4 | ## 2 Ejercicio Hacer un formulario en Tkinter una calculadora que tenga 1 entry y 12 botones para los dígitos 0 al 9
## y las operaciones + - / * = , que al apretar cada botón vaya agregando al valor que muestra en el entry el carácter
## que le corresponde ( como se ve imagen ) y cuando se aprieta en = pone el resultado de evaluar la cadena entrada .
from tkinter import *
ventana = Tk()
ventana.title('Calculadora')
salida = StringVar()
Pantalla = Entry(ventana, textvariable=salida, width=40).grid(column = 0,row=0, columnspan=4)
var=""
def click(num):
global var
var = var+str(num)
salida.set(var)
def operacion():
global var
try:
va =str(eval(var))
except:
borrar()
va=("Error")
salida.set(va)
def borrar():
global var
var =("")
salida.set("0")
ancho=8
altura=3
Boton1=Button(ventana,text="1",width=ancho,height=altura,command=lambda:click(1)).grid(column = 0,row=3)
Boton2=Button(ventana,text="2",width=ancho,height=altura,command=lambda:click(2)).grid(column = 1,row=3)
Boton3=Button(ventana,text="3",width=ancho,height=altura,command=lambda:click(3)).grid(column = 2,row=3)
Boton4=Button(ventana,text="4",width=ancho,height=altura,command=lambda:click(4)).grid(column = 0,row=2)
Boton5=Button(ventana,text="5",width=ancho,height=altura,command=lambda:click(5)).grid(column = 1,row=2)
Boton6=Button(ventana,text="6",width=ancho,height=altura,command=lambda:click(6)).grid(column = 2,row=2)
Boton7=Button(ventana,text="7",width=ancho,height=altura,command=lambda:click(7)).grid(column = 0,row=1)
Boton8=Button(ventana,text="8",width=ancho,height=altura,command=lambda:click(8)).grid(column = 1,row=1)
Boton9=Button(ventana,text="9",width=ancho,height=altura,command=lambda:click(9)).grid(column = 2,row=1)
Boton0=Button(ventana,text="0",width=ancho,height=altura,command=lambda:click(0)).grid(column = 1,row=4)
BotonSuma=Button(ventana,text="+",width=ancho,height=altura,command=lambda:click("+")).grid(column =3,row=1)
BotonResta=Button(ventana,text="-",width=ancho,height=altura,command=lambda:click("-")).grid(column = 3,row=2)
BotonMulti=Button(ventana,text="*",width=ancho,height=altura,command=lambda:click("*")).grid(column = 3,row=3)
BotonDiv=Button(ventana,text="/",width=ancho,height=altura,command=lambda:click("/")).grid(column = 3,row=4)
BotonIgual=Button(ventana,text="=",width=ancho,height=altura,command=operacion).grid(column = 2,row=4)
BotonCE=Button(ventana,text="CE",width=ancho,height=altura, command=borrar).grid(column = 0,row=4)
ventana.mainloop()
|
14934017b3e17301b4ac8929cadb15e70e7f2363 | YuboLuo/budgetrnn_backup | /conversion/layer_conversion.py | 2,037 | 3.671875 | 4 | import numpy as np
from .conversion_utils import create_matrix, tensor_to_fixed_point, float_to_fixed_point, create_constant
def weight_matrix_conversion(layer_name: str, weight_name: str, weight_matrix: np.ndarray, precision: int, is_msp: bool) -> str:
"""
Converts the given Tensorflow variable to a C variable that is quantized in the given fixed
point precision.
Args:
layer_name: Name of the layer containing this variable
weight_name: Name of the variable
weight_matrix: The corresponding weight matrix. This can be a 1d or 2d tensor
precision: The number of fractional bits used during fixed point quantization
is_msp: Whether to define the variables for the MSP device. This controls whether to directly
specify the memory location
Returns:
The C variables associated with this weight matrix. The C variables are newline separated.
"""
assert len(weight_matrix.shape) <= 2, 'Weight matrix can be at most 2 dimensions'
# For 2d matrices, we always transpose the weights. In Tensorflow, a standard dense layer uses the format
# (x^T)(W). In the embedded implementation, we instead use (W^T)x. This is purely a convention--the embedded
# implementation uses a row-based vector format.
if len(weight_matrix.shape) == 2:
weight_matrix = weight_matrix.T
# Create the C variable name for this trainable parameter
c_variable_name = '{0}_{1}'.format(layer_name.upper(), weight_name.upper())
c_variable_name = c_variable_name.replace('-', '_')
# Compress the weight matrix using fixed point values
if len(weight_matrix.shape) == 0:
quantized_value = float_to_fixed_point(weight_matrix, precision=precision)
return create_constant(name=c_variable_name, value=quantized_value, should_add_newline=False)
else:
quantized_matrix = tensor_to_fixed_point(weight_matrix, precision=precision)
return create_matrix(name=c_variable_name, mat=quantized_matrix, is_msp=is_msp)
|
e17fa153a42e313b2aba4b663db20eaee5503fb5 | 2kunal6/self_practice | /python/tuple.py | 116 | 3.8125 | 4 | tup=("aa", "bb", "aa")
print(tup)
print(tup[0])
#tup[0]="a"
for item in tup:
print(item)
print(tup.index("aa"))
|
540157a40081530d8f94077aaf6f8b5cd1d69dc3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/10/usersdata/71/10020/submittedfiles/testes.py | 428 | 3.75 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#entrada
p=input("Insira p: ")
q=input("Insira q: ")
#atribuições
contp=0
contq=0
ip=1
iq=1
#contagens de digitos
while p//ip!=0:
contp=contp+1
ip=ip*10
while q//iq!=0:
contq=contq+1
iq=iq*10
#CP>=cQ
if contq<contp:
print("Não é subnúmero!")
else:
#teste
a=q//(10**(contq-contp))
b=a*(10**(contq-contp))
print a
print b
|
d83ade29f98a797ffe28f8dba3a66ee30ad99459 | nhanlun/code | /Python/Ex33.py | 343 | 4.0625 | 4 | numbers = []
def add_numbers(numbers, n):
# i = 0
# while i < n:
for i in range(n):
print(f"At the top i is {i}")
numbers.append(i)
i = 10
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
add_numbers(numbers, 10)
print("The numbers: ")
for num in numbers:
print(num) |
a4258819587dd532c589a52072234fcf7ca60879 | sluzhynskyi/oop_battleship | /Battle_ship/modules/game.py | 3,024 | 3.546875 | 4 | from field import Field
from player import Player
class Game:
def __init__(self):
"""
This method initializes a new instance of Game class.
"""
self.__fields = [Field(), Field()]
name1 = input("Player 1, input your name\n:")
name2 = input("Player 2, input your name\n:")
self.__players = [Player(name1), Player(name2)]
self.__current_player = 1
self.quantity = 0
def read_position(self):
"""
This method asks current player for the coordinates to shoot at and modifies a field
:return: None
"""
dots = []
while True:
(field_loc, field_my) = (self.__fields[1], self.__fields[0]) if self.__current_player == 1 \
else (self.__fields[0], self.__fields[1])
player_loc = self.__players[0] if self.__current_player == 1 else self.__players[1]
user_input = player_loc.read_position()
if isinstance(user_input, int):
field_my.render_field(mode=user_input)
break
x, y = user_input
ship_loc = field_loc.field[y][x]
if not ship_loc.shoot_at((x, y)):
self.__current_player = 2 if self.__current_player == 1 else 1
field_loc.render_field()
break
else:
if ship_loc.hit.count(True) == len(ship_loc.hit):
if self.player_win():
print("Congratulation %s, you are win" % player_loc.name)
break
x, y = ship_loc.bow
for ad in range(ship_loc.length):
if ship_loc.horizontal:
dots += [(num, y - 1) for num in range(x - 1 + ad, x + 2 + ad)] + \
[(num, y) for num in range(x - 1 + ad, x + 2 + ad)] + \
[(num, y + 1) for num in range(x - 1 + ad, x + 2 + ad)]
else:
dots += [(num, y + 1 + ad) for num in range(x - 1, x + 2)] + \
[(num, y + ad) for num in range(x - 1, x + 2)] + \
[(num, y - 1 + ad) for num in range(x - 1, x + 2)]
for ln in dots:
if ln[0] > -1 and ln[1] > -1:
try:
field_loc.field[ln[1]][ln[0]].hit[0] = True
except IndexError:
pass
field_loc.render_field()
def player_win(self):
field_loc = self.__fields[1] if self.__current_player == 1 else self.__fields[0]
import itertools
flat = itertools.chain.from_iterable(field_loc.field)
for ship_loc in flat:
if ship_loc.ship_type:
self.quantity += ship_loc.hit.count(True)
if self.quantity == 50:
return True
|
346167b151a561405a49ef4cf2ac11e5dd5dc48d | bbluebaugh/Data_Cleanup | /pandas_tutorial.py | 1,511 | 4.40625 | 4 | # tutorial for working with excel files in python
import pandas as pd
import numpy as np
excel_file = "Pandas_Workbook.xlsx" # create a variable to hold a reference to our excel file
df = pd.read_excel(excel_file) # create a dataframe variable for the excel file
# print(df)
# print(df.head(5)) # Using the head function we can view a certain amount depending on what we pass it
# we can also pull out index, columns and datatypes using the following functions
# print(df.index)
# print(df.columns)
# print(df.dtypes)
# we can also pull out specific columns based on column names using square brackets
# print(df['Name'])
# a series contains individual scalars, a datafram contains series of things so we can access each of these using square brackets with some value
names = df['Name']
# print(names[5]) # this yields an individual name in this case name number 6 at index 5
# label based access
# print(df.at[0, "Name"])
df2 = pd.read_excel(excel_file, index_col = "Name")
# print(df2)
# print(df2.at["Beth", "Occupation"])
# integer based access in this case the values in the square brackets are used based on multidimensional array location
# print(df2.iat[1, 1])
# we can select or deselect a range of values in this case using the loc function
# we can also use a logical value to select info as well such as in the case of the Identifier
# print(df.loc[[0,2,4,6], "Age" : "Occupation"])
# print(df.loc[df["Identifier"] == True])
print(df.iloc[0 : 5 : 1, [0, 1]])
|
d17c687f7efe0ad640a198a1c7dad28ababf55f4 | EduardoMachadoCostaOliveira/Python | /CEV/ex051.py | 528 | 3.796875 | 4 | # Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
pri = int(input('Primeiro termo: '))
raz = int(input('Razão: '))
#decimo = pri + (10 - 1) * raz
for c in range(pri, ((10 * raz) + pri), raz):
print(c, end='->')
print('ACABOU')
''' Primeira Solução edu->
pri = int(input('Primeiro termo da PA: '))
raz = int(input('Razão da PA: '))
pa = 0
for c in range(1, 11):
pa = pri + (c - 1) * raz
print(pa, end=' -> ')
print('ACABOU')'''
|
142312d7e5104159020e09d567bce0d935d069e4 | jessrenteria/advent_of_code | /day1/first.py | 360 | 3.96875 | 4 | def parse_input():
with open("input1.txt", 'r') as f:
return f.read()
# Prints the current floor after following the instructions in the input.
def find_floor():
string = parse_input()
floor = 0
for c in string:
if c == '(':
floor += 1
elif c == ')':
floor -= 1
print(floor)
find_floor()
|
412f67856f48e582e2d8b0bac14357db471fdc7d | iswetha522/Plural_Sight | /corepy/files_I_O_and_resource_management/context_manager.py | 1,187 | 4.375 | 4 | # files are context managers which close files on exit.
# Context managers aren't restricted to file-like objects.
"""Demonstrate raiding a refridgerator."""
#Use closing:
from contextlib import closing
# A class for raiding the fridge
class RefridgeratorRaider:
"""Raid a refridgerator"""
# Open the refridgerator door
def open(self):
print("Open fridge door.")
# Take some food
def take(self, food):
print(f"Finding {food}...")
if food == 'deep fried pizza':
raise RuntimeError("Health Warning!")
print(f"Taking {food}")
# Close the refridgerator
def close(self):
print("Close fridge door.")
# Raid for some food!
def raid(food):
# r = RefridgeratorRaider()
with closing(RefridgeratorRaider()) as r: # By using this we get the closing of fridge door. when we call deep fried pizza
r.open()
r.take(food)
# r.close() # Removed explicit call to close()
# print(raid('becon'))
# print(raid('deep fried pizza')) # Here we have a problem the fridge door is not closing so we rectify it
print(raid('spam')) # We get two times of close fridge door. |
4338714dd9ce3bc7ebcc2763e871851d9ace350e | Jonatas-Soares-Alves/Exercicios-do-Curso-de-Python | /MUNDO 2/Exercícios/Exercício 43 (vi12).py | 573 | 3.515625 | 4 | #IMC = 80 kg ÷ (1,80 m × 1,80 m) = 24,69 kg/m2 (Peso ideal)
peso = float(input('Qual o seu peso? '))
altura = float(input('Qual sua altura? '))
imc = peso / (altura ** 2)
if imc < 18.5:
print('Você está \033[33mABAIXO DO PESO!\033[m')
elif imc >= 18.5 and imc < 25:
print('Você está \033[32mNO PESO IDEIAL!\033[m')
elif imc >= 25 and imc < 30:
print('Você está \033[33mCOM SOBREPESO!\033[m')
elif imc >= 30 and imc < 40:
print('Você está \033[31mCOM OBESIDADE!\033[m')
else:
print('Você está \033[7:31mCOM OBESIDADE MÓRBIDA!\033[m')
|
be2c3f20ae7c054cdfcacc9540932459cce2b07f | aishwat/missionPeace | /treeUtils.py | 1,211 | 3.78125 | 4 | class TreeNode:
def __str__(self):
return str(self.val) or 'None'
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.sum = None
self.next = None
class Tree:
def __init__(self, a):
if a:
self.root = self.createTree(a, 0)
def createTree(self, a, i):
if i < len(a) and a[i] is not None:
node = TreeNode(a[i])
node.left = self.createTree(a, (2 * i) + 1)
node.right = self.createTree(a, (2 * i) + 2)
return node
else:
return # TreeNode(None)
def inorder(self, root):
if not root:
return
self.inorder(root.left)
print(root.val, end=" ")
# print(root.val, (root.next and root.next.val))
self.inorder(root.right)
def preorder(self, root):
if root:
print(root.val, end=" ")
if root and root.left:
self.preorder(root.left)
if root and root.right:
self.preorder(root.right)
# a = [0, 1, 2, 3, 4, 5, 6]
# a = [3, 9, 20, None, None, 15, 7]
#
# Tree = Tree()
# root = Tree.createTree(a, 0)
# Tree.preorder(root)
|
0558cb9dc6b91d176526837ad32f91ef20868332 | natayuzyuk/homework | /TPOG11-237.py | 311 | 3.9375 | 4 | def maptolist(map) :
lst = list(map)
print("первый элемент списка: {0}".format(lst[0]))
print("последний элемент списка: {0}".format(lst[len(lst)-1]))
maptolist(map(int, input("Введите целые значения через пробел: ").split()))
|
628c9642a2f4e934f26f76ddf10126c8cdbde777 | XhuiA/Leetcode-collections | /101.对称二叉树.py | 854 | 3.921875 | 4 | #2019.11.18-2
#时间10分钟
#问题分析:需要比较左子树的左、右节点和右子树的右、左节点是否相同,复用原本的树进行比较
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
#复用递归比较
def summetric(root, cproot):
#递归终止条件
if not root and not cproot:
return True
elif not root or not cproot:
return False
elif root.val != cproot.val:
return False
return summetric(root.left, cproot.right) and summetric(root.right, cproot.left)
return summetric(root, root)
|
b2dd97f1a0221ffdfc5f31af32c4fd76ad11537c | RoPalacios74/python-challenge | /PyBank/main.py | 1,839 | 3.75 | 4 | import os
import csv
#set path
budgetpath = os.path.join('Resources','budget_data.csv')
textpath= os.path.join("Analysis", "Analysis")
#initiate values
total =0
average_change = 0
total_rows = 0
greatest_increase = 0
greatest_decrease = 0
with open(budgetpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#'next' to skip first row
next(csvreader)
for row in csvreader:
total_rows += 1
total = total+int(row[1])
previous=int(row[1])
if (greatest_increase < int(row[1])):
greatest_increase = int(row[1])
Positive_Month = row[0]
if (greatest_decrease > int(row[1])):
greatest_decrease = int(row[1])
Negative_Month = row[0]
monthly_change=(int(row[1])+1)-previous
previous=int(row[1])
all_changes = average_change+int(row[1])
average = all_changes / total_rows
#Print to terminal
print("Financial Analysis")
print("---------------------------")
print(f"Total Months: {total_rows}")
print(f"Total:${total}")
print(f"Average Change: ${average}")
print(f"Greatest Increase in Profits: {Positive_Month} ${greatest_increase}")
print(f"Greatest Decrease in Profits: {Negative_Month} ${greatest_decrease}")
output=(
"Financial Analysis\n"
"---------------------------\n"
f"Total Months: {total_rows}\n"
f"Total:${total}\n"
f"Average Change: ${average}\n"
f"Greatest Increase in Profits: {Positive_Month} ${greatest_increase}\n"
f"Greatest Decrease in Profits: {Negative_Month} ${greatest_decrease}\n"
)
print(output)
#Write to the text path
with open(textpath, "w") as txt_file:
txt_file.write(output) |
64ca9ea30c439216ba55ec4cff9f5ace40536821 | Nektarium/Morozov_N_homework | /lesson2_normal.py | 4,778 | 4.125 | 4 | # Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]
import math
list_1 = [2, -5, 8, 9, -25, 25, 4]
list_2 = []
for i in list_1:
if i >= 0:
x = int(math.sqrt(i))
if x ** 2 == i:
list_2.append(x)
print(list_2)
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
date = input("введите дату в формате dd.mm.yyyy ")
days = {
"01": "первое",
"02": "второе",
"03": "третье",
"04": "четвертое",
"05": "пятое",
"06": "шестое",
"07": "седьмое",
"08": "восьмое",
"09": "девятое",
"10": "десятое",
"11": "одинадцатое",
"12": "двенадцатое",
"13": "тринадцатое",
"14": "четырнадцатое",
"15": "пятнадцатое",
"16": "шестандцатое",
"17": "семнадцатое",
"18": "восемнадцатое",
"19": "девятнадцатое",
"20": "двадцатое",
"21": "двадцать первое",
"22": "двадцать второе",
"23": "двадцать третье",
"24": "двадцать четвертое",
"25": "двадцать пятое",
"26": "двадцать шестое",
"27": "двадцать седьмое",
"28": "двадцать восьмое",
"29": "двадцать девятое",
"30": "тридцатое",
"31": "тридцать первое",
}
months = {
"01": "января",
"02": "февраля",
"03": "марта",
"04": "апреля",
"05": "мая",
"06": "июня",
"07": "июля",
"08": "августа",
"09": "сентября",
"10": "октября",
"11": "ноября",
"12": "декабря",
}
date = date.split(".")
print(days[date[0]], months[date[1]], date[2], "года")
# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами
# в диапазоне от -100 до 100. В списке должно быть n - элементов.
# Подсказка:
# для получения случайного числа используйте функцию randint() модуля random
import random
# вариант через for in:
n = int(input("Введите количество элементов списка "))
list = []
for i in range(n):
list.append(random.randint(-100, 100))
print(list)
# вариант через while:
n = int(input("Введите количество элементов списка "))
list = []
i = 0
while i < n:
list.append(random.randint(-100, 100))
i += 1
print(list)
# Задача-4: Дан список, заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут:
# а) неповторяющиеся элементы исходного списка:
# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6]
# б) элементы исходного списка, которые не имеют повторений:
# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6]
print("Задача-4:")
# а) неповторяющиеся элементы исходного списка:
lst = [1, 2, 4, 5, 6, 2, 5, 2]
lst2 = []
var_set = set(lst)
for i in var_set:
lst2.append(i)
print("неповторяющиеся элементы исходного списка:", lst2)
# б) элементы исходного списка, которые не имеют повторений:
lst = [1, 2, 4, 5, 6, 2, 5, 2]
lst2 = []
for i in lst:
if lst.count(i) == 1:
lst2.append(i)
print("элементы исходного списка, которые не имеют повторений:", lst2)
|
2f717ed599a2eb65fc734f85286146e358cd59ed | Strugglingrookie/oldboy2 | /module8/01排序算法/01二分查找.py | 2,478 | 3.671875 | 4 | # 二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
# 非递归 时间复杂度 O(logn)
lis = [1,2,3,4,5,6,7,8,9,10]
def bin_search(lis,value):
low = 0
high = len(lis) - 1
while low <= high:
mid = (low+high) // 2
if lis[mid] == value:
return mid
elif lis[mid] > value:
high = mid - 1
else:
low = mid + 1
else:
print('不存在该数据%s'%value)
# print(bin_search(lis, 10))
# 递归 时间复杂度 O(logn)
def bin_search_plus(lis,value,low,high):
if low > high: # 找不到的时候结束递归,不然会一直递归下去,导致报错
return None
mid = (low + high) // 2
if lis[mid] == value:
return mid
elif lis[mid] > value:
return bin_search_plus(lis, value, low, mid-1) # 必须用 return 来接收最后一次递归返回来的值
else:
return bin_search_plus(lis, value, mid+1, high)
# print(bin_search_plus(lis,11,0,9))
# 习题:输入学生id,输出该学生在列表中的下标,并输出完整学生信息
stus=[{'id':1001, 'name':"张三", 'age':20},
{'id':1002, 'name':"李四",'age':25},
{'id':1003, 'name':"李四2",'age':25},
{'id':1004, 'name':"王五", 'age':23},
{'id':1005, 'name':"王五2", 'age':23},
{'id':1006, 'name':"王五3", 'age':23},
{'id':1007, 'name':"王五4", 'age':23},
{'id':1008, 'name':"王五5", 'age':23},
{'id':1009, 'name':"王五5", 'age':23},
{'id':10010, 'name':"王五7", 'age':23},
{'id':10011, 'name':"王五8", 'age':23},
{'id':10012, 'name':"赵六", 'age':33}]
# 非递归
def find_stu(stus,id):
low = 0
high = len(stus) - 1
while low <= high:
mid = (low+high) // 2
if stus[mid]['id'] == id:
return stus[mid]
elif stus[mid]['id'] > id:
high = mid -1
else:
low = low + 1
# print(find_stu(stus,10011))
# 递归
def find_stu_plus(stus,id,low,high):
if low > high:
return None
mid = (low+high) // 2
if stus[mid]['id'] == id:
return stus[mid]
elif stus[mid]['id'] > id:
return find_stu_plus(stus, id, low, mid - 1) # 必须用 return 来接收最后一次递归返回来的值
else:
return find_stu_plus(stus, id, mid + 1, high)
print(find_stu_plus(stus,10011,0,len(stus)-1)) |
677da282d14c5f0ce73f850a8a4386eff85ff8b0 | salmonofdoubt/TECH | /PROG/PY/py_dummies/pyschools.py | 1,196 | 4.15625 | 4 |
2/
1/13 - %operator
# Write a function that does a decimal to hexadecimal conversion.
# Hint: Make use of "%x" for hexadecimal format.
def dec2hex(num):
hexa = "%X" % num
return hexa
1/12 + complex numbers
# Compute the sum and product of 2 complex numbers:
# (2+3j) and (4+5j)
a = complex(2+3j)
b = complex(4+5j)
sum_ab = a+b
prod_ab = a*b
sum_ab
(6+8j)
prod_ab
(-7+22j)
1/9 +
# Use one or more string methods in above examples, extract the substring
# surrounded by 'xyz' at the beginning and end. Replace the ',' in the substring with '|'.
# and remove all trailing space.
str1 = 'abcefghxyzThis,is,the,target,string xyzlkdjf'
idx1 = str1.find('xyz') # get the position of 'xyz'
idx2 = str1.find('xyz', idx1+1) # get the next 'xyz'
str1 = str1[idx1+3:idx2].replace(',','|') # replace ',' with '|'
str1 = str1.strip( ) # strip trailing spaces.
print str1
This|is|the|target|string
1/8 - Private Test Cases Failed
# Write a function, given a string of characters, return the string together with '_'s of the same length.
def underline(title):
s = "hello"
t = len(s)
s = s + "\n" + "_"*t
return s
|
a77d9bc37f1995c08b3cd74f64149fa7a107a30a | anderalex803/nuwara-online-courses | /datacamp/ML-unsupervised-learning-python/01_kmeans_normalize_pipeline.py | 904 | 3.875 | 4 | "Create pipeline that contains normalizing data then KMeans clustering for stock data"
# KMeans and make_pipeline have been preloaded from sklearn
# Import Normalizer
from sklearn.preprocessing import Normalizer
# Create a normalizer: normalizer
normalizer = Normalizer()
# Create a KMeans model with 10 clusters: kmeans
kmeans = KMeans(n_clusters=10)
# Make a pipeline chaining normalizer and kmeans: pipeline
pipeline = make_pipeline(normalizer, kmeans)
# Fit pipeline to the daily price movements
pipeline.fit(movements)
"Do KMeans clustering in the pipeline to see which stocks move together"
# Import pandas
import pandas as pd
# Predict the cluster labels: labels
labels = pipeline.predict(movements)
# Create a DataFrame aligning labels and companies: df
df = pd.DataFrame({'labels': labels, 'companies': companies})
# Display df sorted by cluster label
print(df.sort_values('labels'))
|
2ec1193679f7af8352058a172ccc26a528ac058a | arrebole/Ink | /src/algorithm/design/1.Brute-Forc/穷举查找/breadth_first_search.py | 605 | 3.8125 | 4 | #!/usr/bin/python3
# Bfs 广度优先搜索, 输入邻接链表法表示的图, 第一个遍历的key
# 象征谨慎:从最近的元素开始搜索
class BFS():
def __init__(self, graph: dict):
self._graph: dict = graph
self._result: list[str] = []
def bfs(self, key: str):
queue: list[str] = [key]
while(len(queue) > 0):
local = queue.pop(0)
for v in self._graph[local]:
if v not in self._result:
self._result.append(v)
queue.append(v)
return self._result
|
217f8e5a500076b7fd552df2ddb6a0869ca850b2 | D12020/my-first-python-programs | /hello.py | 336 | 3.765625 | 4 | # This program says hello and greets a person by name.
#
# Saleem
# August 24, 2017
print("Hello.")
print("What is your name?")
name=input()
print("It is good to meet you, " + name + ".")
print (" Where were you born," + name + " ? ")
born = input ()
print(" That is interesting. I'd like to visit " + born + " one day. ")
|
5353dcc60618e6ccb583ef625ecfd094bd11964d | Sambit2001/Python | /Projects/Fibonacci_Series.py | 197 | 3.9375 | 4 | def fib(n):
if(n<=2):
return 1
else:
return fib(n-1)+fib(n-2)
r=int(input("Enter the limitation for fibonacci series: "))
print("\n")
for i in range(1,r+1):
print(fib(i),end=' ')
|
a0e4ec6bb067ceabd8e02a42abe9d79aa752a217 | sonsuzus/sonsuzus | /Python/Small Pyton Codes/sudoku_solver.py | 7,578 | 3.828125 | 4 | sudoku = list()
"""
Squares:
+-+-+-+
|0|1|2|
|3|4|5|
|6|7|8|
+-+-+-+
"""
def getSquare(game:list, square_num:int):
my_list = list()
for i in range(3):
for j in range(3):
if square_num == 0:
my_list.append(game[i][j])
elif square_num == 1:
my_list.append(game[i][3 + j])
elif square_num == 2:
my_list.append(game[i][6 + j])
elif square_num == 3:
my_list.append(game[3 + i][j])
elif square_num == 4:
my_list.append(game[3 + i][3 + j])
elif square_num == 5:
my_list.append(game[3 + i][6 + j])
elif square_num == 6:
my_list.append(game[6 + i][j])
elif square_num == 7:
my_list.append(game[6 + i][3 + j])
elif square_num == 8:
my_list.append(game[6 + i][6 + j])
return my_list
# Checks in all rows
def checkRows(game:list):
for row in range(9):
empty_characters = list()
needed_characters = dict()
# Empty characters
for x in range(9):
if game[row][x] == ' ':
empty_characters.append((x, row)) # (x, y)
# Find needed numbers
for empty in empty_characters:
needed_characters[empty] = set(range(1, 10))
for _x in range(9):
x, y = empty
try:
needed_characters[empty].remove(int(game[_x][x]))
except:
pass
try:
needed_characters[empty].remove(int(game[y][_x]))
except:
pass
for key in needed_characters.keys():
if len(needed_characters[key]) == 1:
mylist = list(game[key[1]])
mylist[key[0]] = str(next(iter(needed_characters[key])))
game[key[1]] = "".join(mylist)
# Solve
for num in range(1, 10):
found = 0
for key in needed_characters.keys():
if num in needed_characters[key]:
found += 1
if found == 1:
for key in needed_characters.keys():
if num in needed_characters[key]:
mylist = list(game[key[1]])
mylist[key[0]] = str(num)
game[key[1]] = "".join(mylist)
# Checks in all columns
def checkCols(game:list):
for col in range(9):
empty_characters = list()
needed_characters = dict()
# Find all empty characters
for y in range(9):
if game[y][col] == ' ':
empty_characters.append((col, y))
# Save needed numbers
for empty in empty_characters:
needed_characters[empty] = set(range(1, 10))
for _x in range(9):
x, y = empty
try:
needed_characters[empty].remove(int(game[y][_x]))
except:
pass
try:
needed_characters[empty].remove(int(game[_x][x]))
except:
pass
# Solve
for key in needed_characters.keys():
if len(needed_characters[key]) == 1:
mylist = list(game[key[1]])
mylist[key[0]] = str(next(iter(needed_characters[key])))
game[key[1]] = "".join(mylist)
for num in range(1, 10):
found = 0
for key in needed_characters.keys():
if num in needed_characters[key]:
found += 1
if found == 1:
for key in needed_characters.keys():
if num in needed_characters[key]:
mylist = list(game[key[1]])
mylist[key[0]] = str(num)
game[key[1]] = "".join(mylist)
# Checks in all 3x3 squares
def checkSquares(game:list):
for i in range(9):
# Find empty characters
empty_characters = list()
inth_square = getSquare(game, i)
for j in range(len(inth_square)):
if inth_square[j] == ' ':
empty_characters.append((i, j % 3, j // 3)) # (i, xPos, yPos)
avalible = dict()
# Find needed numbers
for k in empty_characters:
needed_numbers = list(range(1, 10))
avalible[k] = set()
for s in inth_square:
try:
needed_numbers.remove(int(s))
except ValueError:
pass
for l in list(range(1, 10)):
x = (k[0] % 3) * 3 + k[1]
y = (k[0] // 3) * 3 + k[2]
for _x in range(9):
if game[_x][x] == str(l):
try:
needed_numbers.remove(l)
except ValueError:
pass
elif game[y][_x] == str(l):
try:
needed_numbers.remove(l)
except ValueError:
pass
for _ in needed_numbers:
avalible[k].add(_)
# Solve
for keys in avalible.keys():
if len(avalible[keys]) == 1:
x_pos = (keys[0] % 3) * 3 + keys[1]
y_pos = (keys[0] // 3) * 3 + keys[2]
my_list = list(game[y_pos])
my_list[x_pos] = str(next(iter(avalible[keys])))
game[y_pos] = "".join(my_list)
for num in range(1, 10):
found = 0
for keys in avalible.keys():
if num in avalible[keys]:
found += 1
if found == 1:
for keys in avalible.keys():
if num in avalible[keys]:
x_pos = (keys[0] % 3) * 3 + keys[1]
y_pos = (keys[0] // 3) * 3 + keys[2]
my_list = list(game[y_pos])
my_list[x_pos] = str(num)
game[y_pos] = "".join(my_list)
"""
Inputs:
- Input must be line by line
- Put spaces for characters that you don't know
Example input:
6 8 5
5 367
37 658 9
6 9 21
14892
3 69
5 4
1 547 3
96 38 51
"""
def getInput(game:list):
# Getting Input
for i in range(9):
line = input()
if len(line) != 9:
print("Unresolved input!")
exit(0)
for c in line:
if c.isalpha() or not (c.isspace() or c.isdigit()):
print("Unresolved input!")
exit(0)
game.append(line)
def solve(game:list):
checkCols(game)
checkRows(game)
checkSquares(game)
def main():
print("Welcome to sudoku solver! Type your sudoku down below (space for unknown characters):")
getInput(sudoku)
i = 0
maxTry = 100
while True:
solve(sudoku)
solved = True
for a in sudoku:
if ' ' in a:
solved = False
if i >= maxTry or solved:
break
i += 1
if i == maxTry:
print("Unfortunately... I couldn't solve it.")
for x in sudoku:
for y in x:
print(y, end = '')
print()
exit(0)
print("There's the answer:")
for i in sudoku:
for j in i:
print(j, end='')
print()
if __name__ == "__main__":
main() |
5261a4e89ebade2b9baa757e966385fe568f60e1 | PoojaK97/PythonSem4 | /9a.py | 565 | 3.953125 | 4 | class time:
def __init__(self,h=0,m=0,s=0):
self.hours=h
self.minutes=m
self.seconds=s
def set_time(self,h,m,s):
self.hours = h
self.minutes = m
self.seconds = s
def __str__(self):
return 'Time: '+str(self.hours)+':'+str(self.minutes)+':'+str(self.seconds)
def get_seconds(self):
return self.hours*3600+self.minutes*60+self.seconds
t=time()
h,m,s=input('Enter hours, minutes and seconds: ').split()
h=int(h)
m=int(m)
s=int(s)
t.set_time(h,m,s)
print(t,'has',t.get_seconds(),'seconds')
|
49ff04317e0243625af4aafca9369a319d423f30 | cejjenkins/robot_controller | /main.py | 3,044 | 4.125 | 4 | """Main class to guide the robot."""
from exceptions import (
OutsideGridException,
InvalidInputException,
InvalidCommandException,
)
class RobotController:
"""The class that controls the robot."""
def __init__(self, size_of_grid, location, commands):
"""Initiate robot controler."""
self.size_of_grid = size_of_grid
self.current_row = int(location[1])
self.current_column = int(location[0])
self.direction = location[2]
self.commands = commands
self.elements = ["N", "E", "S", "W"]
def turn(self, command):
"""Turn the robot right or left."""
if self.direction not in self.elements:
raise InvalidInputException(
"Your input doesn't look right, direction should be a direction."
)
movement = -1 if command == "L" else 1
self.direction = self.elements[
(self.elements.index(self.direction) + movement) % 4
]
def vertical_move(self):
"""Move the robot north or south."""
if self.direction == "N":
self.current_row = self.current_row - 1
self.is_valid_movement()
if self.direction == "S":
self.current_row = self.current_row + 1
self.is_valid_movement()
def horizontal_move(self):
"""Move the robot east or west."""
if self.direction == "W":
self.current_column = self.current_column - 1
self.is_valid_movement()
if self.direction == "E":
self.current_column = self.current_column + 1
self.is_valid_movement()
def is_valid_movement(self):
"""Check to see if you can move, or if it's at the edge."""
if (self.current_column < 0) or (self.current_row < 0):
raise OutsideGridException(
"This move will take the robot outside the grid."
)
if (self.current_column > self.size_of_grid[0]) or (
self.current_row > self.size_of_grid[1]
):
raise OutsideGridException(
"This move will take the robot outside the grid."
)
def is_valid_command(self, command):
""""Check to see if the command is one of the three options."""
if command not in ["L", "R", "F"]:
raise InvalidCommandException(f"Sorry {command} is not a valid command.")
def position(self):
"""Check the current position."""
self.current_position = (
f"{self.current_column} {self.current_row} {self.direction}"
)
return self.current_position
def move(self):
"""Move the robot through all input commands."""
for i in self.commands:
self.is_valid_command(i)
if i in ["L", "R"]:
self.turn(i)
elif (i == "F") and (self.direction in ["N", "S"]):
self.vertical_move()
elif (i == "F") and (self.direction in ["W", "E"]):
self.horizontal_move()
|
e7db77fe0d40b71cdcaea2f03d7b400920e96144 | BereketAbera/alx-higher_level_programming | /0x03-python-data_structures/9-max_integer.py | 231 | 3.625 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
max = None
for index, value in enumerate(my_list):
if index == 0:
max = value
else:
max = max if max > value else value
return max
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.