blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
5aafdef9eee55103097a6a98518bc24a31c8725d | kc3327/Dynamic-Prgoramming | /max_thief.py | 781 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 13:00:56 2020
@author: alun
"""
#%% recursive
money=[2, 5, 1, 3, 6, 2, 4]
def max_thief_recursive(money):
return max_thief_recursive_solve(money,0)
def max_thief_recursive_solve(money,current_index):
if current_index >= len(money):
return 0
stealth1=max_thief_recursive_solve(money,current_index+2)+money[current_index]
stealth2=max_thief_recursive_solve(money,current_index+1)
return max(stealth1,stealth2)
#%% dp
def max_thief_dp(money):
dp=[0 for x in range(len(money))]
dp[0]=money[0]
dp[1]=money[1]
dp[2]=money[0]+money[2]
for i in range(3,len(money)):
dp[i]=max(dp[i-2],dp[i-3])+money[i]
return max(dp) |
e0fed43db726fa33bf7aa1187d72e2b20522ac5c | gabjohann/python_3 | /PythonExercicios/ex030.py | 479 | 4.09375 | 4 | # Crie um programa que leia um número inteiro e mostra na tela se ele é par ou ímpar.
num = float(input('Digite um número: '))
resto = num % 2
if resto == 1:
print('O número é ímpar!')
else:
print('O número é par!')
# Resolução da aula
# número = int(input('Me diga um número qualquer: '))
# resultado = número % 2
# if resultado == 0:
# print('O número {} é PAR'.format(número))
# else:
# print('O número {} é ÍMPAR'.format(número))
|
570793d57c2ab553ab893ad864c7f3dc142b6cd5 | gabriellaec/desoft-analise-exercicios | /backup/user_231/ch26_2020_03_31_22_35_12_754780.py | 232 | 3.921875 | 4 | c=int(input('qual o valor da casa?'))
s=int(input('qual o seu salario?'))
a=int(input('em quantos anos vai pagar?'))
pm=c/(a*12)
x= s*0.3
if pm<=x:
print('Empréstimo aprovado')
else:
print('Empréstimo não aprovado')
|
cb599e55d82540b3054bc4ac3fc4affbb243a758 | guilhermejcmarinho/Praticas_Python_Elson | /01-Estrutura_Sequencial/17-Calc_Tinta_Preco.py | 742 | 3.71875 | 4 | import math
qntMetros = float(input('Informe a quantidade de m² a serem pintados:'))
tintaTotal = round(qntMetros/6, 2)
qntGalao = math.ceil(tintaTotal/3.6)
qntLatas = math.ceil(tintaTotal/18)
precoGalao = qntGalao*25
precoLata = qntLatas*80
if precoGalao > precoLata:
maisBarato = precoLata
else:
maisBarato = precoGalao
print('Quantidade de tinta: {} Litro(s).'.format(tintaTotal))
print('\nQuantidade de {} galao(oes) de 3,6 Litros.'.format(qntGalao))
print('Custo por {} galao(oes) é de R$ {},00'.format(qntGalao, precoGalao))
print('\nQuantidade de {} lata(s) de 18 Litros.'.format(qntLatas))
print('Custo por {} lata(s) é de R$ {},00'.format(qntLatas, precoLata))
print('\nO mais barato é R$ {},00'.format(maisBarato))
|
c5dea1c9708fd15dea0b1c7d8ed0d30375ea1b34 | steban1234/Ejercicios-universidad | /11_elevacion_p.py | 3,398 | 3.65625 | 4 | '''Elevacion del punto (p)'''
# Marlon Steban Romero Perez _20202131029
#Solicitar los datos de campo al usuario:
ca = float(input('Digite cota del punto A:'))
cb = float(input('Digite cota del punto B:'))
hia = float(input('Digite altura instrumental del punto A:'))
hib = float(input('Digite altura instrumental del punto B:'))
dab = float(input('Digite distancia del punto A al punto B:'))
angha = float(input('Digite angulo horizontal en gggmmss medido de A a I:'))
anghb = float(input('Digite angulo horizontal en gggmmss medido de B a I:'))
angva = float(input('Digite angulo vertical en gggmmss medido de A a P:'))
angvb = float(input('Digite angulo vertical en gggmmss medido de B a p:'))
import math #libreria de matematicas
# Pasaremos gggmmss a decimal y luego a radian todos los angulos digitados:
"""Para el angulo horizontal A"""
angulo = int(angha) # Convierto el valor ingresado a un entero
angulo = angulo / 10000 # Pongo el punto decimal para separar los grados
grados = int(angulo)
aux = (angulo - grados) * 100 # Guardo en una variable los minutos como entero y los segundos como la parte decimal
minutos = int(aux)
segundos = (aux - minutos) * 100
angulo_decimal = grados + minutos/60 + segundos/3600
angulo_radianes1 = math.radians(angulo_decimal)
""""""""""""""""""
"""Para el angulo horizontal b"""
angulo = int(anghb) # Convierto el valor ingresado a un entero
angulo = angulo / 10000 # Pongo el punto decimal para separar los grados
grados = int(angulo)
aux = (angulo - grados) * 100 # Guardo en una variable los minutos como entero y los segundos como la parte decimal
minutos = int(aux)
segundos = (aux - minutos) * 100
angulo_decimal = grados + minutos/60 + segundos/3600
angulo_radianes2 = math.radians(angulo_decimal)
""""""""""""""""""
"""Para el angulo vertical a"""
angulo = int(angva) # Convierto el valor ingresado a un entero
angulo = angulo / 10000 # Pongo el punto decimal para separar los grados
grados = int(angulo)
aux = (angulo - grados) * 100 # Guardo en una variable los minutos como entero y los segundos como la parte decimal
minutos = int(aux)
segundos = (aux - minutos) * 100
angulo_decimal = grados + minutos/60 + segundos/3600
angulo_radianes3 = math.radians(angulo_decimal)
""""""""""""""""""
"""Para el angulo vertical b"""
angulo = int(angvb) # Convierto el valor ingresado a un entero
angulo = angulo / 10000 # Pongo el punto decimal para separar los grados
grados = int(angulo)
aux = (angulo - grados) * 100 # Guardo en una variable los minutos como entero y los segundos como la parte decimal
minutos = int(aux)
segundos = (aux - minutos) * 100
angulo_decimal = grados + minutos/60 + segundos/3600
angulo_radianes4 = math.radians(angulo_decimal)
""""""""""""""""""
# hallar distancias horizontales de "A a I" "B a I'"
disthAI = ((dab*(math.sin(angulo_radianes2)))) / (math.sin(angulo_radianes1+angulo_radianes2))
disthBI = ((dab*(math.sin(angulo_radianes1)))) / (math.sin(angulo_radianes1+angulo_radianes2))
# hallar longitud de I a p. a partir del triangulo AIP:
longIPA = disthAI*(math.tan(angulo_radianes3))
# hallar longitud de I a p. a partir del triangulo BIP:
longIPB = disthBI*(math.tan(angulo_radianes4))
# hallamos elevacion para el punto P:
elevP = ((longIPA + ca + hia + longIPB + cb + hib)) / (2)
print()
print( '='*80)
print('la elavacion para el punto P es:' ,elevP)
print( '='*80)
print()
|
4013a88b09b50e8263461ce9f6c124da276fbc3b | semone/advent-of-code-2019 | /day01/day1.py | 679 | 3.703125 | 4 | # --- Day 1: The Tyranny of the Rocket Equation ---
import sys
import os
def calculate_fuel(mass):
return mass // 3 - 2
def calculate_fuel_4_real(mass, sum):
fuel = calculate_fuel(mass)
if fuel <= 0:
return sum
else:
return calculate_fuel_4_real(fuel, sum + fuel)
def day1():
sumPart1 = 0
sumPart2 = 0
with open(os.path.join(sys.path[0], "input_day1.txt")) as file:
for line in file:
sumPart1 += calculate_fuel(int(line))
sumPart2 += calculate_fuel_4_real(int(line), 0)
print('Sum of fuel requirements part1:', sumPart1)
print('Sum of fuel requirements part2:', sumPart2)
day1()
|
7f235138f89f3b12f0862bfaf5f959d99aee88a0 | purvimisal/Leetcode | /lc-67.py | 342 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 1 17:13:34 2019
@author: purvi
"""
def addBinary(a: str, b: str) -> str:
a = int(a,2)
b = int(b,2)
sum = bin(a+b)
s = sum[2:]
return str(s)
if __name__ == "__main__":
a = "101011010011"
b = "1011110011"
addBinary(a,b) |
43cd11f65d47a64656c137e968325ffd237fa8b3 | yuihmoo/algorism | /python study/5063.py | 205 | 3.640625 | 4 | V = int(input())
V_list = []
V_list = list(str(input()))
if V_list.count('A') > V_list.count('B'):
print('A')
elif V_list.count('A') < V_list.count('B'):
print('B')
else:
print('Tie') |
f62e90255d9ba63a0ffd4139f3c3b995e0983a15 | shubhpatel9/Multithreaded-Server | /client.py | 1,645 | 3.59375 | 4 | # ECE 5650
# Project 2 - Client Side
# Shubh Patel
# Reanna John
# 11/18/2020
from socket import *
from client_helperfunctions import *
from server_helperfunctions import compress_file, uncompress_file
SERVERNAME = 'localhost'
SERVERPORT = 12000
# dictionary to work as a switch
what_to_do = {
"search word": search_word,
"replace word": replace_word,
"reverse word": reverse_word,
"display file": display_file,
"exit": Exit,
}
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((SERVERNAME, SERVERPORT))
while clientSocket:
# ======= ask user which operation to do ======
print("Valid Operations: ",
"\t> thread - server sends back the thread serving the current operation",
"\t> Search Word - counts occurances of given word in given file",
"\t> Replace Word - replaces a given word by another given word in a given file",
"\t> Reverse Word",
"\t> Display File",
"\t> Exit", sep="\n")
userInput = input("What operation would you like to do? ").lower()
# =============================================
# ========= handle operation ==================
# print('DEBUG:', userInput)
if userInput == 'thread':
get_thread_name(clientSocket, userInput)
elif userInput in what_to_do.keys():
# preps server for search word function
clientSocket.send(bytes(userInput, 'utf-8'))
what_to_do[userInput](clientSocket)
else:
print('Command does not exist')
# =============================================
|
1c282b9db4e52041bc8cc7dafcfb132558d95313 | amysolman/CMEECourseWork | /Week2/Code/lc2.py | 1,503 | 3.859375 | 4 | #!/usr/bin/env python3
# Date: Oct 2019
__appname__ = 'Ic2.py'
__version__ = '0.0.1'
"""In shell either run lc2.py (for ipython)
or python3 lc2.py. Script contains four modules. First two use list
comprehension to pull high and low rainfall data.
Second two modules serve the same function but using conventional loops."""
# Average UK Rainfall (mm) for 1910 by month
# http://www.metoffice.gov.uk/climate/uk/datasets
rainfall = (('JAN',111.4),
('FEB',126.1),
('MAR', 49.9),
('APR', 95.3),
('MAY', 71.8),
('JUN', 70.2),
('JUL', 97.1),
('AUG',140.2),
('SEP', 27.0),
('OCT', 89.4),
('NOV',128.4),
('DEC',142.2),
)
# (1) Use a list comprehension to create a list of month,rainfall tuples where
# the amount of rain was greater than 100 mm.
high_rainfall = [r for r in rainfall if r[1] > 100.0]
print(high_rainfall)
# (2) Use a list comprehension to create a list of just month names where the
# amount of rain was less than 50 mm.
low_rainfall = [m[0] for m in rainfall if m[1] < 50.0]
print(low_rainfall)
# (3) Now do (1) and (2) using conventional loops (you can choose to do
# this before 1 and 2 !).
high_rainfall = []
for row in rainfall:
if row[1] > 100.0:
high_rainfall.append(row)
print(high_rainfall)
low_rainfall = []
for row in rainfall:
if row[1] < 50.0:
low_rainfall.append(row[0])
print(low_rainfall) |
b63c786a919f9c4e3ef480328078a30b3f613880 | VictorSega/toxic-substances-ship | /Domain/User.py | 834 | 3.53125 | 4 | import sqlite3
import hashlib
conn = sqlite3.connect('Navio.db')
def InsertUser(username, password):
encodedPassword = hashlib.sha1(password.encode()).hexdigest()
cursor = conn.cursor()
cursor.execute(f"INSERT INTO User (Username, Password) VALUES ('{username}', '{encodedPassword}');")
conn.commit()
def GetUsers():
cursor = conn.cursor()
cursor.execute("SELECT Id, Username FROM User")
users = []
for user in cursor.fetchall():
users.append(str(user))
return users
def UpdateUser(username, userId):
cursor = conn.cursor()
cursor.execute(f"UPDATE User SET Username = '{username}' WHERE Id = '{userId}';")
conn.commit()
def DeleteUser(userId):
cursor = conn.cursor()
cursor.execute(f"DELETE FROM User WHERE Id = '{userId}';")
conn.commit() |
e6265197aaf3f43c110a3c282d834c9888ca1952 | LiuFang816/SALSTM_py_data | /python/dvklopfenstein_PrincetonAlgorithms/PrincetonAlgorithms-master/tests/test_Stack.py | 4,178 | 3.6875 | 4 | #!/usr/bin/env python
"""Tests using a Stack"""
import sys
from AlgsSedgewickWayne.Stack import Stack
from AlgsSedgewickWayne.testcode.ArrayHistory import run
def test_Stack_lec_quiz(prt=sys.stdout):
"""Run the quiz in Stats 1, Week 2 lecture, 'Stacks (16:24)'"""
expected = "5 4 3 2 1"
run(Stack(), "1 2 3 4 5 - - - - -", expected, details=None)
run(Stack(), "1 2 5 - 3 4 - - - -", expected, details=None)
run(Stack(), "5 - 1 2 3 - 4 - - -", expected, details=None)
run(Stack(), "5 - 4 - 3 - 2 - 1 -", expected, details=None)
def test_wk2_ex_Stacks_489125(prt=sys.stdout):
"""(seed = 489125)"""
# Suppose that an intermixed sequence of 10 push and 10 pop
# operations are performed on a LIFO stack. The pushes push
# the letters 0 through 9 in order; the pops print out the
# return value. Which of the following output sequence(s)
# could occur?
# result = run(Stack(), "0 1 2 3 4 5 6 7 8 9")
prt.write("\n489125 DONE\n")
#exp = "0 1 3 2 4 6 8 5 7 9"
result = run(Stack(), "0 - 1 - 2 3 - - 4 - 5 6 - 7 8 - - 9 -")
exp = "6 5 4 3 2 1 0 7 8 9"
result = run(Stack(), "0 1 2 3 4 5 6 - - - - - - - 7 - 8 - 9 -")
exp = "3 4 5 8 9 7 6 2 1 0"
result = run(Stack(), "0 1 2 3 - 4 - 5 - 6 7 8 - 9 - - - - - -")
exp = "0 3 7 6 5 4 2 9 8 1"
result = run(Stack(), "0 - 1 2 3 - 4 5 6 7 - - - - - 8 9 - - -")
# exp = "1 0 3 5 2 7 6 8 9 4"
result = run(Stack(), "0 1 - - 2 3 - 4 5 - 6 7 8 9")
def test_wk2_ex_Stacks_634506(prt=sys.stdout):
"""(seed = 634506)"""
# Suppose that an intermixed sequence of 10 push and 10 pop
# operations are performed on a LIFO stack. The pushes push
# the letters 0 through 9 in order; the pops print out the
# return value. Which of the following output sequence(s)
# could occur?
prt.write("\n634506 DONE\n")
result = run(Stack(), "0 1 2 3 - - - 4 5 - 6 7 8 9")
#exp = "3 2 1 5 0 6 7 8 9 4"
exp = "2 1 0 3 4 5 6 7 8 9"
result = run(Stack(), "0 1 2 - - - 3 - 4 - 5 - 6 - 7 - 8 - 9 -", exp)
exp = "0 1 3 2 4 5 6 8 7 9"
result = run(Stack(), "0 - 1 - 2 3 - - 4 - 5 - 6 - 7 8 - - 9 -", exp)
result = run(Stack(), "0 1 2 3 - 4 5 - - 6 7 8 9")
#exp = "3 5 2 4 6 1 0 8 7 9"
exp = "2 1 6 5 4 7 3 8 0 9"
result = run(Stack(), "0 1 2 - - 3 4 5 6 - - - 7 - - 8 - - 9 -", exp)
def test_wk2_ex_Stacks_634506b(prt=sys.stdout):
"""(seed = 634506)"""
prt.write("\n634506b DONE\n")
result = run(Stack(), "0 1 2 3 - - - 4 5 - - 6 7 8 9")
#exp = "3 2 1 5 0 6 7 8 9 4"
exp = "2 1 0 3 4 5 6 7 8 9"
result = run(Stack(), "0 1 2 - - - 3 - 4 - 5 - 6 - 7 - 8 - 9 -", exp)
exp = "0 1 3 2 4 5 6 8 7 9"
result = run(Stack(), "0 - 1 - 2 3 - - 4 - 5 - 6 - 7 8 - - 9 -", exp)
result = run(Stack(), "0 1 2 3 - 4 5 - - 6 7 8 9")
#exp = "3 5 2 4 6 1 0 8 7 9"
exp = "2 1 6 5 4 7 3 8 0 9"
result = run(Stack(), "0 1 2 - - 3 4 5 6 - - - 7 - - 8 - - 9 -", exp)
def test_wk2_ex_Stacks_489125b(prt=sys.stdout):
"""(seed = 489125)"""
prt.write("\n489125b\n")
#result = run(Stack(), "0 1 2 3 4 5 6 7 8 9")
result = run(Stack(), "0 - 1 - 2 3 - - 4 - 5 6 - 7 8 - - 9")
#exp = "0 1 3 2 4 6 8 5 7 9")
exp = "6 5 4 3 2 1 0 7 8 9"
result = run(Stack(), "0 1 2 3 4 5 6 - - - - - - - 7 - 8 - 9 -", exp)
exp = "3 4 5 8 9 7 6 2 1 0"
result = run(Stack(), "0 1 2 3 - 4 - 5 - 6 7 8 - 9 - - - - - -", exp)
exp = "0 3 7 6 5 4 2 9 8 1"
result = run(Stack(), "0 - 1 2 3 - 4 5 6 7 - - - - - 8 9 - - -", exp)
result = run(Stack(), "0 1 - - 2 3 - 4 5 - - 6 7 8 9")
#exp = "1 0 3 5 2 7 6 8 9 4")
def simple_test():
"""Simple sanity check test."""
# (seed = 353020)
run(Stack(), "0 1 2 3 4 5 6 7 8 9")
run(Stack(), "0 1 - - 2 3 4 5 6 7 - 8 - - 9 - - - - -")
def default_examples():
"""Example from lecture."""
run(Stack(), "to be or not to be - - - - - -")
# Slide 6 Week 2 Lecture 4-1-Stacks(16-24)
run(Stack(), "to be or not to - be - - that - - - is")
def run_all():
"""Run all tests."""
test_wk2_ex_Stacks_489125b()
test_wk2_ex_Stacks_634506b()
test_wk2_ex_Stacks_634506()
test_wk2_ex_Stacks_489125()
simple_test()
default_examples()
if __name__ == '__main__':
if len(sys.argv) == 1:
run_all()
else:
run(Stack(), sys.argv[1])
|
f1732f2bfcb96c8d48a04d4d47ebf5924df3f52a | daniel-reich/turbo-robot | /cgyHTJDW5brpXGDy6_3.py | 948 | 4.40625 | 4 | """
Create a function that takes `time1` and `time2` and return how many hours
have passed between the two times.
### Examples
hours_passed("3:00 AM", "9:00 AM") ➞ "6 hours"
hours_passed("2:00 PM", "4:00 PM") ➞ "2 hours"
hours_passed("1:00 AM", "3:00 PM") ➞ "14 hours"
### Notes
`time1` will always be the starting time and `time2` the ending time. Return
"no time passed" if `time1` is equal to `time2`.
"""
def hours_passed(time1, time2):
if time1 == time2:
return "no time passed"
time1_clock, time1_period = time1.split()
time2_clock, time2_period = time2.split()
hours1, minutes1 = time1_clock.split(':')
hours2, minutes2 = time2_clock.split(':')
if time1_period == time2_period:
return str(int(hours2) - int(hours1)) + " hours"
else:
return str(12 - int(hours1) + int(hours2)) + " hours"
print(hours_passed("2:00 PM" , "4:00 PM"))
|
9dd6e3a4054820fe471021030f474be1b6c8d7b3 | Kangjinwoojwk/algorithm | /baekjoon/2562.py | 157 | 3.765625 | 4 | max_number = 0
idx = 0
for i in range(1, 10):
a = int(input())
if a > max_number:
max_number = a
idx = i
print(max_number)
print(idx) |
ce2b942418b1e163b38dad275f80280239b44ed7 | nikkoenggaliano/AlProg | /python/calculator_sederhana.py | 790 | 4 | 4 | # fungsi penjumlahan
def add(x, y):
return x + y
# fungsi pengurangan
def subtract(x, y):
return x - y
# fungsi perkalian
def multiply(x, y):
return x * y
# fungsi pembagian
def divide(x, y):
return x / y
# menu operasi
print("Pilih Operasi.")
print("1.Jumlah")
print("2.Kurang")
print("3.Kali")
print("4.Bagi")
# Meminta input dari user
choice = input("Masukkan pilihan(1/2/3/4): ")
num1 = int(input("Masukkan bilangan pertama: "))
num2 = int(input("Masukkan bilangan kedua: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Input salah")
|
6f3d0db8986d09a910233460857f265bd9cc8524 | 0732sta/starter-python | /standard-input/area_calc.py | 353 | 4.125 | 4 | name=input('Tell me your name:')
#print('salam '+name)
age = input('age? ')
print(name,'you are',age,'!!')
#Calc the area of a circle
#radius=input('Enter the radius of your circle (m):')
#area=3.142*radius**2
# line-8 is error because you not declare the type of radius
#area=3.142*int(radius)**2
#print("The area of your cicrle is:",area) |
cd0712dfa52454e442dab96e1038227b75305d5a | liuluyang/mk | /py3-study/BaseStudy/mk_15_object_study/测试/study_2.py | 5,755 | 4.375 | 4 |
"""
class第二阶段学习
面向对象的三大特征:封装、继承和多态
"""
"""
私有属性和方法
作用:
限制属性和方法的随意调用和修改,使代码更加健壮
"""
"""
需要注意的是,在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,
是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__age__这样的变量名。
有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,
但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,
请把我视为私有变量,不要随意访问”。
"""
class Person:
def __init__(self, name, age, role):
if not 0<=age<=200:
raise ValueError('年龄输入错误')
self.__name = name
self.__age = age
self.__role = role
self.IQ = 200
pass
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if not 0<=age<=200:
raise ValueError('年龄输入错误')
self.__age = age
def info(self):
"""
获取个人信息
:return:
"""
data = (self.__name, self.__age, self.__role)
return data
def birthday(self):
"""
过生日
:return:
"""
self.__age += 1
print('{}又长了一岁'.format(self.__name))
return self.__age
# 把该方法当做属性调用
@property
def isAdult(self):
"""
判断是否成年
:return:
"""
if self.__age >= 18:
print('年龄{}岁,已成年'.format(self.__age))
return True
else:
print('年龄{}岁,未成年'.format(self.__age))
return False
# p = Person('小绿', 20, '学生')
# # print(p.__name)
# print(p.isAdult)
"""
继承和多态
继承:
1、继承父类所有方法属性
2、子类可以添加新的方法
3、使用super()显式的调用父类方法
多态:
相同的方法作用在不同对象上返回不同的结果
"""
class Girl(Person):
# def __init__(self, name, age, role):
# self.name = name
# self.age = age
# self.role = role
# pass
def __init__(self, name, age, role):
super().__init__(name, age, role)
pass
def hz(self):
print('化妆之后更漂亮了')
#
# def info(self):
# data = (self.__name, self.__role) # 无法调用父类私有属性 只能通过公开方法
# return data
g = Girl('小新', 200, '学生')
# print(g.isAdult) # 调用父类方法
# print(g.IQ)
# g.name = 10
# print(g.name)
# print(g.info())
# print(dir(g))
"""
多态:
可以对不同的对象调用同名的操作(方法)
"""
class Test1:
def read(self):
return '我正在写代码。。。'
class Test2:
def read(self):
return '我不知道在干吗。。。'
f = open('readme.md', 'r', encoding='utf8')
t1 = Test1()
t2 = Test2()
def run(obj):
print(obj.read())
# run(f)
# run(t1)
# run(t2)
"""
类的方法和属性
以及静态方法
"""
class D:
nums = 0
def __init__(self, nums):
self.nums = nums
D.nums += 1
# 这是一个类方法
@classmethod
def addnums(cls):
cls.nums += 1
return cls.nums
# 静态方法
@staticmethod
def other():
return 2**10
@staticmethod
def newcls():
return D(110)
# @classmethod
# def newcls(cls):
# return cls(110)
def __str__(self):
return 'I am D'
# d1 = D(10)
# d2 = D(11)
# print(d1.nums)
# print(D.nums)
# print(D.addnums())
# print(D.other())
class DD(D):
def __str__(self):
return 'I am DD'
# obj = DD.newcls()
# print(obj)
"""
"""
class Employe:
def __init__(self, name):
self.name = name
def info(self):
print('我是%s'%self.name)
class Customer:
def __init__(self, age):
self.age = age
def work(self):
print('正在工作', self.age)
class Manager(Customer, Employe):
def __init__(self, age, name):
super().__init__(age)
# self.name = name
# super().__init__(name)
Employe.__init__(self, name)
pass
pass
def other(self):
print('this is other func')
m = Manager(12, 'lly')
# m.work()
# m.info()
# Manager.other = other
"""
限制动态添加属性和方法
"""
from types import MethodType
"""
__slots__ 属性指定的限制只对当前类的实例对象起作用。
如果要限制子类的实例动态添加属性和方法,则需要在子类中也定义 slots 属性,这样,子
类的实例允许动态添加属性和方法就是子类的_slots__ 元组加上父类的_slots_元组的和。
"""
class M:
"""
只可以限制实例对象动态添加某些方法
"""
__slots__ = ('name', 'other')
class MM(M):
"""
如果有继承同时子类也进行了限制
"""
__slots__ = ('age', 'sex') # 没有了__dict__属性
# m = MM()
# m.name = lambda x:print(x)
# m.name(1)
"""
元类metaclass
用来控制类的创建
"""
class CheckMethodName(type):
def __new__(cls, *args, **kwargs):
print(args)
print(kwargs)
attrs = args[-1]
print(attrs.get('read'))
return type.__new__(cls, *args, **kwargs)
class Ne(metaclass=CheckMethodName):
is_check = True
def __init__(self, text):
self.text = text
def read(self):
print(self.text)
# n = Ne('hello world')
# n.read() |
42b7b5c2775a4a7ee5fe3504fa58988a36f2897f | heittre/Year2-Sem2-sliit | /DSA/Exams/Online Exam 1/A1/inserta1.py | 264 | 3.96875 | 4 | def insertion_sort(A):
n = len(A)
for j in range(1, n):
key = A[j]
i = j -1
while(i >= 0 and key < A[i]):
A[i + 1] = A[i]
i -= 1
A[i + 1] = key
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print(arr) |
7aae22d1b04434580da5ab7fbc8088b4f513d7e9 | I-del-hub/Ishmarika-shah | /calculator.py | 605 | 4.125 | 4 | print("enter your choice")
print("select operation")
print("1.add")
print("2.subtract")
print("3.multiply")
print("4.division")
x=int(input("enter first no."))
y=int(input("enter second no."))
c=int(input("enter your choice"))
def add(x,y):
return(x+y)
def subtract(x,y):
return(x-y)
def multiply(x,y):
return(x*y)
def division(x,y):
return(x/y)
if c==1:
ans= add(x,y)
print(ans)
elif c==2:
ans=subtract(x,y)
print(ans)
elif c==3:
ans= multiply(x,y)
print(ans)
elif c==4:
ans=division(x,y)
print(ans)
else:
print("invalid input") |
3fd53ccefe4ea03926a224aac8d2d0760cd102c8 | 6851-2021/MostSignificantSetBit | /mssb_lookup.py | 921 | 3.875 | 4 |
# Find the most significant set bit for given n
def most_significant_set_bit(n):
if n == 0:
return -1
else:
return most_significant_set_bit(n >> 1) + 1
def print_lookup_table(nbits):
lookup = ""
lookup_name = "lookup_{}bit".format(nbits)
max_value = 2 ** nbits
# Open up the `lookup` array
lookup += f"const uint32_t {lookup_name}[] = {{"
for i in range(max_value):
# To avoid too long lines
if i % 16 == 0:
lookup += "\n"
mssb = most_significant_set_bit(i)
if mssb == -1:
lookup += "NO_SET_BITS"
else:
lookup += f"{mssb}"
# Add commas after every element but the last
if i < max_value - 1:
lookup += ", "
# Close the `lookup` array
lookup += "};"
print(lookup)
def main():
print_lookup_table(16)
if __name__ == "__main__":
main()
|
4ea8b9138920af0be650f735d886ec58d19d6b14 | morzen/Greenwhich1 | /COMP1753/week5/L03 Decisions/05HelloNames.py | 314 | 4.125 | 4 | first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
if first_name == str("Chris") and last_name == str("Walshaw"):
print("Hello Chris Walshaw, COMP1753 module leader")
else :
print("Hello " + first_name + " " + last_name)
print()
input("Press return to continue ...")
|
acbef13254cb3f499763d474c236c6f9ad7489a4 | WesGtoX/Intro-Computer-Science-with-Python-Part01 | /Week2/Tarefa 01/Exercicio_02_media_aritmetica.py | 286 | 3.625 | 4 | priN = int(input("Digite a primeira nota: "))
segN = int(input("Digite a segunda nota: "))
terN = int(input("Digite a terceira nota: "))
quaN = int(input("Digite a quarta nota: "))
media = priN + segN + terN + quaN
media_final = media / 4
print("A média aritmética é", media_final) |
cb54dfd38405458b6173a9733715e914a513067c | Yi-Mu/learnpython | /palindrome.py | 160 | 3.734375 | 4 | #-*- coding:utf-8 -*-
def is_palindrome(n):
return str(n)==str(n)[::-1] and len(str(n))>1
output=filter(is_palindrome,range(1000))
print(list(output))
|
5c14251f832def28f67172451b51b92a9c8f1e66 | Flimars/Python3-for-beginner | /_curso_em_video/codes-python-intellij/_exemplos_aulas/aprensentacao.py | 545 | 4.0625 | 4 | ''' Curso em Vídeo: Aula 04 - Usando input - Desafio 01
Curso de Programação em Python
The Python language created in 1991 by Guido Van Rossum.
Aiming at productivity and readability.
'''
print('****************************************************************************')
print('************************** Usando Input em Python **************************')
print('****************************************************************************')
print('')
nome = input('Qual é o seu nome? ')
print('Olá,', nome, 'Prazer em conhecê-lo!') |
cfb8e689e009349dd826955682f1b56759ed8031 | Legonaftik/Yandex-ML-introduction-Coursera | /week1/titanic.py | 2,802 | 4.03125 | 4 | """
Какое количество мужчин и женщин ехало на корабле?
В качестве ответа приведите два числа через пробел.
"""
import pandas
data = pandas.read_csv("titanic.csv", index_col="PassengerId")
sex = data["Sex"]
print("Number of MEN:", sex.value_counts()[0]) # Number of MEN: 577
print("Number of WOMEN:", sex.value_counts()[1]) # Number of WOMEN: 314
"""
Какой части пассажиров удалось выжить?
Посчитайте долю выживших пассажиров. Ответ приведите
в процентах (число в интервале от 0 до 100,
знак процента не нужен).
"""
survived = data["Survived"]
print("Percentage of those who survived:", sum(survived) / len(survived) * 100) # 38.38
"""
Какую долю пассажиры первого класса составляли среди всех пассажиров?
Ответ приведите в процентах
(число в интервале от 0 до 100, знак процента не нужен).
"""
print(sum(data["Pclass"] == 1) / len(data["Pclass"]) * 100,
"per cent of the passengers who survived were from 1-st class") # 24.24
"""
Какого возраста были пассажиры?
Посчитайте среднее и медиану возраста пассажиров.
В качестве ответа приведите два числа через пробел.
"""
mean_age = data.mean()[2]
median_age = data.median()[2]
print("Mean age:", mean_age) # 29.7
print("Median age", median_age) # 28
"""
Коррелируют ли число братьев/сестер с числом родителей/детей?
Посчитайте корреляцию Пирсона между признаками SibSp и Parch.
"""
bros = data["SibSp"]
parents = data["Parch"]
print("Correlation between number of brothers/sisters and number of parents/children", bros.corr(parents)) # 0.41
"""
Какое самое популярное женское имя на корабле?
Извлеките из полного имени пассажира (колонка Name)
его личное имя (First Name).
"""
whole_names = data.loc[data['Sex'] == 'female', 'Name']
new = ""
for name in whole_names:
# Delete noise and save the result in variable "new"
new_name = name.replace("Miss.", "").replace("Mrs.", "").replace(",", "").replace("(", "").replace(")", "")
new += new_name
splitted = new.split()
counts = {}
for name in set(splitted):
counts[name] = splitted.count(name)
print("The most popular names:",
sorted(counts, key=counts.get, reverse=True)[:3]) # We choose Anna because "William" is a surname
|
db792b8717bf0eca48dca40bdd242608383e988c | yomarcs/CodiGoVirtualBack-4 | /pruebas/semana1/dia3/dia3-clases.py | 457 | 3.578125 | 4 | class Mueble:
tipo = 'futon'
valor = ''
color = 'negro'
especificaciones = ['Hecho en Perú','Cedro']
def devolver_especs(self):
return self.especificaciones
mueble1 = Mueble()
mueble1.tipo = 'familiar'
mueble1.valor = 500
mueble1.especificaciones = ['Hecho en Perú','2da mano','2009']
print(mueble1.especificaciones)
print()
mueble2 = Mueble()
mueble2.especificaciones.append('3era mano')
print(mueble2.devolver_especs())
|
6e18239faddde030c57bb158604adb4dc3c76779 | kieferca/quality-indicators-for-text | /python metrics/ws_uppercased(4).py | 1,197 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 16:14:12 2018
Percentage of uppercased letters
"""
from pickle import load
import nltk
from nltk import word_tokenize
# ------------------------------------------------------------------------------
def LoadPickle( fname ):
# from pickle import load
f = open('{:s}.pickle'.format(fname), 'rb')
data = load(f)
f.close()
return data
# ------------------------------------------------------------------------------
print( "Measuring corpora '{:s}.pickle'".format("./corpora_pickle/xx") )
tagged_sents = LoadPickle("./corpora_pickle/xx")
#if necessary, tokenize the text string, then only iterate on words
#tokens = word_tokenize(raw)
islower_list = [];
isupper_list = [];
word_list = [];
for sent in tagged_sents:
for word in sent:
if word.islower():
islower_list.append(word)
if word.isupper():
isupper_list.append(word)
word_list.append(word)
print("numbers of words:")
print(str(len(word_list)))
print("islower: "+ str(len(islower_list)/len(word_list)))
print("isupper: "+ str(len(isupper_list)/len(word_list)))
|
b843e7e34a941e3b12fedc21515e80bc6a2792ce | yred/euler | /python/problem_125.py | 1,960 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Problem 125 - Palindromic sums
The palindromic number 595 is interesting because it can be written as the sum
of consecutive squares: 6² + 7² + 8² + 9² + 10² + 11² + 12².
There are exactly eleven palindromes below one-thousand that can be written as
consecutive square sums, and the sum of these palindromes is 4164. Note that
1 = 0² + 1² has not been included as this problem is concerned with the squares
of positive integers.
Find the sum of all the numbers less than 10^8 that are both palindromic and
can be written as the sum of consecutive squares.
"""
from common import memoize
@memoize
def is_palindrome(n):
"""Returns `True` if `n` is a palindrome"""
nstr = str(n)
return nstr == nstr[::-1]
def solution():
threshold = 10**8
start = 2
limit = int(threshold**0.5)
# Initiliaze the list of the sums of consecutive squares with the first
# "empty" sum
sumsquares = [1]
# The set of palindromic sums
palindromes = set()
for n in range(start, limit):
# The last element is always an "empty" sum (a square number)
for idx, sumsq in enumerate(sumsquares[:-1]):
if is_palindrome(sumsq):
palindromes.add(sumsq)
# Increment all available sums with the square of the current term,
# thus generating a new set of values that can be checked for
# palindromes
sumsquares[idx] += n*n
# Add the square of the current term to the last element of the list,
# before appending it as well to produce its own sequence of sums
sumsquares[-1] += n*n
sumsquares.append(n*n)
# Drop any terms that are no longer valid
drop_idx = next(i for i, v in enumerate(sumsquares) if v < threshold)
if drop_idx:
sumsquares = sumsquares[drop_idx:]
return sum(palindromes)
if __name__ == '__main__':
print(solution())
|
bcd3268707544041bbe83c2789ef39286a4439f0 | Proxy-FHICT/proxy_py_barcode_scanner | /TestBits/AtList.py | 1,321 | 3.546875 | 4 | class AttList:
def __init__(self):
self.StudList = []
def Check(self, inpid):
if inpid > 0:
first = 0
thelist = self.StudList
last = len(thelist) - 1
found = False
while first <= last and not found:
middle = (first + last) // 2 # integer division
if thelist[middle] == inpid:
found = True
else:
if inpid < thelist[middle]:
last = middle - 1
else:
first = middle + 1
index = middle
return found, index
else:
return False, -1
def Check(thelist, inpid):
if inpid>0:
first = 0
last = len(thelist) - 1
found = False
while first <= last and not found:
middle = (first + last) // 2 #integer division
if thelist[middle] == inpid:
found = True
else:
if inpid < thelist[middle]:
last = middle - 1
else:
first = middle + 1
index = middle
return found, index
else:
return False, -1 |
c5daeec1a582b76163fb0180c2f37f0db0438aef | Ximana/INVASAO-ALIENIGINA | /alien.py | 883 | 3.65625 | 4 | import pygame
from pygame import sprite
from pygame.sprite import Sprite
class Alien(Sprite):
"""CLASSE PARA REPRESENTAR UMA ALIEN NA FROTA"""
def __init__(self, ai_settings, screen):
super(Alien, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
#CARREGAR A IMAGEM DO ALIEN E E CONFIGURAR O SEU RECT
self.image = pygame.image.load('imagens/alien.png')
self.rect = self.image.get_rect()
#COMECAR CADA NOVO ALIEN NO CANTO SUPERIOR ESQUERDO DO ECRA
self.rect.x = self.rect.width
self.rect.y = self.rect.height
#GUARGAR A POSICAO EXATA DO ALIEN
self.x = float(self.rect.x)
def blitme(self):
"""DESENHAR O ALIEN NA SUA POSICAO ATUAL"""
self.screen.blit(self.image, self.rect)
|
a4805c668d709a952b30d094474b431e849c982c | dawid0planeta/advent_of_code_2020 | /d02/sol.py | 1,011 | 3.625 | 4 | def parse_data(filename: str) -> list:
data = []
with open(filename) as f:
for line in f:
splitted = line.split(":")
data
data.append([splitted[1].strip(), splitted[0]])
return data
def get_part1(data: list) -> int:
count = 0
for line in data:
paswd, policy = line
occurances, letter = policy.split(" ")
lower, upper = map(int, occurances.split("-"))
letter_count = paswd.count(letter)
if letter_count >= lower and letter_count <= upper:
count += 1
return count
def get_part2(data: list) -> int:
count = 0
for line in data:
paswd, policy = line
occurances, letter = policy.split(" ")
pos1, pos2 = map(int, occurances.split("-"))
if (paswd[pos1 - 1] == letter) ^ (paswd[pos2 - 1] == letter):
count += 1
return count
if __name__ == "__main__":
data = parse_data("data.txt")
print(get_part1(data))
print(get_part2(data))
|
1fb7d709d75fae4b433063df2ae1f9ce103b3873 | mgould1799/Intro-To-Python | /CSCI220/code from class/practice test.py | 374 | 3.84375 | 4 | def printVar():
total = 0
for i in range(5):
total=total+(i+1)
print(total)
print()
def printVar2():
total=0
for i in range(1,4):
for j in range(i,5):
total=total+j
print(total)
print()
def threes():
num2=100
for i in range(num2):
num = i * 3
print(num, end= " ")
print()
|
249ce7efa1d32f05bdc71dffd905fb8549e8122c | codethor/dynamik | /egg_dropping.py | 559 | 3.578125 | 4 | import sys
def eggdrop(n,k):
# n = no of eggs
# k = no of floors
eggfloor = [[0 for i in range(k+1)] for j in range(n+1)]
for j in range(1,k+1):
eggfloor[1][j] = j
for i in range(1,n+1):
eggfloor[i][0] = 0
eggfloor[i][1] = 1
for i in range(2,n+1):
for j in range(2,k+1):
eggfloor[i][j] = sys.maxsize
for x in range(1,j+1):
res = max(eggfloor[i-1][x-1],eggfloor[i][j-x]) + 1
if res < eggfloor[i][j]:
eggfloor[i][j] = res
for row in eggfloor:
print(row)
return eggfloor[n][k]
print(sys.maxsize)
print(eggdrop(2,100))
|
b6edfab11b371b63829addcbead969b925a1a9dd | vancher85/hwork | /hw2/src1/demo_utils.py | 2,026 | 3.515625 | 4 | """Task4. Создать demo_utils.py в котором объединить все предыдущие задания. Написать функцию, которая сперва выводит:
1. Фибоначчи
2. Евклид
3. Счетчик картинок
Ввелите номер Demo функции:
Через input() принимает от пользователя номер задания, и выводит входящие праметры функции, и результат.
Пример:
Ввелите номер Demo функции: 2
Алгоритм евклида: 912, 84. Ответ: 12"""
import fib_1
from nod_2 import nod
from url_3 import pageparser
print("1. Фибоначчи \n"
"2. Евклид\n"
"3. Счетчик картинок")
def demo():
print("введите номер функции")
choice = int(input())
if choice == 1:
print("введите длинну ряда")
n = int(input())
fib_1.func(n)
elif choice == 2:
print("введите два числа для вычисления nod")
a,b = input().split()
a = int(a)
b = int(b)
nod(a,b)
elif choice == 3:
print("введите урл - формат http://onliner.by")
str = input()
pageparser(str)
else:
return
demo()
"""Q3: почему когда импортируешь конкретный метод из пакета from nod_2 import nod весь файл исполняется интерпритатором?
К примеру, если раскомментировать в nod2.py a,b = input().split() и запустить demo_utils.py - сначала будет просить ввести два числа и только потом print("1. Фибоначчи \n") из demo_utils.py?
Как правильно использовать методы других пакетов, чтобы лишний код не исполнялся?"""
|
270779d5e2ce77f559bcabf59282c8fab1e923a7 | zishunwei/Point-in-Polygon-Test-App | /Project Draft/test4.py | 682 | 3.71875 | 4 | a = [(1, 2), (2, 4), (3 , 5), (1, 2)]
b = [5, 6, 7, 8]
def line_crossing(x3, y3, x4, y4, x1, y1):
# arguments are points to be tested,
# (x3, y3, x4, y4) define the lines of poloygon,
# (x1, y1) define the ray which is parallel with the x-axis
if y3 == y4:
if y1 == y3:
if x1 <= x3 or x1 <= x4:
return True
else:
return False
else:
return False
else:
x = (y1 - y3) * (x4 - x3) / (y4 - y3) + x3
if y3 <= y1 <= y4 or y4 <= y1 <= y3:
if x >= x1:
return True
else:
return False
l = line_crossing(1, 3, 2, 3, 2, 6)
print(l)
|
ba544a9961c2187697fe9dfa9adc3c27f8553f8a | raghuprasadks/pythontutoriallatest | /assignment/9-RemovePunctuation.py | 319 | 4.375 | 4 | # define punctuation
punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# take input from the user
my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuation:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct) |
9615e62990d09c0e47cdda77239371bfc95e0c0e | stolmen/assetto-corsa-virtual-wheel-display | /src/wheeldrawer.py | 2,141 | 3.546875 | 4 | import sys
import os
sys.path.append(os.path.dirname(__file__))
import abc
from shapes import ShapeCollection, Annulus, Point, Line
from canvas import Canvas
class WheelDrawer(metaclass=abc.ABCMeta):
@abc.abstractmethod
def paint(self, vectors: ShapeCollection) -> None:
raise NotImplementedError
@property
@abc.abstractmethod
def scale(self) -> float:
""" Scale wheel up by the provided factor.
For example, if 2 is provided, the drawn wheel will double in size. """
return 1
@property
def translate(self) -> tuple:
""" Translate the wheel provided a tuple of (x, y) co-ordinates.
This translation is performed after scaling.
"""
return 0, 0
def display(self, wheel_rotation_degrees: float) -> None:
# Hide ends of rectangular spokes behind the wheel by shortening the rectangular sections to
# less than the outer diameter of the wheel.
offset = 0.5
# TODO: maybe make these parameters user configurable
width = 10
height = 10
wheel_rim_thickness = 1
padding = 1
c = Canvas(size=(width, height))
c.add(
Line(
Point(offset+padding, height / 2),
Point(width - offset-padding, height / 2),
thickness=wheel_rim_thickness,
)
)
c.add(
Line(
Point(width / 2, height / 2),
Point(width / 2, height - offset-padding),
thickness=wheel_rim_thickness,
)
)
c.add(
Annulus(
inner_radius=(width / 2) - padding - wheel_rim_thickness,
outer_radius=width / 2 - padding,
origin=Point(width / 2, height / 2),
)
)
c.rotate(
rotation_degrees=wheel_rotation_degrees,
rotate_about=Point(width / 2, height / 2),
)
c.scale(self.scale)
c.translate(x=self.translate[0], y=self.translate[1])
vectors = c.generate_vectors()
self.paint(vectors)
|
20e82095de257a9d5528045b86d85f5f0b7bea6e | nangia-vaibhavv/Python-Learning | /CHAPTER 7/03_fruitsList.py | 148 | 4.03125 | 4 | # print list of fruits using loops
fruits=['banana','mango','grapes','apple','kela']
i=0
while(i<len(fruits)):
print(fruits[i])
i+=1
|
3dd9413f0c96301f81d43157f026ba7ca38c45e0 | EvanDyce/Sorting-Visiualizer | /Sorting/insertionsort.py | 568 | 3.765625 | 4 | import time
red = '#ff0000'
green = '#00b32d'
black = '#000000'
white = '#ffffff'
grey = '#a6a2a2'
purple = '#ce9eff'
light_blue = '#94afff'
light_pink = '#ffbffc'
light_yellow = '#fffebf'
def InsertionSort(array, func, timeSleep):
i = 1
while i < len(array):
j = i
while j > 0:
if array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
func(array, [red if x == j else white for x in range(len(array))])
j -= 1
time.sleep(timeSleep)
i += 1
return array
|
e667720cd142283f4432a6018f2c5eff9b9bd233 | daniel-reich/turbo-robot | /6LAgr6EGHKoZWGhjd_14.py | 972 | 3.984375 | 4 | """
You face 1 out of the 4 compass directions: `N`, `S`, `E` or `W`.
* A **left turn** is a **counter-clockwise turn**. e.g. `N` (left-turn) ➞ `W`.
* A **right turn** is a **clockwise turn**. e.g. `N` (right-turn) ➞ `E`.
Create a function that takes in a starting direction and a sequence of left
and right turns, and outputs the final direction faced.
### Examples
final_direction("N", ["L", "L", "L"]) ➞ "E"
final_direction("N", ["R", "R", "R", "L"]) ➞ "S"
final_direction("N", ["R", "R", "R", "R"]) ➞ "N"
final_direction("N", ["R", "L"]) ➞ "N"
### Notes
You can only face 1 out of the 4 compass directions: `N`, `S`, `E` or `W`.
"""
def final_direction(initial, turns):
compass = ["N", "E", "S", "W"]
pointer = 0
for direction in turns:
if direction == "R":
pointer += 1
else:
pointer -= 1
initial_idx = compass.index(initial)
return compass[(initial_idx + pointer) % 4]
|
e3d75c766d97c95527890e3d883281532ae8b8f1 | bdugersuren/exercises | /cses/weird.algorithm.py | 163 | 3.6875 | 4 | # https://cses.fi/problemset/task/1068
n=input()
while n!=1:
n=int(n)
print(n, end=' ')
if n%2==0:
n>>=1
continue
n=n*3+1
print(1) |
d75cae79f85327a48abbf07655495582cd9b8c6d | slimdy/some-Important-things-in-Python | /Decorator_study.py | 5,414 | 4.28125 | 4 | """
装饰器本质上是一个Python的函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外的功能
装饰器的返回值是一个函数对象,它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景
有了装饰器,我们就可以抽离大量与函数功能本身无关的雷同代码并继续重用
简单地说:就是给已有的函数添加额外的功能
"""
#sample case
def foo():
print("I'am foo")
foo()
print('*'*50)
#现在有个新的需求 每个函数输出的时候 还要输出函数名称
def printName():
import inspect
caller = inspect.stack()[1][3]
print('[DEBUG] : ENTER {}()'.format(caller))
def foo1():
printName()
print("I'am foo1")
foo1()
print('*'*50)
#但这样 需要在每个函数里写入printName() 很麻烦。这时候装饰器要登场了
def printName1(func):
def wrapper():
print('[DEBUG] : ENTER {}()'.format(func.__name__))
return func()
return wrapper
foo = printName1(foo)
foo()
print('*'*50)
#上面的这个就是一个装饰器,当然如果每个装饰器都这么写,很麻烦。有时候理解起来也很困难
#python 提供了语法糖用来简化
@printName1
def foo2():
print("I'am foo2")
foo2()
print('*'*50)
#那么如果碰到带参数的函数,装饰器也支持参数
def printName2(func):
def wrapper(*args,**kwargs):
print('[DEBUG] : ENTER {}()'.format(func.__name__))
return func(*args,**kwargs)
return wrapper
@printName2
def foo3(something):
print("I'am foo3 and want to say :{}".format(something))
foo3('WTF')
print('*'*50)
#高级一点的装饰器
#现在有需求,需要输出函数不但要有函数名 还要有级别,比如之前的debug 或者是production,test
#这就要求装饰器本身也要带参数
def printName3(level):
def wrapper(func):
def inner_wrapper(*args,**kwargs):
print('[{level}] : ENTER {funcName}()'.format(level=level,funcName=func.__name__))
return func(*args,**kwargs)
return inner_wrapper
return wrapper
@printName3(level='production')
def foo4(something):
print("I'am foo4 and want to say :{}".format(something))
foo4('WTF')
#从这里看出装饰器的参数是在最外层传入的,被修饰的函数本身在第二层传入,函数的参数实在第三层传入的,最后在一层层的返回
print('*'*50)
#装饰器其实是是一个约束接口,他必须接收一个callable的对象作为参数,然后返回一个callable的对象。在python中callabled的对象一般是函数
#但是也有例外,只要某个对象重载了_call_()方法,那么这个对象就是callable的
# class test():
# def __call__(self):
# print('call me')
# t = test()
# t()
#那么用类来实现装饰器也是可行的
class printName4(object):
def __init__(self,level = 'Debug'):
self.level = level
def __call__(self, func):
def wrapper(*args,**kwargs):
print('[{level}] : ENTER {funcName}()'.format(level=self.level, funcName=func.__name__))
func(*args, **kwargs)
return wrapper
@printName4(level='TEST')
def foo5(something):
print("I'am foo5 and want to say :{}".format(something))
foo5('WTF')
print('*'*50)
#装饰器的坑
def printName5(func):
def wrapper(*args,**kwargs):
print('[DEBUG] : ENTER {}()'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
@printName5
def foo6(something):
print("I'am foo6 and want to say :{}".format(something))
foo6('WTF')
print(foo6.__name__) #wrapper
print('-'*25)
#用functools.wrap 可以基本解决这个问题
from functools import wraps
def printName6(func):
@wraps(func)
def wrapper(*args,**kwargs):
print('[DEBUG] : ENTER {}()'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
@printName6
def foo7(something):
print("I'am foo7 and want to say :{}".format(something))
foo7('WTF')
print(foo7.__name__)#foo7
# #但是函数的签名还是拿不到
# import inspect
# print(inspect.getargspec(foo7))
print('*'*50)
#一些好用的装饰器包
#decrotate
from decorator import decorate
import datetime
def wrapper(func,*args,**kwargs):
print("[DEBUG] {}: enter {}()".format(datetime.datetime.now(), func.__name__))
return func(*args, **kwargs)
def logging(func):
return decorate(func,wrapper)#运用decorate 可以让装饰器嵌套没那么复杂看起来
@logging
def foo8(something):
print("I'am foo8 and want to say :{}".format(something))
foo8('WTF')
print('*'*50)
#wrapt 是一个功能完善的包,使用它不用担心获得不了函数名,和源码的问题
import wrapt
@wrapt.decorator
def logging(wrapped,instance,args,kwargs):#instance is must
print("[DEBUG] {}: enter {}()".format(datetime.datetime.now(), wrapped.__name__))
return wrapped(*args,**kwargs)
@logging
def foo9():
print('哈哈')
foo9()
print('*'*50)
#如果需要带参数的可以这么写
def logging(level):
@wrapt.decorator
def wrapper(wrapped,instance,args,kwargs):
print("[{level}] {time}: enter {name}()".format(level=level,time=datetime.datetime.now(), name=wrapped.__name__))
return wrapped(*args, **kwargs)
return wrapper
@logging(level='INFO')
def foo10(something):
print(something)
foo10('WTF') |
dc7798c7d03713b3f6d39265918e7cf05825b7f4 | omar9717/Qodescape | /src/nodetypes/_stmt_while.py | 1,874 | 3.671875 | 4 | from utils import Print
'''
Describes a While block.
TODO:
1. Call a generalized function to map nodes in stmts.
HOW IT WORKS!
1.) It creates a custom node name for the "while" node as it can have multiple "while" nodes in a single scope.
- WHILE.name = WHILE_line_127
2.) Then it creates "WHILE_line_127" node with following labels.
- scope = CLASS.name, CLASS_METHOD.name or FILENAME.name
- WHILE
3.) Then it creates the following relationship if it does not exist.
- relationship_types = WHILE_BLOCK
- (parent_node)-[WHILE_BLOCK]->(WHILE_line_127:{scope:WHILE})
4.) Once done, it looks at the statements inside the "while" block and calls the relavant nodeType method accordingly.
- If it is a "Stmt_Expression", it calls "stmt_expression()".
- ...
'''
def stmt_while(self, slice, parent_node, parent_node_type, scope):
if slice['cond']['attributes']['startLine']:
while_node_type = 'WHILE:{scope}'.format(parent_node=parent_node, scope=scope)
while_node_name = self.generate_block_name_by_line(slice['cond']['attributes']['startLine'], 'WHILE')
# Create While block node
if not self.graph.find_node(while_node_name, while_node_type):
self.graph.create_node(while_node_name, while_node_type)
# Create While_block relationship with parent
if not self.graph.find_relationship(parent_node, parent_node_type, while_node_name, while_node_type, 'WHILE_BLOCK'):
self.graph.create_relationship(parent_node, parent_node_type, while_node_name, while_node_type, 'WHILE_BLOCK')
# Describes statements inside the WHILE block
if slice['stmts']:
for stmt in slice['stmts']:
pass
else:
Print.error_print('[404]', 'Issue in "While[conditions][attributes]"') |
ceffb7fa904badf9d6304964f2223bbfca5caba0 | wan-catherine/Leetcode | /problems/ValidAnagram.py | 635 | 3.53125 | 4 | class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s == t :
return True
sl = list(s)
tl = list(t)
sl.sort()
tl.sort()
if ''.join(sl) != ''.join(tl):
return False
else:
return True
def isAnagram_nice_version(self, s, t):
if len(s) != len(t):
return False
letters = 'abcdefghijklmnopqrstuvwxyz'
for letter in letters:
if s.count(letter) != t.count(letter):
return False
return True |
fbcba0a95e98a1764612e4007162f02555502865 | cham0919/Algorithm-Python | /프로그래머스/정렬/H_Index.py | 503 | 3.59375 | 4 | """https://programmers.co.kr/learn/courses/30/lessons/42747?language=java#fn1"""
citationsList = [
[3, 0, 6, 1, 5]
]
returnList = [
3
]
def solution(citations):
citations.sort()
for v in range(0, len(citations), 1):
h_index = len(citations) - v
if h_index <= citations[v]:
return h_index
return 0
for c, r in zip(citationsList, returnList):
result = solution(c)
if result == r:
print("성공")
else:
print("실패")
|
a4213deb7886ed6d6fcae858f56b6e0eb587bd75 | CoderSaha10/Simple-Calculator | /My_Claculater.py | 2,931 | 4.0625 | 4 | from tkinter import *
root=Tk()
root.title("My Calculator")
# Creating entry window
e=Entry(root,width=65, borderwidth=5)
e.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
# The Methods
def click(number):
current=e.get()
e.delete(0,END)
e.insert(0,str(current) + str(number))
def clear():
e.delete(0, END)
def add():
global symbol
global n1
n1=int(e.get())
e.delete(0, END)
symbol='+'
def subtract():
global symbol
global n1
n1=int(e.get())
e.delete(0,END)
symbol='-'
def multiply():
global symbol
global n1
n1=int(e.get())
e.delete(0,END)
symbol='*'
def divide():
global symbol
global n1
n1=int(e.get())
e.delete(0, END)
symbol='/'
def eq():
n2=int(e.get())
e.delete(0, END)
if symbol=='+':
e.insert(0, str(n1+n2))
if symbol=='-':
e.insert(0, str(n1-n2))
if symbol=='/':
e.insert(0, str(int(n1/n2)))
if symbol=='*':
e.insert(0, str(n1*n2))
# Define the buttons
b1=Button(root, text="1", padx=40, pady=20,borderwidth=10, command=lambda:click(1))
b2=Button(root, text="2", padx=40, pady=20,borderwidth=10, command=lambda:click(2))
b3=Button(root, text="3", padx=40, pady=20,borderwidth=10, command=lambda:click(3))
b4=Button(root, text="4", padx=40, pady=20,borderwidth=10, command=lambda:click(4))
b5=Button(root, text="5", padx=40, pady=20,borderwidth=10, command=lambda:click(5))
b6=Button(root, text="6", padx=40, pady=20,borderwidth=10, command=lambda:click(6))
b7=Button(root, text="7", padx=40, pady=20,borderwidth=10, command=lambda:click(7))
b8=Button(root, text="8", padx=40, pady=20,borderwidth=10, command=lambda:click(8))
b9=Button(root, text="9", padx=40, pady=20,borderwidth=10, command=lambda:click(9))
b0=Button(root, text="0", padx=40, pady=20,borderwidth=10, command=lambda:click(0))
b_clear=Button(root, text="CLEAR",bg='red', padx=40, pady=20, command=clear)
b_equals=Button(root, text="=", padx=40,bg='green', pady=20, command=eq)
b_plus=Button(root, text="+", padx=50, pady=20,bg="yellow", command=add)
b_sub=Button(root, text="-", padx=50, pady=20,bg="yellow", command=subtract)
b_mul=Button(root, text="*", padx=50, pady=20,bg="yellow", command=multiply)
b_div=Button(root, text="/", padx=50, pady=20,bg="yellow", command=divide)
#b_quit=Button(root, text="Exit",padx=50, pady=20,bg="white",fg="red", command=root.quit)
# Gridding the buttons
b1.grid(row=3,column=0)
b2.grid(row=3,column=1)
b3.grid(row=3,column=2)
b4.grid(row=2,column=0)
b5.grid(row=2,column=1)
b6.grid(row=2,column=2)
b7.grid(row=1,column=0)
b8.grid(row=1,column=1)
b9.grid(row=1,column=2)
b0.grid(row=4,column=1)
b_clear.grid(row=4,column=0)
b_equals.grid(row=4,column=2)
b_plus.grid(row=1,column=3)
b_sub.grid(row=2,column=3)
b_mul.grid(row=3,column=3)
b_div.grid(row=4,column=3)
#b_quit.grid(row=0,column=0)
root.mainloop() |
5e03224cf1026d7a064aec991decc365e0e311f5 | cnishop/pycode | /类属性方法.py | 844 | 3.9375 | 4 | class Human:
'''
this is doc
'''
name='ren'
gender ='male'
age='25'
__money = 8000
def __init__(self,name,age):
print("#"*50)
self.name=name
self.age=age
print("#"*50)
self.var2 ="实例的属性"
self.__var3 ="实例的私有属性"
#def __str__(self):
print("string")
#@classmethod
@property
def say(self):
print("my name is %s i have %d " % (self.name,self.__money))
return self.name
def __lie(self):
print("i have 5000")
@staticmethod #python2 的用法
def bye():
print("game over!")
zhangsan =Human('guo',30)
#print(zhangsan,__doc__)
#print(Human.__doc__)
#print(zhangsan.var2)
zhangsan.bye()
print(zhangsan.say)
#Human.bye() #可直接通过类名访问
print(Human.say)
|
031da6e2d9ff8931ffdc4c242f1ce4e2a61a8ddb | phontip/python | /W1/w1_t3.py | 506 | 3.96875 | 4 | num1 = input("input num1 :")
num2 = input("input num2 :")
num3 = input("input num3 :")
num4 = input("input num4 :")
num5 = input("input num5 :")
print('complex of 1 Equal',complex(num1))
print('float of 2 Equal',float(num2))
print('complex of 2 Equal',complex(num2))
print('float of 3 Equal',float(num3))
print('complex of 3 Equal',complex(num3))
print('float of 4 Equal',float(num4))
print('complex of 4 Equal',complex(num4))
print('float of 5 Equal',float(num5))
print('complex of 5 Equal',complex(num5)) |
f3fcd0761f054953a39b09dc39e4e3c982aae0f8 | abhih/ds-algo | /reduce_number_zero.py | 370 | 3.734375 | 4 | #https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
count=0
def numberOfSteps(num):
global count
print(num)
if num<1:
print("count",count)
return count
if num%2==0:
num=num//2
count+=1
else:
num=(num-1)
count+=1
return numberOfSteps(num)
print(numberOfSteps(123))
#accepted |
ce8816394ce074054d1e7c67f592bf2290f3e432 | rhkdgh815/rhkdgh815 | /문9.py | 302 | 3.796875 | 4 | n1 = int(input())
n2 = int(input())
n3 = int(input())
if n1>n2:
if n2>n3:
print(n1,n2,n3)
else:
print(n1,n3,n2)
if n2>n1:
if n1>n3:
print(n2,n1,n3)
else:
print(n2,n3,n1)
if n3>n2:
if n2>n1:
print(n3,n2,n1)
else:
print(n3,n1,n2)
|
a245bcb8f79eb2c62beae910b1045e4ce3cded53 | nyme92/snake_game | /snakegame.py | 4,152 | 4.03125 | 4 | # **************************************************************************** #
# #
# ::: :::::::: #
# snakegame.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: muelfaha <marvin@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2019/05/13 04:14:23 by muelfaha #+# #+# #
# Updated: 2019/05/13 04:53:22 by muelfaha ### ########.fr #
# #
# **************************************************************************** #
import turtle
import time
import random
delay = .1
# Compare and Keep Score
score = 0
score_board = 0
# Create Screen
sn = turtle.Screen()
sn.title("The Original snake Game By Muhammad Elfaham")
sn.bgcolor("black")
sn.setup(width=600, height=600)
sn.tracer(0)
# Create Head of snake
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("blue")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Food
food = turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("red")
food.penup()
food.goto(0,100)
# Array to add to snakelength everytime food is eaten
snakes = []
# Pen to write Score
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.color("white")
pen.write("Score: 0 Good Luck!", align="center", font=("Comic Sans", 40, "bold"))
# Functions for Movements
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_right():
if head.direction != "left":
head.direction = "right"
def go_left():
if head.direction != "right":
head.direction = "left"
def move():
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
def exit ():
turtle.bye()
sn.listen()
sn.onkey(go_up, "Up")
sn.onkey(go_down, "Down")
sn.onkey(go_left, "Left")
sn.onkey(go_right, "Right")
sn.onkey(exit, "q")
# Main Game
while True:
sn.update()
for snake in snakes:
if snake.distance(head) < 20:
print("Game Over: Your Score is: {} ".format(score,score_board))
quit()
# If snake collides with border, snake appears on other side
if head.xcor() > 290:
head.setx(-290)
if head.xcor() < -290:
head.setx(290)
if head.ycor() > 290:
head.sety(-290)
if head.ycor() < -290:
head.sety(290)
# IF snake collides with food, move food to another place and add to snake
if head.distance(food) < 20:
x = random.randint(-290,290)
y = random.randint(-290, 290)
food.goto(x, y)
new_snake = turtle.Turtle()
new_snake.speed(0)
new_snake.shape("square")
new_snake.color("blue")
new_snake.penup()
snakes.append(new_snake)
# Increase the speed of the snake by shortening the delay
delay -= 0.001
# Increase Score
score += 8
if score > score_board:
score_board = score
pen.clear()
pen.write("Score: {} ".format(score,score_board), align="center", font=("Comic Sans", 40, "bold"))
#Move the end snakes first in reverse order to move properly onscreen
for i in range(len(snakes)-1,0,-1):
x = snakes[i -1].xcor()
y = snakes[i - 1].ycor()
snakes[i].goto(x, y)
#Move snakes 0 to where the head is
if len(snakes) > 0:
x = head.xcor()
y = head.ycor()
snakes[0].goto(x,y)
move()
time.sleep(delay)
sn.mainloop()
|
04be6b60570dfc9f60a12ac27f64897643e484fe | balajisraghavan/micropython-debounce-switch | /example/main.py | 803 | 3.53125 | 4 | import machine
from switch import Switch
import time
def main():
switch_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
my_switch = Switch(switch_pin)
while True:
my_switch_new_value = False
# Disable interrupts for a short time to read shared variable
irq_state = machine.disable_irq()
if my_switch.new_value_available:
my_switch_value = my_switch.value
my_switch_new_value = True
my_switch.new_value_available = False
machine.enable_irq(irq_state)
# If my switch had a new value, print the new state
if my_switch_new_value:
if my_switch_value:
print("Switch Opened")
else:
print("Switch Closed")
time.sleep(1)
main()
|
73882337a6c315e32bf77889b8425d8953cf2382 | Mahek2000/Python-Intership | /D3/For list.py | 69 | 3.84375 | 4 | list1=[10,20,"Mahek kalariya"]
for i in list1:
print("Value is :",i) |
fcf0f7aa93c1f00a441ff5e3a966df5a95522243 | NickMonks/AlgorithmsAndDataStructure | /QuickSort.py | 2,450 | 4.40625 | 4 | import unittest
# Best Time : O(n log n) | space O(n log n)
def quickSort(array):
# Explanation of quick sort: we use the Quick sort technique, which consist of declaring
# three pointers: the pivot (P), which is the number we will sort, Left (L)
# which is the leftmost element of the subarray , and Right (R). The following conditions shall apply:
# while R > L:
# If L < R -> move +1
# If R > P -> move -1
# when while breaks, swap R with P.
# then call the quick sort algorithm recursively on the subarray on the left side of the pivot and the right
# base case will be when the len of the subarray is one; in that case, we ensure is bein sorted.
# For our example, we will set the pivot to be at the begining.
quickSortHelper(array, 0, len(array)-1)
return array
def quickSortHelper(array, startIdx, endIdx):
# because we call this recursively, we need to know the bounds on the left and right.
if startIdx >= endIdx:
return # base case: len(1), or that start and end is the same
# we will place the start pivot always at the leftmost
pivotIdx = startIdx
leftIdx = startIdx + 1
rightIdx = endIdx
while rightIdx >= leftIdx:
# we check if we need to swap or not
if array[leftIdx] > array[pivotIdx] and array[rightIdx] < array[pivotIdx]:
swap(leftIdx, rightIdx, array)
# otherwise, check if we need to swap right or left:
if array[leftIdx] <= array[pivotIdx]:
leftIdx += 1
if array[rightIdx] >= array[pivotIdx]:
rightIdx -= 1
# when while breaks, we swap the pivot:
# REMEMBER WE SWAP THE ARRAY[IDX], NOT THE ACTUAL POINTER
swap(pivotIdx, rightIdx, array)
# and finally, we call quick sort recursively. Due to space complexity, we want to call it always
# on the smallest subarray first.
# rightIdx points to the right of the left pointer, so we have to delete 1, and we check if is smaller than
# the other section.
leftSubarrayIsSmaller = rightIdx - 1 - startIdx < endIdx - (rightIdx + 1)
if leftSubarrayIsSmaller:
quickSortHelper(array, startIdx, rightIdx -1)
quickSortHelper(array, rightIdx +1 , endIdx)
else:
quickSortHelper(array, rightIdx +1 , endIdx)
quickSortHelper(array, startIdx, rightIdx -1)
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
class TestProgram(unittest.TestCase):
def test_case_1(self):
self.assertEqual(quickSort([8, 5, 2, 9, 5, 6, 3]), [2, 3, 5, 5, 6, 8, 9])
if __name__ == "__main__":
unittest.main() |
7d278ddd00a0c1453cf4aa0f955f1e9fc34f4325 | rafaelperazzo/programacao-web | /moodledata/vpl_data/55/usersdata/67/23114/submittedfiles/av2_p3_civil.py | 206 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
n=input("Digite a dimensão da matriz:")
pdp=input("Digite a posição a qual deseja pesar o valor da peça:")
linha=n
coluna=n
|
d8e541384f506e5f6e89b13e85b5b1bc7db54c5a | Samkiroko/python-data-structure-and-algorithms | /.history/Recursion/note_20210512154854.py | 2,554 | 4.3125 | 4 | # def factorial(n):
# assert n >= 0 and int(n) == n, 'The number must be positive integer only'
# if n in [0, 1]:
# return 1
# else:
# return n * factorial(n-1)
# print(factorial(10))
# Fibonacci number - Recursion
# def fibonacci(n):
# assert n >= 0 and int(n) == n, 'The number must be positive integer only'
# if n in [0, 1]:
# return n
# else:
# return fibonacci(n-1) + fibonacci(n-2)
# print(fibonacci(-7))
"""How to find sum of digit of a positive integer
number using recursion?
"""
# Recursive case - the flow
# def sumofDigits(n):
# assert n >= 0 and int(n) == n, 'The number must be positive integer only'
# if n == 0:
# return 0
# else:
# return int(n % 10) + sumofDigits(int(n/10))
# print(sumofDigits(13))
# power of the number using Recursion
# Step 1 : Recursive case - the flow
# x**n = x*x**n-1
# def power(x, n):
# return x * x**n-1
# def power(base, exp):
# assert exp >= 0 and int(
# exp) == exp, "The exponent must be positive integer"
# if exp == 0:
# return 1
# if exp == 1:
# return base
# return base * power(base, exp-1)
# print(power(2, 4))
# def gcd(a, b):
# assert int(a) == a and int(b) == b, 'the number must be an integer'
# if a < 0:
# a = -1 * a
# elif b < 0:
# b = -1 * b
# if b == 0:
# return a
# elif a < 0:
# return
# return gcd(b, a % b)
# print(gcd(60, 48))
# def computeGCD(x, y):
# if x > y:
# small = y
# else:
# small = x
# for i in range(1, small+1):
# if((x % i == 0) and (y % i == 0)):
# gcd = i
# return gcd
# a = 60
# b = 48
# # prints 12
# print("The gcd of 60 and 48 is : ", end="")
# print(computeGCD(60, 48))
#####
# How to covert a number from decimal to binary using recursion
# def decimalToBinary(n):
# assert int(n) == n, "The parameter must be an integer only!"
# if n == 0:
# return 0
# else:
# return n % 2 + 10 * decimalToBinary(int(n/2))
# print(decimalToBinary(13))
# def flatten(arr):
# if arr == []:
# return arr
# if isinstance(arr[0], list):
# return flatten(arr[0]) + flatten(arr[1:])
# return arr[:1] + flatten(arr[1:])
# def sumof(n):
# if n == 0:
# return n
# return n + sumof(n-1)
# print(sumof(4))
def grid_path(n, m):
if n == 1 or m == 1:
return 1
return grid_path(n, m-1) + grid_path(n-1, m)
print(grid_path(4, 3))
|
1ef246ae2041d8c8b1cda75c6e637131b8002caf | David27XG/Train-Problems | /trainsproblem.py | 3,965 | 3.578125 | 4 | from railway import RailSystem, NoSuchRoute, NoSuchStation
"""Data for the examples.
Test Input:
For the test input, the towns are named using the first few letters of
the alphabet from A to D. A route between two towns (A to B) with a
distance of 5 is represented as AB5.
Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
"""
def example_railsystem():
railsystem = RailSystem()
# Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
railsystem.add_rail('A', 'B', 5)
railsystem.add_rail('B', 'C', 4)
railsystem.add_rail('C', 'D', 8)
railsystem.add_rail('D', 'C', 8)
railsystem.add_rail('D', 'E', 6)
railsystem.add_rail('A', 'D', 5)
railsystem.add_rail('C', 'E', 2)
railsystem.add_rail('E', 'B', 3)
railsystem.add_rail('A', 'E', 7)
return railsystem
"""Distances for fixed routes.
1. The distance of the route A-B-C.
2. The distance of the route A-D.
3. The distance of the route A-D-C.
4. The distance of the route A-E-B-C-D.
5. The distance of the route A-E-D.
Output: For test input 1 through 5, if no such route exists, output
'NO SUCH ROUTE'. Otherwise, follow the route as given; do not make
any extra stops! For example, the first problem means to start at
city A, then travel directly to city B (a distance of 5), then
directly to city C (a distance of 4).
"""
def example_trips():
trips = [
['A', 'B', 'C'],
['A', 'D'],
['A', 'D', 'C'],
['A', 'E', 'B', 'C', 'D'],
['A', 'E', 'D'] ]
return trips
def print_trip_distances(railsystem):
trips = example_trips()
for trip in trips:
print "Output #%d: " % (trips.index(trip)+1),
try:
distance = railsystem.distance_for_trip(trip)
except NoSuchStation:
print "Surprise!"
except NoSuchRoute:
print "NO SUCH ROUTE"
if distance:
print "%d" % (distance)
distance = 0
"""Distinguishing by stops.
6. The number of trips starting at C and ending at C with a maximum of
3 stops. In the sample data below, there are two such trips:
C-D-C (2 stops).
and C-E-B-C (3 stops).
7. The number of trips starting at A and ending at C with exactly 4
stops. In the sample data below, there are three such trips:
A to C (via B,C,D);
A to C (via D,C,D); and
A to C (via D,E,B).
"""
def print_trip_stops(railsystem):
trips = railsystem.find_trips_from_to('C', 'C', max_stops=4)
print "Output #6: %d" % len( list(trips) )
trips = railsystem.trips_with_stops('A', 'C', 4)
print "Output #7: %d" % len( list(trips) )
"""Shortest route examples.
8. The length of the shortest route (in terms of distance to travel) from A to C.
9. The length of the shortest route (in terms of distance to travel) from B to B.
10.The number of different routes from C to C with a distance of less
than 30. In the sample data, the trips are:
CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.
"""
def print_shortest_trips(railsystem):
a_to_c = railsystem.shortest_from_to('A', 'C')
print "Output #8: %d" % a_to_c.distance()
b_to_b = railsystem.shortest_from_to('B', 'B')
print "Output #9: %d" % b_to_b.distance()
def print_distance_trips(railsystem):
trips = railsystem.find_trips_from_to('C', 'C', max_distance=30-1)
print "Output #10: %d" % len( list(trips) )
"""Outputs.
Expected Output:
Output #1: 9
Output #2: 5
Output #3: 13
Output #4: 22
Output #5: NO SUCH ROUTE
Output #6: 2
Output #7: 3
Output #8: 9
Output #9: 9
Output #10: 7
"""
if __name__ == '__main__':
"""Call each of the sections to answer the ThoughtWorks problem."""
railsystem = example_railsystem()
print_trip_distances(railsystem)
print_trip_stops(railsystem)
print_shortest_trips(railsystem)
print_distance_trips(railsystem)
|
bf87bfb3e34363db827155d6c25b3745594a9a27 | raj-andy1/mypythoncode | /AnandthirthRajagopalan_Homework5.py | 824 | 4.0625 | 4 | """
Homework5 - Anandthirth Rajagopalan
"""
total = 0
myNumList = []
while True:
userNum = input("Enter a number:")
if userNum == '':
break
try:
userNum = float(userNum)
except:
print("That's not an integer")
continue
myNumList.append(userNum)
#print (myNumList)
#print (len(myNumList))
#Calculate total of all numbers and print each number
for num in myNumList:
print (num)
total += num
avg = total / len(myNumList)
#Calculate least number
minNm = myNumList[0]
for num in myNumList:
if num < minNm:
minNm = num
#Calculate largets number
maxNm = myNumList[0]
for num in myNumList:
if num > maxNm:
maxNm = num
print ("Total is",total)
print ("Average is",avg)
print ("Least number is",minNm)
print ("Greatest number is",maxNm)
print ("OK Bye")
|
25891f02b31468e6d4f25b595fae6ef3e9620c74 | Jashwanth-k/Data-Structures-and-Algorithms | /11. Graphs/DFS code .py | 1,517 | 3.515625 | 4 |
class Graph:
def __init__(self,nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)]for i in range(nVertices)] #same as 2D array
def addEdge(self,v1,v2):
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def removeEdge(self,v1,v2):
if self.containsEdge(v1,v2) is False:
return 'Edge is Absent'
self.adjMatrix[v1][v2] = 0
self.adjMatrix[v2][v1] = 0
return 'removed'
def containsEdge(self,v1,v2):
return True if self.adjMatrix[v1][v2] > 0 else False
def __str__(self):
return str(self.adjMatrix)
def __dfsHelper(self,sv,visited): #sv is starting vertex
print(sv,end=' ')
visited[sv] = True
for i in range(self.nVertices):
if self.containsEdge(sv,i) > 0 and visited[i] is False:
self.__dfsHelper(i,visited)
def dfs(self):
visited = [False]*self.nVertices
self.__dfsHelper(0,visited)
def takeinputGraph(self,E):
for i in range(E):
l = [int(ele) for ele in input().split()]
i = 0
j = 1
if len(l) <= 1:
break
g.addEdge(l[i],l[j])
inputlist = [int(ele) for ele in input().split()]
V,E = inputlist[0],inputlist[1]
g = Graph(V)
g.takeinputGraph(E)
g.dfs()
'''g = Graph(5)
g.addEdge(0,1)
g.addEdge(1,3)
g.addEdge(2,4)
g.addEdge(2,3)
'''
|
a56d322336ea2ffdf874925beb192b4d83d6e701 | MapsaBootCamp/django5 | /Algorithm_Section/sorting/merge-sort.py | 739 | 4.1875 | 4 | def merge_sort(arr):
middle_len = len(arr) // 2
if len(arr) > 1:
left = arr[:middle_len]
right = arr[middle_len:]
left = merge_sort(left)
right = merge_sort(right)
arr = []
print("left: ", left)
print("right: ", right)
while len(left) > 0 and len(right) > 0:
if left[0] > right[0]:
arr.append(right[0])
right.pop(0)
else:
arr.append(left[0])
left.pop(0)
for elm in left:
arr.append(elm)
for elm in right:
arr.append(elm)
return arr
# arr = [3, 5, 9, 1, 0, 10, 78, 125, -1, 0, 18]
arr = [3, 7, 1]
print(arr)
print(merge_sort(arr))
|
1e96e2a651e0fbc0908f6643943768cc63ef4625 | adam-weiler/GA-OOP-Inheritance-Part-3 | /system.py | 2,367 | 4.03125 | 4 | class System():
all_bodies = [] #Stores all bodies from every solar system.
def __init__(self, name):
self.name = name
self.bodies = [] #Stores only bodies from this solar system.
def __str__(self):
return f'The {self.name} system.'
def add(self, celestial_body):
if celestial_body not in self.bodies: #Checks if celestial_body is not in the bodies list yet.
System.all_bodies.append(celestial_body)
self.bodies.append(celestial_body)
return f'Adding {celestial_body.name} to the {self.name} system.'
else:
return f'You can\'t add {celestial_body.name} again.'
def list_all(self, body_type):
for body in self.bodies: #Iterates through each body in self.bodies list.
if isinstance(body, body_type): #If current body is of body_type. ie: Planet.
print(body) #Prints the class-specific __str__ method.
@classmethod
def total_mass(cls):
total_mass = 0
for body in cls.all_bodies:
total_mass += body.mass
return total_mass
class Body():
def __init__(self, name, mass):
self.name = name
self.mass = mass
@classmethod
def list_all(self, body_type):
for body in System.bodies: #Iterates through each body in System.bodies list.
if isinstance(body, body_type): #If current body is of body_type. ie: Planet.
print(body) #Prints the class-specific __str__ method.
class Planet(Body):
def __init__(self, name, mass, day, year):
super().__init__(name, mass)
self.day = day
self.year = year
def __str__(self):
return f'-{self.name} : {self.day} hours per day - {self.year} days per year - weighs {self.mass} kg.'
class Star(Body):
def __init__(self, name, mass, star_type):
super().__init__(name, mass)
self.star_type = star_type
def __str__(self):
return f'-{self.name} : {self.star_type} type star - weighs {self.mass} kg.'
class Moon(Body):
def __init__(self, name, mass, month, planet):
super().__init__(name, mass)
self.month = month
self.planet = planet
def __str__(self):
return f'-{self.name} : {self.month} days in a month - in orbit around {self.planet.name} - weighs {self.mass} kg.' |
f1dec1d21481e4e05b0e76ae8bf0a0041910232c | Jgoschke86/Jay | /Classes/py3intro/EXAMPLES/math_operators.py | 190 | 3.75 | 4 | #!/usr/bin/python3
x = 5
x += 10
y = 22
y *= 3
z = 98.7
print("x is ",x)
print("y is ",y)
print("2^16",2**16)
print("x / y",x/y)
print("x // y",x//y)
print("x / z",x/z)
print("x // z",x//z)
|
983ec2073a864c41d8786853f77ca5e632148828 | qinzhouhit/leetcode | /subsets/95generateTrees.py | 1,447 | 3.640625 | 4 | '''
keys:
Solutions:
Similar: 96
T: n*G
S: n*G, G as the Catalan number G(n) = 4^n / (n^(3/2))
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# Estimated time complexity will be O(n*2^n) but the actual time complexity
# O(4^n/sqrt(n)) is bounded by the Catalan number and is beyond the scope of a coding interview. See more details here.
def generateTrees(self, n: int): # -> List[TreeNode]
def helper(start, end):
if start > end:
return [None,]
all_trees = []
for i in range(start, end+1): # pick up a root
# all possible left subtrees if i is chosen to be a root
left_trees = helper(start, i-1)
# all possible right subtrees if i is chosen to be a root
right_trees = helper(i+1, end)
# connect left and right subtrees to the root i
for l in left_trees:
for r in right_trees:
current_tree = TreeNode(i)
current_tree.left = l
current_tree.right = r
all_trees.append(current_tree)
return all_trees
return helper(1, n) if n else []
sol = Solution()
print (sol.generateTrees(3))
|
13192fb881efa7d327182876f729dd29ba1776d4 | gourav47/Let-us-learn-python | /8 simple interest and addition.py | 288 | 3.90625 | 4 | p=input("Enter principle amount: ")
r=input("Enter rate of interest: ")
t=input("Enter the time: ")
si=float(p)*float(r)*float(t)/100
print("simple interest is:", si)
x=input('Enter 1st number: ')
y=input('Enter 2nd number: ')
z=int(x)+int(y)
print('sum of two number is: ',z)
|
3ae1e409a87c5500a9267fef6742009191ea9b23 | EmyTest/untitled5 | /pr.py | 354 | 3.984375 | 4 | import practise
def main():
x = float(input("enter x-coordinate of point: "))
y = float(input("enter y-coordinate of point: "))
z = float(input("enter z-coordinate of point: "))
h = float(input("enter h-coordinate of point: "))
p=practise.Point(x,y,z,h)
print("distance from origin:{0:,.2f}".format(p.distanceFromOrigin()))
main() |
5b02830b73b56e68d91bd98bb8e05ad8972095df | boniaditya/scraping | /SoupTest.py | 607 | 3.546875 | 4 | import urllib2
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = urllib2.urlopen(url)
except urllib2.HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html.read())
title = bsObj.body.h1
except AttributeError as e:
return None
return title
title = getTitle("http://www.pythonscraping.com/pages/pages/page1.html")
if title == None:
print("Title could not be found")
else:
print(title)
html=urllib2.urlopen("https://docs.python.org/3.5/howto/urllib2.html")
bsObj = BeautifulSoup(html.read(),"html.parser")
print(bsObj.h1)
|
8d7539f982fd59911afbef3ddb39f47a9b363cc2 | nikhilbommu/DS-PS-Algorithms | /Leetcode/LeetCode Problems/NumberofStepstoReduceaNumbertoZero.py | 275 | 3.53125 | 4 | class Solution:
def numberOfSteps (self, num):
count=0
while num != 0 :
if num%2 == 0:
num = num//2
else:
num -= 1
count += 1
return count
s = Solution()
print(s.numberOfSteps(6)) |
371f213a07011e44095ec0d14c4fbb9d4f84bcf7 | Xzib/piaic | /nested_loops.py | 390 | 3.578125 | 4 | # my_list = [1,2,3,4,5,6,7,8,9,10]
# for val in my_list:
# count = len(my_list)
# item = val*2
# list_2=item
# print(list_2)
# for i in my_list:
# for x in range(4):
# print(i,x)
user_val = int(input('Énter value one: '))
user_val_1 = int(input('Énter value two: '))
for i in range(user_val,user_val_1+1):
for x in range(11):
print (i*x,end=" ")
|
e8bf3b7b3a4f37a80f65580316565b294e5caa4d | devsantoss/lambda | /EjerMuerteSubita.py | 1,359 | 3.921875 | 4 | """
@author: David S
1. Usando map extraer de una lista de listas el primer y ultimo elemento de cada
lista
2. Dada una lista de numeros enteros, usando map y filter retornar una lista con
los numeros superpares(Todos los digitos son pares)
3. Usando reduce y map extraer los valores máximos de cada lista de una lista
de listas
4. Usando reduce, map y filter extraer los valores mínimos de cada lista de una
lista de listas que cumplen el concepto de número superpar
5. Usando map y filter retornar de una lista los valores menores a la potencia
5 de la cabeza de la lista
6.usando map, filter y/o reduce dada una lista de tuplas caracterizada por
(int x, int y) sumar los x que cumplan con el criterio de ser el número
triangular de y
"""
from functools import reduce
# Primer ejercicio
lista = [[55,1,2,3],[54,5]]
uno = list(map(lambda x: x[0], lista))
ultimo = list(map(lambda x: x[-1], lista))
print(uno + ultimo)
#Segundo ejercicio
lista2 = [10,5,15,22,33,48]
def superPares(lista):
x = list(filter(lambda x: x % 2 == 0, lista))
m = list(map(lambda y: y // 10, x))
return list(filter(lambda x: x % 2 == 0, m))
print(superPares(lista2))
# tercer ejercicio
f = lambda a,b: a if (a > b) else b
x = list(reduce(f, lista))
print(reduce(f, x))
#Cuarto ejercicio
f2 = lambda a,b: a if (a < b) else b
|
512042886111c1af160244b2f75c11184a87f659 | edward-murrell/robot | /robot/parser.py | 1,741 | 3.875 | 4 | from robot import Robot, Aim
class Parser:
"""
Parse lines into robot commands.
"""
def __init__(self, robot: Robot):
"""
Wrap a parser around a robot object.
:param robot: Constructed Robot object.
"""
self.__robot = robot
self.__map = {
'NORTH': Aim.NORTH,
'SOUTH': Aim.SOUTH,
'EAST': Aim.EAST,
'WEST': Aim.WEST
}
def read(self, line: str):
"""
Parse an input line.
This method assumes that lines of a file have been stripped of newlines.
:param line:
:return: None, or str if returned by REPORT commands.
"""
if line == 'MOVE':
self.__robot.move()
elif line == 'LEFT':
self.__robot.turn_left()
elif line == 'RIGHT':
self.__robot.turn_right()
elif line == 'REPORT':
return self.__robot.report()
elif line[:6] == 'PLACE ':
self.__place(line)
def __place(self, line: str):
"""
Call robot.place() with parameters if the parameters are valid.
This method assumes that the first six characters are 'PLACE '.
:param line: A line in the format 'PLACE X,Y,DIRECTION', where X & Y are positive integers, and DIRECTION is one
one of NORTH, SOUTH, EAST, WEST.
"""
parameters = line[6:].split(',')
if len(parameters) != 3:
return
if parameters[0].isdigit() and parameters[1].isdigit() and parameters[2] in self.__map:
x = int(parameters[0])
y = int(parameters[1])
facing = self.__map[parameters[2]]
self.__robot.place(x, y, facing)
|
84a369ef1fb43fa0d7330a568a009b3124f169e8 | Aasthaengg/IBMdataset | /Python_codes/p02686/s254604144.py | 1,150 | 3.9375 | 4 | from collections import namedtuple
Line = namedtuple('Line', ['lowest', 'end'])
def main():
N = int(input())
up_lines = []
down_lines = []
for i in range(N):
s = input()
now = 0
lowest = 0
for c in s:
if c == "(":
now += 1
else:
now -= 1
lowest = min(lowest, now)
if now > 0:
up_lines.append(Line(lowest, now))
else:
down_lines.append(Line(lowest-now, -now))
up_lines.sort(key=lambda line: -line.lowest)
down_lines.sort(key=lambda line: -line.lowest)
left = 0
for line in up_lines:
if left + line.lowest < 0:
print("No")
return
left += line.end
if left < 0:
print("No")
break
right = 0
for line in down_lines:
if right + line.lowest < 0:
print("No")
return
right += line.end
if right < 0:
print("No")
break
if left == right:
print("Yes")
else:
print("No")
if __name__ == "__main__":
main()
|
e85e04eaa3bce7a2487b579ac3c19598532f8dd9 | StuartJSquires/solar-system-sim | /class_definitions.py | 8,077 | 3.71875 | 4 | from read_input import read_body
from itertools import chain, imap
import numpy as np
import os
class Body(object):
"""This is the class used for all bodies. We might want to make subclasses
for different types of bodies at some point in the future.
Attributes:
name: the name of the body
parent: the name of the body that the orbital parameters of this body
are given relative to
mass: the mass of the body
"""
def __init__(self, filename, directory_name, parent = None, **params):
"""This function takes the list of body parameters from the input files
and uses them to create the body object with appropriate attributes.
Args:
filename: the name of the input file to use to create the body
"""
# Get the gravitational constant
G = params["GRAVITATIONAL_CONSTANT"]
# Read in the body params
file_path = os.path.join(directory_name, filename)
body_params = read_body(file_path)
self.name = body_params["name"]
self.parent_name = body_params["parent"] # Note this doesn't do anything
self.mass = body_params["mass"]
# Set these parameters only if the body isn't the top level
if parent is not None:
self.semimajor = body_params["semimajor"]
self.eccentricity = body_params["eccentricity"]
self.argument_of_periapsis = body_params["argument_of_periapsis"]
self.inclination = body_params["inclination"]
self.ascending_node_longitude = body_params["ascending_node_longitude"]
self.direction = body_params["direction"]
self.start = body_params["start"]
# If the body is the top level, it's the origin!
if parent == None:
self.velocity = np.zeros(3)
self.position = np.zeros(3)
else: # Otherwise, we need to initialize the position and velocity
# These are for shorthand
a = self.semimajor
e = self.eccentricity
M = parent.mass
# Get the magnitude of the position and velocity
if self.start == "periapsis":
velocity_magnitude = np.sqrt(((1 + e) * G * M) / ((1 - e) * a))
position_magnitude = a * (1 - e)
elif self.start == "apoapsis":
velocity_magnitude = np.sqrt(((1 - e) * G * M) / ((1 + e) * a))
position_magnitude = a * (1 + e)
else:
print "FATAL ERROR: INVALID START POSITION FOR", self.name
sys.exit("Stopping program.")
# Get angles for rotation transformation
angle_1 = np.radians(self.ascending_node_longitude)
angle_2 = np.radians(self.inclination)
angle_3 = np.radians(self.argument_of_periapsis)
# Calculate the direction vectors. Hopefully they're unit vectors...
# I hope I didn't make a mistake down here!
position_x_direction = ((np.cos(angle_1) *
np.cos(angle_2) *
np.cos(angle_3)) -
(np.sin(angle_1) *
np.sin(angle_2)))
position_y_direction = ((np.cos(angle_1) *
np.sin(angle_3)) +
(np.cos(angle_2) *
np.cos(angle_3) *
np.sin(angle_1)))
position_z_direction = np.cos(angle_3) * np.sin(angle_2)
position_direction = np.asarray([position_x_direction,
position_y_direction,
position_z_direction])
# Create position array
self.position = (position_magnitude * position_direction +
parent.position)
velocity_x_direction = (-(np.cos(angle_3) *
np.sin(angle_1)) -
(np.cos(angle_1) *
np.cos(angle_2) *
np.sin(angle_3)))
velocity_y_direction = ((np.cos(angle_1) *
np.cos(angle_3)) -
np.cos(angle_2) *
np.sin(angle_1) *
np.sin(angle_3))
velocity_z_direction = -np.sin(angle_2) * np.sin(angle_3)
velocity_direction = np.asarray([velocity_x_direction,
velocity_y_direction,
velocity_z_direction])
# Create velocity array
self.velocity = (velocity_magnitude * velocity_direction +
parent.velocity)
# Read in children
self.children = self.__init_children(directory_name, **params)
def __init_children(self, directory_name, **params):
# Get path to children folder
full_directory_name = os.path.join(directory_name, self.name)
# Check if children folder exists
if os.path.isdir(full_directory_name):
# Init children list
children = []
# Walk self.children directory
path, dirs, files = os.walk(full_directory_name).next()
if len(files) > 0:
for filename in files:
children.append(Body(filename, full_directory_name,
self, **params))
return children
else:
print "Directory", full_directory_name, "contains no files."
return None
else:
return None
def __iter__(self):
"""Implement the iterator protocol.
"""
if self.children is not None:
for body in chain(*imap(iter, self.children)):
yield body
yield self
class System():
"""A system is a collection of bodies/subsystems.
Attributes:
members: the list of members of the system
"""
def __init__(self, directory_name, **params):
"""This function should initialize a system given its directory name.
"""
# Initialize the time
self.time = params['BEGIN_TIME']
# Initialize the top level body list
self.members = []
# Walk top directory
full_directory_name = os.path.join("input_data", directory_name)
path, dirs, files = os.walk(full_directory_name).next()
# Make sure there is only one star!
if len(files) == 1 and len(dirs) == 1:
self.members.append(Body(files[0], full_directory_name,
parent = None, **params))
else:
print "Invalid number of stars or folder structure."
sys.exit()
def __iter__(self):
"""Implement the iterator protocol
"""
for body in chain(*imap(iter, self.members)):
yield body
def step(self, timestep, **params):
"""This function updates the system over a timestep using numerical
integration.
"""
if params["INTEGRATOR"] == 'verlet':
self.__verlet_step(timestep, **params)
self.time += timestep
def __verlet_step(self, timestep, **params):
"""
"""
G = params['GRAVITATIONAL_CONSTANT']
for body in list(iter(self)):
body.position += body.velocity * timestep / 2.0
for body in list(iter(self)):
body.sum_of_accelerations = np.zeros(3)
for interacting_body in list(iter(self)):
if interacting_body is not body:
distance = body.position - interacting_body.position
# print "Distance between", body.name, "and", interacting_body.name, "is", distance
acceleration = -(G * interacting_body.mass * distance /
(np.linalg.norm(distance) ** 3.0))
body.sum_of_accelerations += acceleration
for body in list(iter(self)):
body.velocity += body.sum_of_accelerations * timestep
body.position += body.velocity * timestep / 2.0 |
3e34e9f79401253a736881a6da0e0276a9b28f53 | kurakikyrakiujarod/python_ | /day47/05 多继承以及MRO顺序.py | 5,639 | 4.21875 | 4 | # 多继承以及MRO顺序
# 1. 单独调用父类的方法
class Parent(object):
def __init__(self, name):
print('parent的init开始被调用')
self.name = name
print('parent的init结束被调用')
class Son1(Parent):
def __init__(self, name, age):
print('Son1的init开始被调用')
self.age = age
Parent.__init__(self, name)
print('Son1的init结束被调用')
class Son2(Parent):
def __init__(self, name, gender):
print('Son2的init开始被调用')
self.gender = gender
Parent.__init__(self, name)
print('Son2的init结束被调用')
class Grandson(Son1, Son2):
def __init__(self, name, age, gender):
print('Grandson的init开始被调用')
Son1.__init__(self, name, age)
Son2.__init__(self, name, gender)
print('Grandson的init结束被调用')
# gs = Grandson('grandson', 12, '男')
# print('姓名:', gs.name)
# print('年龄:', gs.age)
# print('性别:', gs.gender)
# 运行结果
# Grandson的init开始被调用
# Son1的init开始被调用
# parent的init开始被调用
# parent的init结束被调用
# Son1的init结束被调用
# Son2的init开始被调用
# parent的init开始被调用
# parent的init结束被调用
# Son2的init结束被调用
# Grandson的init结束被调用
# 姓名: grandson
# 年龄: 12
# 性别: 男
# 2. 多继承中super调用有所父类的被重写的方法
class Parent(object):
def __init__(self, name, *args, **kwargs): # 为避免多继承报错,使用不定长参数,接受参数
print('parent的init开始被调用')
self.name = name
print('parent的init结束被调用')
class Son1(Parent):
def __init__(self, name, age, *args, **kwargs): # 为避免多继承报错,使用不定长参数,接受参数
print('Son1的init开始被调用')
self.age = age
super().__init__(name, *args, **kwargs) # 为避免多继承报错,使用不定长参数,接受参数
print('Son1的init结束被调用')
class Son2(Parent):
def __init__(self, name, gender, *args, **kwargs): # 为避免多继承报错,使用不定长参数,接受参数
print('Son2的init开始被调用')
self.gender = gender
super().__init__(name, *args, **kwargs) # 为避免多继承报错,使用不定长参数,接受参数
print('Son2的init结束被调用')
class Grandson(Son1, Son2):
def __init__(self, name, age, gender):
print('Grandson的init开始被调用')
# 多继承时,相对于使用类名.__init__方法,要把每个父类全部写一遍
# 而super只用一句话,执行了全部父类的方法,这也是为何多继承需要全部传参的一个原因
# super(Grandson, self).__init__(name, age, gender)
super().__init__(name, age, gender)
print('Grandson的init结束被调用')
# print(Grandson.__mro__)
# gs = Grandson('grandson', 12, '男')
# print('姓名:', gs.name)
# print('年龄:', gs.age)
# print('性别:', gs.gender)
# 运行结果
# (<class '__main__.Grandson'>, <class '__main__.Son1'>,
# <class '__main__.Son2'>, <class '__main__.Parent'>, <class 'object'>)
# Grandson的init开始被调用
# Son1的init开始被调用
# Son2的init开始被调用
# parent的init开始被调用
# parent的init结束被调用
# Son2的init结束被调用
# Son1的init结束被调用
# Grandson的init结束被调用
# 姓名: grandson
# 年龄: 12
# 性别: 男
# 注意
# 以上2个代码执行的结果不同
# 如果2个子类中都继承了父类,当在子类中通过父类名调用时,parent被执行了2次
# 如果2个子类中都继承了父类,当在子类中通过super调用时,parent被执行了1次
# 3. 单继承中super
class Parent(object):
def __init__(self, name):
print('parent的init开始被调用')
self.name = name
print('parent的init结束被调用')
class Son1(Parent):
def __init__(self, name, age):
print('Son1的init开始被调用')
self.age = age
super().__init__(name) # 单继承不能提供全部参数
print('Son1的init结束被调用')
class Grandson(Son1):
def __init__(self, name, age, gender):
print('Grandson的init开始被调用')
super().__init__(name, age) # 单继承不能提供全部参数
print('Grandson的init结束被调用')
# gs = Grandson('grandson', 12, '男')
# print('姓名:', gs.name)
# print('年龄:', gs.age)
# print('性别:', gs.gender)
# 运行结果
# Grandson的init开始被调用
# Son1的init开始被调用
# parent的init开始被调用
# parent的init结束被调用
# Son1的init结束被调用
# Grandson的init结束被调用
# 姓名: grandson
# 年龄: 12
# 总结
# super().__init__相对于类名.__init__,在单继承上用法基本无差
# 但在多继承上有区别,super方法能保证每个父类的方法只会执行一次,而使用类名的方法会导致方法被执行多次,具体看前面的输出结果
# 多继承时,使用super方法,对父类的传参数,应该是由于python中super的算法导致的原因,必须把参数全部传递,否则会报错
# 单继承时,使用super方法,则不能全部传递,只能传父类方法所需的参数,否则会报错
# 多继承时,相对于使用类名.__init__方法,要把每个父类全部写一遍, 而使用super方法,只需写一句话便执行了全部父类的方法,这也是为何多继承需要全部传参的一个原因
|
a158f7cd365f57f1251d879528232508d3d2cb73 | DreamisSleep/pySelf | /chap5/sum_all_with_default.py | 444 | 3.953125 | 4 | # 기본 매개변수와 키워드 매개변수를 활용해 범위의 정수를 더하는 함수
# 함수 선언
def sum_all(start=0, end=100, step=1):
# 변수 선언
output = 0
# 반복문을 돌려 숫자를 더한다.
for i in range(start, end+1, step):
output += i
# 리턴
return output
# 함수 호출
print("A.", sum_all(0, 100, 10))
print("B.", sum_all(end=100))
print("C.", sum_all(end=100, step=2)) |
890de0f72382467c74121042c435ff9cd854e953 | thatmatt24/Network-Security | /TEA_Encryption.py | 2,014 | 3.921875 | 4 | """
Tiny Encryption Algorithm (TEA):
Takes user inputs K0, K1, K2, K3, L0, R0 as strings,
converts to hexadecimal. Encrypts using two rounds
of blocks, resulting in L1 and R1, and L2 and R2.
With L2 and R2 representing the final results.
Author: Matt McMahon
Date: 9/1/19
"""
from ctypes import c_uint32 as u32
DELTAONE = 0x11111111
DELTATWO = 0x22222222
def main():
K = [""] * 4
L = [""] * 3
R = [""] * 3
for i in range(4):
K[i] = input("Please input K[%s] in Hex String (without " "0x" ")/: " % i)
for i in range(4):
K[i] = u32(int(K[i],16)).value
L[0] = input("Please input L[0] in Hex String (without " "0x" ")/: ")
R[0] = input("Please input R[0] in Hex String (without ""0x"")/: ")
L[1] = '00000000'
L[0] = u32(int(L[0], 16)).value
L[1] = u32(int(L[1], 16)).value
R[0] = u32(int(R[0], 16)).value
L[2] = R[1] = R[2] = L[1]
## encrypt
# Li= Ri-1 Ri= Li-1田F(Ri-1, K0, K1, δi) i=1
# Li+1= Ri Ri+1= Li田F(Ri, K2, K3, δi+1)
D = []
D.append(DELTAONE)
D.append(DELTATWO)
i = j = 1
while i < 3:
if i == 2:
j = 3
# L1 = R0, L2 = R1
L[i] = u32(R[i - 1]).value
# R[1] = L[0] + ((( R[0] << 4 ) + K[0] ) ^ (( R[0] >> 5 ) + K[1] ) ^ ( R[0] + DELTAONE ))
lshift = u32(R[i - 1] << 4).value
add1 = u32(lshift).value + K[j - 1]
rshift = u32(R[i - 1] >> 5).value
add2 = rshift + u32(K[j]).value
add3 = u32(R[i - 1]).value + D[i - 1]
xor1 = u32(add1).value ^ u32(add2).value
xor = u32(xor1).value ^ u32(add3).value
R[i] = u32(L[i - 1] + xor).value
i += 1
for i in range(len(L)):
L[i] = int(L[i])
L[i] = hex(L[i]).replace('0x', '').upper()
R[i] = int(R[i])
R[i] = hex(R[i]).replace('0x', '').upper()
print("L[{}] = {} R[{}] = {}".format(i,L[i],i,R[i]))
if __name__ == "__main__":
main()
|
9a756fc8eac6f99a6e95a7cbe9e99c04ce777eb0 | xpony/LearnPython | /filter.py | 2,078 | 4.25 | 4 | #filter( )函数 用于过滤序列。同样接收一个函数和一个序列,把传入的函数依次作用于每个元素,
#然后根据返回值是True还是False决定保留还是丢弃该元素。和map()一样返回的是Iterator
#例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1 # 判断是否为奇数
num = filter(is_odd, [1, 2, 3, 4, 5, 6, 10])
print(list(num))
#把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip() #strip()去除字符串首尾空格,对单个空格作用后,bool值为False
s = filter(not_empty, ['A', 'B', '', None, ' ']) # None的bool值为False
print(list(s))
#用filter求素数
#构造一个从3开始的奇数序列
def _odd_iter():
n = 1
while True:
n = n + 2
yield n #这是个一个生成器函数
#生成器函数可以用for循环来不断输入结果,也可以生成个对象,然后用next()函数返回下个值
#g = _odd_iter()
# print(next(g))
#定义一个帅选函数
def _not_divisible(n):
return lambda x: x % n > 0
# 再定义一个生成器,不断返回下一个素数
def primes():
yield 2
it = _odd_iter() #生成一个对象,其包括大于3的奇数
while True:
n = next(it) #返回序列的第一个数
yield n #返回素数
it = filter(_not_divisible, it) # 构造新序列
for n in primes(): # 打印100以内的素数:
if n < 100:
print(n)
else:
break
# 练习 数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
#教训!: 命名变量时千万不要用一些内置函数名,否则找找bug找到你哭
# 自然正整数生成函数
def _add_nums():
n = 10
while True:
yield n
n = n + 1
# 判断是否为回数
def number_h(n):
return str(n) == str(n)[::-1]
numbers = _add_nums() #生成自然是想序列的对象
nums = filter(number_h, numbers) # 生成回数序列
for n in nums: #打印出1000以内的回数
if n < 1000:
print(n)
else:
break |
d12cd79e67929b300c0a2ad4a45484a2be032e37 | aqc112420/meachine-learning | /Machine-learning/Adaboost/caogao.py | 132 | 3.671875 | 4 | a = [1,3,5,7,9,11,13,15]
for x in a:
for y in a:
for z in a:
if x + y + z ==30:
print(x,y,z) |
45e392d3cbcdd7d58bf033475786a5ed6f1c9d21 | rabeeaatif/Photo-Editing-using-Python | /image_operations.py | 15,814 | 3.9375 | 4 | from PIL import Image
import array as arr
import math
import copy
### Parent Class MyList and its Iterator ###
class MyListIterator:
''' Iterator class to make MyList iterable.
https://thispointer.com/python-how-to-make-a-class-iterable-create-iterator-class-for-it/
'''
def __init__(self, lst):
# MyList object reference
self._lst: MyList = lst
# member variable to keep track of current index
self._index: int = 0
def __next__(self):
''''Returns the next value from the stored MyList instance.'''
if self._index < len(self._lst):
value = self._lst[self._index]
self._index += 1
return value
# End of Iteration
raise StopIteration
class MyList:
'''A list interface.'''
def __init__(self, size: int, value=None) -> None:
"""Creates a list of the given size, optionally intializing elements to value.
The list is static. It only has space for size elements.
Args:
- size: size of the list; space is reserved for these many elements.
- value: the optional initial value of the created elements.
Returns:
none
"""
self.size = size
def __len__(self) -> int:
'''Returns the size of the list. Allows len() to be called on it.
Ref: https://stackoverflow.com/q/7642434/1382487
Args:
Returns:
the size of the list.
'''
pass
def __getitem__(self, i: int):
'''Returns the value at index, i. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index from which to retrieve the value.
Returns:
the value at index i.
'''
# Ensure bounds.
assert 0 <= i < len(self),\
f'Getting invalid list index {i} from list of size {len(self)}'
pass
def __setitem__(self, i: int, value) -> None:
'''Sets the element at index, i, to value. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index of the elemnent to be set
- value: the value to be set
Returns:
none
'''
# Ensure bounds.
assert 0 <= i < len(self),\
f'Setting invalid list index {i} in list of size {self.size()}'
pass
def __iter__(self) -> MyListIterator:
'''Returns an iterator that allows iteration over this list.
Ref: https://thispointer.com/python-how-to-make-a-class-iterable-create-iterator-class-for-it/
Args:
Returns:
an iterator that allows iteration over this list.
'''
return MyListIterator(self)
def get(self, i: int):
'''Returns the value at index, i.
Alternate to use of indexing syntax.
Args:
- i: the index from which to retrieve the value.
Returns:
the value at index i.
'''
return self[i]
def set(self, i: int, value) -> None:
'''Sets the element at index, i, to value.
Alternate to use of indexing syntax.
Args:
- i: the index of the elemnent to be set
- value: the value to be set
Returns:
none
'''
self[i] = value
"*****************************************************************************************************"
### ArrayList using python array module ###
class ArrayList(MyList):
def __init__(self, size: int, value=None) -> None:
"""Creates a list of the given size, optionally intializing elements to value.
The list is static. It only has space for size elements.
Args:
- size: size of the list; space is reserved for these many elements.
- value: the optional initial value of the created elements.
Returns:
none
"""
#Arraylist size saved
self.size = size
# Array initialized
lst = []
for i in range(0, size):
for j in range(len(value)):
lst.append(value[j])
self.lst = arr.array('i', lst)
def __len__(self) -> int:
'''Returns the size of the list. Allows len() to be called on it.
Ref: https://stackoverflow.com/q/7642434/1382487
Args:
Returns:
the size of the list.
'''
return (self.size)
def __getitem__(self, i: int):
'''Returns the value at index, i. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index from which to retrieve the value.
Returns:
the value at index i.
'''
# Ensure bounds.
assert 0 <= i < len(self.lst),\
f'Getting invalid list index {i} from list of size {len(self)}'
return ((self.lst[i*3], self.lst[(i*3)+1], self.lst[(i*3)+2]))
def __setitem__(self, i: int, value) -> None:
'''Sets the element at index, i, to value. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index of the elemnent to be set
- value: the value to be set
Returns:
none
'''
# Ensure bounds.
assert 0 <= i < len(self.lst),\
f'Setting invalid list index {i} in list of size {self.size()}'
self.lst[(i*3)] = value[0]
self.lst[(i*3)+1] = value[1]
self.lst[(i*3)+2] = value[2]
"*****************************************************************************************************"
### PointerList using singlely link list ###
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class PointerList(MyList):
'''A list interface'''
def __init__(self, size: int, value=None) -> None:
"""Creates a list of the given size, optionally intializing elements to value.
The list is static. It only has space for size elements.
Args:
- size: size of the list; space is reserved for these many elements.
- value: the optional initial value of the created elements.
Returns:
none
"""
self.size = size
self.header = Node(value)
temp = self.header
for i in range(0, size):
temp.next = Node(value)
temp = temp.next
def __len__(self) -> int:
'''Returns the size of the list. Allows len() to be called on it.
Ref: https://stackoverflow.com/q/7642434/1382487
Args:
Returns:
the size of the list.
'''
return self.size
def __getitem__(self, i: int):
'''Returns the value at index, i. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index from which to retrieve the value.
Returns:
the value at index i.
'''
# Ensure bounds.
assert 0 <= i < len(self),\
f'Getting invalid list index {i} from list of size {len(self)}'
temp = self.header
for i in range(1, i):
if temp.next != None:
temp = temp.next
return (temp.data)
def __setitem__(self, i: int, value) -> None:
'''Sets the element at index, i, to value. Allows indexing syntax.
Ref: https://stackoverflow.com/a/33882066/1382487
Args:
- i: the index of the elemnent to be set
- value: the value to be set
Returns:
none
'''
# Ensure bounds.
assert 0 <= i < len(self),\
f'Setting invalid list index {i} in list of size {self.size()}'
temp = self.header
for i in range(1, i):
if temp.next != None:
temp = temp.next
temp.data = value
"*****************************************************************************************************"
### MyImage Class ###
class MyImage:
""" Holds a flattened RGB image and its dimensions.
"""
def __init__(self, size: (int, int), pointer = False) -> None:
"""Initializes a black image of the given size.
Args:
- size: (width, height) specifies the dimensions to create.
Returns:
none
"""
# Save size, create a list of the desired size with black pixels.
width, height = self.size = size
self.pointer = pointer
if pointer == True:
self.pixels: PointerList = PointerList(width * height, value=(0, 0, 0))
else:
self.pixels: ArrayList = ArrayList(width * height, value=(0 , 0, 0))
# ^ CHANGE this line to use your implementation of MyList.
def _get_index(self, r: int, c: int) -> int:
"""Returns the list index for the given row, column coordinates.
This is an internal function for use in class methods only. It should
not be used or called from outside the class.
Args:
- r: the row coordinate
- c: the column coordinate
Returns:
the list index corresponding to the given row and column coordinates
"""
# Confirm bounds, compute and return list index.
width, height = self.size
assert 0 <= r < height and 0 <= c < width, "Bad image coordinates: "\
f"(r, c): ({r}, {c}) for image of size: {self.size}"
return r*width + c
def open(path: str, pointer = False) :
"""Creates and returns an image containing from the information at file path.
The image format is inferred from the file name. The read image is
converted to RGB as our type only stores RGB.
Args:
- path: path to the file containing image information
Returns:
the image created using the information from file path.
"""
# Use PIL to read the image information and store it in our instance.
img: PIL.Image = Image.open(path)
myimg: MyImage = MyImage(img.size, pointer)
width, height = img.size
# Covert image to RGB. https://stackoverflow.com/a/11064935/1382487
img: PIL.Image = img.convert('RGB')
# Get list of pixel values (https://stackoverflow.com/a/1109747/1382487),
# copy to our instance and return it.
for i, rgb in enumerate(list(img.getdata())):
myimg.pixels.set(i, rgb)
return myimg
def save(self, path: str) -> None:
"""Saves the image to the given file path.
The image format is inferred from the file name.
Args:
- path: the image has to be saved here.
Returns:
none
"""
# Use PIL to write the image.
img: PIL.Image = Image.new("RGB", self.size)
img.putdata([rgb for rgb in self.pixels])
img.save(path)
def get(self, r: int, c: int) -> (int, int, int):
"""Returns the value of the pixel at the given row and column coordinates.
Args:
- r: the row coordinate
- c: the column coordinate
Returns:
the stored RGB value of the pixel at the given row and column coordinates.
"""
return self.pixels[self._get_index(r, c)]
def set(self, r: int, c: int, rgb: (int, int, int)) -> None:
"""Write the rgb value at the pixel at the given row and column coordinates.
Args:
- r: the row coordinate
- c: the column coordinate
- rgb: the rgb value to write
Returns:
none
"""
self.pixels[self._get_index(r, c)] = rgb
def show(self) -> None:
"""Display the image in a GUI window.
Args:
Returns:
none
"""
# Use PIL to display the image.
img: PIL.Image = Image.new("RGB", self.size)
img.putdata([rgb for rgb in self.pixels])
img.show()
"*****************************************************************************************************"
### Image Operations ###
def remove_channel(src: MyImage, red: bool = False, green: bool = False,
blue: bool = False) -> MyImage:
"""Returns a copy of src in which the indicated channels are suppressed.
Suppresses the red channel if no channel is indicated. src is not modified.
Args:
- src: the image whose copy the indicated channels have to be suppressed.
- red: suppress the red channel if this is True.
- green: suppress the green channel if this is True.
- blue: suppress the blue channel if this is True.
Returns:
a copy of src with the indicated channels suppressed.
"""
new_image = copy.copy(src)
# Saving the list size to iterate
length = new_image.size[0] * new_image.size[1]
for i in range(0, length):
if green == True:
new_image.pixels[i] = (new_image.pixels[i][0], 0, new_image.pixels[i][2])
if blue == True:
new_image.pixels[i] = (new_image.pixels[i][0], new_image.pixels[i][1], 0)
if red == True:
new_image.pixels[i] = (0, new_image.pixels[i][1], new_image.pixels[i][2])
if blue == False and green == False:
new_image.pixels[i] = (0, new_image.pixels[i][1], new_image.pixels[i][2])
return new_image
# Rotation function for square images only
def rotations(src: MyImage) -> MyImage:
"""Returns an image containing the 4 rotations of src.
The new image has twice the dimensions of src. src is not modified.
Args:
- src: the image whose rotations have to be stored and returned.
Returns:
an image twice the size of src and containing the 4 rotations of src.
"""
new_image = MyImage((2*src.size[0], 2*src.size[1]), src.pointer)
# vertical = width and horizontal = height
width = new_image.size[0]
height = new_image.size[1]
for i in range(width):
for j in range(height):
# top left portion
if i < width//2 and j < height//2:
value = src.get(j, (width//2) - 1 - i)
new_image.set(i, j, value)
# top right portion
elif i < width//2 and j >= height//2:
value = src.get(i, j - (height//2))
new_image.set(i, j, value)
# bottom left portion
elif i >= width//2 and j < height//2:
value = src.get(width - 1 - i, (height//2) - 1 - j)
new_image.set(i, j, value)
# bottom right portion
elif i >= width//2 and j >= height//2:
value = src.get(height - 1 - j, i - (width//2))
new_image.set(i, j, value)
return (new_image)
# helper functions for masking
def file_read(maskfile : str):
mask = open(maskfile, 'r')
file_lst = list(mask.read())
loop = int(file_lst.pop(0))
file_lst.pop(0)
n = 0
lst = []
for i in range(loop):
lst.append([])
for i in range(0, loop):
for j in range(0, loop):
lst[i].append(int(file_lst[n]))
n += 2
mask.close()
return lst
def value_mask(src: MyImage, maskfile: str, average: bool = True):
"""Returns an copy of src with the mask from maskfile applied to it.
maskfile specifies a text file which contains an n by n mask. It has the
following format:
- the first line contains n
- the next n^2 lines contain 1 element each of the flattened mask
Args:
- src: the image on which the mask is to be applied
- maskfile: path to a file specifying the mask to be applied
- average: if True, averaging should to be done when valueing the mask
Returns:
an image which the result of valueing the specified mask to src.
"""
pass
|
609db306b29533fa346b56fe367ef86654bdfd26 | vippiv/python-demo | /demo/module/module1-demo.py | 576 | 3.765625 | 4 | # 模块,一个python文件就是一个模块,每个python都应该是可以导入的
# 导入模块时,python会搜索当前目录指定模块名的文件,如果有直接导入
# 如果没有,再搜索系统目录(由于存在这种行为,如果定义一个和系统模块重名的文件,将导致系统模块无效)
import m1
import m2
import random
m1.say_hello()
m2.say_hello()
c = m1.Cat()
print(c)
d = m2.Dog()
print(d)
print("+" * 100)
print("生成随机数")
print(random.randint(0, 10))
print("当前模块加载路径 %s" % random.__file__)
|
47c3857fc22632de47f97b6ddf6ab2207765a9d9 | asenyarb/Pool-Game | /ball.py | 7,041 | 3.671875 | 4 | from cfg import *
from vector import Vector
from utils import *
class Ball:
location: [int, int]
radius: float
mass: float
velocity: Vector
force: Vector
impulse: Vector
graphical_radius: int
chosen: bool
def __init__(self, add_to_balls_array: bool = False, location: (int, int) = (0, 0)):
# Ball properties
self.location = list(location)
self.mass = MASS
self.radius = RADIUS
# Dynamics
self.velocity = Vector()
self.force = Vector()
self.impulse = Vector()
self.graphical_radius = int(RADIUS * SCALE_COEFFICIENT)
self.chosen = False
# General
if add_to_balls_array:
BALLS.append(self)
def __str__(self):
return 'Ball:\n\tvelocity:' + str(self.velocity)
@property
def location_point(self):
return (int(self.location[0]), int(self.location[1]))
def apply_force(self, force: Vector):
"""Applies certain force to an object."""
self.force += force
def impulse_vector(self):
"""Calculates an impulse of an object."""
return self.velocity * self.mass
def kinetic_energy(self):
return self.mass * (self.velocity.x ** 2 + self.velocity.y ** 2) / 2 # ==self.velocity.magnitude**2 / 2
# def potential_energy(self):
# return (self.location.y - border_bot) * self.mass * cfg.G
def energy(self):
return self.kinetic_energy() # + self.potential_energy()
def update_velocity(self):
"""Updates body's velocity and forces."""
self.velocity += self.force * MOTION_SPEED / (1000 * self.mass)
self.force = Vector()
def update(self):
"""Fully updates object's state."""
self.update_velocity()
self.location[0] += int(self.velocity.x * MOTION_SPEED / 10)
self.location[1] += int(self.velocity.y * MOTION_SPEED / 10)
def friction(self, magnitude):
"""Applies a force with a given magnitude directing backwards relative to the current velocity."""
friction = self.velocity.copy() # The main goal is to get direction
friction.set_magnitude(-magnitude)
self.apply_force(friction)
def two_moving_balls_collision(self, other_ball):
self_mass_coeff = (2 * other_ball.mass) / (self.mass + other_ball.mass)
other_mass_coeff = (2 * self.mass) / (self.mass + other_ball.mass)
self_center = Vector(self.location[0], self.location[1])
other_ball_center = Vector(other_ball.location[0], other_ball.location[1])
self_delta_distance_vector = self_center - other_ball_center
other_delta_distance_vector = other_ball_center - self_center
distance_square = (self_center - other_ball_center).magnitude() ** 2
self.velocity = self.velocity - self_delta_distance_vector * (
self_mass_coeff * (self.velocity - other_ball.velocity).dot(
self_delta_distance_vector) / distance_square)
other_ball.velocity = other_ball.velocity - other_delta_distance_vector * (
other_mass_coeff * (other_ball.velocity - self.velocity).dot(
other_delta_distance_vector) / distance_square)
def one_moving_ball_collision(moving_ball, staying_ball):
delta_location_vector = Vector(staying_ball.location[0] - moving_ball.location[0], -(staying_ball.location[1] - moving_ball.location[1]))
angle = acos(delta_location_vector.dot(Vector(1,0)) / delta_location_vector.magnitude())
staying_mass_coeff = (2 * moving_ball.mass / (moving_ball.mass + staying_ball.mass) *
sin(angle/2))
moving_mass_coeff = sqrt(moving_ball.mass ** 2 + staying_ball.mass ** 2 + 2 *
moving_ball.mass * staying_ball.mass * cos(angle)) / (
moving_ball.mass + staying_ball.mass)
print("\nBefore collision:\nStaying ball:\nx: ", staying_ball.velocity.x, "\ny: ", staying_ball.velocity.y)
print("Moving ball:\nx: ", moving_ball.velocity.x, "\ny: ", moving_ball.velocity.y)
print("\nAngle: ", angle)
staying_ball.velocity = moving_ball.velocity * staying_mass_coeff
moving_ball.velocity = moving_ball.velocity * moving_mass_coeff
print("\nAfter collision:\nStaying ball:\nx: ", staying_ball.velocity.x, "\ny: ", staying_ball.velocity.y)
print("Moving ball:\nx: ", moving_ball.velocity.x, "\ny: ", moving_ball.velocity.y, "\n\n")
def bounce_off_the_board(self, border, bigger, horizontal):
"""Applies bounce force. Literally flips object's speed around certain axis
(specified by horizontal/vertical values). Used to bounce off the walls & floor."""
if horizontal:
self.location[0] = border
self.location[0] -= GRAPHICAL_RADIUS if bigger else -GRAPHICAL_RADIUS
self.velocity = Vector(-self.velocity.x, self.velocity.y)
else:
self.location[1] = border
self.location[1] -= GRAPHICAL_RADIUS if bigger else -GRAPHICAL_RADIUS
self.velocity = Vector(self.velocity.x, -self.velocity.y)
clack()
def collide(self, other_ball) -> int:
in_move_beginning = 0
if self.velocity.magnitude():
in_move_beginning += 1
if other_ball.velocity.magnitude():
in_move_beginning += 1
delta: Vector = Vector(self.location[0] - other_ball.location[0], self.location[1] - other_ball.location[1])
d: float = delta.magnitude()
# Repositioning balls
if delta.x:
k = -delta.y/delta.x
new_delta = Vector()
new_delta.x = (GRAPHICAL_RADIUS * 2) / sqrt(k*k + 1)
new_delta.y = -k * new_delta.x
other_ball.location[0] = self.location[0] + new_delta.x
other_ball.location[1] = self.location[1] + new_delta.y
else:
other_ball.location[0] = self.location[0]
other_ball.location[1] = self.location[1] + delta.y
if in_move_beginning == 2:
self.two_moving_balls_collision(other_ball)
elif self.velocity.magnitude():
self.one_moving_ball_collision(other_ball)
else:
other_ball.one_moving_ball_collision(self)
clack()
in_move_end = 0
if self.velocity.magnitude() != 0:
in_move_end += 1
if other_ball.velocity.magnitude() != 0:
in_move_end += 1
in_move_change = in_move_end - in_move_beginning
return in_move_change
def render(self, color):
"""Renders a as a ball of a given color.
Attaches a velocity vector (multiplied by 15 for better visuals)."""
if self.chosen:
pygame.draw.circle(screen, color, self.location_point, self.graphical_radius, 4)
else:
pygame.draw.circle(screen, color, self.location_point, self.graphical_radius, 1)
# (self.velocity * 15).render(self.location, RED)
|
03e4892a9226b932874a12606fdb7dcaf7eed484 | iRobot2397/Discord_Bot | /Discord Bot.py | 2,359 | 4.34375 | 4 | def calculator():
operation = input("Which operation would you like to do(+, -, *, /): ")
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
whole = input("Would you like to round to a whole number(y/n): ")
#addition
if operation == "+":
number3 = number1 + number2
if whole == "y":
number3 = int(number3)
print("The answer is {}".format(number3))
else:
print("The answer is {}".format(number3))
#subtraction
elif operation == "-":
number3 = number1 - number2
if whole == "y":
number3 = int(number3)
print("The answer is {}".format(number3))
else:
print("Your answer is {}".format(number3))
#multiplaction
elif operation == "*":
number3 = number1 * number2
if whole == "y":
number3 = int(number3)
print("The answer is {}".format(number3))
else:
print("Your answer is {}".format(number3))
#division
elif operation == "/":
number3 = number1 / number2
if whole == "y":
number3 = int(number3)
print("The answer is {}".format(number3))
else:
print("Your answer is {}".format(number3))
else:
print("Your operation is invalid, please try again.")
calculator()
calculator()
again = input("Would you like to use the calculator again?(y/n): ").lower()
again = again.lower()
if again == "y":
print("Okay")
calculator()
again = input("Would you like to use the calculator again?(y/n): ").lower()
again = again.lower()
if again == "y":
print("Okay")
calculator()
again = input("Would you like to use the calculator again?(y/n): ").lower()
again = again.lower()
elif again == "n":
print("Thank you for using the calculator, I hope you come back!")
else:
print("Invalid input please try again.")
again = input("Would you like to use the calculator again?(y/n): ")
elif again == "n":
print("Thank you for using the calculator, I hope you come back!")
else:
print("Invalid input please try again.")
again = input("Would you like to use the calculator again?(y/n): ") |
2f09215dd2a91b7f5a1d4e3b2d6e572bd809dd28 | awhitney1/cmpt120Whitney | /IntroProgrammingLabs/madlib.py | 272 | 3.5625 | 4 | # Andrew Whitney
# Intro to Programming
adjective = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adverb = input("Enter an adverb: ")
print("Your MadLib:")
print("The", adjective, noun, verb, adverb, "under the quick red fox.")
|
4ee52a0c2d68fcab9090fb904ca2d451ee14466c | Iverance/leetcode | /505.the-maze-ii.py | 3,513 | 3.6875 | 4 | #
# [505] The Maze II
#
# https://leetcode.com/problems/the-maze-ii
#
# algorithms
# Medium (38.57%)
# Total Accepted: 8.6K
# Total Submissions: 22.4K
# Testcase Example: '[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]\n[0,4]\n[4,4]'
#
# There is a ball in a maze with empty spaces and walls. The ball can go
# through empty spaces by rolling up, down, left or right, but it won't stop
# rolling until hitting a wall. When the ball stops, it could choose the next
# direction.
#
# Given the ball's start position, the destination and the maze, find the
# shortest distance for the ball to stop at the destination. The distance is
# defined by the number of empty spaces traveled by the ball from the start
# position (excluded) to the destination (included). If the ball cannot stop at
# the destination, return -1.
#
# The maze is represented by a binary 2D array. 1 means the wall and 0 means
# the empty space. You may assume that the borders of the maze are all walls.
# The start and destination coordinates are represented by row and column
# indexes.
#
#
# Example 1
#
# Input 1: a maze represented by a 2D array
#
# 0 0 1 0 0
# 0 0 0 0 0
# 0 0 0 1 0
# 1 1 0 1 1
# 0 0 0 0 0
#
# Input 2: start coordinate (rowStart, colStart) = (0, 4)
# Input 3: destination coordinate (rowDest, colDest) = (4, 4)
#
# Output: 12
# Explanation: One shortest way is : left -> down -> left -> down -> right ->
# down -> right.
# The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.
#
#
#
#
#
# Example 2
#
# Input 1: a maze represented by a 2D array
#
# 0 0 1 0 0
# 0 0 0 0 0
# 0 0 0 1 0
# 1 1 0 1 1
# 0 0 0 0 0
#
# Input 2: start coordinate (rowStart, colStart) = (0, 4)
# Input 3: destination coordinate (rowDest, colDest) = (3, 2)
#
# Output: -1
# Explanation: There is no way for the ball to stop at the destination.
#
#
#
#
# Note:
#
# There is only one ball and one destination in the maze.
# Both the ball and the destination exist on an empty space, and they will not
# be at the same position initially.
# The given maze does not contain border (like the red rectangle in the example
# pictures), but you could assume the border of the maze are all walls.
# The maze contains at least 2 empty spaces, and both the width and height of
# the maze won't exceed 100.
#
#
#
class Solution(object):
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
destination = tuple(destination)
m = len(maze)
n = len(maze[0])
visited = {}
q = []
heapq.heappush(q, (0, tuple(start)))
def move(cur, offset):
i, j = cur
off_i, off_j = offset
step = 0
while -1<i+off_i<m and -1<j+off_j<n and maze[i+off_i][j+off_j] == 0:
i += off_i
j += off_j
step += 1
return step, (i, j)
while q:
steps, point = heapq.heappop(q)
if point in visited and visited[point] <= steps:
continue
visited[point] = steps
if point == destination:
return steps
for direction in [(1,0),(-1,0),(0,1),(0,-1)]: # up, down, right, left,
step, nextP = move(point, direction)
heapq.heappush(q, (steps+step, nextP))
return -1
|
be89a3d690370f7896d35a9ae9f090a5d0b77521 | jiinmoon/Python_Projects | /Code_Challenges/square_root.py | 343 | 3.75 | 4 | # Problem #18
def herons_method(x, n):
result = 1
for _ in range(0, n):
result = (result + x / result) / 2
return result
def main():
f = open('test_square_root.txt', 'r')
f.readline()
for line in f:
(x, n) = map(lambda x: int(x), line.strip().split())
print(herons_method(x, n))
if __name__ == '__main__':
main() |
9302c6df0084c15b44ed020a3f410c4cde0860f7 | nunoa94/Python-Simple-API | /app.py | 529 | 3.59375 | 4 | #import flask module from flask package.
#It is used to create instances of web applications.
from flask import Flask
#creating instance of web application
app = Flask(__name__)
#define the route
@app.route("/")
#define function that will be executed when we access the route above
def hello():
return "Hello World!"
#run flask app when app.py starts
if __name__ == '__main__':
#run app on port 8080
app.run(port=8080)
#setting the debug to true will print out any python errors on the webpage
#app.run(debug=True) |
bfe9d0427fe9c6946ccae5549a93d795a1a3d12a | yuyangzi/python_study | /src/basic/7-03.py | 233 | 3.515625 | 4 | `# for x in range(0, 10):
# print(x)
# for x in range(0, 1+9, 2):
# print(x, end= ' | ')
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# for x in a:
# if x % 2 == 0:
# print(a[x])
print(len(a))
b = a[0:len(a):2]
print(b) |
bbe0d2cf910fb3f5ebd049fe5b26bf40e4de9d8b | rodolfocruzbsb/clean-jboss-tmp-directories | /Banco.py | 512 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#importando módulo do SQlite
import sqlite3
class Banco():
def __init__(self):
self.conexao = sqlite3.connect('favorites.db')
self.createTable()
def createTable(self):
c = self.conexao.cursor()
c.execute("""create table if not exists favorite_server (
id integer primary key autoincrement ,
default boolean not null,
fullpath text)""")
self.conexao.commit()
c.close() |
12e28ec2d8129ef34a3a589d6a745c946d1a9cb7 | KelwinKomka/JudgeProblems | /Python/1060.py | 422 | 3.65625 | 4 | a = float(input())
b = float(input())
c = float(input())
d = float(input())
e = float(input())
f = float(input())
positivo = 0
if (a > 0):
positivo = positivo + 1
if (b > 0):
positivo = positivo + 1
if (c > 0):
positivo = positivo + 1
if (d > 0):
positivo = positivo + 1
if (e > 0):
positivo = positivo + 1
if (f > 0):
positivo = positivo + 1
print("{} valores positivos".format(positivo))
|
fc893699e2ea2aa155f7d59ef2886f06c255b0c2 | MonstroVini/Spock1 | /Game.py | 2,123 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 15:46:30 2015
@author: viniciusra
"""
import random
print ('Vamos jogar?')
print ('Regras do jogo:')
print ('papel cobre pedra')
print ('papel refuta spock')
print ('spock vaporiza pedra')
print ('spock esmaga tesoura')
print ('tesoura corta papel')
print ('tesoura decapita lagarto')
print ('lagarto envenena spock')
print ('lagarto come papel')
print ('pedra quebra tesoura')
print ('pedra esmaga lagarto')
pontuacao_minha = 0
pontuacao_pc = 0
pp="papel"
p = 'pedra'
t = 'tesoura'
sp= 'spock'
l = 'lagarto'
computador = [pp, p, t, sp, l]
pedra=0
spock=0
lagarto=0
tesoura=0
papel=0
while pontuacao_minha != 3 and pontuacao_pc != 3:
x=raw_input('escolha sua opcao\n')
pc = random.choice(computador)
print ('o pc escolheu', pc)
if pc == pp and ( x == 'pedra' or x=='spock'):
pontuacao_pc +=1
print('vacilou!')
if pc == pp and (x == 'tesoura' or x == 'lagarto'):
pontuacao_minha +=1
print ('ae zika')
if pc == sp and (x == 'pedra' or x == 'tesoura'):
pontuacao_pc += 1
print ('putz')
if pc == sp and (x == 'lagarto' or x == 'papel'):
pontuacao_minha += 1
print('booa')
if pc == t and (x== 'papel' or x == 'lagarto'):
pontuacao_pc += 1
print ('vixee')
if pc == t and (x == 'pedra' or x == 'spock'):
pontuacao_minha += 1
print ('vai segurando!')
if pc == l and (x == 'spock' or x == 'papel'):
pontuacao_pc += 1
print ('deu ruim')
if pc == l and (x == 'pedra' or x == 'tesoura'):
pontuacao_minha += 1
print ('mlkao sem freio !')
if pc == p and (x == 'tesoura' or x == 'lagarto'):
pontuacao_pc += 1
print('que feio')
if pc == p and (x == 'papel' or x == 'spock'):
pontuacao_minha += 1
print ('olha isso')
if pontuacao_minha == 3 or pontuacao_pc == 3:
print ('o jogo terminou!')
print ('seu placar foi:', pontuacao_minha )
print ('o pc fez:', pontuacao_pc)
|
4ac9f33875709596c227c3dfb607fe3cad5dd167 | yusseef/Tkinter-simple-Calculator | /Tkinter Calculator.py | 996 | 4.09375 | 4 | from tkinter import *
def calculation():
number1=Entry.get(E1)
number2=Entry.get(E2)
operator=Entry.get(E3)
number1=int(number1)
number2=int(number2)
if operator=="+":
answer=number1+number2
if operator=="-":
answer=number1-number2
if operator=="*":
answer=number1*number2
if operator=="/":
answer=number1/number2
Entry.insert(E4,0,answer)
print(answer)
top = Tk()
L1 = Label(top, text="MY calculator").grid(row=0,column=0)
L2 = Label(top, text="number1").grid(row=1, column=0)
L3 = Label(top, text="number2").grid(row=2, column=0)
L4 = Label(top, text="operator").grid(row=3, column=0)
L5 = Label(top, text="answer").grid(row=4, column=0)
E1 = Entry(top, bd=5)
E1.grid(row=1, column=1)
E2 = Entry(top, bd=5)
E2.grid(row=2, column=1)
E3 = Entry(top, bd=5)
E3.grid(row=3, column=1)
E4 = Entry(top, bd=5)
E4.grid(row=4, column=1)
B = Button(top, text="calculate",command=calculation).grid(row=5, column=1)
top.mainloop()
|
4442b41065a8a470acfe0225555536c2613ca0ef | chandraprakashh/Data_Handling | /Day_1_revision_python/looping_concept.py | 1,171 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 11:09:14 2019
@author: BSDU
"""
"""Hands On 1
# Print all the numbers from 1 to 10 using condition in while loop
"""
"""
Hands On 3
# Print all the even numbers from 1 to 10 using condition in while loop
"""
"""
Hands On 5
# Print all the odd numbers from 1 to 10 using condition in while loop
"""
''' hands on 1 '''
# printing numbers with while loop
n = 1
while n <=10:
print(n)
n=n+1
# printing numbers with for loop
for i in range(1,11):
print(i)
""" hands on 3 """
# printing the numbers with while loop
j = 1
while (j<=10):
if j % 2 == 0:
print(j)
j = j+1
# printing the numbers with for loop
for k in range(1,11):
if k % 2 == 0:
print(k)
''' hands on 5 '''
# printing numbers using while loop
s = 1
while (s<=10):
if s % 2 ==1:
print(s)
s = s+1
# printing numbers using for loop
for a in range(0,11):
if a % 2 == 1:
print(a)
|
e8721e6742daa08d1f2e4c9e4bfc2e204d66109f | omerRabin/monitoring | /Manual.py | 2,413 | 3.609375 | 4 | import string
import datetime
class Manual:
def __init__(self, timestamp_a, timestamp_b):
self.timestamp_a = timestamp_a
self.timestamp_b = timestamp_b
self.year = datetime.date.today().year
# self.month = datetime.date.today().month
txt = open("serviceList.txt", 'r')
self.file_split = str(txt.read()).split("========================================")
self.file_stamp = []
index = 0
num = 0
for i in self.file_split:
if ":" in i or str(self.year) in i:
self.file_stamp.append(i)
def devide_to_samplings(self):
dict = {}
for i in self.file_split:
index1 = i.find("\ndate:")
index2 = i.find("\nHour:")
if index1 < 0 or index2 < 0:
continue
key1 = i[index1 + 7:index2]
# k = i.find("\n\n") # the first occurrence of \n\n
k = i.find("\n\nServices List")
key2 = i[index2 + 6:k]
date_and_hour = key1 + key2
dict[date_and_hour] = i
print(dict)
return dict
def closet_sampling_by_hour(self, l: list, hour: str):
hours = l
now = datetime.datetime.strptime(hour, "%H:%M:%S")
return min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M:%S")))
def closet_sampling_by_date(self, date_and_hour: str): # the format is 'date hour'
date = (date_and_hour.split(" "))[0]
hour = (date_and_hour.split(" "))[1]
d = self.devide_to_samplings()
l = []
for k1 in d.keys():
date_hour = k1.split(" ")
if date_hour[0] == date: # date is good
l.append(date_hour[1]) # add the hours that their dates are good
if len(l) == 0:
return None
close_hour = self.closet_sampling_by_hour(l, hour)
the_key = date + " " + close_hour
return d.get(the_key)
def main():
# add the case if none from the date to do on another date
date1 = "2021.5.24 18:32:40"
date2 = "2021.5.24 18:38:43"
file_stamp = Manual(date1, date2)
# file_stamp.file_by_stamp()
d = file_stamp.devide_to_samplings()
print(d)
s = file_stamp.closet_sampling_by_date(date1)
print(s)
if __name__ == "__main__":
main()
|
c2181b4682b93f830f432ca3a10f55696879e104 | joshurban5/Data-Structures-and-Algorithms | /BST_Test.py | 10,334 | 4.0625 | 4 | #################################################################
# Team Name: TheRevenant
# Binary Search Tree Unit Testing Class
# Project IV: Less Left, More Right
# CSCI 241: Data Structures and Algorithms
#################################################################
import unittest
from Binary_Search_Tree import Binary_Search_Tree
class BST_Test(unittest.TestCase):
"""Unit Testing Class for the Binary_Search_Tree Class"""
def setUp(self):
self._bst = Binary_Search_Tree()
# Testing Insert Element
def test_empty_tree(self):
# Testing to see what an empty tree returns
self.assertEqual('[ ]', str(self._bst), 'Empty list should print as "[ ]"')
self.assertEqual(0, self._bst.get_height())
def test_add_empty(self):
# Adding a value to an empty tree
self._bst.insert_element(12)
self.assertEqual('[ 12 ]', str(self._bst))
def test_add_empty_in_order(self):
# Adding a value to an empty tree and testing In-Order
self._bst.insert_element(12)
self.assertEqual('[ 12 ]', str(self._bst.in_order()))
def test_add_empty_pre_order(self):
# Adding a value to an empty tree and testing Pre-Order
self._bst.insert_element(12)
self.assertEqual('[ 12 ]', str(self._bst.pre_order()))
def test_add_empty_post_order(self):
# Adding a value to an empty tree and testing Post-Order
self._bst.insert_element(12)
self.assertEqual('[ 12 ]', str(self._bst.post_order()))
def test_add_two_empty(self):
# Adding 2 values to an empty tree
self._bst.insert_element(12)
self._bst.insert_element(7)
self.assertEqual('[ 7, 12 ]', str(self._bst))
def test_add_two_empty_in_order(self):
# Adding 2 values to an empty tree and testing In-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self.assertEqual('[ 7, 12 ]', str(self._bst.in_order()))
def test_add_two_empty_pre_order(self):
# Adding 2 values to an empty tree and testing Pre-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self.assertEqual('[ 12, 7 ]', str(self._bst.pre_order()))
def test_add_two_empty_post_order(self):
# Adding 2 values to an empty tree and testing Post-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self.assertEqual('[ 7, 12 ]', str(self._bst.post_order()))
def test_add_three_empty_order(self):
# Adding 3 values to an empty tree
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self.assertEqual('[ 3, 7, 12 ]', str(self._bst))
def test_add_three_empty_in_order(self):
# Adding 3 values to an empty tree and testing In-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self.assertEqual('[ 3, 7, 12 ]', str(self._bst.in_order()))
def test_add_three_empty_pre_order(self):
# Adding 3 values to an empty tree and testing Pre-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self.assertEqual('[ 12, 7, 3 ]', str(self._bst.pre_order()))
def test_add_three_empty_post_order(self):
# Adding 3 values to an empty tree and testing Post-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self.assertEqual('[ 3, 7, 12 ]', str(self._bst.post_order()))
def test_add_four_empty_order(self):
# Adding 4 values to an empty tree
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(20)
self.assertEqual('[ 3, 7, 12, 20 ]', str(self._bst))
def test_add_four_empty_in_order(self):
# Adding 4 values to an empty tree and testing In-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(20)
self.assertEqual('[ 3, 7, 12, 20 ]', str(self._bst.in_order()))
def test_add_four_empty_pre_order(self):
# Adding 4 values to an empty tree and testing Pre-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(20)
self.assertEqual('[ 12, 7, 3, 20 ]', str(self._bst.pre_order()))
def test_add_four_empty_post_order(self):
# Adding 4 values to an empty tree and testing Post-Order
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(20)
self.assertEqual('[ 3, 7, 20, 12 ]', str(self._bst.post_order()))
# Testing Remove Element
def test_remove_leaf_case_0(self):
self._bst.insert_element(12)
self._bst.remove_element(12)
self.assertEqual('[ ]', str(self._bst))
self.assertEqual(0, self._bst.get_height())
def test_remove_two_case_0(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.remove_element(12)
self._bst.remove_element(7)
self.assertEqual('[ ]', str(self._bst))
def test_remove_two_case_1(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.remove_element(7)
self._bst.remove_element(12)
self.assertEqual('[ ]', str(self._bst))
self.assertEqual(0, self._bst.get_height())
def test_remove_leaf_case_1(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(20)
self._bst.insert_element(30)
self._bst.insert_element(25)
self._bst.insert_element(16)
self._bst.remove_element(3)
self.assertEqual('[ 12, 7, 9, 20, 16, 30, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 9, 7, 16, 25, 30, 20, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 7, 9, 12, 16, 20, 25, 30 ]', str(self._bst.in_order()))
self.assertEqual(4, self._bst.get_height())
def test_remove_leaf_case_2(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(20)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(16)
self.assertEqual('[ 12, 7, 3, 9, 20, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 9, 7, 25, 20, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 7, 9, 12, 20, 25 ]', str(self._bst.in_order()))
self.assertEqual(3, self._bst.get_height())
def test_remove_case_right(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(20)
self._bst.insert_element(10)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(10)
self.assertEqual('[ 12, 7, 3, 9, 20, 16, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 9, 7, 16, 25, 20, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 7, 9, 12, 16, 20, 25 ]', str(self._bst.in_order()))
self.assertEqual(3, self._bst.get_height())
def test_remove_left(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(8)
self._bst.insert_element(20)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(8)
self.assertEqual('[ 12, 7, 3, 9, 20, 16, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 9, 7, 16, 25, 20, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 7, 9, 12, 16, 20, 25 ]', str(self._bst.in_order()))
self.assertEqual(3, self._bst.get_height())
def test_remove_two(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(8)
self._bst.insert_element(20)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(20)
self.assertEqual('[ 12, 7, 3, 9, 8, 25, 16 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 8, 9, 7, 16, 25, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 7, 8, 9, 12, 16, 25 ]', str(self._bst.in_order()))
self.assertEqual(4, self._bst.get_height())
def test_remove_two_children(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(8)
self._bst.insert_element(20)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(7)
self.assertEqual('[ 12, 8, 3, 9, 20, 16, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 9, 8, 16, 25, 20, 12 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 8, 9, 12, 16, 20, 25 ]', str(self._bst.in_order()))
self.assertEqual(3, self._bst.get_height())
def test_remove_root(self):
self._bst.insert_element(12)
self._bst.insert_element(7)
self._bst.insert_element(3)
self._bst.insert_element(9)
self._bst.insert_element(8)
self._bst.insert_element(20)
self._bst.insert_element(16)
self._bst.insert_element(25)
self._bst.remove_element(12)
self.assertEqual('[ 16, 7, 3, 9, 8, 20, 25 ]', str(self._bst.pre_order()))
self.assertEqual('[ 3, 8, 9, 7, 25, 20, 16 ]', str(self._bst.post_order()))
self.assertEqual('[ 3, 7, 8, 9, 16, 20, 25 ]', str(self._bst.in_order()))
self.assertEqual(4, self._bst.get_height())
if __name__ == '__main__':
unittest.main()
|
a17989a2004a69988f47225d29f29a6cb790fd0c | hnz71211/Python-Basis | /com.lxh/exercises/20_get_dict_value/__init__.py | 223 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 以列表形式返回字典 {‘Alice’: 20, ‘Beth’: 18, ‘Cecil’: 21} 中所有的值
dict = {'Alice': 20, 'Beth': 18, 'Cecil': 21}
L = list(dict.values())
print(L) |
82691c706c7b837cb8e86b947867610adbeb17cb | leighlondon/foobar | /when_it_rains_it_pours/solution.py | 4,285 | 3.8125 | 4 | """
The solution to the "when_it_rains_it_pours" problem.
"""
def answer(heights):
"""
The solution.
Move along the list of heights, starting at index 0, and search for a
local maxima (a 'peak').
If next neighbour to the right is higher, then discard the current peak
and move forward.
If next is lower, advance the "second peak" towards the next peak.
In the code below, the first peak is "left" and the second is "right".
Once the "right" peak has been found, the area between them needs to be
calculated. This needs to have the values of the slice between them, and
the heights of the peaks as well, to be able to find the "lowest" of the
two peaks and use this to find the missing spaces. Then sum this to the
total area value, and repeat.
"""
# Area starts at 0.
total_area = 0
# Alias the heights to make it easier to follow.
h = heights
# Start at the first (the "left" side).
i = 1
# Set the initial indexes for the "peaks".
left = 0
right = 0
# Defensive bounds checking.
if len(h) == 1:
return 0
# Continue along until we reach the end.
while i < len(h):
# If left is shorter, move forward.
if h[left] <= h[i]:
# If the next item is taller for the left scout,
# simply move along the left scout.
left = i
i = i + 1
# If left is taller, start the right scout.
elif h[left] > h[i]:
# Move the right scout forward until a peak greater
# or equal to the left scout is found, and then find
# the area in that slice.
#
# Once this is found, move the left scout to the right,
# and continue again.
#
# The initial value for the right peak is the trough value, i,
# so that we can check for better-but-not-best peaks.
right = i
# We start up another while loop, but this one has a chance to
# break- and we backtrack the i value as well, anyway.
while i < len(h):
if h[i] >= h[left]:
# An unambiguous peak, just break now. There are no
# better possible peaks for this trough.
right = i
break
elif h[i] >= h[right]:
# There's an ambiguous peak, we don't know if there's a
# better peak a few values further.
right = i
# It's neither a better peak nor the best peak, just keep
# moving forward.
i = i + 1
# Only run the area calculation if it's required.
# This can be for one of two reasons- an ambiguous peak was found
# and no better peak was found in the rest of the values,
# or an unambiguous peak was found. In each case, we can check
# by seeing if the 'right' peak value has changed from the
# initial value.
if right > left + 1:
area = calculate_area(h[left], h[right], h[left:right])
total_area = total_area + area
# Advance the left peak and then repeat. This can, in some cases,
# mean backtracking the current i pointer node. So we just set
# it to the generic case that covers both,
# "move forward the left, then move one further for i".
left = right
i = left + 1
# Pass back the total area.
return total_area
def calculate_area(left, right, heights):
"""
Calculating the area in a slice of numbers.
Needs to know the height of the border peaks and
the values of the slice.
"""
# Defensiveness.
if not heights:
return 0
# Figure out the lower of the two peaks.
lowest = left if left < right else right
# Start the running total.
total = 0
# Account for the first element being the left peak.
# Sub slice it further, calculate area for each column,
# and sum them for the total area in this section.
for element in heights[1:]:
total = total + (lowest - element)
# Return the total.
return total
|
d89f8866bd35dbc794de6c20e906284bb676d356 | Yashasvii/Project-Euler-Solutions-hackerrank | /forProjectEuler/002.py | 594 | 3.90625 | 4 | """
Project Euler Problem 2
=======================
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
def fibonacci_sum():
i = 1
j = 2
sum = 0
while i < 4000000:
temp = i
i = j
j = j + temp
if i % 2 == 0:
sum += i
return sum
if __name__ == '__main__':
print(fibonacci_sum())
|
02ed404fc401f4d4544481dc429657073b7c936d | SergiodeGrandchant/introprogramacion | /practico/ejercicio3.py | 356 | 3.90625 | 4 | # https://bit.ly/36LtifW
dividendo = int(input("Dame el dividendo: "))
divisor = int(input("Dame el divisor: "))
cociente = dividendo // divisor
resto = dividendo % divisor
if dividendo % divisor == 0:
print("La division dada es exacta")
else:
print("La division dada no es exacta")
print("El cociente es: ", cociente)
print("El resto es: ", resto) |
fe3c3d77c33c68e02b746af7f17450104b715b46 | qcgm1978/py-test | /test/others/args.py | 2,701 | 3.65625 | 4 | import unittest
class TestIs(unittest.TestCase):
def testArgs(self):
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
aList=[]
for arg in argv:
aList.append (arg)
return aList
self.assertListEqual(myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') ,['Hello', 'Welcome', 'to', 'GeeksforGeeks'])
def testFirstArg(self):
def myFun(arg1, *argv):
aList=[]
aList.append( arg1)
for arg in argv:
aList.append( arg)
return aList
bList=myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
self.assertEqual(bList, ['Hello', 'Welcome', 'to', 'GeeksforGeeks'])
def testKeywordArgs(self):
# *kargs for variable number of keyword arguments
def myFun(**kwargs):
alist=[]
for key, value in kwargs.items():
alist.append ("%s = %s" %(key, value))
return alist
# Driver code
self.assertItemsEqual(myFun(first = 'Geeks', mid = 'for', last = 'Geeks'),['first = Geeks', 'mid = for', 'last = Geeks'])
def testMixedKeywords(self):
# variable number of keyword arguments with
# one extra argument.
def myFun(arg1, **kwargs):
alist = []
alist.append(arg1)
for key, value in kwargs.items():
alist.append ("%s = %s" %(key, value))
return alist
# Driver code
blist=myFun("Hi", first ='Geeks', mid ='for', last='Geeks')
self.assertItemsEqual(blist,["Hi",'first = Geeks', 'mid = for', 'last = Geeks'])
def testCallByStar(self):
def myFun(arg1, arg2, arg3):
return (arg1,arg2,arg3)
# Now we can use *args or **kwargs to
# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
self.assertEqual(myFun(*args) ,args)
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"}
self.assertEqual(myFun(**kwargs) ,("Geeks", "for", "Geeks"))
def testMixed(self):
def myFun(*args, **kwargs):
alist=[]
alist.append("args: "+ str(args) )
alist.append("kwargs: "+str( kwargs) )
return alist
# Now we can use both *args ,**kwargs to pass arguments to this function :
self.assertEqual(myFun('geeks','for','geeks',first="Geeks",mid="for",last="Geeks") ,["args: ('geeks', 'for', 'geeks')","kwargs: {'last': 'Geeks', 'mid': 'for', 'first': 'Geeks'}"])
if __name__ == "__main__":
unittest.main()
|
ef177c1651a700ced2a8e7bafd3342c38f0873d2 | amitray1608/PCcodes | /python/while.py | 201 | 4.09375 | 4 | #18BCS2059
#AMIT KUMAR
'''
PROGRAM TO IMPLEMENT WHILE LOOP AND PRINT EVEN NUMBERS IN
A RANGE (1 - 20)
'''
n = 20;
i = 1
print("Even numbers in the range 1 - 20")
while i <= 20:
if(~i&1):
print(i)
i+=1
|
556b2fd6d7cbaffa3e6ff5ea60d23505e1b4fb2e | DillonCh/youtube_to_spotify | /custom/youtube_to_spotify.py | 3,319 | 3.921875 | 4 | """ Add Youtube liked songs to a playlist in Spotify
Tasks:
Step 1. log into youtube
Step 2. Get to liked videos
Step 3. Create a new playlist
Step 4. Search for the song in spotify
Step 5. Add the song to the new playlist
API's:
Youtube API
Spotify Web API
youtube-dl library
"""
from datetime import datetime as dt
import youtube_dl
from core.spotify import Spotify
from core.youtube import Youtube
class HttpError(Exception):
pass
class YoutubeToSpotify:
def __init__(self):
self.spotify = Spotify()
self.youtube = Youtube()
def enrich_youtube_liked_songs_with_spotify_data(self, n=50):
"""
:param n: if None then capture entirety of users liked videos
:return:
"""
# Get my last n liked videos
liked_video_data = self.youtube.get_liked_videos(n=n)
output = {}
for video in liked_video_data:
id = video['id']
youtube_url = f"https://www.youtube.com/watch?v={id}"
video_name = video['snippet']['title']
# Use the youtube_dl library to extract song_name and artist from the video
video = youtube_dl.YoutubeDL({}).extract_info(youtube_url, download=False)
song_name = video['track']
artist = video['artist']
if song_name is not None and artist is not None:
# Check if a song is found on Spotify
spotify_uri = self.spotify.get_track_uri(song_name=song_name, artist=artist)
if spotify_uri is not None:
output[video_name] = {
# Youtube information
'youtube_url': youtube_url,
'song_name': song_name,
'artist': artist,
# Youtube information used to get the Spotify song uri
'spotify_uri': spotify_uri
}
if len(output) > 0:
return output
def youtube_likes_to_spotify(self, playlist_name=None, youtube_videos_lookback=5):
# Capture youtube likes and add them to a new playlist or an existing one if <playlist_name> exists
playlist_id = None
if playlist_name is not None:
playlist_id = self.spotify.get_playlist_id(playlist_name)
if playlist_id is None:
print(f"Playlist with exact name: {playlist_name} not found\nA new one with this name will be created")
playlist_id = self.spotify.create_playlist(name=playlist_name)
if playlist_id is None:
playlist_name = "_new_{:%Y%m%d_%H%M}".format(dt.today())
print(f"A [laylist will be created with this name: {playlist_name}")
playlist_id = self.spotify.create_playlist(name=playlist_name)
song_data = self.enrich_youtube_liked_songs_with_spotify_data(n=youtube_videos_lookback)
uris = []
for song_name, song in song_data.items():
uris.append(song['spotify_uri'])
if len(uris) == 0:
return
response_json = self.spotify.add_song_to_playlist(playlist_id=playlist_id, uri=uris)
return response_json
if __name__ == "__main__":
yts = YoutubeToSpotify()
yts.youtube_likes_to_spotify(youtube_videos_lookback=10)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.