blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b772bc7a8556a4070ebf851945f161225e10e8c9 | anamariagds/listas_remoto | /semana7/eh_primo.py | 412 | 3.75 | 4 | def eh_primo(n):
inicio = 1
divisor = 0
while inicio<= n:
if n % inicio == 0:
divisor +=1
inicio +=1
return divisor
def main():
n =int(input("Digite um número: "))
d = eh_primo(n)
if d ==2:
print(f'O número {n} é Primo')
else:
print(f'O número {n} não é primo')
if __name__ == '__main__':
main()
|
1ce025f3c757223a58d45f1297c77792d2bc169a | anamariagds/listas_remoto | /semana7/H.py | 269 | 3.734375 | 4 | def somatorio():
n = int(input("Digite o valor de n: "))
i = 1
H = 1
while i <n:
i+=1
H += (1/i)
if i ==n:
break
print(f'O valor de H é {H:.4f}')
def main():
somatorio()
if __name__=='__main__':
main()
|
420a970d2a73a9219d5fad02ab0b01d825409e04 | anamariagds/listas_remoto | /projetos_pec166/semana8/ex3.py | 477 | 3.921875 | 4 | from random import *
print("Gerador de cumprimentos")
adjetivos = ['maravilhosa', 'acima da média', 'excelente', 'íncrivel', 'competente']
hobbies = ['andar de bicicleta', 'programar', 'fazer chá', 'em leitura', 'cantar']
nome = input("Qual é o seu nome?: ")
print("Aqui está o seu cumprimento", nome , ":")
#obtém item aleatório de ambas as listas e adiionaós ao cumprimento
print( nome, "você é", choice(adjetivos), "em", choice(hobbies),"!")
print("De nada!") |
ab1039cfe770712d7ab98a9b413765013c4e2c26 | anamariagds/listas_remoto | /semana8/maiorqmedialistasex.py | 463 | 3.640625 | 4 | def ler_notas(n):
notas = []
for i in range(n):
notas.append(float(input(f'Nota {i+1} de {n}: ')))
return notas
def media(notas):
return sum(notas)/len(notas)
def maiores_que(media, notas):
maiores = []
for nota in notas:
if nota > media:
maiores.append(nota)
return maiores
def main():
notas = ler_notas(7)
m = media(notas)
print(maiores_que(m, notas))
if __name__== '__main__':
main() |
2428a5c917bc1b5b99401b3461f7fe3e9b144c7c | anamariagds/listas_remoto | /projetos_pec166/testandopedac.py | 643 | 3.859375 | 4 |
score = 0
def q1(marcou):
if marcou.lower() == 'a':
global score
score = score+1
return f'Certa!'
elif marcou.lower() == 'b':
return f'Pense um pouco'
elif marcou.lower() == 'c':
return f'Estude mais!'
else:
return f'Você não escolheu uma alternativa válida.'
def main():
print(''' Que nome leva o movimento em que a Terra gira ao redor de sim mesma, ou seja, ao redor do seu próprio eixo?
a- Rotação
b - Translação
c - Precessão
''')
rspt = str(input())
r = q1(rspt)
print(r)
if __name__=='__main__':
main() |
f1073e9fd0b05a6ed68dd4efca274204ebcea20d | anamariagds/listas_remoto | /condicionais/evogal.py | 241 | 3.640625 | 4 | def vogal(l):
if l in 'a A e E i I o O u U':
return True
else:
return False
def main():
letra = str(input("Digite uma letra: "))
teste = vogal(letra)
print(teste)
if __name__ == '__main__':
main()
|
7579f7c27794f366b1d1e47b32f0b0f7e447683c | anamariagds/listas_remoto | /projetos_pec166/semana8/ex2.py | 328 | 3.546875 | 4 | from random import*
print("Gerador de Cumprimentos")
print("-------------------")
cumprimentos=["Excelente trabalho. Realmente muito bem feito.",
"Suas habilidades de programaçãp são muito, muito boas!",
"Você é um humano excelente"
]
print(choice(cumprimentos))
print("De nada!") |
28dce4905d8671b15c6175afdead6a90619ee16b | anamariagds/listas_remoto | /semana10/conversorparte3.py | 2,132 | 3.984375 | 4 | def menu():
print("trdtr de exprss")
print("="*13)
print("Menu: ")
print('''
c = converter uma frase
p = imprimir dicionário
a = adicionar uma palavra
d = remover uma palavra
q = sair
''')
def convertetxt(texto):
sentence = input("Insira uma frase: ").lower()
transformaFrase = ""
#remove pontuação
for char in '?!.,':
sentence = sentence.replace(char,'')
palavraTOlista = sentence.split()
#passa por cada palavra da lista
for palavra in palavraTOlista:
#adiciona a palavra traduzida caso ela exista no dicionário
if palavra in texto:
transformaFrase += texto[palavra] + " "
#mantém a palavra original caso não exista tradução
else:
transformaFrase += palavra + " "
print("==>")
print(transformaFrase)
def addDicionario(texto):
txtToAdd = input("Insere a expressão a ser adicionada ao dicionário: ")
signfcd = input("O que ela quer dizer? : ")
texto[txtToAdd]= signfcd
def deleteitem(texto):
txtTOdelete = input("Expressão pra remover: ")
#remove a expressão, se ela pertencer ao dicionário se não nada acontece
if txtTOdelete in texto.keys():
del texto[txtTOdelete]
else:
pass
def main():
texto = {
"rs" : "risos",
"tbm" : "também",
"vc" : "você",
"pq" : "porque"
}
running = True
menu()
#repete até que o usuário digite 'q' para sair
while running == True:
escolhaMenu = input(">_").lower()
#c para converter
if escolhaMenu == 'c':
convertetxt(texto)
#p para imprimir
elif escolhaMenu == 'p':
print(texto)
#a para adicionar
elif escolhaMenu == 'a':
addDicionario(texto)
#d para remover
elif escolhaMenu == 'd':
deleteitem(texto)
#q para sair
elif escolhaMenu == 'q':
running = False
else:
print("Escolha inválida")
if __name__=='__main__':
main() |
65926fa0c9bce1efd05487eab5df936a22f2a771 | anamariagds/listas_remoto | /condicionais/maisatual.py | 786 | 3.9375 | 4 | def recente(ano1, ano2, mes1, mes2, dia1, dia2):
if (ano1 > ano2) or (ano1 == ano2 and mes1>mes2) or (ano1 == ano2 and mes1==mes2 and dia1>dia2):
return f'{dia1}/{mes1}/{ano1}'
elif (ano2 > ano1) or (ano1 == ano2 and mes2 > mes1) or (ano1 == ano2 and mes2==mes1 and dia2>dia1):
return f'{dia2}/{mes2}/{ano2}'
elif ano1 == ano2 and mes1 == mes2 and dia1 == dia2:
return f'{dia2}/{mes2}/{ano2}'
def main():
dia1= int(input("Diga o dia: "))
mes1 = int(input("Diga o mês: "))
ano1 = int(input("Diga o ano: "))
dia2= int(input("Diga o dia: "))
mes2 = int(input("Diga o mês: "))
ano2 = int(input("Diga o ano: "))
atual = recente(ano1, ano2, mes1, mes2, dia1, dia2)
print(atual)
if __name__ == '__main__':
main()
|
1e36a8f36f30a8f4131ffa58c2c6664dc88bf76f | aefritz/fivethirtyeight-cafe-solution | /solution.py | 283 | 3.84375 | 4 | import math
iterator = 0
accumulator = 0.00000
while iterator <= 50:
accumulator += float(math.factorial(50 + iterator)*pow(.5, 50)*pow(.5,iterator)*(50-iterator)/(math.factorial(iterator)*math.factorial(50)))
iterator += 1
print("The expected value is " + str(accumulator))
|
af2c02c975c53c1bd12955b8bbe72bac35ab54fd | BryanBain/Statistics | /Python_Code/ExperimProbLawOfLargeNums.py | 550 | 4.1875 | 4 | """
Purpose: Illustrate how several experiments leads the experimental probability
of an event to approach the theoretical probability.
Author: Bryan Bain
Date: June 5, 2020
File: ExperimProbLawOfLargeNums.py
"""
import random as rd
possibilities = ['H', 'T']
num_tails = 0
num_flips = 1_000_000 # change this value to adjust the number of coin flips.
for _ in range(num_flips):
result = rd.choice(possibilities) # flip the coin
if result == 'T':
num_tails += 1
print(f'The probability of flipping tails is {num_tails/num_flips}')
|
76410773c1e3e749db0098d256f86f71e6ab9c05 | BryanBain/Statistics | /Python_Code/ttest1samp.py | 4,481 | 3.765625 | 4 | """
Purpose: Perform a t test for a one sample mean with user input.
Author: Bryan Bain
Date: July 10, 2020
File Name: ttest1samp.py
"""
import scipy.stats as stats
import math
import numpy as np
def obsToT(xbar, mu, sigma, n):
return (xbar-mu)/(sigma/math.sqrt(n))
quit = False
while not quit:
mu = input("Please enter the given population mean: ")
if mu == 'q': # quit the program
quit = True
break
significance = input("Please enter the significance level, as a decimal: ")
if significance == 'q': # quit the program
quit = True
break
mu = float(mu)
significance = float(significance)
print()
print("Is this a left-tailed, right-tailed, or two-tailed test?")
print("1. Left-tailed (Population Mean < Claimed Mean)")
print("2. Right-tailed (Population Mean > Claimed Mean)")
print("3. Two-tailed (Population Mean != Claimed Mean)")
left_right_two = input()
print("Are you given data or summary statitiscs? ")
print("1. Data set")
print("2. Summary statistics")
data_or_sum = input()
if data_or_sum == 'q': # quit the program
quit = True
elif data_or_sum == "1": # user will be manually entering a dataset
done = False
dataset = []
print("Please enter the data set. Press 'd' when done, and 'u' to undo.")
while not done:
element = input()
if element == 'd': # user is done entering data values
break
elif element == 'u': # undo the last data entry
dataset.pop()
print(dataset)
continue
elif element == 'q': # quit the program
quit = True
break
dataset.append(float(element)) # cast entry as a float and append to dataset
print(dataset) # prints dataset for user after entering each value
xbar = np.mean(dataset)
std_dev = np.std(dataset, ddof=1)
sample_size = len(dataset)
print()
print(f"Sample mean: {xbar:0.4f}")
print(f"Sample standard deviation: {std_dev:0.4f}")
print(f"Sample size: {sample_size:0.0f}")
else: # user will manually enter summary statistics
xbar = input("Please enter the sample mean: ")
if xbar == 'q': # quit the program
quit = True
break
xbar = float(xbar)
std_dev = input("Please enter the sample standard deviation: ")
if std_dev == 'q': # quit the program
quit = True
break
std_dev = float(std_dev)
sample_size = input("Please enter the sample size: ")
if sample_size == 'q': # quit the program
quit = True
break
sample_size = int(sample_size)
print()
test_statistic = obsToT(xbar, mu, std_dev, sample_size) # calculate test statistic t
df = sample_size - 1 # degrees of freedom
area = stats.t.cdf(test_statistic, df=df, loc=0, scale=1) # area under curve
ci_min = stats.t.interval(1-2*significance, df=df, loc=xbar, scale=std_dev/math.sqrt(sample_size))[0] # minimum of confidence interval
ci_max = stats.t.interval(1-2*significance, df=df, loc=xbar, scale=std_dev/math.sqrt(sample_size))[1] # maximum of confidence interval
print(f"Test statistic: {test_statistic:0.4f}")
if left_right_two == '1':
print(f"Population Mean < Claimed Mean critical value: {stats.t.ppf(significance,df):0.4f}")
print(f"p-value: {area:0.4f}")
print(f"{100*(1-significance):.0f}% Upper Bound: {ci_max:0.4f}")
elif left_right_two == '2':
print(f"Population Mean > Claimed Mean critical value: {stats.t.ppf(1-significance,df):0.4f}")
print(f"p-value: {1-area:0.4f}")
print(f"{100*(1-significance):.0f}% Lower Bound: {ci_min:0.4f}")
elif left_right_two == '3':
ci_min = stats.t.interval(1-significance, df=df, loc=xbar, scale=std_dev/math.sqrt(sample_size))[0] # minimum of confidence interval
ci_max = stats.t.interval(1-significance, df=df, loc=xbar, scale=std_dev/math.sqrt(sample_size))[1] # maximum of confidence interval
print(f"Population Mean != Claimed Mean critical value: +/-{math.fabs(stats.t.ppf(significance/2,df)):0.4f}")
print(f"p-value: {2*min(area,1-area):0.4f}")
print(f"{100*(1-significance):.0f}% Confidence Interval: ({ci_min:0.4f}, {ci_max:0.4f})")
print()
|
e151546301909f5fed9bdc0e85a83a3a86080a9f | lannyMa/py_infos | /01/in_func.py | 169 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
# 实现in
a = "i am maotai"
is_in = False
stra = "ma"
for s in a:
if s == stra:
is_in=True
break
print is_in |
df8334c84f13066e6b62f062f049709225de1065 | lannyMa/py_infos | /03/zhuce.py | 497 | 3.6875 | 4 | #!/usr/bin/env python
# coding=utf-8
#----------------
# 注册模块
#----------------
while True:
name = raw_input("name: ").strip()
pwd = raw_input("pwd: ").strip()
pwd2 = raw_input("pwd: ").strip()
if pwd != pwd2:
print "密码不一致,re-enter"
continue
if name and pwd:
with open("user.txt","a+") as f:
f.write("%s:%s\n"%(name,pwd))
print "%s register sucessful"%name
else:
print "user or pass emyty,reenter" |
0bd4d260bef0115c7b7bbd1f1a3ff961b8d12f11 | dart-neitro/xmltodict3 | /tests/test_xml_to_dict.py | 6,521 | 3.53125 | 4 | import xml.etree.ElementTree as ElementTree
from xmltodict3 import XmlToDict
def test_simple_case():
text = "<root>1</root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': '1'}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_nested_case():
text = "<root><node>1</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': '1'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_nested_case_with_spaces():
text = """
<root>
<node>
1
</node>
</root>"""
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': '1'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_multi_different_nested_case():
text = "<root><node1>1</node1><node2>2</node2></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node1': '1', 'node2': '2'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_multi_same_nested_case():
text = "<root><node>1</node><node>2</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': ['1', '2']}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_multi_mixed_nested_case():
text = "<root><node>1</node><node1>33</node1><node>2</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': ['1', '2'], 'node1': '33'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_case_with_attribute():
text = "<root attr='attr_value1'>1</root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'#text': '1', '@attr': 'attr_value1'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_case_with_attributes():
text = "<root attr='attr_value1' attr2='attr_value2'>1</root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'#text': '1',
'@attr': 'attr_value1',
'@attr2': 'attr_value2'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_nested_case_with_attributes():
text = "<root attr='attr_value1' attr2='attr_value2'><node>1</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': '1',
'@attr': 'attr_value1',
'@attr2': 'attr_value2'}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_nested_case_with_attributes_2():
text = "<root><node attr='attr_value1' attr2='attr_value2'>1</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': {
'#text': '1', '@attr': 'attr_value1', '@attr2': 'attr_value2'}}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_mixed_nested_case_with_attributes_2():
text = "<root><node attr='attr_value1' attr2='attr_value2'>1</node>" \
"<node>3</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': [{
'#text': '1', '@attr': 'attr_value1', '@attr2': 'attr_value2'}, '3']}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_mixed_nested_case_with_attributes_3():
text = "<root attr=\"attr_val\">" \
"<node attr='attr_value1' attr2='attr_value2'>1</node>" \
"<node>3</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'@attr': 'attr_val', 'node': [{
'#text': '1', '@attr': 'attr_value1', '@attr2': 'attr_value2'}, '3']}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_simple_case_with_namespace():
text = '<root xmlns="http://test.com/test_shema">1</root>'
etree_element = ElementTree.fromstring(text)
expected_result = {'root': '1'}
result = XmlToDict(etree_element, ignore_namespace=True).get_dict()
assert result == expected_result, result
def test_multi_different_nested_case_with_namespace():
text = '<root xmlns="http://test.com/test_shema">' \
'<node1>1</node1><node2>2</node2></root>'
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node1': '1', 'node2': '2'}}
result = XmlToDict(etree_element, ignore_namespace=True).get_dict()
assert result == expected_result, result
def test_mixed_nested_case_with_attributes_with_namespace():
text = "<root attr=\"attr_val\" xmlns=\"http://test.com/test_shema\">" \
"<node attr='attr_value1' attr2='attr_value2'>1</node>" \
"<node>3</node></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'@attr': 'attr_val', 'node': [{
'#text': '1', '@attr': 'attr_value1', '@attr2': 'attr_value2'}, '3']}}
result = XmlToDict(etree_element, ignore_namespace=True).get_dict()
assert result == expected_result, result
####
def test_empty_element():
text = "<root><node>1</node><node /></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node': ['1', None]}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_tag_with_hyphen():
text = "<root><node-n>1</node-n><node-n /></root>"
etree_element = ElementTree.fromstring(text)
expected_result = {'root': {'node-n': ['1', None]}}
result = XmlToDict(etree_element).get_dict()
assert result == expected_result, result
def test_tag_with_schema():
text = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:root type="integer">
data
</xs:root>
</xs:schema>"""
etree_element = ElementTree.fromstring(text)
expected_result = {'schema': {'root': {
'#text': 'data', '@type': 'integer'}}}
result = XmlToDict(etree_element, ignore_namespace=True).get_dict()
assert result == expected_result, result
|
4f0019dc7b77f7c5190b4dd3dba50244af97a009 | Qazaqbala-N/last | /lab7/WEBDEV/Informatics/Cycle/while/b.py | 55 | 3.578125 | 4 | a = int(input())
i = 2
while a%i!=0:
i=i+1
print(i) |
d635853788e48b21f636edba4327923fac5a1863 | Qazaqbala-N/last | /lab7/WEBDEV/Informatics/Cycle/for/c.py | 130 | 3.75 | 4 | import math
a = int(input())
b = int(input())
print(" ".join([str(i) for i in range(a,b+1) if math.sqrt(i)==int(math.sqrt(i))] ))
|
8fa63d49d396110d5d6d87f55fd1c29a9bf5eb64 | ali-a10/Sudoku-Solver | /Solver.py | 630 | 3.78125 | 4 |
from typing import runtime_checkable
def valid_move(board, number, position):
# check column
for row in range(len(board)):
if board[row][position[1]] == number and position[0] != row:
return False
# check row
for col in range(len(board)):
if board[position[0]][col] == number and position[1] != col:
return False
# check box
box_x = position[1] // 3
box_y = position[0] // 3
for i in range(box_y*3, box_y*3+3):
for j in range(box_x*3, box_x*3+3):
if board[i][j] == number and (i, j) != position:
return False |
d2e63bfba6fdfa348260d81a84628cacc6243a18 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 7/investment_calculator.py | 986 | 4.125 | 4 | """A program on an Investment Calculator"""
import math
# user inputs
# the amount they are depositing
P = int(input("How much are you depositing? : "))
# the interest rate
i = int(input("What is the interest rate? : "))
# the number of years of the investment
t = int(input("Enter the number of years of the investment: "))
# simple or compound interest
interest = input("Enter either 'Simple' or 'Compound' interest: ").lower()
# the 'r' variable is the interest divided by 100
r = i / 100
# check if the user entered either Simple or Compound and perform the relevant calculations
# Simple Interest Formula : A = P*(1+r*t) N.B. A is the total received or accumulated amount
if interest == 'simple':
A = P * (1 + r*t)
elif interest == 'compound':
# Compound Interest Formula : A = P* math.pow((1+r),t)
A = P * math.pow((1 + r), t) # t is the power
# print out the Accrued amount ie. the received or accumulated amount
print(f"The Accrued amount is : {round(A, 2)}")
|
720fefd121f1bc900454dcbfd668b12f0ad9f551 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 2/conversion.py | 445 | 4.25 | 4 | """Declaring and printing out variables of different data types"""
# declare variables
num1 = 99.23
num2 = 23
num3 = 150
string1 = "100"
# convert the variables
num1 = int(num1) # convert into an integer
num2 = float(num2) # convert into a float
num3 = str(num3) # convert into a string
string1 = int(string1) # convert string to an integer
# print out the variables with new data types
print(num1)
print(num2)
print(num3)
print(string1) |
1143957f959a603f694c7ed6012acf2f7d465a4c | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 7/control.py | 258 | 4.125 | 4 | """Program that evaluates a person's age"""
# take in user's age
age = int(input("Please enter in your age: "))
# evaluate the input
if age >= 18:
print("You are old enough!")
elif age >= 16:
print("Almost there")
else:
print("You're just too young!") |
cf657243453a2c909570465f0e4e30072dac3eff | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 3/example.py | 9,396 | 4 | 4 |
# ========= What are Strings? ===========
# A string is a common data type which is used to represent text.
# It is a sequence of characters, such as, letters, numerals, symbols and special characters.
# In Python, strings must be written within “quotation marks” in order for the computer to be able to read it.
# The smallest possible string contains 0 characters and is called an empty string.
# ************ Example 1 ************
# Some examples of strings
name = "John Doe"
fact = "A traffic jam lasted lasted for more than 10 days, with cars only moving 0.6 miles a day."
address = "77 Winchester Lane"
empty_str = ""
# ========= Indexing Strings ===========
# Since a string is basically a list of characters, you can extract the characters of a Ssring.
# Each character of a string (including spaces) is indexed by numbers starting from 0 for first character on the left.
# The characters are also indexed from right to left using negative numbers, where -1 is the rightmost index and so on.
# ************ Example 2 ************
word = "Hello"
print ("Example 2: ")
# Indexing from 0 to 4
char1 = word[0]
char2 = word[1]
char3 = word[2]
char4 = word[3]
char5 = word[4]
print (char1)
print (char2)
print (char3)
print (char4)
print (char5)
print ("Example 2 backwards: ")
# Indexing from -5 to -1
char1 = word[-1]
char2 = word[-2]
char3 = word[-3]
char4 = word[-4]
char5 = word[-5]
print (char1)
print (char2)
print (char3)
print (char4)
print (char5)
# ========= Slicing Strings ===========
# Slicing in Python, extracts characters from a string based on a starting index and ending index
# It enables you to extract more than one character or "chunk" of characters from a string.
# ************ Example 3 ************
print ("Example 3: ")
very_long_word = "supercalifragilisticexpialidocious"
print (very_long_word[0:5]) # prints out 'super',
# ************ Example 4 ************
print ("Example 4: ")
index = 6
print (very_long_word[index:9]) # prints out 'ali' - you can use variables as indices
# ************ Example 5 ************
# You can omit either or both of the indices
# If the first index is omitted it defaults to 0, so that your chunk starts from the beginning of the original string
# If the second index is omitted it defaults to the highest index in the string, so that your chunk ends at the end of the original string.
print ("Example 5: ")
print (very_long_word[0:])
print (very_long_word[:])
# both these statements print out all the characters from the 0th position (the start of the string) to the end.
print (very_long_word[:9]) # prints out 'supercali'
# ==== Concatenating Strings ====
# You can add, or 'concatenate' Strings together to form a sentence or longer word.
# Simply use the '+' operator to join strings together
# ************ Example 6 ************
name = "Tim"
sentence = "My name is " + name
# ************ Example 7 ************ IMPORTANT
# You cannot add a string and a non string together, you must convert the non string if you want to do this.
# If you try run code that adds a string with a non-string, you will get an error.
# You'll see many examples in our code where we have to cast things to a string in order to print (them out.
age = 12
sentence = "And my age is " + str(age) # Casting integer to string.
# Explanation:
# The way numbers are stored and arranged differ to the way strings are stored.
# In the example above, we are wanting to state that your age is 12.
# The problem lies with the integer, how do we convert an integer to a string that can be easily joined in the string statement?
# We do this by converting the integer to a String using casting and then joining it to the desired text.
# ************ Example 8 ************
print ("Example 8: ")
sentence_two = "No people under the age of " + str(18)+"."
age = int(input("Enter your age: "))
# Explanation:
# We wish to join the number 18 as a string with another string, the result of the concatenation is stored in the variable sentence_two.
# In the next line, we would like input of the user's age, so we make use of the function input(...) and call it with a string parameter.
# input(...) is a function and a function is a series of operations used to access, perform and/or set some actions to/with data if it is needed.
# The string "Enter your age" is read by the function input(...) which accesses the string given to it and prints it on the screen.
# The next step input(...) takes is to read what the user types on the keyboard. This is given back to us as a string.
# Seeing that age is a something which could increase or decrease, we can say that it should be treated like a number.
# That is why we use the int(...) function to take the user's input, and return it as a number which is then stored as such in the age variable.
# ===== Defining multi-line Strings ====
# Sometimes, it's useful to have long strings that can go over one line.
# We use triple single quotes to define a multi-line string
# Defining a multi-line String preserves the formatting of the string
# ************ Example 9 ************
long_string = ''' This is a long string
using triple quotes preserves everything inside it as a string
even on different lines and with different /n spacing. '''
# ========= The len() Function ===========
# A function is a group of statements that perform a specific task.
# A useful function is the len("string") function which returns the length of the string
# ========= String Methods ===========
# String methods are built in code that perform certain operations on strings
# There are many built in string methods that can provide useful functionality to your program without extra coding.
# You are able to reuse these methods over and over again.
# Some useful String methods are as follows:
# - string.upper() ---> converts lowercase letters to uppercase
# - string.lower() ---> converts uppercase letters to lowercase
# - string.replace("old" , "new") ---> replaces all occurrences of substring old with the substring new
# - string.strip('char') ---> removes leading and trailing characters 'char'
# ************ Example 10 ************
print ("Example 10: ")
manip_string = "***Welcome$to$the$world$of$programming***"
manip_string = manip_string.replace("$", " ")
print ("manip_string.replace(""$"", " "): " + manip_string)
manip_string = manip_string.strip('*')
print ("manip_string.strip(""*""): " + manip_string)
manip_string = manip_string.upper()
print ("manip_string.upper(): " + manip_string)
manip_string = manip_string.lower()
print ("manip_string.lower(): " + manip_string)
print ("len(manip_string): " + str(len(manip_string)))
# Remember that you can run this file to see output, or copy and paste sections of it into your own Python files and run them to understand the code better.
# ========= Note on Lists ===========
# If you noticed, the split method above returns a list
# A list is a datatype that can be thought of as a container that holds a number of other items, such as strings, integers or floats.
# A list is created by placing all the items inside a square bracket [ ] and separating them by commas.
# For example, a list of integers can be created as follows:
# int_list = [1, 2, 3, 4]
# To add an item to the end of your list, you use the append method.
# For example list.append(item) adds the single item within the brackets to the end of list
# You will learn more about lists later on in this course.
# ========= Escape Character ===========
# Python uses the backslash (\) as an escape character
# The backslash (\) is used as a marker character to tell the compiler/interpreter that the next character has some special meaning.
# The backslash together with certain other characters are know as escape sequences
# Some useful escape sequences can be found below:
# \n - Newline
# \t - Tab
# \s - Space
# The escape character can also be used if you need to include quotation marks within a string.
# You can put a backslash (\) in front of a quotation mark so that it doesn't terminate the string.
# You can also but a backslash in front of another backslash if you need to include a backslash in a string.
# ************ Example 11 ************
print ("Example 11: ")
people = "Person 1 \nPerson 2"
print (people)
# Notice the line break between the two words. The \n character is invisible - it's a command to insert a new line.
# ************ Example 12 ************
print ("Example 12: ")
wage = "Person 1: \t R123.22"
print (wage)
# Notice the tab between the two words. The \t character is invisible - it's a command to insert a new tab space.
# ************ Example 13 ************
print ("Example 13: ")
sentence = "\"The escape character (\\) is a character which invokes an alternative interpretation on subsequent characters in a character sequence.\""
print (sentence)
# Notice that the quotation marks and backslash are printed out as part of the string.
# ****************** END OF EXAMPLE CODE ********************* #
# == Make sure you have read and understood all of the code in this Python file.
# == Please complete the compulsory tasks in the lesson (refer to the PDF file) to proceed to the next task. ===
# == Ensure you complete your work in this folder so that your mentor can easily locate and mark it. ===
|
aa41b93ab44deded12fa4705ea497d2c6bbc74e8 | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 10/logic.py | 648 | 4.1875 | 4 | """A program about fast food service"""
menu_items = ['Fries', 'Beef Burger', 'Chicken Burger', 'Nachos', 'Tortilla', 'Milkshake']
print("***MENU***")
print("Pick an item")
print("1.Fries\n2.Beef Burger\n3.Chicken Burger\n4.Nachos\n5.Tortilla\n6.Milkshake")
choice = int(input("\nType in number: "))
for i in menu_items:
if choice == i:
print(f"You have chosen {choice}") # Nothing gets printed out
"""The reason why it doesn't print out is because when we are looping through the list it is
printing out the strings, not the positions.
So, if we are going to compare a string and an integer then it wont reach the print statement"""
|
ac6d9333960c992aef690fa764d7f98ffdc9963c | Yasthir01/Bootcamp-Tasks-and-Projects-Part1 | /Level 1/Task 17/animal.py | 815 | 4.1875 | 4 | """Inheritance in Python"""
class Animal(object):
def __init__(self, numteeth,spots,weight):
self.numteeth = numteeth
self.spots = spots
self.weight = weight
class Lion(Animal):
def __init__(self, numteeth, spots, weight):
super().__init__(numteeth, spots, weight)
self.type()
def type(self):
"""Determine type of lion based on weight"""
if self.weight < 80:
self.lion_type = 'Cub'
elif self.weight < 120:
self.lion_type = 'Female'
elif self.weight > 120:
self.lion_type = 'Male'
class Cheetah(Animal):
def __init__(self, numteeth, spots, weight, prey):
super().__init__(numteeth, spots, weight)
self.prey = prey
# lion object
lion1 = Lion(30, 0, 130)
print(lion1.lion_type)
# cheetah object
cheetah = Cheetah(20, 5, 100, ['Buffalo', 'Gazelle'])
print(cheetah.prey)
|
8be702fc476fbcca1b173f18a46f5fc02e3607ce | evilowl/learnpython | /qiuhe.py | 1,003 | 3.5625 | 4 | def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
def person(name, age, **kw):
print 'name', name, 'age', 'other',kw
def func(a, b, c=0, *args, **kw):
print 'a=', a, 'b=',b, 'c=', c, 'args=', args, 'kw=', kw
def fact(n):
if n == 1:
return 1
# print n
return n * fact(n - 1)
def facts(n):
return facts_iter(n, 1)
def facts_iter(num, product):
if num == 1:
return product
return facts_iter(num - 1, num * product)
def fib(max):
n , a, b = 0, 0, 1
while n < max:
#print b
yield b
a, b = b, a + b
n = n + 1
def f(x):
return x * x
def fn(x, y):
return x * 10 + y
def srt2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0}[s]
return reduce(fn, map(char2num, s))
|
5a4ae83572e2cad5a3021d95d8a88ea5dcea1da4 | smblasik/Python_Excercises | /intro/celcius.py | 298 | 3.78125 | 4 | # Function to Convert Celcius to Farenheit
def fer(cel):
if cel > -273.15:
answer = cel * 1.8 + 32
return answer
temperatures=[10,-20,-289,100]
for c in temperatures:
with open("temp.txt","a+") as file:
if c > -273.15:
file.write(str(fer(c)) + "\n")
|
7eafe6d1231ff66b56fdeab6c409922e82ec5691 | purvajakumar/python_prog | /pos.py | 268 | 4.125 | 4 | #check whether the nmuber is postive or not
n=int(input("Enter the value of n"))
if(n<0):
print("negative number")
elif(n>0):
print("positive number")
else:
print("The number is zero")
#output
"""Enter the value of n
6
positive number"""
|
cb79a2766eac1ec30b3e443a469dbcd14bdc8358 | dashboardijo/py_ln | /com/py/finanindic/compute_psi.py | 4,934 | 3.5 | 4 | # Python代码实现PSI群体稳定指数
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import math
def cal_psi(actual, predict, bins=10):
"""
功能: 计算PSI值,并输出实际和预期占比分布曲线
:param actual: Array或series,代表真实数据,如训练集模型得分
:param predict: Array或series,代表预期数据,如测试集模型得分
:param bins: 分段数
:return:
psi: float,PSI值
psi_df:DataFrame
Examples
-----------------------------------------------------------------
# >>> import random
# >>> act = np.array([random.random() for _ in range(5000000)])
# >>> pct = np.array([random.random() for _ in range(500000)])
# >>> psi, psi_df = cal_psi(act,pct)
# >>> psi
1.65652278590053e-05
# >>> psi_df
actual predict actual_rate predict_rate psi
0 498285 49612 0.099657 0.099226 1.869778e-06
1 500639 50213 0.100128 0.100428 8.975056e-07
2 504335 50679 0.100867 0.101360 2.401777e-06
3 493872 49376 0.098775 0.098754 4.296694e-09
4 500719 49710 0.100144 0.099422 5.224199e-06
5 504588 50691 0.100918 0.101384 2.148699e-06
6 499988 50044 0.099998 0.100090 8.497110e-08
7 496196 49548 0.099239 0.099098 2.016157e-07
8 498963 50107 0.099793 0.100216 1.790906e-06
9 502415 50020 0.100483 0.100042 1.941479e-06
"""
actual_min = actual.min() # 实际中的最小概率
actual_max = actual.max() # 实际中的最大概率
binlen = (actual_max - actual_min) / bins
cuts = [actual_min + i * binlen for i in range(1, bins)] # 设定分组
cuts.insert(0, -float("inf"))
cuts.append(float("inf"))
actual_cuts = np.histogram(actual, bins=cuts) # 将actual等宽分箱
predict_cuts = np.histogram(predict, bins=cuts) # 将predict按actual的分组等宽分箱
actual_df = pd.DataFrame(actual_cuts[0], columns=['actual'])
predict_df = pd.DataFrame(predict_cuts[0], columns=['predict'])
psi_df = pd.merge(actual_df, predict_df, right_index=True, left_index=True)
psi_df['actual_rate'] = (psi_df['actual'] + 1) / psi_df['actual'].sum() # 计算占比,分子加1,防止计算PSI时分子分母为0
psi_df['predict_rate'] = (psi_df['predict'] + 1) / psi_df['predict'].sum()
psi_df['psi'] = (psi_df['actual_rate'] - psi_df['predict_rate']) * np.log(
psi_df['actual_rate'] / psi_df['predict_rate'])
psi = psi_df['psi'].sum()
return psi, psi_df
# import random
# act = np.array([random.random() for _ in range(5000000)])
# pct = np.array([random.random() for _ in range(500000)])
# psi, psi_df = cal_psi(act,pct)
# print(psi)
# print(psi_df)
def psi_calc(actual,predict,bins=10):
'''
功能: 计算PSI值,并输出实际和预期占比分布曲线
输入值:
actual: 一维数组或series,代表训练集模型得分
predict: 一维数组或series,代表测试集模型得分
bins: 违约率段划分个数
输出值:
字典,键值关系为{'psi': PSI值,'psi_fig': 实际和预期占比分布曲线}
'''
psi_dict = {}
actual = np.sort(actual)
predict = np.sort(predict)
actual_len = len(actual)
predict_len = len(predict)
psi_cut = []
actual_bins = []
predict_bins = []
actual_min = actual.min()
actual_max = actual.max()
cuts = []
binlen = (actual_max-actual_min) / bins
for i in range(1, bins):
cuts.append(actual_min+i*binlen)
for i in range(1, (bins+1)):
if i == 1:
lowercut = float('-Inf')
uppercut = cuts[i-1]
elif i == bins:
lowercut = cuts[i-2]
uppercut = float('Inf')
else:
lowercut = cuts[i-2]
uppercut = cuts[i-1]
actual_cnt = ((actual >= lowercut) & (actual < uppercut)).sum()+1
predict_cnt = ((predict >= lowercut) & (predict < uppercut)).sum()+1
actual_pct = (actual_cnt+0.0) / actual_len
predict_pct = (predict_cnt+0.0) / predict_len
psi_cut.append((actual_pct-predict_pct) * math.log(actual_pct/predict_pct))
actual_bins.append(actual_pct)
predict_bins.append(predict_pct)
psi = sum(psi_cut)
nbins = len(actual_bins)
xlab = np.arange(1, nbins+1)
fig = plt.figure()
plt.plot(xlab, np.array(actual_bins),'r',label='actual')
plt.plot(xlab, np.array(predict_bins),'b',label='predict')
plt.legend(loc='best')
plt.title('Psi Curve')
plt.show()
# plt.close()
psi_dict['psi'] = psi
psi_dict['psi_fig'] = fig
return psi_dict
import random
act = np.array([random.random() for _ in range(5000000)])
pct = np.array([random.random() for _ in range(500000)])
psi_dict = psi_calc(act,pct)
print(psi_dict) |
bc52c54d5824c404709f3252210e77c0d1da393e | AdamSpannbauer/minimal_python_package | /my_pkg/perimeter.py | 371 | 4.03125 | 4 | def rect_perimeter(w, h):
"""Calc perimeter of a rectangle
:param w: width of rectangle
:param h: height of rectangle
:return: perimeter of rectangle
"""
return w * 2 + h * 2
def square_perimeter(a):
"""Calc perimeter of a square
:param a: length of square legs
:return: perimeter of square
"""
return rect_perimeter(a, a)
|
2bc98f3ff734b47d6cc64effebe893718221ebb0 | Bart94/Project1 | /ExternalMethods.py | 1,871 | 3.53125 | 4 | from CircularPositionalList import CircularPositionalList
def bubblesorted(cplist):
temp = cplist.copy()
if not cplist.is_sorted():
current_node = temp._header._next
for i in range(len(temp) - 1):
next_node = current_node._next
for j in range(i, len(temp) - 1):
if current_node._element is not None or next_node._element is not None:
if current_node._element > next_node._element:
current_node._element, next_node._element = next_node._element, current_node._element
next_node = next_node._next
current_node = current_node._next
for elem in temp:
yield elem
# Caso peggiore O(n)
def merge(cplist_one, cplist_two):
ret_list = CircularPositionalList()
if type(cplist_one) == type(cplist_two):
if cplist_one.is_sorted() and cplist_two.is_sorted():
if cplist_one.is_empty():
return cplist_two.copy()
if cplist_two.is_empty():
return cplist_one.copy();
if cplist_one.last().element() > cplist_two.last().element():
cplist_one, cplist_two = cplist_two, cplist_one
current = cplist_one._header._next
current2 = cplist_two._header._next
for elem in cplist_one:
while current2._element < elem:
ret_list.add_last(current2._element)
current2 = current2._next
current = current._next
ret_list.add_last(elem)
while current2._element is not None:
ret_list.add_last(current2._element)
current2 = current2._next
else:
raise Exception("Each list must be sorted!")
else:
raise TypeError("Error in lists type!")
return ret_list
|
85035bf134a0430c29da49fea24440c04f307faf | yuta-nakashima-10antz/behavior_tree | /main.py | 3,616 | 3.703125 | 4 | import random
my_hp = 150
enemy_hp = 120
#整数か判断
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
#ルート
class Root(object):
sequence = []
node_count = 0
def __init__(self,my_hp,enemy_hp):
self.my_hp = my_hp
self.enemy_hp = enemy_hp
def add(self,node):
self.sequence.append(node)
self.node_count += 1
def print_node(self):
i = 0
for node in self.sequence:
if type(node[0]) == int:
self.enemy_hp = self.enemy_hp - node[0]
else:
if(self.node_count-1 == i):
if node[1]():
for v in node[0](self.enemy_hp):
print(v, end="")
print("")
else:
if node[1]():
for v in node[0]():
print(v,end="")
print("")
i += 1
#スタート
start = lambda: "出発" ,lambda: True
#敵に近づく
get_closer_enemy = lambda : "敵に寄る" , lambda: True
#condition_node
my_hp_condition = lambda: get_closer_enemy[0](),lambda: True if my_hp >= 100 else False
#友達クラス
class Friend(object):
def __init__(self,name):
self.name = name
#parallelの処理
def parallel(parallel_node):
count = 0
node_num = len(parallel_node)
result = []
for node in parallel_node:
if node:
result.append(node.name)
count += 1
if count == node_num:
return result
else:
return False
#parallelノード
parallel_node = []
parallel_node.append(Friend("友達A"))
parallel_node.append(Friend("友達B"))
parallel_lambda = lambda : parallel(parallel_node), lambda: True if parallel(parallel_node) != False else False
#RepeaterNode
def repeter(selector):
for i in range(2):
if selector[1]():
result = selector[0]()
return result,True
#skill1のActionNode
def skill1(enemy_hp,skill1_probability):
l = [1]*skill1_probability
l = l + [0]*(1-skill1_probability)
result = random.choice(l)
if result == 1:
enemy_hp = enemy_hp - 50
return enemy_hp
skill1_lambda = lambda enemy_hp,skill1_probability:skill1(enemy_hp,skill1_probability),lambda: True
#skill2のActionNode
skill2 = lambda: enemy_hp - 60, lambda: True
def skill_selector(skill1_lambda,skill2,enemy_hp,skill1_probability):
l = [0,1]
result = random.choice(l)
if result == 0:
return skill1_lambda(enemy_hp,skill1_probability)
else:
return skill2[0]()
skill_selector_lambda = lambda: skill_selector(skill1,skill2,enemy_hp,skill1_probability),lambda: True
#最終結果のActionNode
enemy_hp_jadge = lambda enemy_hp: "End1" if enemy_hp == 0 else "End2", lambda: True
if __name__ == "__main__":
while(1):
skill1_probability = input("skill1の発動確率(%)を入力してください\n")
if is_integer(skill1_probability):
skill1_probability = float(skill1_probability)
skill1_probability = int(skill1_probability)
if skill1_probability > 100 or skill1_probability < 0:
print("発動確率(%)は整数(0以上100以下)で入力してください")
else:
break
root = Root(my_hp,enemy_hp)
root.add(start)
root.add(my_hp_condition)
root.add(parallel_lambda)
root.add(repeter(skill_selector_lambda))
root.add(enemy_hp_jadge)
root.print_node()
|
168cf6562d8ebe5fa96d605ce088d29dd2be0a25 | LucianLaFleur/pythonPath | /security_scripts/dictBruteForce.py | 685 | 3.65625 | 4 | #!/use/bin/env python
import requests
target_url = "example.com"
# last item in dictionary is the button for submitting
data_dict = {"username": "potato1", "password":"", "Login":"submit"}
with open("path/to/dictionary.txt", "r") as wordlist_file:
for line in wordlist_file:
# assuming each keyword is on its own line in the text file, otherwise use split(",") or something
word = line.strip()
# set value at "password" to current word in iteration
data_dict["password"] = word
response = requests.post(target_url, data=data_dict)
if "failed" not in response.content:
print("Password found --> " + word)
exit()
print("Password not in word-list") |
d91936546e575c5b3daa3c20061d2541d379dc3b | AMJefford/Simulation-and-Chemistry-System | /Student File.py | 25,676 | 3.5625 | 4 | from tkinter import *
import tkinter.messagebox as tm
import sqlite3
import array
import string
import DatabaseKey
from cryptography.fernet import Fernet
from Simulation import *
import random
import time
class Login:
def __init__(self, root):
self.__UsernameE = Entry(root)
self.__PasswordE = Entry(root,show = "*")
self.CreateDisplay()
def CreateDisplay(self):
UsernameL = Label(root,text = "Username").grid(row = 0, padx = 5)
PasswordL = Label(root,text = "Password").grid(row = 1, padx = 5)
self.__UsernameE.grid(row = 0, column = 1)
self.__PasswordE.grid(row = 1, column = 1)
root.minsize(width = 250,height = 80)
Button(text = "Login", command = self.ButtonClicked).grid(column = 2, pady = 5)
def ButtonClicked(self):
Username = self.__UsernameE.get()
Password = self.__PasswordE.get()
Database.CheckCreds(Username,Password)
class Main(object):
def __init__(self, StudentSetClass, StudentFN, Username):
self.__StudentSN = Username[1:]
self.__Class = StudentSetClass
self.__StudentFN = StudentFN
print(self.__StudentFN)
Main.MainWindow(self)
def MainWindow(self):
Window = Toplevel(root)
OnlineHomework = Label(Window, text = "Online Homework", font = ("Georgia", 20),bg = "#E59866", fg = "white").grid(sticky = N+S+E+W)
Description = Label(Window, bg = "white", text = '''Hello! Welcome to the self marking homework system! This program will allow your
homework to be automatically marked upon completion. \nMeaning you wont have to wait for a result or feedback!''').grid(padx = 20, pady = 5)
Window["bg"] = "white"
Window.title("Home")
Window.resizable(height = False, width = False)
GoToHomework = Button(Window, text = "Check To-Do Homework", command = lambda: ToCompleteClass(self.__Class, self.__StudentSN, self.__StudentFN))
GoToHomework.grid(padx = 300, pady = 5, sticky = N+E+S+W)
PreviousHomework = Button(Window, text = "Check Previous Homework", command = lambda: PreviousHomeworkClass(self.__Class, self.__StudentSN, self.__StudentFN))
PreviousHomework.grid(padx = 300, pady = 5, sticky = N+E+S+W)
SimulationButton = Button(Window, text = "Go To Simulation", command = lambda: Simulation.RunSimulation())
SimulationButton.grid(padx = 300, pady = 5, sticky = N+E+S+W)
menuBar = Menu(Window)
Window.winfo_toplevel()['menu'] = menuBar
file = Menu(menuBar)
file.add_command(label = 'Log Out', command = Window.destroy)
file.add_command(label = 'Help', command = Main.Help)
menuBar.add_cascade(label = "File", menu = file)
def Help():
Window = Toplevel(root)
Info = Text(Window, height = 30, width = 100)
Info.pack()
Info.insert(END,'''HELP:
This program is intended for acedemic purposes. In the main menu you will find three options:
Check To-Do Homework
Check Previous Homework
Go To Simulation
Check To-Do Homework:
Here you will be presented with any live homework set by your teachers that you have yet to
complete. Upon selection, you will be presented with a series of questions that have been set for
you where you can either type of select your answer. Once the series of questions have been
completed, you will be presented with a new page displaying your score, and the questions you got
correct/incorrect, along with the correct answer. Your scores and answers will then be available to
view by your teachers.
Check Previous Homework:
Selecting this option will allow you to view any homework that you have completed before. A list of your previous homework will be shown where you can then select an option to view the questions
and answers to the homework, along with your score.
Go To Simulation:
The simulation is a classic PV=nRT simulation whereby you can alter the conditions to view the
effects. You have three conditions to change: temperature, volume, and number of moles. To gradually
change a condition, click either the green (increase) or red (decrease) button. To view the effect
more quickly, hold down the chosen button.
If there is any further help required, please email:
help@system.co.uk ''')
class ToCompleteClass(object):
def __init__(self, StudentSetClass, StudentSN, StudentFN):
self.__Class = StudentSetClass
self.__StudentFN = StudentFN
self.__StudentSN = StudentSN
self.__ListofButtons = []
self.__HomeworkData = []
self.SelectHomework()
def SelectHomework(self):
Window = Toplevel(root)
Window.title("Select a homework to complete.")
ListOfHomeworks = []
try:
HomeworkFile = open("Live Homework.txt","r")
except FileNotFoundError:
tm.showinfo("File Error.", "Can Not Find File.")
Window.withdraw()
return
for line in HomeworkFile:
line = (line.strip("\n")).split(",")
self.__HomeworkData.append(line)
HomeworkFile.close()
Info1 = Label(Window, text = "You have no homework to complete!")
Info = Label(Window, text = "Select one of the following homework to complete:")
if len(self.__HomeworkData) == 0:
Info1.grid()
else:
Info.grid()
def DetermineSelection(button):
ButtonText = button['text']
CompletedList = []
QuestionData = []
Text = ButtonText.split("-")
self.__HomeworkSelection = Text[0].strip(" ")
Window.destroy()
print(self.__HomeworkSelection)
self.LiveHomework(0, 0, CompletedList, QuestionData)
def PrintOptions():
try:
CompletedHomework = open("Completed Homework.txt", "r")
except FileNotFoundError:
tm.showinfo("File Error.", "Completed Homework File Not Found.")
Window.withdraw()
return
CompletedHomework = CompletedHomework.readlines()
StudentsCompletedHomework = []
for X in range(len(CompletedHomework)):
StudentsCompleted = str(CompletedHomework[X]).split(",")
StudentCompletedHWID = str(StudentsCompleted[1]).strip("\n")
if StudentsCompleted[0] == (self.__StudentFN + " " + self.__StudentSN):
StudentsCompletedHomework.append(StudentCompletedHWID)
for Y in range(len(self.__HomeworkData)):
if self.__HomeworkData[Y][8] == self.__Class and self.__HomeworkData[Y][9] not in ListOfHomeworks and self.__HomeworkData[Y][9] not in StudentsCompletedHomework:
HomeworkInfo = str(self.__HomeworkData[Y][9]) + " - " + str(self.__HomeworkData[Y][2]) + " -" + str(self.__HomeworkData[Y][3])
Button1 = Button(Window, text = HomeworkInfo)
Button1.configure(command = lambda button = Button1: DetermineSelection(button))
Button1.grid(sticky = N+E+W+S)
self.__ListofButtons.append(Button1)
ListOfHomeworks.append(self.__HomeworkData[Y][9])
if not ListOfHomeworks:
Info1.grid()
Info.destroy()
PrintOptions()
def LiveHomework(self, Y, Score, CompletedList, QuestionData):
self.__HomeworkData = []
try:
HomeworkFile = open("Live Homework.txt","r")
except FileNotFoundError:
tm.showinfo("File Error.","Live Homework File Not Found.")
return
for line in HomeworkFile:
line = (line.strip("\n")).split(",")
self.__HomeworkData.append(line)
HomeworkFile.close()
if Y+1 <= len(self.__HomeworkData):
QuestionText = self.__HomeworkData[Y][0]
self.__MCAnswers = []
if self.__HomeworkData[Y][4] == "MC":
self.__MCAnswers.append(self.__HomeworkData[Y][5])
self.__MCAnswers.append(self.__HomeworkData[Y][6])
self.__MCAnswers.append(self.__HomeworkData[Y][7])
self.__MCAnswers.append(self.__HomeworkData[Y][1])
self.__CorrectAnswer = self.__HomeworkData[Y][1]
random.shuffle(self.__MCAnswers)
else:
self.WriteScoretoFile(Score, CompletedList, QuestionData, Y)
return
if self.__HomeworkData[Y][8] == self.__Class and self.__HomeworkData[Y][9] == self.__HomeworkSelection:
self.__Unit = self.__HomeworkData[Y][2]
self.__Topic = self.__HomeworkData[Y][3]
print(self.__Topic)
print(self.__Unit)
NewWindow = Toplevel(root)
NewWindow.title("Homework.")
NewWindow.geometry("+200+200")
NewWindow["bg"] = "#ffffff"
NewWindow.resizable(width = False, height = False)
QuestionData.append(self.__HomeworkData[Y])
NewWindow.title("Get Homework")
var = StringVar()
var.set("Label")
label = Label(NewWindow, text = QuestionText, bg = "#ffffff").grid(columnspan = 2, pady = 5, row = 0, column = 0, sticky = N+E+S+W)
self.v = IntVar()
self.v.set(0)
if self.__MCAnswers:
for val in range(len(self.__MCAnswers)):
UserChoiceMC = Radiobutton(NewWindow,
indicatoron = False,
text = self.__MCAnswers[val],
tristatevalue = "x",
padx = 20,
variable = self.v, value = val).grid(sticky = N+E+S+W, columnspan = 2)
else:
self.AnswerBox = Entry(NewWindow)
self.AnswerBox.grid(columnspan = 2, sticky = N+E+S+W)
NextButton = Button(NewWindow, text = "Confirm Answer",command = lambda: self.Confirm(NewWindow, Y, Score,
CompletedList, QuestionData)).grid(padx = 20, pady = 20, row = 10, column = 1, sticky = E)
else:
self.LiveHomework(Y+1, Score, CompletedList, QuestionData)
def Confirm(self, NewWindow, Y, Score, CompletedList, QuestionData):
Correct = False
KeyAnswer = ""
KeyWords = []
print(self.__HomeworkData[Y][4])
if self.__HomeworkData[Y][4] == 'MC':
UserAnswer = self.v.get()
UserAns = (self.__MCAnswers[UserAnswer])
CompletedUsersAnswer = UserAns
if UserAns == self.__CorrectAnswer:
Score += 1
Correct = True
elif self.__HomeworkData[Y][4] == 'Not MC':
UserAnswer = self.AnswerBox.get()
WordsIn = 0
if "/" in self.__HomeworkData[Y][1]:
KeyWords = ((self.__HomeworkData[Y][1]).lower()).split("/")
elif " " in self.__HomeworkData[Y][1]:
KeyWords = ((self.__HomeworkData[Y][1]).lower()).split(" ")
else:
KeyAnswer = (self.__HomeworkData[Y][1]).lower()
UserAnswer = UserAnswer.split(" ")
CompletedUsersAnswer = self.AnswerBox.get()
for x in range(len(UserAnswer)):
if UserAnswer[x].lower() in KeyWords:
WordsIn += 1
if WordsIn >= 3 or UserAnswer[x] == KeyAnswer:
Score += 1
Correct = True
Answer = [CompletedUsersAnswer, str(Correct) ,self.__HomeworkData[Y][4] , self.__HomeworkData[Y][0], self.__HomeworkData[Y][1]]
CompletedList.append(Answer)
NewWindow.destroy()
self.LiveHomework(Y+1, Score, CompletedList, QuestionData)
def WriteScoretoFile(self, Score, CompletedList, QuestionData, Y):
try:
StudentScoreFile = open("Student Scores File.txt", "a")
except FileNotFoundError:
tm.showinfo("File Error.", "Can Not Save Score.")
return
StudentScoreFile.write(self.__StudentFN + " " + self.__StudentSN + "," + str(Score) +"," + self.__Class + "," + self.__HomeworkSelection + "\n")
StudentScoreFile.close()
try:
CompletedHomework = open("Completed Homework.txt","a")
except FileNotFoundError:
tm.showinfo("File Error.","Can Not Save Progress.")
return
CompletedHomework.write(self.__StudentFN + " " + self.__StudentSN + "," + self.__HomeworkSelection + "\n")
CompletedHomework.close()
try:
PreviousHomework = open("Previous Homework.txt", "a")
except FileNotFoundError:
tm.showinfo("File Error.","Previous Homework File Not Found.")
return
CrucialInfo = "," + self.__StudentFN + " " + self.__StudentSN + "," + self.__HomeworkSelection + "," + str(Score) + "," + self.__Unit + "," + self.__Topic
for X in range(len(CompletedList)):
NoExcess = str.maketrans("", "", "[]''")
print(CompletedList[X])
Pure = ((str(CompletedList[X])).translate(NoExcess))
PreviousHomework.write(Pure)
PreviousHomework.write(CrucialInfo)
PreviousHomework.write("\n")
PreviousHomework.close()
self.CompletedScreen(CompletedList, QuestionData, Score)
def CompletedScreen(self, CompletedList, QuestionData, Score):
Window = Toplevel(root)
Window.geometry("600x600")#mass e, prot mg, lig, similar?
Window.title("Results.")#ligand complex
def Data(CompletedList, QuestionData, Score):
Congratulations = str("Your score: ") + str(Score)
Label(frame, text = Congratulations).grid()
for x in range(len(CompletedList)):
Label(frame, text = (CompletedList[x][3]).capitalize()).grid()
if CompletedList[x][1] == 'True':
Label(frame, text = "Your answer was correct: ").grid()
Label(frame, text = CompletedList[x][0]).grid()
else:
Label(frame, text = "Your answer was: ").grid()
Label(frame, text = CompletedList[x][0]).grid()
if CompletedList[x][2] == "MC":
Label(frame, text = "Correct answer: ").grid()
Label(frame, text = CompletedList[x][4]).grid()
else:
Label(frame, text = "Your answer must include at least 3 of the below key words: ").grid()
Label(frame, text = CompletedList[x][4]).grid()
Label(frame, text = "\n").grid()
def ChangeScroll(event):
self.Canvas.configure(scrollregion = self.Canvas.bbox("all"), width = 550, height = 550)
MyFrame=Frame(Window, relief = GROOVE, width = 550, height = 550, bd = 1)
MyFrame.place(x = 10,y = 10)
self.Canvas = Canvas(MyFrame)
frame = Frame(self.Canvas)
myscrollbar = Scrollbar(MyFrame, orient = "vertical",command = self.Canvas.yview)
self.Canvas.configure(yscrollcommand = myscrollbar.set)
myscrollbar.pack(side = "right",fill = "y")
self.Canvas.pack(side = "left")
self.Canvas.create_window((200,200), window = frame, anchor = 'nw')
frame.bind("<Configure>",ChangeScroll)
Data(CompletedList, QuestionData, Score)
class PreviousHomeworkClass(object):
def __init__(self, Class, StudentSurname, StudentFN):
self.__Class = Class
self.__StudentSN = StudentSurname
self.__StudentFN = StudentFN
self.PresentData()
def PresentData(self):
try:
PreviousHwResults = open("Previous Homework.txt", "r")
except FileNotFoundError:
tm.showinfo("File Error","Previous Homework File Not Found.")
return
PreviousHwResults = PreviousHwResults.readlines()
if not PreviousHwResults:
tm.showinfo("None.", "There are no completed homeworks.")
return
Window = Toplevel(root)
Window.geometry("650x270")
Window.title("Previous Homework.")
def ChangeScroll(event):
self.Canvas.configure(scrollregion = self.Canvas.bbox("all"))
MyFrame = Frame(Window, relief = GROOVE, bd = 1)
MyFrame.place(x = 10,y = 10)
self.Canvas = Canvas(MyFrame)
self.__Frame = Frame(self.Canvas)
myscrollbar = Scrollbar(MyFrame, orient = "vertical", command = self.Canvas.yview)
hscrollbar = Scrollbar(MyFrame, orient = "horizontal", command = self.Canvas.xview)
self.Canvas.configure(yscrollcommand = myscrollbar.set)
self.Canvas.configure(xscrollcommand = hscrollbar.set)
hscrollbar.pack(fill = "x")
myscrollbar.pack(side = "right",fill = "y")
self.Canvas.pack(side = "left")
IDS = []
self.__StudentData = []
if len(PreviousHwResults) == 0:
Label(self.__Frame, text = "There are no completed homeworks yet!").grid()
else:
def ViewPreAnswers(button):
def ChangeScroll2(event):
self.Canvas2.configure(scrollregion = self.Canvas2.bbox("all"))
Window = Toplevel(root)
Window.title("Previous Homework.")
Window.geometry("530x230")
MyFrame2 = Frame(Window,relief = GROOVE,bd = 1)
MyFrame2.place(x = 10,y = 10)
self.Canvas2 = Canvas(MyFrame2, width = 500, height = 200)
self.__Frame = Frame(self.Canvas2)
myscrollbar = Scrollbar(MyFrame2,orient = "vertical",command = self.Canvas2.yview)
hscrollbar = Scrollbar(MyFrame2, orient = "horizontal", command = self.Canvas2.xview)
self.Canvas2.configure(xscrollcommand = hscrollbar.set)
self.Canvas2.configure(yscrollcommand = myscrollbar.set)
hscrollbar.pack(fill = "x")
myscrollbar.pack(side = "right",fill = "y")
self.Canvas2.pack(side = "left")
self.Canvas2.create_window((0,0),window = self.__Frame,anchor = 'nw')
ButtonText = button['text']
Text = ButtonText.split(":")
HomeworkID = Text[1]
Label(self.__Frame, text = "Question").grid(row = 0, sticky = W, padx = 5, pady = 5)
Label(self.__Frame, text = "Answer/Key Words").grid(row = 0, column = 1, sticky = W, padx = 5, pady = 5)
Label(self.__Frame, text = "Your answer").grid(row = 0, column = 2, sticky = W, padx = 5, pady = 5)
for x in range(len(self.__StudentData)):
if self.__StudentData[x][6] == HomeworkID:#0 = user ans, 1 = if correct, 2 = mc, 3 = question, 4 = acc answer, 5 = name, 6 = id, 7 = score
Label(self.__Frame, text = self.__StudentData[x][3]).grid(row = x + 2, sticky = W, padx = 5, pady = 5)#question
Label(self.__Frame, text = self.__StudentData[x][4]).grid(row = x + 2, sticky = W, column = 1, padx = 5, pady = 5)#acc answer
Label(self.__Frame, text = self.__StudentData[x][0]).grid(row = x + 2, column = 2, sticky = W, padx = 5, pady = 5)
self.__Frame.bind("<Configure>", ChangeScroll2)
def PrintOptions():
Label(self.Canvas, text = "HomeworkID").grid(row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Score").grid(column = 1, row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Unit").grid(column = 2, row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Topic").grid(column = 3, row = 0, sticky = W, padx = 5, pady = 5)
for line in range(len(PreviousHwResults)):
p = (PreviousHwResults[line])
l = p.split(",")
ID = l[6]
if l[5] == self.__StudentFN + " " + self.__StudentSN:
self.__StudentData.append(l)
if ID not in IDS:
Label(self.Canvas, text = l[8]).grid(row = line + 1, sticky = W, column = 2, pady = 5)
IDS.append(ID)
Label(self.Canvas, text = l[6]).grid(row = line + 1, column = 0, sticky = W, padx = 5, pady = 5)#id
Label(self.Canvas, text = l[7]).grid(row = line + 1, column = 1, sticky = W, padx = 5, pady = 5)#score[8][9]
Label(self.Canvas, text = l[9].strip("\n")).grid(row = line + 1, column = 3, sticky = W, pady = 5, padx = 5)
Info = "View Answers to ID:" + str(ID)
ButtonID = Button(self.Canvas, text = Info)
ButtonID.configure(command = lambda button = ButtonID: ViewPreAnswers(button))
ButtonID.grid(sticky = W, column = 4, row = line + 1, padx = 5, pady = 5)
print(self.__StudentData)
print("here")
if not self.__StudentData:
Label(self.Canvas, text = "You have no completed homework yet.").grid()
PrintOptions()
self.__Frame.bind("<Configure>", ChangeScroll)
class Database:
def CheckCreds(Username,Password):
conn=sqlite3.connect('OnlineHomework.db', timeout = 1)
c=conn.cursor()
Cipher_Suite = Fernet(DatabaseKey.key)
StudentUsername = []
StudentPassword = []
StudentFN = []
StudentClass = []
c.execute("SELECT * FROM StudentLogin;")
for column in c:
StudentClass.append(column[4])
StudentFN.append(column[0])
c.execute("SELECT Username FROM StudentLogin;")
for column in c:
StudentUsername.append(column[0])
c.execute("SELECT Password FROM StudentLogin;")
for column in c:
UncipheredText = Cipher_Suite.decrypt(column[-1])
PlainText = (bytes(UncipheredText).decode("utf-8"))
StudentPassword.append(PlainText)
if Username in StudentUsername:
Correct = int(StudentUsername.index(Username))
StudentFN = StudentFN[(StudentUsername.index(Username))]
if str(Password) == StudentPassword[Correct]:
tm.showinfo("Login info", "Welcome " + Username)
StudentSetClass = StudentClass[(StudentUsername.index(Username))]
root.withdraw()
Main(StudentSetClass, StudentFN, Username)
else:
tm.showerror("Login error", "Incorrect Username or Password. Please try again.")
else:
tm.showerror("Login error", "Incorrect Username or Password. Please try again.")
print(StudentUsername)
print(StudentClass)
print(StudentFN)
print(StudentPassword)
conn.commit()
conn.close()
root = Tk()
root.resizable(width=False,height=False)
root.wm_title("Please login.")
root.minsize(width=300,height=300)
Login(root)
root.mainloop()
|
1253e8d2eeda3c4f0f71b7457c9a77239fceeed9 | yamyak/plutus-stock-analysis | /Algorithms/Algorithm.py | 875 | 3.90625 | 4 | # algorithm base class
class Algorithm:
# initialize the weights and needs to nothing
def __init__(self, needs):
self.__weights = 0
self.__needed_values = needs
# verify that provided stock has all the entries the current algorithm needs
def verify_needs(self, stock):
# get all parameters the current stock has
keys = stock.get_all_keys()
# iterate through needed parameters of current algorithm
for need in self.__needed_values:
# check if needed parameter is in stock parameters and is not None
if need not in keys or stock.get_parameter(need) is None:
return False
return True
# should be abstract method
def process_list(self, stock_list):
return []
# should be abstract method
def process_stock(self, stock):
return stock
|
2b4534fe8edd038ffae69c1512b225305b00a46b | ky822/assignment7 | /hz990/Q4.py | 552 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def Run():
'''This function returns the Mandelbrot fractal image
'''
# Setting initial parameters
N_max = 50
some_threshold = 50.
x = np.linspace(-2, 1, 1000)
y = np.linspace(-1.5, 1.5, 1000)
# Constructing the grid
c = x[:,np.newaxis] + 1j*y[np.newaxis,:]
z = c
# Mandelbrot iteration
for j in range(N_max):
z = z**2 + c
a = abs(z) < some_threshold
# Printing the Mandelbrot fractal image
plt.imshow(a.T, extent = [-2, 1, -1.5, 1.5])
plt.gray()
plt.savefig("mandelbrot.png")
|
f69927d9d6d8546f676889c04db0f0c467758fd2 | ky822/assignment7 | /yx887/question4.py | 761 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def run_program():
print '-------- Begin Question 4 --------'
# Creat a grid of x, y
print 'Creating meshgrid ...'
nx, ny = 300, 300
x = np.linspace(-2, 1, nx)
y = np.linspace(-1.5, 1.5, ny)
xv, yv = np.meshgrid(x, y)
c = xv + 1j * yv
# Do the iteration
print 'Doing Mandelbrot iteration ...'
N_max = 50
threshold = 50
z = c
for v in range(N_max):
z = z**2 + c
# Get the 2-d mask
mask = abs(z) < threshold
# save the result to an image
print 'Drawing fancy pictures ...'
plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5])
plt.gray()
plt.savefig('mandelbrot.png')
if __name__ == '__main__':
run_program()
|
0fc620866a5180d3a6d0d51547d74896a6d3c193 | ky822/assignment7 | /yl3068/questions/question3.py | 734 | 4.3125 | 4 | import numpy as np
def result():
print '\nQuestion Three:\n'
#Generate 10*3 array of random numbers in the range [0,1].
initial = np.random.rand(10,3)
print 'The initial random array is:\n{}\n'.format(initial)
#Question a: pick the number closest to 0.5 for each row
initial_a = abs(initial-0.5).min(axis=1)
#Question b: find the column for each of the numbers closest to 0.5
colunm_ix = (abs(initial-0.5).argsort())[:,0]
#Question c: a new array containing numbers closest to o.5 in each row
row_ix = np.arange(len(initial))
result = initial[row_ix, colunm_ix]
print 'The result array containing numbers closest to 0.5 in each row of initial array is:\n{}\n'.format(result)
|
1f501409ef108fa83f7fb3b1522cb31d44cfb75c | ky822/assignment7 | /wl1162/question_sets/question3.py | 306 | 3.71875 | 4 | import numpy as np
def question3():
array=np.random.rand(10,3)
difference=abs(array-0.5) # find the differences with 0.5
rank=np.argsort(difference) # find the column index of the smallest elements
result=array[np.arange(10), [rank.T[0]]] # fancy index
print result
|
34bdf85e0820099703a3ed9a45aa010638f9f2ae | ky822/assignment7 | /fs1214/answers/Question2.py | 576 | 3.8125 | 4 | '''
Created on Oct 30, 2014
@author: ds-ga-1007
'''
import numpy as np
def main():
print '-----Question2-----'
#create array a and b.
a = np.arange(25).reshape(5,5)
b = np.array([1.,5,10,15,20])
print 'The dividend array - a is:'
print a
print 'The divisor array - b is:'
print b
#a divides each column elementwise with b, using broadcasting.
result = a/b.reshape(5,1)
print 'The answer of a dividing each column elementwise with b is:'
print result
print '----------------'
if __name__ == '__main__':
main() |
2942e089197e0524fa7ebe26d2ca7f9763efc8fe | ky822/assignment7 | /yl3068/questions/question1.py | 1,123 | 3.953125 | 4 | import numpy as np
def result():
print '\nQuestion One:\n'
#Generate the initial array
initial = np.arange(1,16,1).reshape((3,5)).transpose()
print 'The initial array is :\n{}\n'.format(initial)
#Question a: generate a new array that contains the 2nd and 4th rows
initial_a = initial[(1,3), :]
print 'A new array containing the 2nd and 4th rows is :\n{}\n'.format(initial_a)
#Question b: generate a new array that contains the 2nd column
initial_b = initial[:,1]
print 'A new array containing the 2nd colunm is :\n{}\n'.format(initial_b)
#Question c: generate a new array that contains all the elements between [1,0] and [3,2].
initial_c = initial[1:4, :]
print 'A new array containing elements in the rectangular section between [1,0] and [3,2] is :\n{}\n'.format(initial_c)
#Question d: generate a new array that contains elements who's value are between 3 and 11
selection_d = (initial >= 3) * (initial <= 11)
initial_d = initial[selection_d]
print 'A new array containing elements whose value are between 3 and 11 is :\n{}\n'.format(initial_d)
|
ddb6449e2fa4edd65569aa5cde8c3efa0f671c8d | ky822/assignment7 | /ql516/question4.py | 1,632 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def construct_a_grid():
"""
construct a grid of c = x + 1j*y values in range [-2,1] x [-1.5,1.5]
Return
======
an m x n numpy array
"""
grid_number = 100
x = np.linspace(-2,1,grid_number)
y = np.linspace(-1.5,1.5,grid_number)
c = []
for i in range(grid_number):
row = []
for j in range(grid_number):
C_element = x[i]+1j*y[j]
row.append(C_element)
c.append(row)
c = np.array(c)
return c
def do_iteration(c):
"""
Do the Mandelbrot iteration
Argument
========
the grid array C
Return
======
array : the result of the iteration
"""
N_max = 50
z = np.copy(c)
for v in range(N_max):
z = z**2+c
return z
def generate_mask_array(z):
"""
return a boolean matrix mask indicating which points are in the set
"""
some_threshold = 50
mask = abs(z) < some_threshold
return np.array(mask)
def MandelbrotPlot(mask):
"""
plot the image of the points in the set and save it
"""
import matplotlib.pyplot as plt
plt.imshow(mask.T,extent=[-2,1,-1.5,1.5])
plt.gray()
plt.savefig('mandelbrot.png')
def mandelbrot():
"""
the main function to generate a mandelbrot plot
"""
c = construct_a_grid()
z = do_iteration(c)
mask = generate_mask_array(z)
MandelbrotPlot(mask)
print "The mandelbrot image has been saved in the working directory"
if __name__ == "__main__":
mandelbrot()
|
39e36aeb85538a4be57dd457d005fd12bc642e25 | ky822/assignment7 | /ql516/question3.py | 1,927 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def array_generate():
"""
generate a 10x3 array of random numbers in range[0,1]
"""
array = np.random.rand(10,3)
return array
def GetClosestNumber(array):
"""
for each row, pick the number closest to .5
"""
min_index = np.argmin(np.abs(array-0.5),1)
closest_array = array[np.arange(10),min_index]
return closest_array
def GetClosestNumberBySort(array):
"""
Generte an array contain the numbers closest to 0.5 in each rows
Argument
========
array: numpy array
Return
======
an array contain the closest numbers
Example
=======
>>>array1 = array_generate()
>>>array1
array([[ 0.63665097, 0.50696162, 0.76121097],
[ 0.68714886, 0.20228392, 0.52424866],
[ 0.3275332 , 0.76667842, 0.41314787],
[ 0.05645787, 0.6146244 , 0.69211519],
[ 0.13655137, 0.84564668, 0.57381465],
[ 0.65070546, 0.7825995 , 0.67390848],
[ 0.23796975, 0.97312122, 0.87593416],
[ 0.39804522, 0.30356075, 0.79707104],
[ 0.45504483, 0.28996881, 0.71733035],
[ 0.94605093, 0.65489037, 0.54693193]])
>>>print GetClosestNumberBySort(array1)
array[ 0.50696162 0.52424866 0.41314787 0.6146244 0.57381465 0.65070546
0.23796975 0.39804522 0.45504483 0.54693193]
"""
row_number = 10
array_abs = np.abs(array-0.5)
array_sorted_index = np.argsort(array_abs)
sorted_array = array[np.arange(row_number).reshape((row_number,1)),array_sorted_index]
closest_array = sorted_array[:,0]
return closest_array
def main():
array = array_generate()
print array
#print "get closest number: \n",GetClosestNumber(array)
print "get closest number for each row: \n", GetClosestNumberBySort(array)
if __name__ == "__main__":
main()
|
32d88c9bf149a9f95d4b9dc97f28ebb06291a881 | ky822/assignment7 | /xz1082/question3.py | 989 | 4.09375 | 4 | import numpy as np
def answers():
print '\n------------this is question 3---------------'
array = np.random.rand(10, 3)
print 'The initial array is:\n{}\n'.format(array)
#3a
#find the minimum number in each row after subtracting 0.5 from each element in the matrix
array_close_to_half = abs(array - 0.5).min(axis = 1)
#3b
#argsort the elements in each row of the new matrix after subtracting each element by 0.5
row_sort = np.argsort(abs(array - 0.5), axis = 1)
#select the first column in the new matrix which is the index of the number closet to 0.5 in each row
column_index = row_sort[:, 0]
#3c
#create an array with range(0, number of rows)
row_index = np.arange(len(array))
#fancy indexing
result_array = array[row_index, column_index]
print 'New array containing the values closest to 0.5 in each row of original array is:\n{}\n'.format(result_array)
if __name__ == '__main__':
answers()
|
7d82924a9a4123d5a340cbbd352ddea2bd4b3e18 | ky822/assignment7 | /wl1207/question1.py | 694 | 4.125 | 4 | import numpy as np
def function():
print "This is the answer to question1 is:\n"
array = np.array(range(1,16)).reshape(3,5).transpose()
print "The 2-D array is:\n",array,"\n"
array_a = array[[1,3]]
print "The new array contains the 2nd column and 4th rows is:\n", array_a, "\n"
array_b = array[:, 1]
print "The new array contains the 2nd column is:\n",array_b, "\n"
array_c = array[1:4, :]
print "The new array contains all the elements in the rectangular section is:\n", array_c, "\n"
array_d = array[np.logical_and(array>=3, array<=11)]
print "The new array contains all the elements between 3 and 11 is:\n", array_d, "\n"
if __name__ =='__main__':
function()
|
5bf6e766d1df7624410a3b1fc243cfb1bc3b096b | ky822/assignment7 | /mj1547/Question2.py | 464 | 3.984375 | 4 | '''
@author: jiminzi
'''
from numpy import *
def Question2():
# create the array from 0 to 24 and 5*5
a = arange(25).reshape(5,5)
b = array([1., 5, 10, 15, 20])
#re shape the b array to a column
b = b.reshape(5,1)
#divide each column by b.reshape
result2 = divide(a,b)
print 'question 2\n'
print 'divide each column of a by b by construct an array by repeating'
print result2
if __name__ == '__main__':
Question2() |
81f5a75d870f8e67f5694b03307f80a98a879c0d | f287772359/pythonProject | /practice_9.py | 2,983 | 4.125 | 4 | from math import sqrt
# 动态
# 在类中定义的方法都是对象方法(都是发送给对象的消息)
# 属性名以单下划线开头
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter方法
@property
def name(self):
return self._name
# 访问器 - getter方法
@property
def age(self):
return self._age
# 修改器 - setter方法
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)
class Person(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)
# 静态
# 实际上,写在类中的方法并不需要都是对象方法,例如定义一个“三角形”类,
# 通过传入三条边长来构造三角形,
# 用于验证三条边是否构成三角形的方法显然不是对象方法
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a, b, c = 3, 4, 5
# 静态方法和类方法都是通过给类发消息来调用的
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print(t.perimeter())
# 也可以通过给类发消息来调用对象方法但是要传入接收消息的对象作为参数
# print(Triangle.perimeter(t))
print(t.area())
# print(Triangle.area(t))
else:
print('无法构成三角形.')
# person = Person('王大锤', 22)
# person.play()
# person._gender = '男'
# print(person._gender) # slots限定了绑定的属性,gender可以赋值并输出,但需要加单下划线
# person._is_gay = True # slots中没有这个属性,所以添加此属性,赋值以及输出
# print(person._is_gay)
# person = Person('王大锤', 12)
# person.play()
# person.age = 22
# person.play()
# person.name = '白元芳' # AttributeError: can't set attribute
if __name__ == '__main__':
main() |
a8cac862a46c4305f8fdffe159af73950c612ed7 | zhuangzhuangsun/pgnlm | /pgnlm/helperfuncs.py | 5,837 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: jorag
"""
import numpy as np
def length(x):
"""Returns length of input.
Mimics MATLAB's length function.
"""
if isinstance(x, (int, float, complex, np.int64)):
return 1
elif isinstance(x, np.ndarray):
return max(x.shape)
try:
return len(x)
except TypeError as e:
print('In length, add handling for type ' + str(type(x)))
raise e
def rand_coord(x_range, y_range, n_coords, unique_only=True):
"""Create a list of random coordinates from specified x and y range.
Can be used for sampling random pixels from images.
By default the draw is without replacement, but that can be changed by
setting unique_only = False
"""
# Create inital list of coordinates
x = np.random.randint(x_range[0], high=x_range[1], size=n_coords)
y = np.random.randint(y_range[0], high=y_range[1], size=n_coords)
# Initialize output
coord_list = []
if unique_only:
# Combine and check
for i_coord in range(0, length(x)):
coord_candidate = (x[i_coord], y[i_coord])
# Regenerate in case coordinate has been generated before
while coord_candidate in coord_list:
coord_candidate=(np.random.randint(x_range[0], high=x_range[1]),
np.random.randint(y_range[0], high=y_range[1]))
# Add unique coordinate to list
coord_list.append(coord_candidate)
else:
# Combine coordinates
for i_coord in range(0, length(x)):
coord_list.append((x[i_coord], y[i_coord]))
return coord_list
def norm01(input_array, norm_type='global', min_cap=None, max_cap=None, min_cap_value=np.NaN, max_cap_value=np.NaN):
"""Normalise data.
Parameters:
norm_type:
'none' - return input array
'channel' - min and max of each channel is 0 and 1
'global' - min of array is 0, max is 1
min_cap: Truncate values below this value to min_cap_value before normalising
max_cap: Truncate values above this value to max_cap_value before normalising
"""
# Ensure that original input is not modified
output_array = np.array(input_array, copy=True)
# Replace values outside envolope/cap with NaNs (or specifie value)
if min_cap is not None:
output_array[output_array < min_cap] = min_cap_value
if max_cap is not None:
output_array[output_array > max_cap] = max_cap_value
# Normalise data for selected normalisation option
if norm_type.lower() in ['global', 'all', 'set']:
# Normalise to 0-1 (globally)
output_array = input_array - np.nanmin(input_array)
output_array = output_array/np.nanmax(output_array)
elif norm_type.lower() in ['band', 'channel']:
# Normalise to 0-1 for each channel (assumed to be last index)
# Get shape of input
input_shape = input_array.shape
output_array = np.zeros(input_shape)
# Normalise each channel
for i_channel in range(0, input_shape[2]):
output_array[:,:,i_channel] = input_array[:,:,i_channel] - np.nanmin(input_array[:,:,i_channel])
output_array[:,:,i_channel] = output_array[:,:,i_channel]/np.nanmax(output_array[:,:,i_channel])
return output_array
def dB(x, ref=1, input_type='power'):
"""Return result, x, in decibels (dB) relative to reference, ref."""
if input_type.lower() in ['power', 'pwr']:
a = 10
elif input_type.lower() in ['amplitude', 'amp']:
a = 20
return a*(np.log10(x) - np.log10(ref))
def iq2complex(x, reciprocity=False):
"""Merge I and Q bands to complex valued array.
Create an array with complex values from separate, real-vauled Inphase and
Quadrature components.
"""
shape_in = x.shape
# Number of bands determines from of expression
if reciprocity and shape_in[2] == 8:
# Initialise output
array_out = np.zeros((shape_in[0], shape_in[1], 3), dtype=complex)
# Input is real arrays: i_HH, q_HH, i_HV, q_HV, i_VH, q_VH, i_VV, q_VV
array_out[:,:,0] = x[:,:,0] + 1j * x[:,:,1] # HH
array_out[:,:,1] = (x[:,:,2] + 1j*x[:,:,3] + x[:,:,4] + 1j*x[:,:,5])/2 # HV (=VH)
array_out[:,:,2] = x[:,:,6] + 1j * x[:,:,7] # VV
elif not reciprocity and shape_in[2] == 8:
# Initialise output
array_out = np.zeros((shape_in[0], shape_in[1], 4), dtype=complex)
# Input is real arrays: i_HH, q_HH, i_HV, q_HV, i_VH, q_VH, i_VV, q_VV
array_out[:,:,0] = x[:,:,0] + 1j * x[:,:,1] # HH
array_out[:,:,1] = x[:,:,2] + 1j * x[:,:,3] # HV
array_out[:,:,2] = x[:,:,4] + 1j * x[:,:,5] # VH
array_out[:,:,3] = x[:,:,6] + 1j * x[:,:,7] # VV
elif shape_in[2] == 6:
# Initialise output
array_out = np.zeros((shape_in[0], shape_in[1], 3), dtype=complex)
# Input is real arrays: i_HH, q_HH, i_HV, q_HV, i_VV, q_VV (reciprocity assumed)
array_out[:,:,0] = x[:,:,0] + 1j * x[:,:,1] # HH
array_out[:,:,1] = x[:,:,2] + 1j * x[:,:,3] # HV (=VH)
array_out[:,:,2] = x[:,:,4] + 1j * x[:,:,5] # VH
return array_out
def complex2real(c):
"""Divide complex array elements into Re and Im.
Return real valued array.
"""
shape_in = c.shape
# Number of bands determines form of expression
array_out = np.zeros((shape_in[0], shape_in[1], 2*shape_in[2]), dtype=np.float64)
# Get real values of bands
for i_element in range(shape_in[2]):
array_out[:,:,2*i_element] = np.real(c[:,:,i_element])
array_out[:,:,2*i_element+1] = np.imag(c[:,:,i_element])
return array_out
|
07f3932421101e7c415565e2a124dc2eaf9e3975 | KonstantinSKY/LeetCode | /922_Sort_Array_By_Parity_II.py | 981 | 3.515625 | 4 | """922. Sort Array By Parity II https://leetcode.com/problems/sort-array-by-parity-ii/ """
import time
from typing import List
class Solution:
def sortArrayByParityII2(self, A: List[int]) -> List[int]:
even = []
odd = []
res = []
for i in A:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
for i in range(len(even)):
res.append(even[i])
res.append(odd[i])
return res
def sortArrayByParityII(self, A: List[int]) -> List[int]:
res = [0] * len(A)
odd, even = 1, 0
for a in A:
if a % 2:
res[odd] = a
odd += 2
else:
res[even] = a
even += 2
return res
if __name__ == "__main__":
start_time = time.time()
print(Solution().sortArrayByParityII([4,2,5,7]))
print("--- %s seconds ---" % (time.time() - start_time))
|
8991eacf77fc4888ecd774733c4bbeed147bee45 | KonstantinSKY/LeetCode | /961_N-Repeated_Element_in_Size_2N_Array.py | 658 | 3.65625 | 4 | """ 961 https://leetcode.com/problems/n-repeated-element-in-size-2n-array/"""
import time
from typing import List
class Solution:
def repeatedNTimes2(self, A: List[int]) -> int:
for num in A:
if A.count(num) == len(A) / 2:
return num
def repeatedNTimes(self, A: List[int]) -> int:
new = []
for num in A:
if num not in new:
new.append(num)
else:
return num
if __name__ == "__main__":
start_time = time.time()
print(Solution().repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4]))
print("--- %s seconds ---" % (time.time() - start_time))
|
0c7e4a4bbb9de2a3f8ac1df103eb1405b8206a7d | KonstantinSKY/LeetCode | /811_Subdomain_Visit_Count.py | 1,421 | 3.515625 | 4 | """811. Subdomain Visit Count https://leetcode.com/problems/subdomain-visit-count/ """
import time
from typing import List
class Solution:
def subdomainVisits2(self, cpdomains: List[str]) -> List[str]:
domains = {}
for cp in cpdomains:
cp_list = cp.split()
domain_list = cp_list[1].split(".")
for i in range(len(domain_list)):
domain = ".".join(domain_list[i:])
if domain not in domains:
domains.update({domain: 0})
domains[domain] += int(cp_list[0])
print(domains)
return [str(domains[v])+" "+v for v in domains]
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
from collections import defaultdict
domains = defaultdict(int)
for cp in cpdomains:
count, s = cp.split()
count = int(count)
pos = s.find(".")
while pos > 0:
domains[s] += count
pos = s.find(".")
s = s[pos+1:]
return [str(domains[v])+" "+v for v in domains]
if __name__ == "__main__":
start_time = time.time()
print(Solution().subdomainVisits(["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]))
print(Solution().subdomainVisits(["9001 discuss.leetcode.com"]))
print("--- %s seconds ---" % (time.time() - start_time))
|
17d1add048a7e5db1e09574e9d1fe27e3d3112e2 | KonstantinSKY/LeetCode | /running_sum_array.py | 513 | 3.609375 | 4 | """ """
import time
from typing import List
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
if __name__ == "__main__":
start_time = time.time()
print(Solution().runningSum([1, 2, 3, 4]))
print(Solution().runningSum([1, 1, 1, 1, 1]))
print(Solution().runningSum([3, 1, 2, 10, 1]))
print(Solution().runningSum([3]))
print("--- %s seconds ---" % (time.time() - start_time))
|
5de53095fb6440e8b67413a449cc8dd5409ffdde | KonstantinSKY/LeetCode | /905_Sort_Array_By_Parity.py | 785 | 3.609375 | 4 | """ 905 https://leetcode.com/problems/sort-array-by-parity/ """
import time
from typing import List
class Solution:
def sortArrayByParity2(self, A: List[int]) -> List[int]:
res = []
for num in A:
if num % 2 == 0:
res.insert(0, num)
else:
res.append(num)
return res
def sortArrayByParity(self, A: List[int]) -> List[int]:
res1 = []
res2 = []
for num in A:
if num & 1 == 0:
res1.append(num)
else:
res2.append(num)
return res1 + res2
if __name__ == "__main__":
start_time = time.time()
print(Solution().sortArrayByParity([3, 1, 2, 4]))
print("--- %s seconds ---" % (time.time() - start_time))
|
51d7876779936ede418062de2ea567a439f0df4e | KonstantinSKY/LeetCode | /1417_Reformat_The_String.py | 688 | 3.65625 | 4 | """1417. Reformat The String https://leetcode.com/problems/reformat-the-string/ """
import time
from typing import List
class Solution:
def reformat(self, s: str) -> str:
chars1 = list(filter(str.isalpha, s))
chars2 = list(filter(str.isdigit, s))
if abs(len(chars1) - len(chars2)) > 1:
return ""
if len(chars1) < len(chars2):
chars1, chars2 = chars2, chars1
return "".join([char for pair in zip(chars1, chars2) for char in pair] + chars1[len(chars2):])
if __name__ == "__main__":
start_time = time.time()
print(Solution().reformat("a0b1c2d"))
print("--- %s seconds ---" % (time.time() - start_time))
|
cf4f98186af476549d3287c95428522e712123a2 | KonstantinSKY/LeetCode | /977_Squares_of_a_Sorted_Array.py | 551 | 3.734375 | 4 | """977 Squares of a Sorted Array https://leetcode.com/problems/squares-of-a-sorted-array/"""
import time
from typing import List
class Solution:
def sortedSquares1(self, nums: List[int]) -> List[int]:
return sorted([num ** 2 for num in nums])
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted(list(map(lambda x: x ** 2, nums)))
if __name__ == "__main__":
start_time = time.time()
print(Solution().sortedSquares([-4, -1, 0, 3, 10]))
print("--- %s seconds ---" % (time.time() - start_time))
|
6eabac430bffdd2f7480e9f91fe1076da46745db | TakashiNomura/tempy | /test2.py | 472 | 3.640625 | 4 | # coding: UTF-8
import sys
# フィボナッチ数を返す
def fibonacci(n):
a1, a2 = 1, 0
while n > 0:
a1, a2 = a1 + a2, a1
n -= 1
return a1
lines = sys.stdin.readlines()
for i, line in enumerate(lines):
line = line.strip("\n")
if line.isdigit() == True:
floor = int(line)
room = fibonacci(floor)
if floor < 16:
print(room)
if floor >= 16:
print(room%16)
|
d9c561375dadb8c61638d849295d6f6dc454f031 | rodforrb/cobsched | /sched.py | 8,353 | 3.6875 | 4 | '''
Scheduling algorithm implementation
Ben Rodford
'''
import collections
import csv
from dataclasses import dataclass
from collections import defaultdict
from random import shuffle
# https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
# This class represents a directed graph using adjacency matrix representation
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
def BFS(self, s, t, parent):
'''Returns true if there is a path from source 's' to sink 't' in
residual graph. Also fills parent[] to store the path '''
# Mark all the vertices as not visited
visited = [False] * (self.ROW)
# Create a queue for BFS
queue = collections.deque()
# Mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
# Standard BFS Loop
while queue:
u = queue.popleft()
# Get all adjacent vertices's of the dequeued vertex u
# If a adjacent has not been visited, then mark it
# visited and enqueue it
for ind, val in enumerate(self.graph[u]):
if (visited[ind] == False) and (val > 0):
queue.append(ind)
visited[ind] = True
parent[ind] = u
# If we reached sink in BFS starting from source, then return
# true, else false
return visited[t]
# Returns the maximum flow from s to t in the given graph
def EdmondsKarp(self, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (self.ROW)
max_flow = 0 # There is no flow initially
# Augment the flow while there is path from source to sink
while self.BFS(source, sink, parent):
# Find minimum residual capacity of the edges along the
# path filled by BFS. Or we can say find the maximum flow
# through the path found.
path_flow = float("Inf")
s = sink
while s != source:
path_flow = min(path_flow, self.graph[parent[s]][s])
s = parent[s]
# Add path flow to overall flow
max_flow += path_flow
# update residual capacities of the edges and reverse edges
# along the path
v = sink
while v != source:
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = parent[v]
return max_flow
@dataclass
class Avail:
name : str
hours : int
timeslots : tuple
@dataclass
class Shift:
# specific to time and location
timeslot : str
staff : int
def edges_to_graph(edges, size):
graph = []
for i in range(size):
graph.append([0]*size)
for u, v, c in edges:
graph[u][v] = c
return graph
def max_flow_edges(edges):
# highest numbered node
size = max(edges, key=lambda e: e[1])[1] + 1
G = Graph(edges_to_graph(edges, size))
G.EdmondsKarp(0, 1)
residual = G.graph
max_flow_edges = []
for u,v,c in edges:
max_flow_edges.append( (u, v, residual[v][u]) )
return max_flow_edges
'''
expects a csv file
'''
def avail_from_file(filename):
avail = []
with open(filename, 'r') as filein:
lines = csv.reader(filein)
titles = lines.__next__()
for line in lines:
ts = [] # timeslots
for l, location in enumerate(line[2:5]):
if location == "1":
for t, timeslot in enumerate(line[5:]):
if timeslot == "1":
ts.append(titles[l+2] + titles[t+5])
shuffle(ts)
avail.append(Avail(line[0], # name
int(line[1]), # hours
ts.copy())) # randomized timeslots
return avail
def shifts_from_file(filename):
shifts = []
with open(filename, 'r') as filein:
lines = csv.reader(filein)
titles = lines.__next__()[1:]
for line in lines:
for i, staff in enumerate(line[1:]):
shifts.append(Shift(line[0]+titles[i], staff))
return shifts
'''
avail : Avail
where locations and days are tuples of (0 or 1) booleans
days is made of 7 3-tuples representing availability for
morning/daytime/evening for each day
shifts : Shifts
returns schedule of type dict{str : list[shift]} ,
contracts of type dict{shift : list[str]}
'''
def run_graph(avail, shifts):
# edges is a list of (u, v, capacity) tuples, derived as follows:
# name becomes u
# every timeslot becomes a separate v
# name -> slot capacities = 1 # TODO could do number of hours?
# source -> name capacities = max allocation per person
# slot -> sink capacities = inf
edges = []
# source node is 0
# sink node is 1
# remaining nodes start at 2
node_index = 2
name_to_node = {}
node_to_name = {}
node_to_shift = {}
# reducing the problem to a flow diagram
# adding shift nodes and edges
for s in shifts:
if s.timeslot not in name_to_node:
name_to_node[s.timeslot] = node_index
node_to_shift[node_index] = s.timeslot
# attach timeslot to sink
edges.append((name_to_node[s.timeslot], 1, int(s.staff)))
node_index += 1
# adding person nodes and edges
for person in avail:
# person has no node yet so make them one
name_to_node[person.name] = node_index
node_to_name[node_index] = person.name
# attach source to person
edges.append((0, name_to_node[person.name], int(person.hours)))
for ts in person.timeslots:
# attach person to timeslot
edges.append((node_index, name_to_node[ts], 1))
node_index += 1
# solve the flow network
max_flow = max_flow_edges(edges)
# un-reducing back to a schedule
schedule = defaultdict(list) # {person : [shifts]}
contracts = defaultdict(list) # {shift : [people]}
for u,v,c in max_flow:
# check if node is a person
if u in node_to_name:
# check if person is assigned to that shift
if c > 0:
contracts[node_to_name[u]].append(node_to_shift[v])
schedule[node_to_shift[v]].append(node_to_name[u])
return schedule, contracts
def schedule_to_file(schedule, filename):
# minimum lines for times
padding = (6, 6, 6)
with open(filename, 'w') as fileout:
# columns are going to be written horizontally, then transposed
lines = []
for location in ('Ald', 'Tans', 'Cent'):
lines.append([location])
for day in ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'):
line = [day]
for time in (1, 2, 3):
line.append(['Morning', 'Daytime', 'Evening'][time-1])
timeslot = location+str(time)+day
rows = 0
for person in schedule[timeslot]:
line.append(person)
rows += 1
while rows < padding[time-1]:
line.append('')
rows += 1
# minimum 1 empty line
line.append('')
lines.append(line)
# transpose the 2d list/matrix and write
# the width becomes the number of lines
width = len(max(lines, key=len))
print("width:", width)
for i in range(width):
for j in range(len(lines)):
# the row still has elements to add
if i < len(lines[j]):
fileout.write(lines[j][i] + ',')
else:
# otherwise we need to pad the column
fileout.write(',')
fileout.write('\n')
avail = avail_from_file("avail.csv")
shifts = shifts_from_file("shifts.csv")
schedule, contracts = run_graph(avail, shifts)
print(schedule)
schedule_to_file(schedule, "schedule.csv")
|
1757639b83d3a01f0586d78340f1e759d0213b14 | vdedejski/course-AI | /code.finki tasks/Lab01-2020/gradebook.py | 819 | 3.515625 | 4 | from math import ceil
def sumPoints(points):
li = [int(i) for i in points]
grade = ceil(sum(li)/10)
if grade >= 6: return grade
else: return 5
if __name__ == '__main__':
dictionary = {}
while True:
s = input()
if s == 'end': break
listInformation = s.split(",")
name = listInformation[0] + " " + listInformation[1]
index = listInformation[2]
course = listInformation[3]
points = [listInformation[4], listInformation[5], listInformation[6]]
totalPoints = sumPoints(points)
tuple = [name, course, totalPoints]
dictionary.setdefault(index, []).append(tuple)
for x in dictionary.keys():
print(f'\nStudent: {dictionary[x][0][0]}')
for i in dictionary[x]:
print(f'\t{i[1]}: {i[2]}')
|
16cc78a20222a11c562fb235a71d7d1f1f46c347 | yanzn0415/myedu | /day04/obiect_demo.py | 608 | 3.625 | 4 | class yan(object):
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def tiaochuan(self):
print('%s在跳船'%self.name)
def shuijiao(self):
print('%s在睡觉'%self.name)
class nan(yan):
def gongzuo(self):
self.tiaochuan
print('%s在修船'%self.name)
self.shuijiao
print('%s没修好'%self.name)
if __name__ == '__main__':
# nan=yan('杰克','25','男')
# nan.tiaochuan()
# nan.shuijiao()
# nan.tiaochuan()
nan=nan('杰克','25','男')
nan.gongzuo()
nan.shuijiao() |
deb9eb639725ca8cf4abf150161ec37108db96b6 | HaugenBits/CompProg | /ProgrammingChallenges/Chapter_1/CheckTheCheck/ChecktheCheck.py | 4,658 | 3.546875 | 4 | import sys
class ChessBoard:
def __init__(self, cBoard, num):
self.cBoard = cBoard
self.num = num
self.kinginCheck = "no"
self.kingOnBoard = False
def checkForCheck(self):
for y, line in enumerate(self.cBoard):
for x, ele in enumerate(line.strip()):
self.checkTile(ele, x, y)
def setKingInCheck(self, ele):
if isWhite(ele):
self.kinginCheck = "black"
else:
self.kinginCheck = "white"
def checkTile(self, ele, x, y):
if ele == ".":
return
elif ele == "p" or ele == "P":
if checkPawn(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "b" or ele == "B":
if checkBishop(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "r" or ele == "R":
if checkRook(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "n" or ele == "N":
if checkKnight(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "q" or ele == "Q":
if checkQueen(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "k" or ele == "K":
self.kingOnBoard = True
def printResult(self):
if self.kingOnBoard:
print("Game #", self.num, ": ", self.kinginCheck, " king is in check.", sep='')
def inBounds(x, y):
return 0 <= x < 8 and 0 <= y < 8
def isWhite(piece):
return piece.isupper()
def isBlack(piece):
return not piece.isupper()
def isWhiteKing(piece):
return piece == 'K'
def isBlackKing(piece):
return piece == 'k'
def handleInputV1():
lines = sys.stdin.readlines()
boards = []
for i in range(0, len(lines), 9):
boards.append([i.strip() for i in lines[i:i+8]])
return boards
def handleInputV2():
with open("simpleTest.txt", "r") as fil:
lines = fil.readlines()
boards = []
for i in range(0, len(lines), 9):
boards.append([i.strip() for i in lines[i:i+8]])
return boards
def getKnightMoves(x, y):
return [(x+i, y+k) for i, k in [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)]]
def getDirections(x, y):
n, w, s, e = (y - 1, x - 1, y + 1, x + 1)
return n, w, s, e
def getDiagonals(x, y):
nw = [(x-i, y-k) for i, k in zip(range(1, x+1), range(1, y+1))]
ne = [(x+i, y-k) for i, k in zip(range(1, 8-x), range(1, y+1))]
sw = [(x-i, y+k) for i, k in zip(range(1, x+1), range(1, 8-y))]
se = [(x+i, y+k) for i, k in zip(range(1, 8-x), range(1, 8-y))]
return [nw, ne, sw, se]
def getCross(x, y):
n = [(x, y-i) for i in range(1, y+1)]
w = [(x-i, y) for i in range(1, x+1)]
s = [(x, y+i) for i in range(1, 8-y)]
e = [(x+i, y) for i in range(1, 8-x)]
return [n, w, s, e]
def checkPawn(pawn, x, y, board):
n, w, s, e = getDirections(x, y)
if isWhite(pawn):
nw = inBounds(w, n) and isBlackKing(board[n][w])
ne = inBounds(e, n) and isBlackKing(board[n][e])
return nw or ne
if isBlack(pawn):
sw = inBounds(w, s) and isWhiteKing(board[s][w])
se = inBounds(e, s) and isWhiteKing(board[s][e])
return sw or se
def checkKnight(ele, x1, y1, board):
area = getKnightMoves(x1, y1)
for x, y in area:
if inBounds(x, y):
current = board[y][x]
whitecheck = isWhite(ele) and current == "k"
blackcheck = isBlack(ele) and current == "K"
if whitecheck or blackcheck:
return True
return False
def checkBishop(piece, x, y, board):
area = getDiagonals(x, y)
return checkPiece(piece, board, area)
def checkRook(piece, x, y, board):
area = getCross(x, y)
return checkPiece(piece, board, area)
def checkQueen(piece, x, y, board):
area = getDiagonals(x, y) + getCross(x, y)
return checkPiece(piece, board, area)
def checkPiece(piece, board, area):
for direction in area:
for xCoord, yCoord in direction:
current = board[yCoord][xCoord]
whitecheck = isWhite(piece) and current == "k"
blackcheck = isBlack(piece) and current == "K"
if whitecheck or blackcheck:
return True
elif current != ".":
break
return False
def main():
boards = handleInputV2()
for val, board in enumerate(boards, 1):
current = ChessBoard(board, val)
current.checkForCheck()
current.printResult()
print()
if __name__ == '__main__':
main()
|
54354c8ecf440c6da31add2fb1464a295193f6db | amenzl/programming-challenge | /DAG.py | 640 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 07:38:37 2019
@author: anna
"""
import networkx as nx
#networkx creates graphs, functions include Graph(), add_nodes, add_edges
G=nx.Graph()
class DAG(nodes, edges):
def __init__(self):
self.nx.Graph()
def add_node(nodes):
for i in nodes:
nx.add_node(i)
def add_edges(edges):
for i in edges:
nx.add_egdes
##Note sure yet what to put here
class node(name, number, neighbor1, neighbor2):
def __init__(self):
class edges()
##To draw the graph
nx.draw(G)
|
441782770872fb7fd4b5d74caf8efe783bafbc76 | lion7500000/python-selenium-automation | /Python program/1111111.py | 222 | 3.5625 | 4 | def likes(names):
for name in names:
i = [name]
print (i)
if len[i] >= 4:
print (f'{i[0]},{i[1]} and 2 others like this')
names =["Ivan","Petr","Slava","Nik"]
print (likes(names)) |
f9ef83fec9801fce7dbaa3ff233147568fa3e17e | slawiko/machine-learning-examples | /Week_1/Lesson_2_Signs_Importance/importance.py | 654 | 3.5 | 4 | import numpy
import pandas
from sklearn.tree import DecisionTreeClassifier
default_data = pandas.read_csv('../titanic.csv', index_col='PassengerId')
data = pandas.DataFrame(data=default_data, columns=['Survived', 'Pclass', 'Fare', 'Age', 'Sex'])
data = data.dropna()
data = data.replace(to_replace='male', value=1)
data = data.replace(to_replace='female', value=0)
target_data = numpy.array(pandas.DataFrame(data=data, columns=['Pclass', 'Fare', 'Age', 'Sex']))
target_variable = numpy.array(pandas.DataFrame(data=data, columns=['Survived']))
clf = DecisionTreeClassifier()
clf = clf.fit(target_data, target_variable)
print clf.feature_importances_
|
7c04c0d710d45acf96f6c7f87ec27dcf4a316112 | twsswt/pydysofu | /pydysofu/find_lambda.py | 1,535 | 3.59375 | 4 | """
Utility routines for extracting lambda expressions from source files.
@twsswt
"""
import ast
def find_candidate_object(offset, source_line):
start = source_line.index('lambda', offset)-1
end = start + 7
while end <= len(source_line):
try:
candidate_source = source_line[start:end]
return compile(candidate_source, filename='blank', mode='exec').co_consts[0], candidate_source, end
except SyntaxError:
end += 1
def find_lambda_ast(source_line, lambda_object):
"""
Searches for the source code representation of the supplied lambda object within the line of code. Note that the
source line does not have to be a valid Python statement or expression, but *the search assumes that the lambda
expression is delimited by brackets*. Compiled byte codes and name declarations from the supplied lambda_object
are compared against potential candidates, since a source line may contain several lambda functions.
:param source_line: the line of code to search.
:param lambda_object: the compiled representation of the lambda expression.
:return : An AST representation of the lambda expression.
"""
offset = 0
while True:
candidate_object, candidate_source, offset = find_candidate_object(offset, source_line)
if candidate_object.co_code == lambda_object.func_code.co_code:
if candidate_object.co_names == lambda_object.func_code.co_names:
return ast.parse(candidate_source).body[0]
|
07de99725f8f7c3efe6099dc1502106fe24b6b53 | Luffky/INFOX | /app/analyse/util/localfile_tool.py | 2,266 | 3.703125 | 4 | import os
import json
def write_to_file(file, obj):
""" Write the obj as json to file.
It will overwrite the file if it exist
It will create the folder if it doesn't exist.
Args:
file: the file's path, like : ./tmp/INFOX/repo_info.json
obj: the instance to be written into file (can be list, dict)
Return:
none
"""
path = os.path.dirname(file)
if not os.path.exists(path):
os.makedirs(path)
with open(file, 'w') as write_file:
write_file.write(json.dumps(obj))
print('finish write %s to file....' % file)
def get_repo_info(main_path):
""" Get the info of repo.
Args:
main_path: the file store location.
Return:
A json object.
"""
with open(main_path + '/repo_info.json') as read_file:
repo_info = json.load(read_file)
return repo_info
def get_forks_info_dict(main_path):
""" Get the info of fork.
It includes language, description, forks number.
Args:
main_path: the file store location.
Return:
A dict contains information of the forks.
The key is fork's full name, the value is a dict of fork's information.
"""
# print '---------------------------------------'
forks_info = {}
with open(main_path + '/forks.json') as read_file:
forks_list = json.load(read_file)
for fork in forks_list:
fork_name = fork["full_name"].split('/')[0]
forks_info[fork_name] = fork
return forks_info
"""
def get_forks_list(main_path):
# Get the list of forks and it's last committed time.
#Args:
# main_path: the file store location.
#Return:
# A list of tuple of fork's full name and last committed time.
forks = []
dir_list = os.listdir(main_path)
for dir in dir_list:
if os.path.isdir(main_path + '/' + dir):
with open(main_path + '/' + dir + '/commits.json') as read_file:
commits = json.load(read_file)
try:
date = commits[0]["commit"]["committer"]["date"]
forks.append((dir, date))
except:
pass
# print "missing commit on %s" % dir
return forks
"""
|
af2936763343333885ceb68b18f675591da9885e | yvanwangl/pythonLesson | /itertoolsFuncs/countFunc.py | 554 | 3.859375 | 4 | import itertools
# for it in itertools.count(1):
# print(it)
# for it in itertools.cycle('abc'):
# print(it)
# for it in itertools.repeat('b'):
# print(it)
# for it in itertools.repeat('b', 3):
# print(it)
# for it in itertools.takewhile(lambda x: x <= 10, itertools.count(1)):
# print(it)
# for it in itertools.chain('abc', 'xyz'):
# print(it)
# for key, group in itertools.groupby('AaBBBcc'):
# print(key, list(group))
for key, group in itertools.groupby('AaBBbCc', lambda x: x.upper()):
print(key, list(group))
|
893e14ac378b0716ae960815d2e35d935c4b3726 | adriano2004/Dobro_Triplo_Raiz | /dtr.py | 179 | 4 | 4 | n = float(input('Digite um número: '))
dobro = n*2
triplo = n*3
raiz = n** (1/2)
print(' O dobro é {} \n O triplo é {} \n A raiz quadrada é {:.2f}'.format(dobro,triplo,raiz)) |
8ce335b82eb993c91cfeb10aff2a127fe45c246f | huangm96/Intro-Python-II | /src/player.py | 1,457 | 3.703125 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.backpack = []
def travel(self, direction_cmd):
new_room = self.room.get_room_in_direction(direction_cmd)
if new_room is not None:
self.room = new_room
print(f"\n************************* WALKING ***************************")
else:
print("\n******************** You cannot go there! ************************\n")
def pick_up_item(self, item):
# if item is in the room, put it in backpack, and remove from the room
if item in self.room.items:
print(f"\n************** Picked_up {item}! ******************\n")
self.backpack.append(item)
self.room.items.remove(item)
print(f"Your backpack: {self.backpack}")
else:
print("This item is not in the room!")
def drop_item(self, item):
# if item is in the backpack, remove from backpack and put it in the room
if item in self.backpack:
print(f"\n************** Dropped {item}! ******************\n")
self.backpack.remove(item)
self.room.items.append(item)
print(f"Your backpack: {self.backpack}")
else:
print("This item is not in your backpack!")
|
cf4f2389d5b947b91a22e50f75820bc7ded815f9 | Kamilet/learning-coding | /simple-program/check-io-solutions/remove-accents.py | 873 | 3.53125 | 4 | ACIENTS = {'ā': 'a', 'á': 'a', 'ǎ': 'a', 'à': 'a', 'ă': 'a',
'ō': 'o', 'ó': 'o', 'ǒ': 'o', 'ò': 'o', 'ớ': 'o',
'ê': 'e', 'ē': 'e', 'é': 'e', 'ě': 'e', 'è': 'e',
'ī': 'i', 'í': 'i', 'ǐ': 'i', 'ì': 'i',
'ū': 'u', 'ú': 'u', 'ǔ': 'u', 'ù': 'u',
'ǖ': 'u', 'ǘ': 'u', 'ǚ': 'u', 'ǜ': 'u', 'ü': 'u'}
import codecs
def checkio(in_string):
"remove accents"
in_string = list(in_string)
for i in range(len(in_string)):
if in_string[i] in ACIENTS:
in_string[i] = ACIENTS[in_string[i]]
return ''.join(in_string)
# These "asserts" using only for self-checking and not necessary for
# auto-testing
if __name__ == '__main__':
assert checkio(u"préfèrent") == u"preferent"
assert checkio(u"loài trăn lớn") == u"loai tran lon"
print('Done')
|
6779c9a4de1ac252d6c913d5de26aff3cbc64153 | Kamilet/learning-coding | /python/ds_reference.py | 534 | 4.25 | 4 | print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist只是指向同一对象的另一名称
mylist = shoplist
# 购买了apple删除
del shoplist[0] #和在mylist中删除效果一样
print('shoplist is', shoplist)
print('my list is', mylist)
#注意打印结果
#二者指向同一对象,则会一致
print('Copy by making a full slice')
mylist = shoplist[:] #复制完整切片
#删除第一个项目
del mylist[0]
print('shoplist is', shoplist)
print('my list is', mylist)
#此时已经不同 |
42b4268cba541335b2c70c9b78ceffc486ee429f | Kamilet/learning-coding | /simple-program/check-io-solutions/x-o-referee.py | 1,118 | 3.609375 | 4 | def checkme(ox, game_result):
if ox in game_result:
return True
for i in [0, 1, 2]:
if ox == game_result[0][i]+game_result[1][i]+game_result[2][i]:
return True
if ox == game_result[0][0]+game_result[1][1]+game_result[2][2]:
return True
if ox == game_result[0][2]+game_result[1][1]+game_result[2][0]:
return True
return False
def checkio(game_result):
if checkme('XXX', game_result):
flag = 'X'
elif checkme('OOO', game_result):
flag = 'O'
else:
flag = 'D'
return flag
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio([
"O.X",
"XX.",
"XOO"]) == "X", "Xs wins again"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
98cf14d0264de7daa98d239358b3778c549d9e85 | Kamilet/learning-coding | /simple-program/check-io-solutions/reverse_roman.py | 996 | 3.765625 | 4 | '''罗马数字转阿拉伯数字'''
'''
Numeral Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
'''
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
def reverse_roman(roman_string):
number = 0
for i in range(0, len(roman_string)-1):
if roman_dict[roman_string[i]] < roman_dict[roman_string[i+1]]:
number -= roman_dict[roman_string[i]]
else:
number += roman_dict[roman_string[i]]
return abs(number) + roman_dict[roman_string[-1]]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert reverse_roman('VI') == 6, '6'
assert reverse_roman('LXXVI') == 76, '76'
assert reverse_roman('CDXCIX') == 499, '499'
assert reverse_roman('MMMDCCCLXXXVIII') == 3888, '3888'
print('Great! It is time to Check your code!');
assert reverse_roman('MMMCMXCIX') == 3999, '3999' |
f055c541cf8f0622ac8323b7ac1cde14c1c21b40 | Kamilet/learning-coding | /simple-program/check-io-solutions/bird-language.py | 564 | 3.515625 | 4 | '''
辅音字母后随机加一个元音字母
元音字母重复2次
元音字母aeiouy
反向翻译
'''
def translate(song):
s = 0
word = []
while s != len(song):
word.append(song[s])
if song[s] in 'aeiouyAEIOUY':
s += 3
elif song[s] in ' ?!.':
s += 1
else:
s += 2
return ''.join(word)
translate("hieeelalaooo") == "hello"
translate("hoooowe yyyooouuu duoooiiine") == "how you doin"
translate("aaa bo cy da eee fe") == "a b c d e f"
translate("sooooso aaaaaaaaa") == "sos aaa" |
69ae3110fd5d49957b309a88ebe6229e0c12d493 | Kamilet/learning-coding | /simple-program/check-io-solutions/triangular-number.py | 239 | 3.59375 | 4 | '''
生成三角数
'''
def gen_triangular_number(limit):
numbers = [0]
height = 1
while numbers[-1] <= limit:
numbers.append(numbers[-1]+height)
height+=1
return numbers
print(gen_triangular_number(1000)) |
ae63f36897ced379ec1f7b20bc399182c36682c5 | Kamilet/learning-coding | /python/ds_str_methods.py | 305 | 4.1875 | 4 | #这是一个字符串对象
name = 'Kamilet'
if name.startswith('Kam'):
print('Yes, the string starts with "Kam"')
if 'a' in name:
print('Yes, contains "a"')
if name.find('mil') != -1:
print('Yes, contains "mil"')
delimiter='_*_'
mylist = ['aaa', 'bbb', 'ccc', 'ddd']
print(delimiter.join(mylist)) |
543bae19127af09272b507ba5ad37f2130c8191d | Kamilet/learning-coding | /simple-program/check-io-solutions/skew-symmetric-matrix.py | 3,752 | 4.0625 | 4 | '''
求一个矩阵是否和共轭矩阵+负号相等
'''
# in using sMartix
# https://github.com/Kamilet/Simple-Matrix-python
# From --------------------------------------
def sm_trans(matrix):
'''Transpose'''
_row, _colume = sm_check(matrix)
new_matrix = sm_gen(_colume,_row)
for _r in range(_row):
for _c in range(_colume):
new_matrix[_c][_r] = matrix[_r][_c]
return new_matrix
def sm_copy(matrix):
'''perform a deep copy for matrix'''
_row = len(matrix)
_colume = len(matrix[0])
new_matrix = sm_gen(_row, _colume)
for _r in range(_row):
for _c in range(_colume):
new_matrix[_r][_c] = matrix[_r][_c]
return new_matrix
def sm_check(matrix):
'''Check if the row and colume >=1
Check if all row has same length'''
try:
_row = len(matrix)
_colume = len(matrix[0])
if _colume:
for items in matrix:
if len(items) != _colume:
return False
return _row, _colume
else:
return False
except IndexError:
return False
def sm_numcheck(matrix):
'''Check is matrix is legal.
And all items must be number.'''
if not sm_check(matrix):
return False
_colume = len(matrix[0])
for items in matrix:
for _c in range(_colume):
try:
_temp = eval(str(items[_c]))
except NameError:
return False
except TypeError: # new for plural, wrong input will cause Eror
pass
return True
def sm_number(matrix, force=False):
'''set every numbers to numbertype
set force=True will replace letters and '' with 0'''
new_matrix = sm_copy(matrix)
for _r in range(len(new_matrix)):
for _c in range((len(new_matrix[0]))):
try:
new_matrix[_r][_c] = eval(str(new_matrix[_r][_c]))
except NameError:
assert force, 'Error: Your matrix is not all numbers!\n\
You can try to use force=True for argument in function like:sm_number(matrix, force).'
new_matrix[_r][_c] = 0
except TypeError: # new for plural, wrong input will cause Eror
pass
return new_matrix
def sm_negative(matrix):
'''Set every numbers to -(number)'''
if sm_numcheck(matrix):
new_matrix = sm_copy(matrix)
new_matrix = sm_number(new_matrix)
for _r in range(len(new_matrix)):
for _c in range((len(new_matrix[0]))):
new_matrix[_r][_c] *= -1
return new_matrix
else:
assert False, 'Error: Your matrix is not all numbers'
def sm_gen(row: int = 1, colume: int = 1, items=0, unit=False, eye=False):
'''Generate a matrix with row and colume,
items can be numbers or string (can't calculate)
set unit=True or eye=True to generate a unit matrix with row: sm_gen(row, eye=True)'''
if unit or eye:
matrix = sm_gen(row, row, items=0)
for i in range(row):
matrix[i][i] = 1
else:
matrix = [None] * row
for _r in range(row):
matrix[_r] = [items] * colume
return matrix
# End --------------------------------------
def checkio(matrix):
return matrix == sm_negative(sm_trans(matrix))
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([
[0, 1, 2],
[-1, 0, 1],
[-2, -1, 0]]) == True, "1st example"
assert checkio([
[0, 1, 2],
[-1, 1, 1],
[-2, -1, 0]]) == False, "2nd example"
assert checkio([
[0, 1, 2],
[-1, 0, 1],
[-3, -1, 0]]) == False, "3rd example"
|
aaff8a9ee177b70e7a554239ab6a848a23fc1489 | Kamilet/learning-coding | /simple-program/check-io-solutions/achilles-tortoise.py | 728 | 3.5 | 4 | '''
追击问题
输入checkio(v_fast,v_slow,advantage)
v_fast和v_slow代表两人速度
advantage代表慢的人领先的时间
求追击时间
'''
def chase(v_fast, v_slow ,advantage):
chase_time = advantage * v_fast / (v_fast - v_slow)
# print(round(chase_time,8))
return round(chase_time,8)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
def almost_equal(checked, correct, significant_digits):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert almost_equal(chase(6, 3, 2), 4, 8), "example"
assert almost_equal(chase(10, 1, 10), 11.111111111, 8), "long number"
|
00623edf113252c423ac60fbc70ac528d77c9146 | hzhou/parser | /python_0/calc.py | 2,277 | 3.875 | 4 | import re
def main():
print(calc("1+2*-3"))
def calc(src):
src_len=len(src)
src_pos=0
precedence = {'eof':0, '+':1, '-':1, '*':2, '/':2, 'unary': 99}
re1 = re.compile(r"\s+")
re2 = re.compile(r"[\d\.]+")
re3 = re.compile(r"[-+*/]")
stack=[]
while 1:
while 1: # $do
# r"\s+"
m = re1.match(src, src_pos)
if m:
src_pos=m.end()
continue
# r"[\d\.]+"
m = re2.match(src, src_pos)
if m:
src_pos=m.end()
num = float(m.group(0))
cur=( num, "num")
break
# r"[-+*/]"
m = re3.match(src, src_pos)
if m:
src_pos=m.end()
op = m.group(0)
cur = (op, op)
break
if src_len>=src_pos:
cur = ('', "eof")
break
t=src[0:src_len]+" - "+src[src_len:]
raise Exception(t)
break
while 1: # $do
if cur[1]=="num":
break
if len(stack)<1 or stack[-1][1]!="num":
cur = (cur[0], 'unary')
break
if len(stack)<2:
break
if precedence[cur[1]]<=precedence[stack[-2][1]]:
if stack[-2][1] == "unary":
t = -stack[-1][0]
stack[-2:]=[(t, "num")]
elif stack[-2][1]=='+':
t = stack[-3][0] + stack[-1][0]
stack[-3:]=[(t, "num")]
elif stack[-2][1]=='-':
t = stack[-3][0] - stack[-1][0]
stack[-3:]=[(t, "num")]
elif stack[-2][1]=='*':
t = stack[-3][0] * stack[-1][0]
stack[-3:]=[(t, "num")]
elif stack[-2][1]=='/':
t = stack[-3][0] / stack[-1][0]
stack[-3:]=[(t, "num")]
continue
break
if cur[1]!="eof":
stack.append(cur)
else:
if len(stack)>0:
return stack[-1][0]
else:
return None
if __name__ == "__main__":
main()
|
5db7ec314516082fd84e7feb746374f4aae24fb1 | ranaputta/Timeseries-Notebook | /Concrete Strength.py | 1,745 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import matplotlib as plt
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
# 1. Load the CSV data into a pandas data frame. Print some high-level statistical info about the data frame's columns.
# In[7]:
df=pd.read_csv("Concrete_Data.csv")
df.head()
# 2. How many rows have a compressive strength > 40 MPa?
# In[8]:
sum(df['Concrete_Compressive_Strength']>40)
# 3. Plot the histogram of Coarse Aggregate and Fine Aggregate values
# In[9]:
df.hist("Coarse_Aggregate")
# In[10]:
df.hist("Fine_Aggregate")
# 4. Make a plot comparing compressive strength to age
# In[11]:
df.plot(x="Age",y="Concrete_Compressive_Strength",kind="scatter")
# 5. Make a plot comparing compressive strength to age for only those rows with < 750 fine aggregate.
# In[12]:
df2=df[df["Fine_Aggregate"]<750]
# In[13]:
df2.head()
# In[14]:
df2.plot(x="Age",y="Concrete_Compressive_Strength",kind="scatter")
# 6. Try to build a linear model that predicts compressive strength given the other available fields.
# In[23]:
from sklearn import linear_model
lin_m = linear_model.Lasso(alpha=0.01)
y=df["Concrete_Compressive_Strength"]
x=df.drop("Concrete_Compressive_Strength",axis=1)
lin_m.fit(x,y)
pd.DataFrame([dict(zip(x, lin_m.coef_))])
# 7. Generate predictions for all the observations and a scatterplot comparing the predicted compressive strengths to the actual values.
# In[30]:
predictm = lin_m.predict(x)
predict_df = df.assign(prediction=predictm)
predict_df[["Concrete_Compressive_Strength", "prediction"]]
# In[32]:
predict_df.plot(kind="scatter", x="Concrete_Compressive_Strength", y="prediction")
# In[ ]:
|
ed2333967457b6aa9431fbd57355fd98a326107e | lishuoluke/lintcode_practice | /lintcode_Search a 2D Matrix.py | 574 | 3.828125 | 4 | class Solution:
"""
@param: matrix: matrix, a list of lists of integers
@param: target: An integer
@return: a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if (matrix == []):
return False
numrows = len(matrix) # 3 rows in your example
numcols = len(matrix[0])
for i in range(0, numrows):
for j in range(0, numcols):
if (matrix[i][j] == target):
return True
return False |
7e4ac8f93572c5b82948cd755b6ab5c1c6cab94c | lishuoluke/lintcode_practice | /lintcode_longestwords.py | 436 | 3.609375 | 4 | class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
# write your code here
max = -1
list = []
for item in dictionary:
if len(item) > max:
max = len(item)
for haha in dictionary:
if len(haha) == max:
list.append(haha)
return list
|
d8d779957f605b53341a6b40594394f7e750a4d9 | lishuoluke/lintcode_practice | /lintcode_Two Strings Are Anagrams.py | 355 | 3.671875 | 4 | class Solution:
"""
@param s: The first string
@param t: The second string
@return: true or false
"""
def anagram(self, s, t):
# write your code here
aaa = list(s)
bbb = list(t)
for item in aaa:
if (aaa.count(item) != bbb.count(item)):
return False
return True
|
35e00bb8977bf34fccc17ae88babdd233bb0b2c3 | lishuoluke/lintcode_practice | /Min Stack.py | 604 | 3.734375 | 4 | class MinStack:
def __init__(self):
# do intialization if necessary
self.stack1 = []
self.stack2 = []
def push(self, number):
# write your code here
self.stack1.append(number)
if len(self.stack2) == 0 or number <= self.stack2[-1]:
self.stack2.append(number)
def pop(self):
# write your code here
tmp = self.stack1.pop()
if tmp == self.stack2[-1]:
return self.stack2.pop()
else:
return tmp
def min(self):
# write your code here
return self.stack2[-1]
|
c7b0231d769f6a301883b1ab2020a6f1142f033c | QiyuZ/Voronoi_Pic-App | /Voronoi_realization.py | 7,919 | 3.53125 | 4 | import math
from data_structure import Point, Seg, Arc, Event, PriorityQueue
class Voronoi:
def __init__(self, points):
self.output = [] # Result, a list of segment
self.arc = None # parabola arcs
self.event = PriorityQueue() # circle events, old arc disappears
self.points = PriorityQueue() # site event, new arc appears
# make an origin bounding box
self.x0 = -0.0 # these value can be changed
self.x1 = -0.0
self.y0 = 0.0
self.y1 = 0.0
# insert points
for ps in points:
point = Point(ps[0], ps[1])
self.points.push(point)
# update bounding box
if point.x < self.x0:
self.x0 = point.x
if point.y < self.y0:
self.y0 = point.y
if point.x > self.x1:
self.x1 = point.x
if point.y > self.y1:
self.y1 = point.y
# The follow can also be skipped
dx = (self.x1 - self.x0 + 1) / 10.0
dy = (self.y1 - self.y0 + 1) / 10.0
self.x0 = self.x0 - dx
self.x1 = self.x1 + dx
self.y0 = self.y0 - dy
self.y1 = self.y1 + dy
# main process
def process(self):
# deal with points
while not self.points.empty():
if not self.event.empty() and (self.points.top().x >= self.event.top().x):
self.circle_event() # circle event
else:
self.site_event() # site event
# deal with remaining circle events
while not self.event.empty():
self.circle_event()
# get segment and finish the edge
self.finish_edge()
def finish_edge(self):
val = self.x1 + (self.x1 - self.x0) + (self.y1 - self.y0)
a = self.arc
while a.next is not None:
if a.s1 is not None:
# find the intersected point and make it finished point of s1
p = self.intersection(a.p, a.next.p, val * 3.0)
a.s1.finish(p)
a = a.next # until this is no arc
def circle_event(self):
# get event
e = self.event.pop()
if e.valid:
# add an edge
s = Seg(e.p)
self.output.append(s)
# remove the nearby parabola
a = e.a
if a.pre is not None:
a.pre.next = a.next
a.pre.s1 = s
if a.next is not None:
a.next.pre = a.pre
a.next.s0 = s
# finish the edge
if a.s0 is not None:
a.s0.finish(e.p)
if a.s1 is not None:
a.s1.finish(e.p)
# recheck
if a.pre is not None:
self.check_cEvent(a.pre, e.x)
if a.next is not None:
self.check_cEvent(a.next, e.x)
def site_event(self):
# get new point from points
p = self.points.pop()
# add new arc
self.addArc(p)
def check_cEvent(self, a, x0):
# find new circle event at arc a
if (a.e is not None) and (a.e.x != self.x0):
a.e.valid = False
a.e = None
if (a.pre is None) or (a.next is None):
return
visited, x, o = self.circle(a.pre.p, a.p, a.next.p)
if visited and (x > self.x0):
a.e = Event(x, o, a)
self.event.push(a.e)
def addArc(self, p):
if self.arc is None:
self.arc = Arc(p)
else:
# find the existing arc
a = self.arc
while a is not None:
visited, z = self.intersect(p, a)
if visited:
visited, zz = self.intersect(p, a.next)
if (a.next is not None) and (not visited):
a.next.pre = Arc(a.p, a, a.next)
a.next = a.next.pre
else:
a.next = Arc(a.p, a)
a.next.s1 = a.s1
# add p between a and a.next
a.next.pre = Arc(p, a, a.next)
a.next = a.next.pre
a = a.next # a is new arc now
# create and connect the new line
seg = Seg(z)
self.output.append(seg)
a.pre.s1 = a.s0 = seg
seg = Seg(z)
self.output.append(seg)
a.next.s0 = a.s1 = seg
# check cir event of this new arc
self.check_cEvent(a, p.x)
self.check_cEvent(a.pre, p.x)
self.check_cEvent(a.next, p.x)
return
a = a.next
# if p never intersects an arc, append it to the list
a = self.arc
while a.next is not None:
a = a.next
a.next = Arc(p, a)
# insert new seg
x = self.x0
y = (a.next.p.y + a.p.y) / 2.0
start = Point(x, y)
seg = Seg(start)
a.s1 = a.next.s0 = seg
self.output.append(seg)
def circle(self, a, b, c):
# check if bc is a "right turn" from ab
if ((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)) > 0:
return False, None, None
# This method is learned from Joseph O'Rourke, Computational Geometry in C (2nd ed.) p.189
A = b.x - a.x
B = b.y - a.y
C = c.x - a.x
D = c.y - a.y
E = A * (a.x + b.x) + B * (a.y + b.y)
F = C * (a.x + c.x) + D * (a.y + c.y)
G = 2 * (A * (c.y - b.y) - B * (c.x - b.x))
if (G == 0):
return False, None, None # Points are co-linear
# point o is the center of the circle
ox = 1.0 * (D * E - B * F) / G
oy = 1.0 * (A * F - C * E) / G
x = ox + math.sqrt((a.x - ox) ** 2 + (a.y - oy) ** 2) # o.x plus radius equals max x coord
o = Point(ox, oy) # the centre of a circle;
return True, x, o
def intersect(self, p, a):
# check if the parabola of p intersect with a acr a
# return a visited flag and a point
if (a is None) or (a.p.x == p.x):
return False, None
o1 = 0.0
o2 = 0.0
if a.pre is not None:
o1 = (self.intersection(a.pre.p, a.p, 1.0 * p.x)).y
if a.next is not None:
o2 = (self.intersection(a.p, a.next.p, 1.0 * p.x)).y
# Find the intersection of point
if ((a.pre is None) or (o1 <= p.y)) and ((a.next is None) or (o2 >= p.y)):
py = p.y
px = 1.0 * (a.p.x ** 2 + (a.p.y - py) ** 2 - p.x ** 2) / (2 * a.p.x - 2 * p.x)
res = Point(px, py)
return True, res
return False, None
def intersection(self, p0, p1, xval):
# find the intersection of two parabolas
p = p0
if p0.x == p1.x:
py = (p0.y + p1.y) / 2.0
elif p1.x == xval:
py = p1.y
elif p0.x == xval:
py = p0.y
p = p1
else:
# use quadratic formula
z0 = 2.0 * (p0.x - xval)
z1 = 2.0 * (p1.x - xval)
# calculate the result , cross point
a = 1.0 / z0 - 1.0 / z1
b = -2.0 * (p0.y / z0 - p1.y / z1)
c = 1.0 * (p0.y ** 2 + p0.x ** 2 - xval ** 2) / z0 - 1.0 * (p1.y ** 2 + p1.x ** 2 - xval ** 2) / z1
py = 1.0 * (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a)
px = 1.0 * (p.x ** 2 + (p.y - py) ** 2 - xval ** 2) / (2 * p.x - 2 * xval)
res = Point(px, py)
return res
def get_res(self):
res = []
for ans in self.output:
p0 = ans.start
p1 = ans.end
res.append((p0.x, p0.y, p1.x, p1.y))
return res
|
3f84337e2e1de9db7e2e79b73e5548d6a93084ce | deepdsavani/MachineLearning | /Machine Learning with Data Mining + Data Analysis and Visulization/Assignments solutions of ML for Data mining/cnn tensorflow.py | 4,086 | 3.5 | 4 | import tensorflow as tf
import numpy as np
#from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("data", one_hot=True)
#images_test = mnist.test.images
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
print("x_train shape:", x_train.shape, "y_train shape:", y_train.shape)
print("x_train shape:", x_test.shape, "y_train shape:", y_test.shape)
IMAGE_PIXELS = x_train.shape[1]*x_train.shape[2]*x_train.shape[3];
x_train = x_train.reshape(x_train.shape[0],x_train.shape[1]*x_train.shape[2]*x_train.shape[3]);
x_test = x_test.reshape(x_test.shape[0],x_test.shape[1]*x_test.shape[2]*x_test.shape[3]);
print("x_train shape:", x_train.shape, "y_train shape:", y_train.shape)
print("x_train shape:", x_test.shape, "y_train shape:", y_test.shape)
x_train=x_train/255.0;
x_test=x_test/255.0;
y_Train = [];
y_Test = [];
for l in y_train:
t = np.zeros(10);
t[l]=1;
y_Train.append(t);
for l in y_test:
t = np.zeros(10);
t[l]=1;
y_Test.append(t);
y_train = np.array(y_Train, dtype=np.float32);
y_test = np.array(y_Test, dtype=np.float32);
n_classes = 10
batch_size = 128
# Matrix -> height x width
# height = None, width = 32x32
x = tf.placeholder('float',[None, 32*32*3])
y = tf.placeholder('float')
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def maxpool2d(x):
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
def convolutional_neural_network(x) :
weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,3,32])), # 5x5 convolution 1 input 32 features
'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
'W_fc':tf.Variable(tf.random_normal([8*8*64,1024])),
'out':tf.Variable(tf.random_normal([1024,n_classes]))}
biases = {'b_conv1':tf.Variable(tf.random_normal([32])), # 5x5 convolution 1 input 32 features
'b_conv2':tf.Variable(tf.random_normal([64])),
'b_fc':tf.Variable(tf.random_normal([1024])),
'out':tf.Variable(tf.random_normal([n_classes]))}
x = tf.reshape(x, shape=[-1,32,32,3])
conv1 = tf.add(conv2d(x, weights['W_conv1']),biases['b_conv1'])
conv1 = maxpool2d(conv1)
conv2 = (tf.add(conv2d(conv1, weights['W_conv2']),biases['b_conv2']))
conv2 = maxpool2d(conv2)
fc = tf.reshape(conv2, [-1, 8*8*64])
fc = tf.nn.relu(tf.add(tf.matmul(fc, weights['W_fc']),biases['b_fc']))
output = tf.add(tf.matmul(fc,weights['out']),biases['out'])
return output
prediction = convolutional_neural_network(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)
n_epochs = 20 # cycles of feed forward + backprop
cur = 0
def get_next_epoch_data():
out_x = x_train[cur:cur+batch_size,:]
out_y = y_train[cur:cur+batch_size]
return out_x, out_y
with tf.Session() as sess :
sess.run(tf.global_variables_initializer())
for epoch in range(n_epochs) :
epoch_loss = 0
cur = 0
for _ in range(int(len(x_train)/batch_size) ) :
epoch_x, epoch_y = get_next_epoch_data()
cur += batch_size
_, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
epoch_loss += c
print ('Epoch', epoch, 'completed out of', n_epochs, 'loss:', epoch_loss)
correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct,'float'))
accs = {}
for i in range(int(len(x_test)/batch_size) ) :
accs[i] = accuracy.eval({x:x_test[(i*batch_size):((i+1)*batch_size)], y:y_test[(i*batch_size):((i+1)*batch_size)]})
tot = 0.0
for i in accs :
tot+=accs[i]
print ("Accuracy:", float(tot/((len(x_test)/batch_size))) )
#train_neural_network(x) |
bf8131f0a9c520a177487dc18a37689a2114cf11 | djole103/mangareader | /src/fun.py | 1,420 | 3.609375 | 4 | from collections import Counter
from random import randrange
import math
import re
def main():
str = "Shingeki No Kyojin"
print(str)
strlower = str.lower()
print(strlower)
finalstr = re.sub(pattern='\ ',repl='-',string=strlower)
print(finalstr)
spli = re.sub(pattern='-',repl=' ',string=finalstr)
print(spli)
startstr = spli.title()
print(startstr)
# count = 0;
# dict = {"a":1,"b":2,"c":2}
# print(dict)
# a = [1,2,3,4,5]
# for x in range(1,5):
# print("{}".format(x))
# #for key in dict.keys():
# # print(dict[key])
# prime = True
# for x in range(2,3):
# print(x)
# N = int(input())
# for i in range(2,N):
# print("Integer: {}\n".format(i))
# for x in range(2,math.ceil(math.sqrt(i))+1):
# prime = True
# print("Testing prime on: {}\n".format(x))
# if(i%x==0 and i!=x):
# prime = False
# break
# if prime == True:
# print("Prime: {}".format(i))
# count+=1
# print(count)
# randn = [randrange(10) for i in range(100)]
# print(len(randn))
# cntr = Counter()
# for i in randn:
# cntr[i]+=1
# print(cntr)
# print (cntr[0])
#dict = {key: value for key,value in enumerate(cntr)}
#print (dict)
if __name__ == "__main__":
main() |
2605eb18b7237fe6a6d179741b4bbc55103ece08 | gurgenXD/chess | /src/knight.py | 1,355 | 3.6875 | 4 | from piece import Piece, COLORS, BLACK, WHITE
from empty import Empty
CONSOLE_IMAGE = {
BLACK: '\33[94m♞',
WHITE: '\33[93m♘'
}
class Knight(Piece):
""" Knight """
def make_move(self, piece_to):
if self.can_move(piece_to):
self.board.history.append('{0}({1}) --> {2}({3})'.format(self, self.position, piece_to, piece_to.position))
self.board[self.position], self.board[piece_to.position] = Empty(None, self.board), self.board[self.position]
if self.first_move:
self.first_move = False
if not isinstance(piece_to, Empty):
self.board.deleted_pieces.append(piece_to)
else:
raise Exception('Knight can\'t move there')
def can_move(self, piece_to):
pos_from, pos_to = self.board.get_coords(self.position), self.board.get_coords(piece_to.position)
if self.side != piece_to.side:
if (pos_to[0] in (pos_from[0] - 1, pos_from[0] + 1) and pos_to[1] in (pos_from[1] + 2, pos_from[1] - 2) or
pos_to[0] in (pos_from[0] - 2, pos_from[0] + 2) and pos_to[1] in (pos_from[1] + 1, pos_from[1] - 1)):
return True
return False
def __str__(self):
return CONSOLE_IMAGE[self.side]
def __repr__(self):
return f'<Knight ({COLORS[self.side]})>'
|
2ce8822c0cf6bef4548538f3dffb4ffa6faef59a | FrontEnd404/CIS1501-Fall2020 | /test of lab 7.py | 2,414 | 4.09375 | 4 | import math
def payment_amount(p, r, t):
r = r/(12*100)
t = t*12
payment_amount = (p*r*pow(1+r,t))/(pow(1+r,t)-1)
return payment_amount
def number_of_payments(rate, payment_amount, present_value ):
number_of_payments = (-math.log(1 - rate * present_value/ payment_amount))/ math.log(1 + rate)
return number_of_payments
print("would you like to calculate payment or number of payments?")
which_function = input("if you would like to calculate payment type 1 if you would like to calculate number of payments type 2 ")
if which_function == "1":
keep_going = "yes"
while keep_going == "yes":
try:
principal = float(input("what is the total amount of the loan you took out?"))
except:
print("sorry you must enter a number")
continue
try:
rate = float(input("what is the annual interest rate percentage? "))
except:
print("sorry you must enter a number")
continue
if rate > 100 or rate < 0:
print("sorry the interest rate must be between 1 and 100")
try:
time = float(input("how will it take to pay off this loan?"))
except:
print("sorry you must enter a number")
continue
payment_amount = payment_amount(principal, rate, time)
print("payment amount is $", payment_amount)
keep_going = "no"
if which_function == "2":
keep_going = "yes"
while keep_going == "yes":
try:
present_value = float(input("what is the total amount of the loan you took out?"))
except:
print("sorry you must enter a number")
continue
try:
rate = float(input("what is the annual interest rate percentage? "))/100
except:
print("sorry you must enter a number")
continue
if rate > 100 or rate < 0:
print("sorry the interest rate must be between 1 and 100")
try:
payment_amount = float(input("how much do you pay each period?"))
except:
print("sorry you must enter a number")
continue
number_of_payments = number_of_payments(rate,payment_amount, present_value )
print("the number of payments is", number_of_payments)
keep_going = "no"
|
ecc9a79e0aa2a467f181dde137c589da0c27fd5f | CyrilHub/GA | /Additional Problems/Problem 1 - Linear Search/Problem 1 - Linear Search.py | 228 | 3.875 | 4 | object_list = ["Maria","Dana","David","Lauren","David"]
look_for = "Dana"
def finder(object,target):
for name in object_list:
index = objec
if name == target
print
finder(object_list,look_for)
|
6b5679a3806e7c8dedccd1b71c65fb1b409c3177 | puncoz/machine-learning-kss-yipl | /kss-1-linear-regression/lr-salaries-clean.py | 8,155 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
def linear_equation(m, x, c):
return m * x + c
def plot(x, y, m, c):
plt.scatter(x, y)
plt.xlabel("Experience")
plt.ylabel("Salary")
plt.plot(x, linear_equation(m, x, c), label="fit for line y={0}x + {1}".format(m, c))
plt.legend()
plt.show()
def mse(c, m, x, y):
total_error = 0
for i in range(0, len(x)):
total_error += (y[i] - (m * x[i] + c)) ** 2
return total_error / float(len(x))
def sse(x, y, m, c):
total = 0
for i in range(0, len(x)):
total += (y[i] - (m * x[i] + c)) ** 2
return total
def sst(x, y):
total = 0
y_mean = np.mean(y)
for i in range(0, len(x)):
total += (y[i] - y_mean) ** 2
return total
def r_square(x, y, m, c):
return 1 - sse(x, y, m, c) / sst(x, y)
def r_square_adjusted(x, y, m, c):
n = len(x)
p = 1
return 1 - (1 - r_square(x, y, m, c)) * ((n - 1) / (n - p - 1))
def step_gradient(c_current, m_current, x, y, learning_rate):
c_gradient = 0
m_gradient = 0
n = float(len(x))
for i in range(0, len(x)):
c_gradient += -(2 / n) * (y[i] - ((m_current * x[i]) + c_current))
m_gradient += -(2 / n) * x[i] * (y[i] - ((m_current * x[i]) + c_current))
new_c = c_current - (learning_rate * c_gradient)
new_m = m_current - (learning_rate * m_gradient)
return [new_c, new_m]
def calculate_m_b_with_gradient_descent(x, y, starting_m, starting_c, learning_rate, iterations, is_normalized):
c_best = starting_c
m_best = starting_m
err_best = mse(c_best, m_best, x, y)
r_sq = r_square(x, y, m_best, c_best)
r_sq_ad = r_square_adjusted(x, y, m_best, c_best)
c_arr = np.array([c_best])
m_arr = np.array([m_best])
error_arr = np.array([err_best])
r_sq_arr = np.array([r_sq])
r_sq_ad_arr = np.array([r_sq_ad])
iter_arr = np.array([0])
fig = plt.figure(figsize=(20, 6))
ax = fig.add_subplot(221)
grad, = ax.plot(c_arr, m_arr)
ax.set(xlabel="c", ylabel="m")
if is_normalized:
ax.set_xlim(0, 0.5)
ax.set_ylim(0, 0.1)
else:
ax.set_xlim(0, 500)
ax.set_ylim(0, 2000)
bx = fig.add_subplot(222)
bx.scatter(x, y)
lr, = bx.plot(x, linear_equation(m_best, x, c_best))
cx = fig.add_subplot(223)
ep, = cx.plot(iter_arr, error_arr)
cx.set(xlabel="iterations", ylabel="error")
cx.set_xlim(0, iterations)
cx.set_ylim(0, err_best)
dx = fig.add_subplot(224)
r2, = dx.plot(iter_arr, r_sq_arr, label="r2")
r2_ad, = dx.plot(iter_arr, r_sq_ad_arr, label="r2_ad")
dx.set(xlabel="iterations", ylabel="goodness of fit (r-squared)")
dx.set_xlim(0, iterations)
dx.set_ylim(-1, 1)
dx.legend()
plt.ion()
plt.show()
for i in range(iterations):
c_best, m_best = step_gradient(c_best, m_best, x, y, learning_rate)
err_best = mse(c_best, m_best, x, y)
r_sq = r_square(x, y, m_best, c_best)
r_sq_ad = r_square_adjusted(x, y, m_best, c_best)
print(m_best, c_best, err_best, r_sq, r_sq_ad)
c_arr = np.append(c_arr, c_best)
m_arr = np.append(m_arr, m_best)
error_arr = np.append(error_arr, err_best)
r_sq_arr = np.append(r_sq_arr, r_sq)
r_sq_ad_arr = np.append(r_sq_ad_arr, r_sq_ad)
iter_arr = np.append(iter_arr, i + 1)
grad.set_data(c_arr, m_arr)
lr.set_data(x, linear_equation(m_best, x, c_best))
ep.set_data(iter_arr, error_arr)
r2.set_data(iter_arr, r_sq_arr)
r2_ad.set_data(iter_arr, r_sq_ad_arr)
# print(np.array(range(i+2)).shape, error_arr.shape, c_arr.shape, m_arr.shape)
plt.pause(0.0000000000000000001)
plt.show(block=True)
return m_best, c_best, err_best
def run(initial_c, initial_m, x, y, learning_rate, iterations, is_normalized):
# plot(x, y, initial_m, initial_c)
error = mse(initial_c, initial_m, x, y)
print("Error at b = {0}, m = {1}, error = {2}".format(initial_c, initial_m, error))
m, c, error = calculate_m_b_with_gradient_descent(x, y, initial_m, initial_c, learning_rate, iterations, is_normalized)
# Model Evaluation - Coefficient of Determination (R-squared)
# i.e. goodness of fit of our regression model.
# https://towardsdatascience.com/coefficient-of-determination-r-squared-explained-db32700d924e
# R^2 = 1 - SSE / SST
# SSE = the sum of squared errors of our regression model
# SST = the sum of squared errors of our baseline model (which is worst model).
print("r square = {0} and r_squared_adjusted = {1}".format(r_square(x, y, m, c), r_square_adjusted(x, y, m, c)))
def run_with_normalization(data, initial_c, initial_m, learning_rate, iterations):
x = data.experience
y = data.salary
y_min = np.min(y)
y_max = np.max(y)
# implementing min-max scaling
y = data['salary'].apply(lambda salary: ((salary - y_min) / (y_max - y_min)))
run(initial_c, initial_m, x, y, learning_rate, iterations, True)
class OutlierRemover:
def __init__(self, df):
# Apply replace() on each column of the dataframe
df = df.apply(self.replace, axis=1)
# remove the rows containing any outlier:
df = df[~df.apply(self.is_outlier).any(axis=1)]
self.df = df
def is_outlier(self, x):
# a number "a" from the vector "x" is an outlier if
# a > median(x)+1.5*iqr(x) or a < median-1.5*iqr(x)
# iqr: interquantile range = third interquantile - first interquantile
# The function return a boolean vector: True if the element is an outlier. False, otherwise.
return np.abs(x - x.median()) > 1.5 * (x.quantile(.75) - x.quantile(0.25))
def replace(self, x):
# Replace the upper outlier(s) with the 95th percentile and the lower one(s) with the 5th percentile
out = x[self.is_outlier(x)]
return x.replace(to_replace=[out.min(), out.max()], value=[np.percentile(x, 5), np.percentile(x, 95)])
def get(self):
return self.df
def distribution_plot(data):
plt.figure(figsize=(10, 8))
plt.subplot(221)
plt.xlim(data.experience.min(), data.experience.max() * 1.1)
# Plot kernel distribution
ax = data.experience.plot(kind='kde')
plt.subplot(223)
plt.xlim(data.experience.min(), data.experience.max() * 1.1)
sns.boxplot(x=data.experience)
plt.subplot(222)
plt.xlim(data.salary.min(), data.salary.max() * 1.1)
# Plot kernel distribution
bx = data.salary.plot(kind='kde')
plt.subplot(224)
plt.xlim(data.salary.min(), data.salary.max() * 1.1)
sns.boxplot(x=data.salary)
plt.show()
if __name__ == '__main__':
plt.interactive(True)
initial_c = initial_m = 0
data = pd.read_csv('./salaries_clean.csv', encoding='utf-8')
# Data Cleaning
data = data[['total_experience_years', 'annual_base_pay']]
data.columns = ['experience', 'salary']
# ## Removing infinities and na form data
data = data.replace([np.inf, -np.inf], np.nan).dropna()
# ## This data has outliers
plt.scatter(data.experience, data.salary)
plt.show()
# ## To visualize outliers, box plot is better
distribution_plot(data)
print("before removing outliers: ")
print(data.describe())
# ## Removing outliers
# ## For each series in the dataframe, we could use between and quantile (or percentile) to remove outliers.
data = OutlierRemover(data).get()
distribution_plot(data)
print("after removing outliers: ")
print(data.describe())
plt.scatter(data.experience, data.salary)
plt.show(block=True)
data = data.reset_index()
x = data.experience
y = data.salary
learning_rate = 0.01
iterations = 1000
# print(data.describe())
# run(initial_c, initial_m, x, y, learning_rate, iterations, False)
# Why, How and When to Scale (or normalize) Features
# https://medium.com/greyatom/why-how-and-when-to-scale-your-features-4b30ab09db5e
run_with_normalization(data, initial_c, initial_m, learning_rate, iterations)
|
bf74e88b39ea7f8803515285093c230b92e1d08e | pedrore1z/CodigosPythonTurmaDSI | /Exercicios1/Exercicio5.py | 183 | 3.90625 | 4 |
valor = int(input("Informe um valor inteiro qualquer:"))
'''
if valor %2 == 0:
print("É par")
else:
print("É ímpar")
'''
print("É par" if valor % 2==0 else "É ímpar") |
cc0a17edab86e5b6bc41b52df483d5ff7edccab4 | pedrore1z/CodigosPythonTurmaDSI | /Exercicios1/Exercicio1.py | 350 | 3.84375 | 4 | print("*"*10,"Atividade 01","*"*10)
medida = float(input("Informe a base do seu terreno: "))
medida2 = float(input("Informe a altura do seu terreno: "))
print("\n\nPara cada m² o valor da construção será de R$850\n\n")
area = medida * medida2
print("Sua area é: ", area)
metros = 850
print("Você deverá pagar o valor de R$:", area * metros) |
b80f5888649a78baff290dc4b654f8ee82b0230a | Austin-Deccentric/snbank | /main.py | 2,980 | 3.5625 | 4 | import itertools
from datetime import datetime
import time
from random import choices, seed
import string
from os import remove
import sys
def login():
condition = True
while condition != 'end' :
print("Please enter your login details")
username = input("Please enter username: ").strip()
password = input("Please enter password: ").strip()
with open('staff.txt') as f:
for line1,line2 in itertools.zip_longest(*[f]*2):
if line1.startswith('Username'):
name = line1.strip().split(' ')[1]
passkey = line2.strip().split(' ')[1]
if username.lower()==name.lower() and (password ==passkey):
print('Welcome to the Portal')
condition = 'end'
break
else:
print("Invalid username or password")
return username
def session_file(user):
log = open('log.txt','w')
log.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S')+ " - %s" %user)
log.write("\n")
log.close()
print("Welcome to SN Bank".center(100,'*'))
while True:
user_input = input('''Please select an option:
1 Staff Login
2 Close App
> ''').strip()
if user_input not in ['1','2']:
print('Enter a valid option')
continue
else:
user_input = int(user_input)
if user_input == 1:
username = login()
session_file(username)
actions = True
while actions != '3':
actions = input('''Please select an Option
1. Create a new account
2. Check account details
3. Logout
> ''').strip()
if actions == '1':
acc_name = input("Enter account holder's name: ")
opening_balance = float(input('Enter Opening Balance: '))
acc_type = input("Enter account type: ")
acc_email = input("Enter Account email: ")
seed(datetime.now())
acc_num = ''.join(choices(string.digits,k = 10))
with open('customer.txt', 'a') as file:
file.write('{}: {}, {}, {}, {}'.format(acc_num,acc_name,opening_balance,acc_type,acc_email))
file.write('\n')
print("\n Your account number is: ",acc_num)
continue
if actions == '2':
acc_num = input("Enter account number: ").strip()
with open('customer.txt', 'r') as file:
for line in file:
if line.startswith(acc_num):
acc_details = line.strip().split(' ',1)[1].split(',')
print(f'''Account Name: {acc_details[0]}
Balance:{acc_details[1]}
Account type:{acc_details[2]}
Email:{acc_details[3]}
''')
if actions == '3':
remove('log.txt')
break
continue
if user_input == 2:
sys.exit() |
43636e7cfc6c066118a154979fb28893de350770 | dalboalvaro/PythonChallenge | /PyBank/main.py | 1,980 | 3.921875 | 4 | import os
import csv
Profit=[]
# Path to collect data from the Resources folder
budgetCSV = os.path.join('budget_data.csv')
# Read in the CSV file
with open(budgetCSV, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
# Create variable months
# Count number of rows and store as months
Months = 0
for row in csvreader:
Months += 1
#Create Variable Total
# Sum all values in column 2
Profit.append(float(row[1]))
# Create list of yearly change - value in column 2 from next row less present row
change=[]
for i in range(1, len(Profit)):
change.append((float(Profit[i]-float(Profit[i-1]))))
# Calculate average, greatest increase and decrease
averagechange = sum(change) / float(Months-1)
greatestIncrease = max(change)
greatestdecrease = min(change)
# Print Summary
print("Financial Analysis")
print("--------------------")
print("Total Months:" + str(Months))
print("Total:" + str(sum(Profit)))
print("Average Change:" + str(averagechange))
print("Greatest Increase in Profits:" + str(greatestIncrease))
print("Greatest Decrease in Profits:" + str(greatestdecrease))
# Set variable for output file
output_file = os.path.join("FinancialAnalysis.csv")
# Open the output file
with open(output_file, "w", newline="") as datafile:
writer = csv.writer(datafile)
# Print to the CSV output
writer.writerow(["Financial Analysis"])
writer.writerow(["----------------"])
writer.writerow(["Total Months:" + str(Months)])
writer.writerow(["Total:" + str(sum(Profit))])
writer.writerow(["Average Change:" + str(averagechange)])
writer.writerow(["Greatest Increase in Profits:" + str(greatestIncrease)])
writer.writerow(["Greatest Decrease in Profits:" + str(greatestdecrease)])
|
237909d12a8b40d25190b39f114ea7e45f163d25 | Sauvikk/practice_questions | /Level6/Trees/Populate Next Right Pointers Tree.py | 1,700 | 4.0625 | 4 | # Given a binary tree
#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# Populate each next pointer to point to its next right node.
# If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are set to NULL.
#
# Note:
# You may only use constant extra space.
# Example :
#
# Given the following binary tree,
#
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# After calling your function, the tree should look like:
#
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ / \
# 4->5->6->7 -> NULL
# Note 1: that using recursion has memory overhead and does not qualify for constant space.
# Note 2: The tree need not be a perfect binary tree.
from collections import deque
class Solution:
def solution(self, root):
current_level = deque()
next_level = deque()
current_level.append(root)
temp = []
result = []
while len(current_level) > 0:
curr_node = current_level[0]
current_level.popleft()
if curr_node:
temp.append(curr_node)
next_level.append(curr_node.left)
next_level.append(curr_node.right)
if len(current_level) == 0:
if temp:
if len(temp) == 1:
temp[0].next = None
for i in range(0, len(temp)-1):
temp[i].next = temp[i+1]
temp[-1].next = None
temp = []
current_level, next_level = next_level, current_level
|
f1eaa8be26c79ee21721f948864ef016a22a5852 | Sauvikk/practice_questions | /Level6/Trees/Next Greater Number BST.py | 1,708 | 3.890625 | 4 | # Given a BST node, return the node which has value just greater than the given node.
#
# Example:
#
# Given the tree
#
# 100
# / \
# 98 102
# / \
# 96 99
# \
# 97
# Given 97, you should return the node corresponding to 98 as thats the value just greater than 97 in the tree.
# If there are no successor in the tree ( the value is the largest in the tree, return NULL).
#
# Using recursion is not allowed.
#
# Assume that the value is always present in the tree.
from Level6.Trees.BinaryTree import BinaryTree
class Solution:
def find(self, root, data):
while root:
if root.val == data:
return root
if data < root.val:
root = root.left
else:
root = root.right
def find_min(self, root):
if root is None:
return root
while root.left:
root = root.left
return root
def solution(self, root, data):
current = self.find(root, data)
if current is None:
return None
if current.right:
return self.find_min(current.right)
else:
successor = None
ancestor = root
while ancestor:
if current.val < ancestor.val:
successor = ancestor
ancestor = ancestor.left
else:
ancestor = ancestor.right
return successor
A = BinaryTree()
A.insert(100)
A.insert(98)
A.insert(102)
A.insert(102)
A.insert(96)
A.insert(99)
A.insert(97)
A.insert(97)
res = Solution().solution(A.root, 97)
print(res)
|
5b01a489805c58909979dae65c04763df722bfaa | Sauvikk/practice_questions | /Level6/Trees/Balanced Binary Tree.py | 1,233 | 4.34375 | 4 | # Given a binary tree, determine if it is height-balanced.
#
# Height-balanced binary tree : is defined as a binary tree in which
# the depth of the two subtrees of every node never differ by more than 1.
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
# 1
# / \
# 2 3
#
# Return : True or 1
#
# Input 2 :
# 3
# /
# 2
# /
# 1
#
# Return : False or 0
# Because for the root node, left subtree has depth 2 and right subtree has depth 0.
# Difference = 2 > 1.
from Level6.Trees.BinaryTree import BinaryTree
class Solution:
def is_balanced(self, root):
if root is None:
return True
if self.get_depth(root) == -1:
return False
return True
def get_depth(self, root):
if root is None:
return 0
left = self.get_depth(root.left)
right = self.get_depth(root.right)
if left == -1 or right == -1:
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1
A = BinaryTree()
A.insert(100)
A.insert(102)
A.insert(96)
res = Solution().is_balanced(A.root)
print(res)
|
97c6c72d6f1630885880672535719d4ae8205205 | Sauvikk/practice_questions | /Level6/Trees/Root to Leaf Paths With Sum.py | 1,466 | 3.78125 | 4 | # Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
#
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
# return
#
# [
# [5,4,11,2],
# [5,8,4,5]
# ]
from Level6.Trees.BinaryTree import BinaryTree, Node
class Solution:
def generate_path(self, root, target, result, temp):
if root.left is None and root.right is None and target == 0:
result.append(temp[:])
if root.left:
temp.append(root.left.val)
self.generate_path(root.left, target-root.left.val, result, temp)
temp.pop()
if root.right:
temp.append(root.right.val)
self.generate_path(root.right, target-root.right.val, result, temp)
temp.pop()
def solution(self, root, target):
result = []
if root is None:
return result
temp = [root.val]
self.generate_path(root, target-root.val, result, temp)
return result
root = Node(5)
root.left = Node(4)
root.left.left = Node(11)
root.left.left.left = Node(7)
root.left.left.right = Node(2)
root.right = Node(8)
root.right.right = Node(4)
root.right.left = Node(13)
root.right.right.right = Node(1)
root.right.right.left = Node(5)
res = Solution().solution(root, 22)
print(res)
|
50580ee661fdbf765c1e825c7580fdace4c8d0ef | Sauvikk/practice_questions | /Level8/Word Search Board.py | 1,618 | 3.90625 | 4 | # Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The cell itself does not count as an adjacent cell.
# The same letter cell may be used more than once.
#
# Example :
#
# Given board =
#
# [
# ["ABCE"],
# ["SFCS"],
# ["ADEE"]
# ]
# word = "ABCCED", -> returns 1,
# word = "SEE", -> returns 1,
# word = "ABCB", -> returns 1,
# word = "ABFSAB" -> returns 1
# word = "ABCD" -> returns 0
# Note that 1 corresponds to true, and 0 corresponds to false.
class Solution:
def exist(self, board, word):
m = len(board)
n = len(board[0])
result = 0
for i in range(m):
for j in range(n):
if self.dfs(board, word, i, j, 0) == 1:
result = 1
return result
def dfs(self, board, word, i, j, k):
m = len(board)
n = len(board[0])
if i < 0 or j < 0 or i >= m or j >= n:
return 0
if board[i][j] == word[k]:
temp = board[i][j]
if k == len(word) - 1:
return 1
elif (self.dfs(board, word, i - 1, j, k + 1)
or self.dfs(board, word, i + 1, j, k + 1)
or self.dfs(board, word, i, j - 1, k + 1)
or self.dfs(board, word, i, j + 1, k + 1)):
return 1
return 0
b = [ "FEDCBECD", "FABBGACG", "CDEDGAEC", "BFFEGGBA", "FCEEAFDA", "AGFADEAC", "ADGDCBAA", "EAABDDFF" ]
print(Solution().exist(b, "BCDCB"))
|
9cea8f90b8556dcacec43dd9ae4a7b4500db2114 | Sauvikk/practice_questions | /Level6/Trees/Sorted Array To Balanced BST.py | 951 | 4.125 | 4 | # Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#
# Balanced tree : a height-balanced binary tree is defined as a
# binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example :
#
#
# Given A : [1, 2, 3]
# A height balanced BST :
#
# 2
# / \
# 1 3
from Level6.Trees.BinaryTree import BinaryTree, Node
class Solution:
def generate_bt(self, num, start, end):
if start > end:
return None
mid = int((start+end)/2)
node = Node(num[mid])
node.left = self.generate_bt(num, start, mid-1)
node.right = self.generate_bt(num, mid+1, end)
return node
def solution(self, num):
if num is None or len(num) == 0:
return num
return self.generate_bt(num, 0, len(num)-1)
res = Solution().solution([1, 2, 3, 4, 5, 6, 7])
BinaryTree().pre_order(res)
|
3e5acab0b12687cbf10ba1c9bcf9d3220507ef58 | Sauvikk/practice_questions | /Level7/Dynamic Programming/Min Sum Path in Matrix.py | 1,295 | 3.515625 | 4 | # Given a m x n grid filled with non-negative numbers, find a path
# from top left to bottom right which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
# Example :
#
# Input :
#
# [ 1 3 2
# 4 3 1
# 5 6 1
# ]
#
# Output : 8
# 1 -> 3 -> 2 -> 1 -> 1
class Solution:
def sol(self, grid):
if grid is None or len(grid) == 0:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0 for x in range(n)] for x in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, n):
dp[0][i] = dp[0][i-1] + grid[0][i]
for j in range(1, m):
dp[j][0] = dp[j-1][0] + grid[j][0]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i][j]
return dp[m-1][n-1]
c = [
[20, 29, 84, 4, 32, 60, 86, 8, 7, 37],
[77, 69, 85, 83, 81, 78, 22, 45, 43, 63],
[60, 21, 0, 94, 59, 88, 9, 54, 30, 80],
[40, 78, 52, 58, 26, 84, 47, 0, 24, 60],
[40, 17, 69, 5, 38, 5, 75, 59, 35, 26],
[64, 41, 85, 22, 44, 25, 3, 63, 33, 13],
[2, 21, 39, 51, 75, 70, 76, 57, 56, 22],
[31, 45, 47, 100, 65, 10, 94, 96, 81, 14]
]
print(Solution().sol(c))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.