text stringlengths 37 1.41M |
|---|
from keyword import iskeyword
def contains_keyword(*arg):
for string in arg:
if iskeyword(string):
return True
return False
print(contains_keyword("hello", "goodbye")) |
cities = ['Los Angeles', 'San Jose', 'San Luis Obispo', 'Los Angeles']
print(f"{cities =}")
print(f"{set(cities) =}")
print(f"{list(set(cities)) =}") |
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values
print(f"X = {X}")
print(f"Y = {Y}")
print()
# Split Dataset: Training Set and Test Set
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
print(f"X_train = {X_train}")
print(f"X_test = {X_test}")
print(f"Y_train = {Y_train}")
print(f"Y_test = {Y_test}")
print()
# Feature Scaling (done after splitting to avoid information leakage.)
from sklearn.preprocessing import StandardScaler
standardScaler = StandardScaler()
X_train_scaled = standardScaler.fit_transform(X_train)
X_test_scaled = standardScaler.transform(X_test)
print(f"X_train_scaled = {X_train_scaled}")
print(f"X_test_scaled = {X_test_scaled}")
print()
# Naïve-Bayes Classifier
## A non-linear model with a probabilistic approach.
## Helps rank predictions by their probability.
## Baye's Theorem
### 1. Calculate P(A|X) = P(X|A) * P(A) / P(X)
#### P(A) -> Prior Probability
##### Equal to probability of A given a total number of observations.
#### P(X) -> Marginal Likelihood
##### Select a radius around the obversation in question.
###### Radius is chosen in the same way as in KNN.
##### All obvervations that lie inside the radius are deemed similar to the original observation in question.
##### Equal to the total of these similar observations divided by the total number of observations.
#### P(X|A) -> Likelihood
##### Equal to the total number of the similar observations above divided by the number of observations in class A.
#### P(A|X) -> Posterior Probability
##### Calculate using Baye's Theorem
### 2. Calculate P(B|X) = P(X|B) * P(B) / P(X)
#### Use same procedure above
### 3. P(A|X) vs P(B|X)
#### Whichever is greater decides the class of the new observation in question.
## Why Naïve?
### Assumes the observations are independent.
### May still give good results eventhough the observations may be somewhat corrolated.
### Still used eventhough some correlation may exist between observations that define the classes.
## P(X) Shortcut
### The Marginal Likelihood does not chance whether Baye's Theorem is calculated for class A or B.
### Therefore, P(X|A) * P(A) = P(X|B) * P(B)
# Create and train Naïve-Bayes model
## Use Gaussian Radial-Basis Function (RBF) kernel
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train_scaled, Y_train)
# Predict using Naïve-Bayes model
Y_predict = classifier.predict(X_test_scaled)
print(f"[Y_predict Y_test] = {np.concatenate((Y_predict.reshape(len(Y_predict), 1), Y_test.reshape(len(Y_test), 1)), axis = 1)}")
print()
# Create Confusion Matrix
## Not the optimal method to evaluate the performance of the model - K-Fold Cross Validation is preferred and it involves using validation tests.
from sklearn.metrics import confusion_matrix
print(f"Confusion Matrix = {confusion_matrix(Y_test, Y_predict)}")
print()
# Generate Accuracy Score
## Accuracy Paradox
### Do not rely just on the accuracy score to evaluate a model.
### If a model only generates True Negatives and False Negatives, or only False Positives and True Positives, the accuracy might increase!
from sklearn.metrics import accuracy_score
print(f"Accuracy Score = {accuracy_score(Y_test, Y_predict)}")
print()
# Cumulative Accuracy Profile (CAP)
## Accuracy Ratio = Area under Perfect Model / Aread under Classifier CAP
### If Accuracy Ratio > 90%, may be overfitting or may have forward-looking variables.
### If Accuracy Ratio < 70%, consider another model.
## Edit independent_variable_threshold definition depending on threshold of classifier output
Y_train_only_zeros_and_ones = True
for y in Y_train:
if not ((y == 0) or (y == 1)):
Y_train_only_zeros_and_ones = False
break
independent_variable_threshold = 3
if not Y_train_only_zeros_and_ones:
Y_test = (Y_test > independent_variable_threshold).astype(int)
Y_predict = (Y_predict > independent_variable_threshold).astype(int)
Y_test_length = len(Y_test)
Y_test_one_count = np.sum(Y_test)
Y_test_zero_count = Y_test_length - Y_test_one_count
## Plot Perfect Model
plt.plot([0, Y_test_one_count, Y_test_length], [0, Y_test_one_count, Y_test_one_count], c = 'g', linewidth = 2, label = 'Perfect Model')
## Plot Cumulative Accuracy Profile (CAP) for classifier
classifier_CAP = [y for _, y in sorted(zip(Y_predict, Y_test), reverse = True)]
plt.plot(np.arange(0, Y_test_length + 1), np.append([0], np.cumsum(classifier_CAP)), c = 'k', linewidth = 2, label = 'Naïve-Bayes Classifier')
## Plot Random Model
plt.plot([0, Y_test_length], [0, Y_test_one_count], c = 'r', linewidth = 2, label = 'Random Model')
## Area under Random Model
random_model_area = np.trapz([0, Y_test_one_count], [0, Y_test_length])
## Area under classifier CAP
classifier_CAP_area = np.trapz(np.append([0], np.cumsum(classifier_CAP)), np.arange(0, Y_test_length + 1)) - random_model_area
## Area under Perfect Model
perfect_model_area = np.trapz([0, Y_test_one_count, Y_test_one_count], [0, Y_test_one_count, Y_test_length]) - random_model_area
## Accuracy Ratio
accuracy_ratio = classifier_CAP_area / perfect_model_area
print(f"Accuracy Ratio = {accuracy_ratio}")
plt.legend()
plt.title(f"Cumulative Accuracy Profile (CAP), AR = {round(accuracy_ratio, 3)}")
plt.xlabel('# of Data Points in Y_test')
plt.ylabel('# of True Positive Predictions')
plt.legend()
plt.savefig('Naive_Bayes_Classification_Cumulative_Accuracy_Profile_(CAP).png')
plt.clf()
|
from random import choice
print('Rock...')
print('Paper...')
print('Scissors...')
player1 = input('Player 1, make your move: ').lower()
player2 = choice(['rock', 'paper', 'scissors'])
print(f'Computer plays {player2}')
if player1 == player2:
print('Its a TIE!')
elif player1 == 'rock' and player2 == 'scissors':
print('Player 1 WINS!')
elif player1 == 'paper' and player2 == 'rock':
print('Player 1 WINS!')
elif player1 == 'scissors' and player2 == 'paper':
print('Player 1 WINS!')
else:
print('Computer WINS!')
|
sum1 = 0 #sum of all numbers<1000 divisible by 3
sum2 = 0 #sum of all numbers <1000 divisible by 5
sum3 = 0 #sum of all numbers <1000 divisible by 15
i = 3
j = 5
k = 15
while i<1000: #slowest pointer
sum1+=i
i+=3
if j<1000:
sum2+=j
j+=5
if k <1000:
sum3+=k
k+=15
print(sum1+sum2-sum3) #excluding the double count |
# input data
# I propose to change "sudoku" var to input_list_of_digits - OK, no prob :)
input_list_of_digits = "..5..79...2..9..4.3..8....66.....4...7.....3...8.....28....2..3.6..7..9...45....."
print "Number of sudoku elements: %d" % len(input_list_of_digits)
def sudoku_grid(data):
for i in range(len(data)):
#print "%d>" % i,
print data[i],
if (i+1) % 9 == 0 and i > 0:
print
if (i+1) % 3 == 0 and i > 0 and not (i+1) % 9 == 0:
print "|",
if (i+1) % 27 == 0 and i > 0 and i < 80:
print "- - - + - - - + - - -"
# As far as I read on the internet there always has to be something returned in a definition otherwise we get "None" if there is no return at all. So I'd say we go for "return ''" in my opinon
return ""
# When you add "," at the end of "print" statement there is no extra line
#print sudoku_grid(input_list_of_digits),
# function to refer to a field as row/column index e.g. field 0 is A1, field 1 is A2 etc.
# Create list of keys e.g. A1, B1 etc.
row_column_list = []
temporary_string = ""
def create_row_column_index(data):
for i in range(len(data)):
#print row/column index that depends on position in "data"
# every row is letter based (A-I), every column is number based (1-9)
if i < 9:
temporary_string = "A" + str(i + 1)
row_column_list.append(temporary_string)
if i >8 and i < 18:
temporary_string = "B" + str(i - 8)
row_column_list.append(temporary_string)
if i >17 and i < 27:
temporary_string = "C" + str(i - 17)
row_column_list.append(temporary_string)
if i >26 and i < 36:
temporary_string = "D" + str(i - 26)
row_column_list.append(temporary_string)
if i >35 and i < 45:
temporary_string = "E" + str(i - 35)
row_column_list.append(temporary_string)
if i >44 and i < 54:
temporary_string = "F" + str(i - 44)
row_column_list.append(temporary_string)
if i >53 and i < 63:
temporary_string = "G" + str(i - 53)
row_column_list.append(temporary_string)
if i >62 and i < 72:
temporary_string = "H" + str(i - 62)
row_column_list.append(temporary_string)
if i >71 and i < 81:
temporary_string = "I" + str(i - 71)
row_column_list.append(temporary_string)
return row_column_list
#print sudoku_grid(row_column_key_value_list)
# function to add values to indexed positions e.g. A1 becomes A1:. etc.
row_column_key_value_list ={}
def replace_index_with_key_value_list(data):
for i in range(len(data)):
row_column_key_value_list
#>>> d['mynewkey'] = 'mynewvalue'
#>>> print d
#{'mynewkey': 'mynewvalue', 'key': 'value'}
#data.update({'a':1})
row_column_key_value_list.update({row_column_list[i]:input_list_of_digits[i]})
#row_column_key_value_list[row_column_list[i]] = input_list_of_digits[i]
return row_column_key_value_list
replace_index_with_key_value_list(create_row_column_index(input_list_of_digits))
#for i in range(len(row_column_key_value_list)):
# print row_column_key_value_list.itervalues().next(),
# print key/value pairs in sudoku matrix function
def sudoku_matrix_key_value(data):
for i in range(len(data)):
#for key, value in data.iteritems():
#print "%d>" % i,
#print data[i],
print key, ":", value,
if (i+1) % 9 == 0 and i > 0:
print
if (i+1) % 3 == 0 and i > 0 and not (i+1) % 9 == 0:
print "|",
if (i+1) % 27 == 0 and i > 0 and i < 80:
print "- - - + - - - + - - -"
return ""
print sudoku_matrix_key_value(row_column_key_value_list)
#print range(len(row_column_key_value_list))
# validation test
# check if a digit not duplicated in a square (3*3)
# list all squares
#square_top_lef = input_list_of_digits[0]
#print square_top_lef
#print replace_digits_with_row_column_index(input_list_of_digits),
|
'''19. Faça um programa que:
insira dez números inteiros em um vetor
crie um segundo vetor, substituindo os números multiplos de 3 por "999""
exiba os dois vetores
não use nenhuma função pronta da linguagem Python'''
vetor1 = []
vetor2 = []
for i in range(5):
vetor1.append(int(input('Digite um número inteiro: ')))
if vetor1[i] % 3 == 0:
vetor2.append(vetor1[i])
vetor2[i] = 999
else:
vetor2.append(vetor1[i])
print(vetor1)
print(vetor2)
|
# 9. Criar um algoritmo que leia dados para um vetor de 10 elementos inteiros, imprimir o maior, o menor, o percentual de números pares e a média dos elementos do vetor. Obs.: percentual = quantidade contada * 100 / quantidade total. Não use nenhuma função pronta da linguagem Python.
numeros = []
pares = []
cont = 0
soma_num = 0
for i in range(10):
numeros.append(int(input("Digite um número inteiro: ")))
# achado o maior e o menor número
for i in range(10):
if i == 0:
menor = numeros[i]
maior = numeros[i]
if numeros[i] > maior:
maior = numeros[i]
elif numeros[i] < menor:
menor = numeros[i]
# percentual de números pares
for i in range(10):
if numeros[i] % 2 == 0:
cont += 1
pares.append(numeros[i])
percent = (cont * 100) / 10
# média dos números
for i in range(10):
soma_num += numeros[i]
media = soma_num / len(numeros)
print(numeros)
print(f'O maior número foi {maior} e o menor número foi {menor}')
print(f"O percentual dos números pares foi de {percent} %")
print(f"A média dos elementos da lista foi de {media}")
|
salario = float(input("Informe aqui o salário base do funcionario: "))
perImposto = float(input("Informe aqui a porcentagem do imposto: "))
imposto = salario * perImposto / 100
salario_a_receber = salario + 50 - imposto
print("O salário a receber é de R$ {:.2f}".format(salario_a_receber)) |
num = []
pares = []
impares = []
cont_par = cont_impar = 0
for i in range(6):
num.append(int(input('Digite um número inteiro: ')))
for i in range(6):
if num[i] % 2 == 0:
pares.append(num[i])
cont_par += 1
else:
impares.append(num[i])
cont_impar += 1
print(f'A quantidade de números pares foi de {cont_par} números, sendo eles {pares}')
print(f'A quantidade de números ímpares foi de {cont_impar} números, sendo eles {impares}') |
i = 0
soma = 0
while i < 5:
preco = (float(input("Coloque o preço de um produto: ")))
soma += preco
i += 1
media = soma / i
print(f"A média dos 5 produtos são de R$ {media:.2f}") |
deposito = float(input("Coloque aqui o valor que você deseja depositar: "))
taxa = float(input("Coloque aqui o valor da taxa de juros: "))
rendimento = deposito * taxa / 100
total = deposito + rendimento
print("O valor do rendimento é de R$ {:.2f}".format(rendimento))
print("O valor total do rendimento de um mês é de R$ {:.2f}".format(total))
|
valor_salario = float(input("Coloque o valor salário mínimo: "))
qtde_quilowatt = float(input("Informe a quantidade de quilowatts consumido: "))
valor_quilowatt = valor_salario / 5
valor_em_reais = valor_quilowatt * qtde_quilowatt
valor_descontado = valor_em_reais * 15 / 100
valor_com_desconto = valor_em_reais - valor_descontado
print("O valor de cada quilowatt é de {:.2f} reais".format(valor_quilowatt))
print("O valor total a ser pago é de R$ {:.2f}".format(valor_em_reais))
print("O valor total com desconto de 15% é de R$ {:.2f}".format(valor_com_desconto)) |
angulo = int(input('Insira aqui um valor de ângulo em graus: '))
if angulo > 360 or angulo < -360:
voltas = angulo // 360
angulo = angulo % 360
else:
voltas = 0
if angulo == 0 or angulo == 90 or angulo == 180 or angulo == 270 or angulo == 360 or angulo == -90 or angulo == -180 or angulo == -270 or angulo == -360:
print('Está em cima de algum dos eixos')
if (angulo > 0 and angulo < 90) or (angulo < -270 and angulo > -360):
print('1º Quadrante')
elif (angulo > 90 and angulo < 180) or (angulo < -180 and angulo > -270):
print('2º Quadrante')
elif (angulo > 180 and angulo < 270) or (angulo < -90 and angulo > -180):
print('3º Quadrante')
elif (angulo > 270 and angulo < 360) or (angulo < -0 and angulo > -90):
print('4º Quadrante')
if angulo < 0:
sentido = "horário"
else:
sentido = "anti-horário"
print(f'{voltas} volta(s) no sentido {sentido}') |
"""Faça um programa que preencha um vetor com sete números inteiros. Calcule e mostre:
os números múltiplos de 2;
os números múltiplos de 3;
os números múltiplos de 2 e de 3."""
numeros = []
num2 = []
num3 = []
num = []
for i in range (7):
numeros.append(int(input("Digite um número inteiro: ")))
for i in range (7):
if numeros[i] % 2 == 0:
num2.append(numeros[i])
for i in range (7):
if numeros[i] % 3 == 0:
num3.append(numeros[i])
for i in range (7):
if numeros[i] % 2 == 0 and numeros[i] % 3 == 0:
num.append(numeros[i])
print(f'Os números multiplos de 2 são {num2}')
print(f'Os números multiplos de 3 são {num3}')
print(f'Os números multiplos de 2 e 3 são {num}') |
# 7. Faça um algoritmo que calcule e apresente a média de alturas superior a 1,80 de 10 alunos. Informe também quantos e quais (índice/posição) são os alunos. Não use nenhuma função pronta da linguagem Python.
import sys
altura = []
altura_m = 0
cont = 0
indice = []
for i in range(10):
altura.append(float(input("Digite a altura do aluno: ")))
for i in range(10):
if altura[i] > 1.8:
altura_m += altura[i]
cont += 1
indice.append(i)
if cont == 0: # caso nenhum aluno tenha altura não vai dar erro
print('Não tem nenhum aluno com altura superior a 1.80')
sys.exit()
media = altura_m / cont
print(f'A media de altura dos alunos superiores a 1.80 é de {media:.2f}')
print(f'Existem {cont} alunos com altura superior a 1.80, e eles se encontram no índice {indice}')
|
codigo_estado = int(input('Digite aqui o codigo do estado de origem da carga (codigo de 1 a 5): '))
peso_carga = float(input("Insira o peso da carga do caminhão em toneladas: "))
codigo_carga = int(input('Digite o codigo da carga (codigo de 10 a 40): '))
peso_kg = peso_carga * 1000
print(f'O peso da carga do caminhão em kg é de {peso_kg:.0f}')
if codigo_carga >= 10 and codigo_carga <= 20:
preco_carga = peso_kg * 100
elif codigo_carga > 20 and codigo_carga <= 30:
preco_carga = peso_kg * 250
elif codigo_carga > 30 and codigo_carga <= 40:
preco_carga = peso_kg * 400
print(f'O preço da carga em kg é de R$ {preco_carga:.2f}')
if codigo_estado == 1:
imposto = preco_carga * (35/100)
elif codigo_estado == 2:
imposto = preco_carga * (25/100)
elif codigo_estado == 3:
imposto = preco_carga * (15/100)
elif codigo_estado == 4:
imposto = preco_carga * (5/100)
elif codigo_estado == 5:
imposto = 0
print(f'O valor do imposto do produto neste estado é de R$ {imposto:.2f}')
total = preco_carga + imposto
print(f'O valor total do produto é de R$ {total:.2f}')
|
print("Vamos aumentar teu salário")
salario = float(input("Informe aqui teu salário: "))
percentual = float(input("Informe aqui qual a porcentagem de aumento do salario: "))
aumento = salario * percentual/100
novo_salario = salario + aumento
print("O salário a receber é de R$ {:.2f}".format(novo_salario)) |
#Faça um programa que carregue um vetor com a média de dez alunos, calcule e mostre a MÉDIA DA SALA e quantos alunos estão acima e abaixo da média da sala.
vet_media = []
soma_media = 0
alunos_cima = 0
alunos_baixo = 0
for i in range(10):
vet_media.append(float(input(f'Insira a média do {i+1}º aluno: ')))
soma_media = soma_media + vet_media[i]
media = soma_media / len(vet_media)
for i in range(10):
if vet_media[i] >= media:
alunos_cima += 1
else:
alunos_baixo += 1
print(f'A média de nota da sala com {i+1} alunos, é de {media}')
print(f'A quantidade de alunos acima da média é de {alunos_cima} alunos, e a quantidade de alunos abaixo da média é de {alunos_baixo} alunos') |
import sqlite3
import SQLExample
def UpdateFactionStats(fname, ftype, ftier, stat, newvalue):
# connecting to the database
connection = sqlite3.connect("myTable.db")
# cursor
cursor = connection.cursor()
#fname = input("Choose a Faction: ")
#Faction does not have to be validated as a new faction will result in a new row
validate = 0
while validate < 5:
print("1: Production")
print("2: Prototype")
#ftype = input("Choose a Type: ")
if ftype == "1" or ftype == "Production":
ftype = "Production"
break
elif ftype == "2" or ftype == "Prototype":
ftype = "Prototype"
break
else:
validate = validate + 1
print("Invalid Input: Attempts Remaining {0}".format(5 - validate))
if validate == 5:
print("Input Failed")
return
#Validate Type
validate = 0
while validate < 5:
#ftier = input("Choose a Tier: ")
try:
x = int(ftier)
except ValueError:
validate = validate + 1
print("Invalid Input: Attempts Remaining {0}".format(5 - validate))
else:
if x < 1:
validate = validate + 1
print("Invalid Input: Attempts Remaining {0}".format(5 - validate))
else:
break
if validate == 5:
print("Input Failed")
return
validate = 0
#Validate Stat
while validate < 5:
print("1: Navy")
print("2: Agency")
print("3: Market")
print("4: University")
print("5: Court")
#stat = input("Choose a Statistic: ")
if stat == "1" or stat == "navy":
stat = "navy"
break
elif stat == "2" or stat == "agency":
stat = "agency"
break
elif stat == "3" or stat == "market":
stat = "market"
break
elif stat == "4" or stat == "university":
stat = "university"
break
elif stat == "5" or stat == "court":
stat = "court"
break
else:
validate = validate + 1
print("Invalid Input: Attempts Remaining {0}".format(5 - validate))
if validate == 5:
print("Input Failed")
return
print(stat)
#Validate Value
validate = 0
while validate < 5:
#newvalue = input("Choose a Value: ")
try:
x = int(newvalue)
except ValueError:
validate = validate + 1
print("Invalid Input: Attempts Remaining {0}".format(5 - validate))
else:
if x < 0:
validate = validate + 1
print("Negative Input: Attempts Remaining {0}".format(5 - validate))
else:
break
if validate == 5:
print("Input Failed")
return
#All Validation Passed
print("All Validation Passed")
SQLExample.ModifyStat(cursor,fname,ftype,ftier,stat,newvalue)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
return
def DisplayAllStats():
# connecting to the database
connection = sqlite3.connect("myTable.db")
# cursor
crsr = connection.cursor()
print("Displaying All Stats")
rows = SQLExample.SelectAllTable(crsr,"Statistics")
FormatDisplay(rows)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
return rows
def DisplayFactionStats(fname):
# connecting to the database
connection = sqlite3.connect("myTable.db")
# cursor
cursor = connection.cursor()
#fname = input("Choose a Faction: ")
#import sqlite3
#sql_command = str(""" SELECT findex FROM Statistics WHERE faction = '{0}' AND type = '{1}' AND tier = {2}""".format(faction,type,tier))
sql_command = str("""SELECT * FROM Statistics WHERE faction = '{0}'""".format(fname))
#print(sql_command)
try:
cursor.execute(sql_command)
except sqlite3.IntegrityError as err:
print("CreateTable: IntegrityError {0}".format(err))
rows = cursor.fetchall()
if len(rows)== 0:
print("Invalid Faction")
return
FormatDisplay(rows)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
return rows
def DeleteFaction(fname, verify):
# connecting to the database
connection = sqlite3.connect("myTable.db")
# cursor
cursor = connection.cursor()
#fname = input("Choose a Faction: ")
#verify = input ("Confirm Deletion of: {0} (Y/N)".format(fname))
if verify == "Y":
print("Deleting {0}".format(fname))
else:
print("Deletion Cancelled")
return
#import sqlite3
#sql_command = str(""" SELECT findex FROM Statistics WHERE faction = '{0}' AND type = '{1}' AND tier = {2}""".format(faction,type,tier))
#sql = 'DELETE FROM tasks WHERE id=?'
sql_command = str("""DELETE FROM Statistics WHERE faction = '{0}'""".format(fname))
#print(sql_command)
try:
cursor.execute(sql_command)
except sqlite3.IntegrityError as err:
print("CreateTable: IntegrityError {0}".format(err))
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
def FormatDisplay(rows):
#Display headers
print(str("Faction").center(20), end='|')
print(str("Type").center(15), end='|')
print(str("Tier").center(6), end='|')
print(str("Navy").center(6), end='|')
print(str("Agency").center(8), end='|')
print(str("Market").center(8), end='|')
print(str("University").center(12), end='|')
print(str("Court").center(7))
#Display Rows
for row in rows:
print(str(row[1]).ljust(20), end='|')
print(str(row[2]).ljust(15), end='|')
print(str(row[3]).ljust(6), end='|')
print(str(row[4]).ljust(6), end='|')
print(str(row[5]).ljust(8), end='|')
print(str(row[6]).ljust(8), end='|')
print(str(row[7]).ljust(12), end='|')
print(str(row[8]).ljust(7))
return
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
column_name = ['user_id', 'item_id', 'rating', 'timestamp']
df = pd.read_csv('u.data', sep='\t', names= column_name)
print(df.head())
movie_titles = pd.read_csv('Movie_Id_Titles')
# Merging the two datasets together
df = pd.merge(df, movie_titles, on='item_id')
### Exploratory Data Analysis (EDA)
# Let's explore the data and look at some of the best rated movies
# We create a new dataframe with average rating and number of ratings: Sorted from highest to lowest rating
df_group1 = df.groupby('title')['rating'].mean().sort_values(ascending=False)
df_group2 = df.groupby('title')['rating'].count().sort_values(ascending=False)
# Creating a dataframe with the mean rating values and number of ratings:
ratings = pd.DataFrame(df.groupby('title')['rating'].mean())
ratings['Total rating count'] = pd.DataFrame(df.groupby('title')['rating'].count())
plt.figure(figsize=(10,4))
plt.title('Total Number of Ratings')
plt.hist(ratings['Total rating count'], bins=70)
plt.figure(figsize=(10,4))
plt.title('Movie Ratings Vs Number of People')
plt.hist(ratings['rating'], bins=70)
#plt.figure(figsize=(10,10))
sns.jointplot(x='rating', y='Total rating count', data=ratings, alpha=0.5)
#plt.show()
### Recommending Similar Movies:
#Creating a Pivot Table with UserId as the index axis and Movie title as another axis.
#Each cell consists of the rating the user gave to that movie.
moviemat = df.pivot_table(index='user_id', columns='title', values='rating')
print(moviemat.head())
print(ratings.sort_values('Total rating count', ascending=False).head())
# We now grab the user ratings for two movies
starwars_user_ratings = moviemat['Star Wars (1977)']
liarliar_user_ratings = moviemat['Liar Liar (1997)']
# We can the use corrwith() method to get correlations between two panda series
similar_to_starwars = moviemat.corrwith(starwars_user_ratings)
similar_to_liarliar = moviemat.corrwith(liarliar_user_ratings)
#Let us clean this by NAN values and using a DataFrame instead of a series:
corr_starwars = pd.DataFrame(similar_to_starwars, columns=['Correlation'])
corr_starwars.dropna(inplace=True)
corr_liarliar = pd.DataFrame(similar_to_liarliar, columns=['Correlation'])
corr_liarliar.dropna(inplace=True)
# Higher the correlation, the more correlated the movie is and thereby we recommend the highest correlated movies
# Sorting wrt highest correlation.
corr_starwars.sort_values('Correlation', ascending=False)
# We will take only the movies that have been rated by more than 100 users:
# For this, we will first add the Total rating count column to our dataframe and then sort them
corr_starwars = corr_starwars.join(ratings['Total rating count'])
corr_starwars = corr_starwars[corr_starwars['Total rating count']>100].sort_values('Correlation', ascending=False)
corr_liarliar = corr_liarliar.join(ratings['Total rating count'])
corr_liarliar = corr_liarliar[corr_liarliar['Total rating count']>100].sort_values('Correlation', ascending=False)
print(corr_starwars.head())
print(corr_liarliar.head())
plt.show()
|
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param new_interval, a Interval
# @return a list of Interval
def insert(self, intervals, new_interval):
def isIntersectionEmpty(i1, i2):
if(i1.end < i2.start or i2.end < i1.start):
return 1
else:
return 0
mergedIntervals = []
for interval in intervals:
if(isIntersectionEmpty(interval, new_interval)):
mergedIntervals.append(interval)
else:
aList = [interval.start, interval.end, new_interval.start, new_interval.end]
new_interval = Interval(min(aList), max(aList))
mergedIntervals.append(new_interval)
return sorted(mergedIntervals, key=lambda interval: interval.start)
|
# File: proj3.py
# Author: Dylan McQuaid
# Date: 11/27/17
# Section: 27
# E-mail: mcdyl1@umbc.edu
# Description: This program uses a recursive search algorithm to solve a maze
# read in from file
# 1, 0, 0, 1
#wall on right, open bottom, open left, wall on top
#constants for indexes representing the sides of the squares
RIGHT = 0
BOTTOM = 1
LEFT = 2
TOP = 3
###############################################################################
# readDimensions(): takes in the file and reads the first
# line to get the rows and cols of the maze
# Input: mazeFile; a txt file opened in main
# Output: dimensionLine; a list of the first line containing
# the dimensions
def readDimensions(mazeFile):
dimensionLine = mazeFile.readline()
dimensionLine = dimensionLine.split()
return (dimensionLine)
###############################################################################
# readFinish(): takes in the file and reads in the second
# line to get where the finish is located
# Input: mazeFile; a txt file opened in main
# Output: finishLine; a list of the second line containing
# the location of the finish
def readFinish(mazeFile):
finishLine = mazeFile.readline()
finishLine = finishLine.split()
return (finishLine)
###############################################################################
# readMaze(): takes in the file and reads in the rest of the
# lines forming them into a 3D list
# Input: mazeFile; a txt file opened in main
# numRows; int for length of list
# numCols; int for length of list
# Output: maze; a 3D list representing the final maze
def readMaze(mazeFile, numRows, numCols):
squareWalls = mazeFile.readlines()
maze = []
row = []
squares = []
#2D list containing squares
for line in squareWalls:
squares.append(line.split())
#make 3D list
for i in range(len(squareWalls)):
row.append(squares[i])
#make rows correct length
if len(row) == numCols:
maze.append(row)
row = []
return maze
###############################################################################
# searchMaze(): recursively finds the path to take from the
# start to find the finish
# Input: maze; 3D list representing the final maze
# row; int for current row spot
# col; int for current column spot
# path; list representing the path so far
# finishRow; row of finish in 3D list
# finishCol; col of finish in 3D list
# Output: path; final path of the way to solution or None
# if no solution is found
def searchMaze(maze, row, col, path, finishRow, finishCol):
#Base cases: found solution and start with
#no where to go
if row == finishRow and col == finishCol:
print("Solution Found")
path.append((row, col))
return path
elif maze[row][col][RIGHT] == '1' and maze[row][col][LEFT] == '1' and \
maze[row][col][TOP] == '1' and maze[row][col][BOTTOM] == '1':
return None
else:
#Recursive cases for going in each direction
if maze[row][col][RIGHT] == '0' and (row, col + 1) not in path:
path.append((row, col))
rightPath = searchMaze(maze, row, col + 1, path, finishRow, finishCol)
#check if leads to deadend
if rightPath != None:
return path
path.remove((row, col))
if maze[row][col][LEFT] == '0' and (row, col - 1) not in path:
path.append((row, col))
leftPath = searchMaze(maze, row, col - 1, path, finishRow, finishCol)
#check if leads to deadend
if leftPath != None:
return path
path.remove((row, col))
if maze[row][col][TOP] == '0' and (row - 1, col) not in path:
path.append((row, col))
topPath = searchMaze(maze, row - 1, col, path, finishRow, finishCol)
#check if leads to deadend
if topPath != None:
return path
path.remove((row, col))
if maze[row][col][BOTTOM] == '0' and (row + 1, col) not in path:
path.append((row, col))
bottomPath = searchMaze(maze, row +1, col, path, finishRow, finishCol)
#check if leads to deadend
if bottomPath != None:
return path
path.remove((row, col))
#if no solution is found
return None
###############################################################################
# getValidInput(): prompt user until input is valid
# Input: prompt; string to give info to user
# maximum; maximum value that can be entered
# Output: userInput; the correct input taken from the user
def getValidInput(prompt, maximum):
userInput = int(input(prompt))
while userInput < 0 or userInput > maximum:
print("Error, number must be between 0 and", maximum, "(inclusive)")
userInput = int(input(prompt))
return userInput
###############################################################################
def main():
print("Welcome to the Maze Solver!")
filename = input("Enter the filename of the maze: ")
mazeFile = open(filename)
dimensions = readDimensions(mazeFile)
numRows = int(dimensions[0])
numCols = int(dimensions[1])
finish = readFinish(mazeFile)
finishRow = int(finish[0])
finishCol = int(finish[1])
maze = readMaze(mazeFile, numRows, numCols)
startRowPrompt = "Please enter the starting row: "
startRow = getValidInput(startRowPrompt, (numRows - 1))
startColPrompt = "Please enter the starting column: "
startCol = getValidInput(startColPrompt, (numCols - 1))
path = []
path = searchMaze(maze, startRow, startCol, path, finishRow, finishCol)
#what to print out based on return of searchMaze
if path != None:
for i in range(len(path)):
print(path[i])
if path == None:
print("No solution found")
main()
|
while True:
try:
num1 = int(input("Enter THE number: "))
result = num1%3
res2 = num1%5
if result == 0 and res2 == 0:
print("fizzbuzz")
elif result == 0:
print("fizz")
elif res2 == 0:
print("buzz")
except ValueError:
break |
def list_handler(in_list):
max = 0
min = 100
for item in in_list:
if item > max:
max = item
if item < min:
min = item
result = max - min
return result
def userinput(text):
usr_in = input(text)
return usr_in
def handle_input(text):
proper_input = False
while not proper_input:
try:
user_input = userinput(text)
user_input = int(user_input)
proper_input = True
except ValueError:
pass
return user_input
def list_count():
text = "How many items do you want in your list? "
count_list = handle_input(text)
return count_list
def item_input(count_list):
counter = 0
text = "Give one item of the list: "
usr_list = []
while counter != count_list:
list_item = handle_input(text)
usr_list.append(list_item)
counter += 1
return usr_list
def main():
user_list = []
usr_list_count = 0
usr_list_count = list_count()
user_list = item_input(usr_list_count)
print(list_handler(user_list))
main()
|
import random
coordsys = []
for x in range(0, 5):
coordsys.append([])
for y in range(0, 5):
coordsys[x].append(0)
coordsys[2][2] = "X"
middle_x = 2
middle_y = 2
robot_snail_pos_x = random.randint(0, 5)
robot_snail_pos_y = random.randint(0, 5)
robot_snail_pos = coordsys[robot_snail_pos_x][robot_snail_pos_y]
coordsys[robot_snail_pos_x][robot_snail_pos_y] = "S"
print(coordsys)
if robot_snail_pos_x >= 2:
distance_x = middle_x - robot_snail_pos_x
else:
distance_x = robot_snail_pos_x - middle_x
if robot_snail_pos_y >= 2:
distance_y = middle_y - robot_snail_pos_y
else:
distance_y = robot_snail_pos_y - middle_y
print("The distance is : x: ", distance_x, "y: ", distance_y)
|
stringlist = {}
string = "egy kettő kfasédf 3 négy"
def checkio(string):
stringlist = list(string.split())
count = 0
for i in range(len(stringlist)):
variable = stringlist[i]
if variable.isdigit():
count = 0
else:
count += 1
if count == 3:
return True
return False
print(checkio(string))
|
#!/usr/bin/env python
'''
Created on Oct 1, 2012
@author: josh
'''
from player import playerone
import random
from dice import Die
def fight():
from enemylist import enemylist
# PICKS AN ENEMY FROM ENEMYLIST FILE
opponent=random.choice(enemylist)
print "You are fighting "+opponent.Name, "\n\tOpponent's max HP:", opponent.hpmax, "\n\tYour HP:", playerone.current_hp
while opponent.current_hp > 0 or playerone.current_hp > 0:
dice = Die()
player_initiative = dice.roll(1, 21)
opponent_initiative = dice.roll(1, 21)
if player_initiative > opponent_initiative:
print "Player goes first."
player_attacks(playerone, opponent)
if opponent.current_hp <= 0:
won_fight(playerone, opponent)
break
enemy_attacks(opponent, playerone)
if playerone.current_hp <= 0:
playerone.current_hp = playerone.hpmax
print "You were defeated. Returning to main menu"
break
print "Your hp: ", playerone.current_hp, "Enemy's hp: ", opponent.current_hp
elif opponent_initiative>player_initiative:
print "Opponent goes first."
enemy_attacks(opponent, playerone)
if playerone.current_hp <= 0:
playerone.current_hp = playerone.hpmax
print"You were defeated. Returning to main menu"
player_attacks(playerone, opponent)
if opponent.current_hp <= 0:
won_fight(playerone, opponent)
break
print "Your hp: ", playerone.current_hp, "Enemy's hp: ", opponent.current_hp
print "END OF TURN\n-----------------------------"
def enemy_attacks(enemy, player):
if enemy.attack() > player.defense_value():
attack_value = enemy.attack() - player.defense_value()
player.current_hp -= attack_value
return player.current_hp
def player_attacks(player, enemy):
if player.attack() > enemy.defense_value():
attack_value = player.attack() - enemy.defense_value()
enemy.current_hp -= attack_value
return enemy.current_hp
def won_fight(player, opponent):
player.xp += opponent.xp_value
player.gold += opponent.gold
player.renown += opponent.renown_value
check_for_levelup(player)
player.current_hp = player.hpmax
print "Your XP:", player.xp, "\nyou defeated the enemy, returning to main menu"
def check_for_levelup(player):
print "about to check for level up"
if player.xp >= player.next_levelup:
print "Checking for level up"
player.level += 1
player.hpmax += int(playerone.hpmax*.15)
player.next_levelup = int(player.next_levelup*.2 + player.next_levelup)
print "**** You leveled up! ****\n your new level is: ", player.level, "your next level-up in: ", player.next_levelup, "your new hp is: ", player.hpmax
player.xp = 0
|
#!/usr/bin/env python
'''
Created on Sep 27, 2012
@author: josh
'''
import random
def roll(dice, sides):
total=0
for x in range(1, dice+1):
total += random.randrange(1, sides+1)
return int(total)
|
# 类调用实例
# 列表
# 递归
def print_test(the_list):
if isinstance(the_list, list):
for t in the_list:
print(t)
print_test("not list")
else:
print(the_list)
|
'''
Created on Nov 12, 2015
@author: prefalo
'''
from random import random
from timeit import timeit
def aList():
lst = []
for _ in range(1000000):
lst.append(random())
return lst
def aGen():
for _ in range(1000000):
yield random()
print("List Comprehension from List")
print(timeit("[x for x in aList()]", "from __main__ import aList", number = 1))
print("List Comprehension from Generator")
print(timeit("[x for x in aGen()]", "from __main__ import aGen", number = 1))
print("list() from List")
print(timeit("list(aList())", "from __main__ import aList", number = 1))
print("list() from Generator")
print(timeit("list(aGen())", "from __main__ import aGen", number = 1))
if __name__ == '__main__':
pass
"""
list(x*x for x in sequence == [x*x for x in sequence]
# Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
>>> for i in (10000, 100000, 1000000, 10000000, 20000000, 50000000):
... lst = [random() for j in range(i)]
... print("Length", i)
... print(timeit("sum(x+1 for x in lst)", "from __main__ import lst", number=1))
... print(timeit("sum([x+1 for x in lst])", "from __main__ import lst", number=1))
""" |
#!/usr/local/bin/python3
"""Lesson 16 Obj 2 - final.py
Read in text from a file given on the command line. Count the frequency
of words of each length without punctuation and display results.
USAGE: ./final.py file.txt
"""
import sys
import collections
import string
def len_no_punctuation(w):
""" This function taks a string (word) as a parameter and then
counts up just the ascii.letters for each word. It returns the
number of actual letters and an integer.
"""
n = 0 # loop over the letters and count up just the ascii_letters
for letter in w:
if letter in string.ascii_letters:
n += 1
return n
if __name__ == "__main__":
try:
fn = sys.argv[1]
f = open(fn,'r') # create file f the close it
except IndexError: # catch index problem with file
print('A test file is required')
sys.exit()
except FileNotFoundError: # catch file not found
print('Cannot find that file')
sys.exit()
except Exception as msg: # catch if something else when wrong
print("Something unexpected occurred: {0}".format(msg))
sys.exit()
lst_of_words = list() # declare an empty list
lst_of_words = f.read().strip().split() # read text into list as stripped of white space and split
c = collections.Counter() # form the dict c using .Counter()
for word in lst_of_words: # update dict c for each key
c.update({len_no_punctuation(word):1}) # uses def to exclude punctuation in the letter count
print("Length Count")
for k, v in sorted(c.items()): # print results of dict c
if ( k == 0 ): # ignore the '&' word result
continue
print(k, v)
|
from tkinter import *
ALL = N+S+W+E
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.rowconfigure(0, weight=1, minsize="100px")
self.master.columnconfigure(0, weight=1, minsize="170px")
self.grid(sticky=ALL)
for r in range(4):
self.rowconfigure(r, weight=1)
for c in range(5):
self.columnconfigure(c, weight=1)
Button(self, text="Button {0}".format(c + 1)).grid(row=4, column=c, sticky=E+W)
f1 = Frame(self, bg="green")
f1.grid(row=0, column=0, rowspan=2, columnspan=2, sticky=ALL)
l1 = Label(f1, text="Frame1", bg="green", fg="white")
l1.pack(side=TOP, fill=BOTH, expand=True)
f2 = Frame(self, bg="blue")
f2.grid(row=2, column=0, rowspan=2, columnspan=2, sticky=ALL)
l2 = Label(f2, text="Frame2", bg="blue", fg="white")
l2.pack(side=TOP, fill=BOTH, expand=True)
f3 = Frame(self, bg="red")
f3.grid(row=0, column=2, rowspan=4, columnspan=3, sticky=ALL)
l3 = Label(f3, text="Frame3", bg="red", fg="white")
l3.pack(side=TOP, fill=BOTH, expand=True)
root = Tk()
app = Application(master=root)
app.mainloop()
|
################################################################################
# Differential Op Amp
################################################################################
# Author: N. Dodds
# Written on: Python xy (python 2.7)
# References:
# [1] http://www.electronics-tutorials.ws/opamp/opamp_5.html
################################################################################
############################################
# Defines the class for simulating a differential Op Amp
############################################
class DiffentialOpAmp:
#Class instantiation
def __init__(self, R1, R2, R3, R4):
#Basic Properties of RTD from DataSheet
self.R1 = R1 # Resistor Connected to Negative OpAmp input to Vin1
self.R2 = R2 # Resistor Connected to Positive OpAmp input to Vin2
self.R3 = R3 # Resistor Connected to Feedback loop to Negative OpAmp input.
self.R4 = R4 # Resistor Connected to Positive OpAmp input to ground.
self.V1 = 0
self.V2 = 0
self.Gn = 0 #Calculated Gain
self.calculate() #Calculate initial values
#Default get function - Standard Function to get access to class members
def __get__(self, obj, objtype):
return self.val
#Set V1 input voltage
def set_V1(self,value):
self.v1 = value
self.calculate()
#Set V2 input voltage
def set_V2(self,value):
self.v2 = value
self.calculate()
#Set the sensed temperature (true temperature) in degC
def calculate(self):
#
self.Vout = -self.V1*(self.R3/self.R1) + self.V2*(self.R4/(Self.R2+self.R4))*((self.R1 + self.R3)/self.R1)
|
from cipher import *
from math import sqrt
from copy import copy
import argparse
messages = ["1989\nOver hill, over dale,\n\
Thorough bush, thorough brier,\n\
Over park, over pale,\n\
Thorough flood, thorough fire!\n\
I do wander everywhere,\n\
Swifter than the moon's sphere;\n\
And I serve the Fairy Queen,\n\
To dew her orbs upon the green;\n\
The cowslips tall her pensioners be;\n\
In their gold coats spots you see",
"What does family mean to you? In a perfect world, all families should be happy and everyone should get on well together. I know a lot of families that have many problems. Brothers and sisters who don’t like each other, parents who never talk to each other. I wonder why this is. How can you live so close to your family members and feel apart from them? There is a lot of talk in the news about the breakdown of family life. Divorce is rising everywhere in the world. This means single parents have less time to spend with their children, which creates problems. Maybe the stress of modern life puts too much pressure on families. It seems as though family life was better a generation or two ago. Is this true for families in your country?", \
]
def test_message():
m = Message("My Message", False, a=5)
print(m)
def test_Encryptor():
e = CaesarEncryptor(3)
m = Message("You are the best!!!")
e.fit(m)
def test_Caesar():
message = Message(messages[0])
enc = CaesarEncryptor(7)
enc.fit(message)
shifred = enc.encrypt()
print(shifred)
enc.fit(shifred)
shifred = enc.encrypt()
print(shifred)
decr = CaesarDecryptor(14)
decr.fit(shifred)
unshifred = decr.decrypt()
print(unshifred)
if unshifred.text != message.text:
raise Exception("Wrong decrypt! Caesar")
def test_Caesar_krack():
message = Message(messages[0])
enc = CaesarEncryptor(7)
enc.fit(message)
shifred = enc.encrypt()
unshif = CaesarDecryptor.decryptWithoutKey(shifred)
if unshif.text != message.text:
raise Exception("Wrong decrypt! Caesar krack")
# print(unshif)
def test_Caesar_krack1():
mess = Message(messages[1])
enc = CaesarEncryptor(14)
enc.fit(mess)
shifred = enc.encrypt()
# print('shifred:\n{}'.format(shifred))
# print()
unshif = CaesarDecryptor.decryptWithoutKey(shifred)
if unshif.text != mess.text:
raise Exception("Wrong decrypt krack Caesar 1!")
# print(unshif)
def test_Vigner():
mess = Message("ATTACKATDAWN")
enc = VigenerEncryptor("LEMON")
enc.fit(mess)
shifred = enc.encrypt()
print(shifred)
def test_Vigner1():
mess = Message(messages[0])
enc = VigenerEncryptor("lEmON")
enc.fit(mess)
shifred = enc.encrypt()
# print(shifred)
dec = VigenerDecryptor("LeMon")
dec.fit(shifred)
unshifred = dec.decrypt()
# print(unshifred)
if unshifred.text != mess.text:
raise Exception("Wrong decrypt Vigener!")
def test_Vernam():
mess = Message("Ciper")
enc = VernamEncryptor("lEmON")
enc.fit(mess)
shifred = enc.encrypt()
print(shifred)
dec = VernamDecryptor("LeMon")
dec.fit(shifred)
unshifred = dec.decrypt()
print(unshifred)
print(dec.message.text)
if unshifred.text != mess.text:
raise Exception("Wrong decrypt Vernam!")
from random import randint
def test_Vernam1():
mess = Message(messages[0])
keyw = [chr(ord('a') + randint(0, 25)) for i in mess.text if i.isalpha()]
enc = VernamEncryptor(keyw)
enc.fit(mess)
shifred = enc.encrypt()
#print(shifred)
dec = VernamDecryptor(keyw)
dec.fit(shifred)
unshifred = dec.decrypt()
#print(unshifred)
if unshifred.text != mess.text:
raise Exception("Wrong decrypt Vernam1!")
class StoreDictKeyPair(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
self._nargs = nargs
super(StoreDictKeyPair, self).__init__(option_strings, dest, nargs=nargs, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
my_dict = {}
print
"values: {}".format(values)
for kv in values:
k, v = kv.split("=")
my_dict[k] = v
setattr(namespace, self.dest, my_dict)
parcer = argparse.ArgumentParser(description='In')
parcer.add_argument('--mode', type=str)
parcer.add_argument('--path_from', type=str)
parcer.add_argument('--path_to', type=str)
parcer.add_argument('--typeCipher', type=str)
parcer.add_argument('--params', dest="my_dict", action=StoreDictKeyPair, nargs="+", metavar="KEY=VAL")
args = parcer.parse_args()
if args.typeCipher == 'Stega':
img_path = args.my_dict['image_path']
img = Image.open(img_path)
new_img = None
if args.mode == 'Enc':
fin = open(args.path_from, 'r')
text = fin.read()
mess = Message(text)
enc = StegaEncryptor(img)
enc.fit(mess)
new_img = enc.encrypt()
new_img.save(args.path_to + "/ciphred_img.png", "PNG")
exit(0)
else:
fout = open(args.path_to, 'w')
dec = StegaDecryptor(img)
sz = 50
if 'mess_length' in args.my_dict:
sz = int(args.my_dict['mess_length'])
dec.fit(sz)
mess = dec.decrypt()
fout.write(mess.text)
exit(0)
fin = open(args.path_from, 'r')
fout = open(args.path_to, 'w')
text = fin.read()
mess = Message(text)
if args.mode == 'Hack':
fout.write(CaesarDecryptor.decryptWithoutKey(mess).text)
fin.close()
fout.close()
exit(0)
if args.typeCipher == 'Caesar':
enc = CaesarEncryptor(int(args.my_dict['shift']))
dec = CaesarDecryptor(int(args.my_dict['shift']))
if args.typeCipher == 'Vigener':
enc = VigenerEncryptor(args.my_dict['keyword'])
dec = VigenerDecryptor(args.my_dict['keyword'])
if args.typeCipher == 'Vernam':
enc = VernamEncryptor(args.my_dict['keyword'])
dec = VernamDecryptor(args.my_dict['keyword'])
if args.typeCipher == 'Gronsfeld':
enc = GronsfeldEncryptor(args.my_dict['digits'])
dec = GronsfeldDecryptor(args.my_dict['digits'])
if args.mode == 'Enc':
obj = enc
if args.mode == 'Dec':
obj = dec
obj.fit(mess)
if args.mode == 'Enc':
text = obj.encrypt()
if args.mode == 'Dec':
text = obj.decrypt()
fout.write(text.text)
fin.close()
fout.close()
'''
parcer = argparse.ArgumentParser(description='In')
parcer.add_argument('first', type=str)
parcer.add_argument('second', type=str)
args = parcer.parse_args()
print("First: {}, Second: {}".format(args.first, args.second))
test_Caesar()
test_message()
test_Encryptor()
test_Caesar_krack()
test_Caesar_krack1()
test_Vigner1()
test_Vernam()
test_Vernam1()
freq = dict(a=8.2, b=1.5, c=2.8, d=4.3, e=13, f=2.2, g=2.0, h=6.1, i=7.0, j=0.15, k=0.77, l=4.0, m=2.4, n=6.7,
o=7.5, p=1.9, q=0.095, r=6.0, s=6.3, t=9.1, u=2.8, v=0.98, w=2.4, x=0.15, y=2.0, z=0.074)
freq = [8.2, 1.5, 2.8, 4.3, 13, 2.2, 2.0, 6.1, 7.0, 0.15, 0.77, 4.0, 2.4, 6.7, 7.5, 1.9, 0.095, 6.0, 6.3, 9.1, 2.8,
0.98, 2.4, 0.15, 2.0, 0.074]
def normalize(lst):
freq = copy(lst)
mean = sum(freq) / len(freq)
std = sqrt(sum([(x - mean) ** 2 for x in freq]) / len(freq))
freq = [(x - mean) / std for x in freq]
return freq
print(normalize(freq))
print('AAA'.lower())
t = [['a'] * 26 for i in range(26)]
t[0][1] = '6'
t[1][0] = '4'
for i in range(26):
for j in range(26):
t[i][j] = chr(ord('a') + (i + j) % 26)
for i in range(26):
for j in range(26):
print(t[i][j], end='')
print()
for i in enumerate(range(1, 5, 2)):
print(i)
'''
|
"""
calcgpa.py
Calculates GPA of certain courses according to a query.
"""
import argparse
from sys import exit
from os import path
def filter_courses(original_courses_list, year, upper_bound, lower_bound, semester):
"""
Returns the filtered list of courses by fulfilling ALL of the filter demands specified in the command line.
"""
filtered_courses_list = []
for course in original_courses_list:
if year is not None and course.year != year:
continue
if upper_bound is not None and course.grade > upper_bound:
continue
if lower_bound is not None and course.grade < lower_bound:
continue
if semester is not None and course.semester != semester:
continue
filtered_courses_list.append(course)
return filtered_courses_list
def print_output(filtered_courses_list):
"""
Beautifully prints the details for the filtered courses list.
"""
if not filtered_courses_list:
print("No courses matched the query.")
return
max_name_length = max([len(course.name) for course in filtered_courses_list])
print(" Sem | Course ID | Pts | " +
" " * ((max_name_length - 11) // 2 + (max_name_length - 1) % 2) + "Course Name" + " " * ((max_name_length - 11) // 2) +
" | Grade")
print("______|___________|_____|" + "_" * (max_name_length + 2) + "|______")
for course in filtered_courses_list:
print(str(course.year) + course.semester, end=" | ")
print(course.cid, end=" | ")
print(course.creditpts, end=" | ")
print(course.name, end=" " * (max_name_length - len(course.name) + 1) + "| ")
print(course.grade)
print("\nGPA: " + ("%.3f" % calculate_weighted_average(filtered_courses_list)))
def calculate_weighted_average(filtered_courses_list):
"""
Calculates the weighted average grade for the input courses list.
"""
total_creditpts = 0
weighted_average = 0
for course in filtered_courses_list:
total_creditpts += course.creditpts
for course in filtered_courses_list:
weighted_average += ((course.creditpts /
total_creditpts) * course.grade)
return weighted_average
class ParseError(Exception):
def __init__(self, filename):
msg = f"calcgpa: error: '{filename}' is not of valid format."
super().__init__(msg)
class Course:
def __init__(self, semester, year, cid, creditpts, name, grade):
self.semester = semester
self.year = year
self.cid = cid
self.creditpts = creditpts
self.name = name
self.grade = grade
def parse_datafile(datafile):
"""
Read the datafile and create a list of courses.
"""
lines = datafile.readlines()[1:] # ignore first line
datafile.close()
course_list = []
for i, line in enumerate(lines):
line = line.strip()
if not line or line[0] in ('#', '-', '_'): # ignore lines that begin with '#', '-' or '_'
continue
cells = line.split('|')
try:
# put stripped content of each cell in corresponding variable
full_semester, cid, creditpts, name, grade = tuple(map(lambda cell: cell.strip(), cells))
semester = full_semester[-1]
year = full_semester[:-1]
if grade != '???':
course_list.append(
Course(semester, int(year), cid, int(creditpts), name, int(grade)))
except:
print(ParseError(path.basename(datafile.name)))
exit(1)
return course_list
def get_args():
"""Initialize argument parser and receive filename from user.
"""
parser = argparse.ArgumentParser(
description='Calculates various grade statistics.')
parser.add_argument('datafile', type=argparse.FileType('r'),
help='name of the file in which the data is stored')
parser.add_argument('-y', '--year', metavar='YYYY', type=int, #
help='filter by year')
parser.add_argument('-ub', '--upper-bound', metavar='0-100', type=int, #
help='filter by grade upper bound (inclusive)')
parser.add_argument('-lb', '--lower-bound', metavar='0-100', type=int,
help='filter by grade lower bound (inclusive)')
parser.add_argument('-s', '--semester', metavar='A|B|C', type=str,
help='filter by semester')
return parser.parse_args()
def main():
args = get_args()
courses_list = parse_datafile(args.datafile) # get courses
filtered_courses_list = filter_courses( # filter courses
courses_list, args.year, args.upper_bound, args.lower_bound, args.semester)
print_output(filtered_courses_list) # show gpa
if __name__ == "__main__":
main()
|
import nltk
def openFile(file_path_name):
with open(file_path_name) as file:
text = file.read()
return text
paragraph = openFile("nltk_file2.txt")
token_words = nltk.word_tokenize(paragraph)
# # porter stemming the words
# stemmer = nltk.PorterStemmer()
# stem_words = [stemmer.stem(wd) for wd in token_words]
# print(token_words)
# print(stem_words)
'''
Stemming the words has caused more mistakes
# This --> Thi
# divided --> divide and visited --> visit and travelled --> travel
# up-to-date --> up-to-d, motivated --> motiv
# O'Kelly --> O'Kelli , necessarily --> necessarili
# computing --> comput
# titles --> titl
# language --> languag
# systematically --> systemat
'''
# Leminization
pos_words = nltk.pos_tag(token_words)
lem_words = nltk.ne_chunk(pos_words, binary=True)
print(lem_words)
|
from nltk.corpus import stopwords
# stop words to be removed
stop_words = stopwords.words('english')
base = "hurricane ophelia hits ireland and schools close"
# List of sentences
sentences = ["hurricane ophelia hits ireland and schools close",
"hurricane ophelia misses england and work still closed",
"storm ophelia hits ireland and schools close",
"hurricane ophelia hits cork and houses destroyed",
"tornado sarah hits usa and colleges close",
"there was a hurricane in Ireland today",
"the schools in ireland close as hurricane ophelia is to hits them"]
# Two Functions to calculate the jaccard distance
def jaccardIndex (str1, str2):
set1 = set(str1.split())
set2 = set(str2.split())
ans = float(len(set1 & set2)) / len(set1|set2)
return round(1 - ans, 2)
# This one removes the stop words first
def jaccardIndexStops (str1, str2):
str1 = str1.split()
str2 = str2.split()
# Get rid of stop words
strings1 = [word.lower() for word in str1 if word not in stop_words]
strings2 = [word.lower() for word in str2 if word not in stop_words]
set1 = set(strings1)
set2 = set(strings2)
ans = float(len(set1 & set2)) / len(set1|set2)
return round(1 - ans, 2)
# Showing the result on a base sentence
for sentence in sentences:
print("Score with stop words: " + str(jaccardIndex(base, sentence)))
print("Scores without stops: " + str(jaccardIndexStops(base, sentence)))
print()
# Empirically show by calculating it across all the sentences
base = ["hurricane ophelia hits ireland and schools close",
"hurricane ophelia misses england and work still closed",
"storm ophelia hits ireland and schools close",
"hurricane ophelia hits cork and houses destroyed",
"tornado sarah hits usa and colleges close",
"there was a hurricane in Ireland today"]
# Show the resutls of each sentance against one another
count = 0
dict_val = {"0": "X", "1": "Y", "2": "Z", "3": "A", "4": "B", "5": "C"}
while count < len(base):
innerCount = 0
while innerCount<len(base):
if innerCount!=count:
print("Sentence "+dict_val[str(count)]+" and "+dict_val[str(innerCount)]+" resulted in: " + str(jaccardIndex(base[count], base[innerCount])))
innerCount += 1
count += 1
|
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
newNum = num * 3 + 1
print(newNum)
return newNum
print('Enter number:')
num = int(input())
while num != 1:
num = collatz(num)
|
num = int(input('Enter any number: '))
if num % 2 == 0:
print('Oh yeah this bitch is even')
else:
print('No thank you i dont mess with odds')
|
import numpy as np
def hNeuron(W, X):
'''
Task 3.1
Function immitating functionality of neuron using step function
:param W: weight vector of (D+1)-by-1
:param X: data matrix of D-by-N
:return: Y: output vector of N-by-1
'''
bias = W[0]
W = np.delete(W, 0)
a = np.dot(W.T,X) + bias
Y = (a >= 0).astype(int)
return Y
|
from math import *
from random import *
from copy import *
from Direction import *
class IA():
def __init__(self,liste):
"""
Constructeur de la classe, prend en paramètre la liste qui correspond à la grille du 2048
Initialise également la liste de Direction qui servira dans play() et playAgainst()
:param liste: grille du 2048
:type liste: int[][]
"""
self.liste = liste
self.dir = [Direction.UP, Direction.LEFT, Direction.DOWN, Direction.RIGHT] #Tableau des directions
def play(self):
"""
Simule toutes les matrices possibles sur 3 déplacements, ainsi que leur valeur
Retourne les 3 déplacements à faire pour obtenir le meilleur coup.
:param return: tableau des 3 directions à prendre
:rtype: Direction[]
"""
bestScore = -inf #init du meilleur score
nonOpti= False #init du booléen
for i in range(4): #p=1
for j in range(4): #p=2
for k in range(4): #p=3
grille = deepcopy(self.liste)
moved = self.move(grille, self.dir[i])
value = self.moveValue(grille) #Valeur de la grille
moved = moved or self.move(grille, self.dir[j])
value = value + self.moveValue(grille) #Valeur de la grille
moved = moved or self.move(grille, self.dir[k]) #True si la grille est différente de la liste
value = value + self.moveValue(grille) #Valeur de la grille
value = value/3
if self.maxCoin(grille) and (value > bestScore or nonOpti) and moved: #Si le nombre max est dans un coin et si la valeur est supérieure au meilleur score ou que le booléen est vraie et que la grille est différente de la grille de base
indexI = i
indexJ = j
indexK = k
bestScore = value
nonOpti = False
elif bestScore == -inf and value > bestScore and moved: #Si aucun move opti n'a été trouvé on prend juste le meilleur
indexI = i
indexJ = j
indexK = k
bestScore = value
nonOpti = True
return(self.dir[indexI], self.dir[indexJ], self.dir[indexK]) #on retourne les directions à prendre
def playAgainst(self):
"""
Idem que play mais renvoie le pire move sur 1 de profondeur
:param return: Pire direction
:rtype: Direction
"""
worstScore = inf
nonOpti = False
for k in range(4):
grille = deepcopy(self.liste)
self.move(grille, self.dir[k])
value = self.moveValue(grille)
if not self.maxCoin(grille) and (value < worstScore or nonOpti):
worstScore = value
indexK = k
nonOpti = False
elif worstScore == inf and value < worstScore:
worstScore = value
indexK = k
nonOpti = True
return self.dir[indexK]
def move(self, grille, direction):
"""
Déplace les nombres dans la direction choisie et retourne True si un mouvement a été fait
:param grille: grille de 2048
:param direction: direction à prendre
:type grille: int[][]
:type direction: Direction
:param return: vrai si un mouvement a été fait
:rtype: bool
"""
ret = False
modif = True
if (direction == Direction.UP):
while modif == True:
modif = False
for i in range(1,len(grille)):
for j in range(len(grille[i])):
if (grille[i][j] != 0 and (grille[i][j] == grille[i-1][j] or grille[i-1][j] == 0) and grille[i][j] >= 0):
if (grille[i][j] == grille[i-1][j] and grille[i][j]>0):
grille[i-1][j] = grille[i-1][j]*(-2)
grille[i][j] = 0
else:
grille[i-1][j] = grille[i][j]
grille[i][j] = 0
ret = True
modif = True
elif (direction == Direction.RIGHT):
while modif == True:
modif = False
for i in range(len(grille)):
for j in range(len(grille[i])-2,-1,-1):
if (grille[i][j] != 0 and (grille[i][j] == grille[i][j+1] or grille[i][j+1] == 0) and grille[i][j] >= 0):
if (grille[i][j] == grille[i][j+1] and grille[i][j]>0):
grille[i][j+1] = grille[i][j+1]*(-2)
grille[i][j] = 0
else:
grille[i][j+1] = grille[i][j]
grille[i][j] = 0
ret = True
modif = True
elif (direction == Direction.LEFT):
while modif == True:
modif = False
for i in range(len(grille)):
for j in range(1,len(grille[i])):
if (grille[i][j] != 0 and (grille[i][j] == grille[i][j-1] or grille[i][j-1] == 0) and grille[i][j] >= 0):
if (grille[i][j] == grille[i][j-1] and grille[i][j] > 0):
grille[i][j-1] = grille[i][j-1]*(-2)
grille[i][j] = 0
elif (grille[i][j] != grille[i][j-1]):
grille[i][j-1] = grille[i][j]
grille[i][j] = 0
ret = True
modif = True
elif (direction == Direction.DOWN):
while modif == True:
modif = False
for i in range(len(grille)-2,-1,-1):
for j in range(len(grille[i])):
if (grille[i][j] != 0 and (grille[i][j] == grille[i+1][j] or grille[i+1][j] == 0) and grille[i][j] >= 0):
if (grille[i][j] == grille[i+1][j] and grille[i][j] > 0):
grille[i+1][j] = grille[i+1][j]*(-2)
grille[i][j] = 0
else:
grille[i+1][j] = grille[i][j]
grille[i][j] = 0
ret = True
modif = True
for i in range(len(grille)):
for j in range(len(grille[i])):
if (grille[i][j]<0):
grille[i][j]=grille[i][j]*(-1)
return ret
def moveValue(self, grille):
"""
Evalue la valeur de la grille en fonction de sa position dans celle-ci et de sa position relative aux autres nombres
:param grille: grille de 2048
:type grille: int[][]
:param return: valeur de grille
:rtype: int
"""
valeurs = {0:2000, 2:2, 4:4, 8:8, 16:16, 32:32, 64:64, 128:128, 256:512, 512:1024, 1024:2048, 2048:1000000}
val = 0
for i in range(len(grille)):
for j in range(len(grille[0])):
val += pow(valeurs[grille[i][j]], 3)
if i == 0 and j == 0: #Coin Haut-Gauche
val += pow(valeurs[grille[i][j]], 4) #On ajoute la valeur ^14
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i][j+1]: #si il est égal à un de ses voisins
val += pow(valeurs[grille[i][j]], 3) #On ajoute la valeur ^50
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2) #Et on soustrait la valeur absolue de sa différence avec ses voisins ^10
elif i == 0 and j == len(grille[0])-1: #Coin Haut-Droite
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2)
elif i == len(grille)-1 and j == len(grille[0])-1: #Coin Bas-Droite
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i-1][j] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i-1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2)
elif i == len(grille)-1 and j == 0: #Coin Bas-Gauche
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i-1][j] or grille[i][j] == grille[i][j+1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i-1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2)
elif i == 0: #Ligne Haut
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i][j+1] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2)
elif j == 0: #Ligne Gauche
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i][j+1] or grille[i][j] == grille[i-1][j]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2) + pow(fabs(grille[i][j]-grille[i-1][j]), 2)
elif i == len(grille)-1: #Ligne Bas
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i-1][j] or grille[i][j] == grille[i][j+1] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i-1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2)
elif j == len(grille[0])-1: #Ligne Droite
val += pow(valeurs[grille[i][j]], 4)
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i-1][j] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i-1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2)
else: #A l'intérieur
val += valeurs[grille[i][j]]
if grille[i][j] == grille[i+1][j] or grille[i][j] == grille[i-1][j] or grille[i][j] == grille[i][j+1] or grille[i][j] == grille[i][j-1]:
val += pow(valeurs[grille[i][j]], 3)
val -= pow(fabs(grille[i][j]-grille[i+1][j]), 2) + pow(fabs(grille[i][j]-grille[i][j+1]), 2) + pow(fabs(grille[i][j]-grille[i][j-1]), 2) + pow(fabs(grille[i][j]-grille[i-1][j]), 2)
return val
def maxCoin(self, grille):
"""
Retourne True si le nombre maximum est dans un coin
:param grille: grille de 2048
:type grille: int[][]
:param return: vrai si le max est dans un coin
:rtype: bool
"""
max = -inf
for i in range(4):
for j in range(4):
if grille[i][j] > max:
max = grille[i][j]
iI = i
iJ = j
couple = (iI, iJ)
return couple in [(0, 0), (0, 3), (3, 0), (3, 3)] #True si les coordonnées du max sont dans un coin
|
#https://www.hackerrank.com/contests/algoritmos-2018-i-contest-1/challenges/sherlock-and-array
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the balancedSums function below.
def balancedSums(arr):
leng = len(arr)
nos=arr
for i in range(1,leng):
nos[i] += nos[i-1]
#print(nos)
found=False
if leng==1:
found=True
pass
for i in range(1,leng-1):
sum1=0
sum2=0
sum1=nos[i-1]
sum2=nos[-1] - nos[i]
if sum1==sum2:
found=True
break
if found:
return ("YES")
else:
return ("NO")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
T = int(input().strip())
for T_itr in range(T):
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = balancedSums(arr)
fptr.write(result + '\n')
fptr.close()
|
#set inn et tak for hvor høyt du vil finne summen av alle tallene delelig med 3 eller 5
def multiple3n5():
n=1 #vi starter tellingen fra n=1
tak=int(input("input a roof")) #set inn et tak for hvor høyt du vil finne summen av alle tallene delelig med 3 eller 5
list=[] #etablerer en tom liste vi skal fylle med alle tall delelig på 3 eller 5
while n < tak: #mens vi regner på tall under taket
if n%3==0 or n%5==0: #hvis n er delelig på 3 eller 5 legg den til listen
list.append(n)
n+=1 #inkrementerer n uavhenging av om tallet går opp i 3 eller 5
return(sum(list)) #til slutt summerer vi alle tallene i listen
print(multiple3n5()) |
def read_from_file(filename):
file=open(filename)
return file.read()
def make_dict_CSV(filename):
text=read_from_file(filename)
output={}
for i in text.splitlines():
items=i.split(",")
output[items[0]]=items[1]
return output
def åpnestudier(filename):
dictionary=make_dict_CSV(filename)
counter=0
åpnestudier_liste=[]
for studie in dictionary:
print(dictionary[studie])
if "Alle" in str(dictionary[studie]):
counter+=1
åpnestudier_liste.append(studie)
return (counter, åpnestudier_liste)
print(åpnestudier("poenggrenser_2011.csv"))
def avg_NTNTU(filename):
dictionary=make_dict_CSV(filename)
temp=[]
for key in dictionary:
if key[1:5]=="NTNU":
if dictionary[key]=="Alle":
dictionary[key]=0
temp.append(dictionary[key])
else:
temp.append(float(dictionary[key]))
return sum(temp)/len(temp)
avg_NTNTU("poenggrenser_2011.csv")
|
n=input()
def evenfibonacci(n):
a=1
b=2
fibs=[]
EvenFibs=[]
while a<n:
fibs.append(a)
fibs.append(b)
a=a+b
b=a+b
print(fibs)
for n in fibs:
if n%2==0:
EvenFibs.append(n)
print(sum(EvenFibs))
return EvenFibs
evenfibonacci(100000)
|
def Factor(n):
i = 2
factors = []
while i * i <= n: #alle primtallsfaktorer av n er mindre eller lik kvadratroten av n
if n % i != 0: #vi sjekker om vi kan dele på i, dersom resten er ulik 0 er i ikke en faktor av n
i += 1 #vi øker i for å sjekke om i+1 er en faktor ettersom i ikke var det
else:
n //= i #er nå vist i en faktor av n, vi deler derfor n på i slik at vi nå tester på n=n/i
factors.append(i) #vi setter i inn i listen siden der er en faktor og øker ikke i slik at hvis i fortsatt er en faktor kan vi teste den
if n>1:
factors.append(n) #når vi har testet alle i opp til kvadratroten av n og da må n være lik 1 eller den siste faktoren i n
return factors
factorlist=[]
for n in range(1,21):
factorlist.append(Factor(n))
print (factorlist)
factor2=[]
factor3=[]
factor5=[]
factor7=[]
factor11=[]
factor13=[]
factor17=[]
factor19=[]
for a in factorlist:
factor2.append(a.count(2)) |
# coding=utf-8
import random as rnd
import numpy as np
import scipy as sci
import matplotlib.pyplot as plt # Import plotting library
def draw(nums,n):
li=[0]*n
i=0
while li[-1]==0:
draw=rnd.randint(0,len(nums)-1)
if nums[draw] not in li:
li[i]=nums[draw]
i+=1
return li
dt = 0.1 # Time-step
T = 10 # Total integration time
nt = round(T / dt) # Total number of time-steps
x = np.zeros((2, nt + 1)) # Make a matrix (array) with 2 rows and nt+1 columns called x
x[:, 0] = np.array([1, 0.2]) # Set the first column of x equal to [1,0.2] (the rest are still zero) this column is x_0 or the "intitial conditions"
def f(x):
dx = -4 * x[1] * x[0] ** 2
dy = 2 * x[0] ** 2 - 0.1 * x[1]
return np.array([dx, dy])
def g(x):
return np.array([(x[0] - 1) ** 2, (x[1] - 2) ** 2])
def dg(x):
jacobian = np.zeros((2, 2))
jacobian[0][0] = 2 * x[0]
jacobian[1][1] = 2 * x[1]
return jacobian
def error(x, f, tol=10 ** -10):
if f(x)[0] < tol and f(x)[1] < tol:
return True
else:
return False
def newton(x, g, dg, tol=10 ** -10):
k = 0
print(error(x, g, tol))
while not error(x, g, tol) and k < 1000:
x = x - np.linalg.inv(dg(x)) @ g(x)
print(x)
k += 1
return x
p = print
x0 = [2, 1]
print(newton(np.array([1, 1]), g, dg))
for it in range(0, nt):
x[:, it + 1] = x[:, it] + dt * f(x[:, it]) # Forward Euler (you will modify this line to implement the backward Euler method with Newton iterations)
t = np.array(range(0, nt + 1)) * dt # The discrete times that the solution is evaluated on (i.e., the horizontal axis of the following plot)
plt.plot(t, x[0, :], 'ro-', t, x[1, :], 'bx-') # Plot both solution components, now using arraysimport matplotlib.pyplot as plt # Import plotting library
############################## keksamen 2012
weatherdata={1:[1,0,30,3],2:[5,30,50,5],3:[3,120,65,7]}
def print_db(weather):
print()# blank linje ikke viktig
print("DAY | temp | rain | humidity | wind") #"Hardkodet" tabell teksten
print("====+======+======+==========+=====")# "hardkodet" tabell formatering
for day in weather: #for hver dag i dictionary, day itererer over alle nøkler i dictionaryen
temp, rain,humidity,wind=weather[day] # google "python sequence unpacking" hvis du ikke skjønner dette
print(f"{day:4}{temp:7}{rain:7}{humidity:11}{wind:6}") # pyformat.info har masse info om .format() som fungerer veldig likt som f-strings
#print_db(weatherdata) #ser ut som tallene i LF er litt feil, men det viktige er at dere får til å formatere teksten.
# tar inn en fil og splitter teksten på delimiter, returner alle utenom det første segmentet
def get_chapters(filename, delimiter):
f=open(filename,"r") #åpne fil
return f.read().split(delimiter)[1:] #les fil og split på delim returner alle uten om første segment
#går gjennom en liste med strenger og teller forekomster av word, returnerer en liste med telling fra hver sekvens
def count_words(string_list,word):
count=[]# tellingens liste
for string in string_list: # for hver tekstsegment
count.append(string.lower().count(word.lower())) #legg tell forekomster av ord og legg til i count
return count
def create_nums(num):# ubrukelig tullefunksjon som kan erstates av range(1,num+1)
return [i for i in range(1,num+1)]
#teller forekomster av et ord i en tekstfil og plotter resultatet som funksjon av hvilken sekvens det forekommer i
def anal_book(filename,delim,word):
chaps=get_chapters(filename,delim)
words=count_words(chaps,word)
plt.plot(range(1,len(chaps)+1),words,label=f"{word}")
plt.xlabel("Chapters")
plt.ylabel(f"number of {word}")
plt.legend()
plt.title("Word analysis")
plt.show()
#anal_book("alice_in_wonderland.txt","CHAPTER","alice")
def anal_gangbang(file,delim,words): #kjører anal_book for flere ord.
for word in words:
anal_book(file,delim,word)
#print(len(get_chapters("alice_in_wonderland.txt","CHAPTER")))
|
longest=0
length_max=0
for i in range(1000000):
startpoint=i
length=0
while i>1:
if i%2==1:
i=3*i+1
length+=1
else:
i=i//2
length += 1
if length>length_max:
longest=startpoint
print (longest) |
# Created by: Yusuf Moussa
# Created on: 01 April 2019
# Created for: ICS3U
# Daily Assignment Unit 4-04
# This is convert levels into grades
from tkinter import *
root = Tk()
root.title("Cylinder volume calculator")
root.geometry("500x300")
Label(root, text="This is a program to calculate the volume of a cylinder").grid(row=1, column=1)
Label(root, text="Enter the radius here: ").grid(row=2, column=1)
er = Entry(root)
er.grid(row=2, column=2)
Label(root, text="Enter the height here: ").grid(row=3, column=1)
eh = Entry(root)
eh.grid(row=3, column=2)
def volume():
radius = int(er.get()) **2
height = int(eh.get())
volume = 3.14 * radius * height
Label(root, text=str(volume)).grid(row=5, column=1)
vol = Button()
vol ["text"] = "Calculate"
vol ["command"] =volume
vol.grid(row=4, column=1)
root.mainloop() |
# -*- coding:utf-8 -*-
class BlockChain(object):
def __init__(self):
self.head = None # 指向最新的一个区块
self.blocks = {} # 包含所有区块的一个字典
def add_block(self, new_block):
previous_hash = self.head.hash() if self.head else None
new_block.previous_hash = previous_hash
self.blocks[new_block.identifier] = {
'block': new_block,
'previous_hash': previous_hash,
'previous': self.head,
}
self.head = new_block
def __repr__(self):
num_existing_blocks = len(self.blocks)
return 'Blockchain<{} Blocks, Head: {}>'.format(
num_existing_blocks,
self.head.identifier if self.head else None
) |
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data=pd.read_csv('wineQualityReds.csv')
#print(data.head())
print(data.info())
#print(data.columns)
#print(data.iloc[:,0])
data=data.rename(columns={'quality':'Wine_rating'})
print(data.tail())
print(data.iloc[:,12])
x=data.drop('Wine_rating',axis=1)
y=data['Wine_rating']
X_train,X_test,Y_train,Y_test=train_test_split(x,y,test_size=0.2)
model=LinearRegression()
model.fit(X_train,Y_train)
predication=model.predict(X_test)
print(predication[:5])
|
class Hangman():
#Thanks to Darvyn for this code!
#Thanks to Jessica for helping me debug the code.
#We start with a function that descibes the game and instructions.
#In []: is an example of an absolute value function
#Def X(): defines a function
#Print (): is a function that prints whatever is in the single quotes
#if is a boolean function that only returns a true expression
#else is a boolean function that only returns a false expression
#Quotation marks 'letter' or "spaces" are strings of data
#Parentheses ( e1, e2, e3 ) are tuples
#tuples are values in parentheses (2,4,8) that cannot be edited. a = (2,4,8) a is now the tuple.
#lists are values that occur within square brackets and can be edited.
#Curly braces {key1 : value1, key2 : value2} provides a dictionary of items
#rawinput() provides a method for user input.
#import X - import must occur at the top/first line of a program
#random functions:
#random.choice (values) - choose from a list
#random.randint(5,8) - choose int from 5 - 8
#random.uniform(5,8) - choose float between 5 & 8
def __init__(self):
#The user is presented with a decision point to either play or leave the game.
print "Welcome to 'Hangman.' Hangman is a game that starts with a secret word that must be revealed before you run out of options and die?"
print "(1)Yes, ready the gallows\n(2)No, get me outta here!"
user_choice_1 = raw_input("->")
#After starting the game the user guesses a letter, enter and the program returns either a successful attempt or a move closer to the gallows.
if user_choice_1 == '1':
print "First the executioner must test the gallows by dropping some sand bags"
self.start_game()
elif user_choice_1 == '2':
print "Good bye..."
else:
print "I'm sorry, I'm hard of hearing, could you repeat that?"
self.__init__()
def start_game(self):
print "The gallows passed the test and is ready."
print "Now the prisoner is brought out."
print "Officials, media and the public have gathered."
print "The judge asks if the prisoner has any last words"
print "The prisoner is hooded and the noose is placed around his neck"
print "The Judge reads outloud the final decision, by the powers vested in me by the state of PLTW let the exection begin."
print "The prisoner's is given last rights"
print "Whether or not the prisoner dies or lives is in your hands so choose wisely!"
self.core_game()
#With each successive wrong answer the gallows image gains a symbol until all are used and the user and prisoner lose.
#With each successively correct answer the user and prisoner move toward winning a stay of execution.
def core_game(self):
guesses = 0
letters_used = ""
the_word = "scott"
progress = ["?", "?", "?", "?", "?"]
while (guesses < 6) and ("?" in progress):
guess = raw_input("Guess a letter ->")
if guess in the_word and not (guess in letters_used):
print "Your guess was RIGHT, earning the prisoner a temporary stay!"
letters_used += "," + guess
self.hangman_graphic(guesses)
print "Progress: " + self.progress_updater(guess, the_word, progress)
print "Letter used: " + letters_used
elif guess not in the_word and not(guess in letters_used):
guesses += 1
print "Your guess was WRONG!"
print "The crowd is growing more excited"
print "and demand justice?"
letters_used += "," + guess
self.hangman_graphic(guesses)
print "Progress: " + "".join(progress)
print "Letter used: " + letters_used
else:
print "That's the wrong letter, the grim reaper awaits?"
print "Try again and pay attention!"
if "?" not in progress:
print "You WON, the prisoner lives!"
else:
print "You LOSE, you have carried out the first execution of this week and its only Monday!"
#Below are the successive fuctions displayed as wrong answers are given.
def hangman_graphic(self, guesses):
if guesses == 0:
print "________ "
print "| | "
print "| "
print "| "
print "| "
print "| "
elif guesses == 1:
print "________ "
print "| | "
print "| 0 "
print "| "
print "| "
print "| "
elif guesses == 2:
print "________ "
print "| | "
print "| 0 "
print "| / "
print "| "
print "| "
elif guesses == 3:
print "________ "
print "| | "
print "| 0 "
print "| /| "
print "| "
print "| "
elif guesses == 4:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| "
print "| "
elif guesses == 5:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / "
print "| "
else:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / \ "
print "| "
print "The noose tightens around his neck, and you feel the"
print "crowd leans in. Snap and thud as the sentence is carried out"
print "You have carried out the first execution of this week and its only Monday, GAME OVER!"
self.__init__()
def progress_updater(self, guess, the_word, progress):
i = 0
while i < len(the_word):
if guess == the_word[i]:
progress[i] = guess
i += 1
else:
i += 1
return "".join(progress)
game = Hangman() |
from karel.stanfordkarel import *
"""
File: RampClimbingKarel.py
--------------------
When you finish writing this file, RampClimbingKarel should be
able to draw a line with slope 1/2 in any odd sized world
"""
def main():
"""
You should write your code to make Karel do its task in
this function. Make sure to delete the 'pass' line before
starting to write your own code. You should also delete this
comment and replace it with a better, more descriptive one.
"""
beep()
def beep():
while no_beepers_present():
put_beeper()
if not_facing_east():
turn_left()
turn_left()
turn_left()
if front_is_clear():
dim()
else:
dim()
def dim():
move()
move()
turn_left()
move()
if __name__ == '__main__':
run_karel_program('RampKarel1.w')
|
def largest_ten(l):
# Assuming list size greater than 10
'''
@l: list of integers
remember to mention your runtime as comment!
@return: largest ten elements in list l, as a new list. (Order doesn't matter.)
'''
top_ten = []
for i in range(0, 10):
max_num = 0
for j in range(len(l)):
if l[j] > max_num:
max_num = l[j]
l.remove(max_num)
top_ten.append(max_num)
return(top_ten)
'''
Note:
To get autograded on gradescope, you program can't print anything.
Thus, please comment out the main function call, if you are submitting for auto grading.
'''
def main():
print(largest_ten([9,8,6,4,22,68,96,212,52,12,6,8,99]))
print(largest_ten([42,10,90,75,79,98,11,90,92,11,21,8,47,72,25,94,99,54,69,60]))
#main()
#The worst case runtime for my program is O(n). |
def hash_str(string):
''' return a integer hash value for the given string.
you should follow the hash function property:
1. hash same thing gives the same result.
2. hash different thing should give different result. The more different, the better.
@string: the string to be hashed.
return: integer value, the hash value for given string.
Hint: Be creative! There are many correct answers.
'''
# To do
h = 150
for i in string:
h = (( h << 7) + h) + ord(i)
return h
''' This question can not get autograded. '''
def main():
print("Hash lee: ", hash_str("lee"))
print("Hash Lee: ", hash_str("Lee"))
print("Hash ele: ", hash_str("ele"))
print("Hash eel: ", hash_str("eel"))
for i in range(5):
print("Hash lee: ", hash_str("lee"))
main() |
def merge(I1, I2):
'''
@I1: the first iterable object. Can be a string!
@I2: the second iterable object.
required runtime: O(n).
@return: alternately merged I1, I2 elements in a list.
'''
a = []
b = []
c = []
for i in I1:
a.append(i)
for j in I2:
b.append(j)
if len(a) >= len(b):
more = a
less = b
else:
more = b
less = a
for k in range(0, len(more)):
if k < len(a):
c.append(a[k])
if k < len(b):
c.append(b[k])
return(c)
'''
Note:
To get autograded on gradescope, you program can't print anything.
Thus, please comment out the main function call, if you are submitting for auto grading.
'''
def main():
print([i for i in merge("what",range(100,105))])
print([i for i in merge(range(5),range(100,101))])
print([i for i in merge(range(1),range(100,105))])
#main() |
class LeakyStack():
def __init__(self, max_size):
self._data = [None] * max_size # Static size
self._size = 0 # Track current number of elements
self._top = 0 # Use this variable to make the stack circular
def push(self, e): # O(1)
if self._size < len(self._data):
self._data[(self._top + self._size) % len(self._data)] = e
self._size += 1
else:
self._data[(self._top + self._size) % len(self._data)] = e
self._top += 1
def pop(self): # O(1)
location = (self._top + self._size) % len(self._data)
location -= 1
new = self._data[location]
self._data[location] = None
self._size -= 1
return new
def __len__(self): # O(1)
return self._size
def is_empty(self): # O(1)
return self._size == 0
def __str__(self): # O(n) or O(1) up to you, not graded
return str(self._data)
##############TEST CODES#################
''' Comment out the test code if you are grading on gradescope.'''
#def main():
#leakystack = LeakyStack(5) # Max size = 5 stack.
#leakystack.push('a')
#leakystack.push('b')
#leakystack.push('c')
#print(leakystack) # top of stack --> c b a
#leakystack.push('d')
#leakystack.push('e')
#print(leakystack) # top of stack --> e d c b a
#leakystack.push('f')
#print(leakystack) # top of stack --> f e d c b, a is gone because it is the oldest.
#print(leakystack.pop()) # f popped
#print(leakystack.pop()) # e popped
#print(leakystack) # top of stack --> d c b
#main() |
import copy
def knapsack_driver(capacity, weights):
'''
@capacity: positive integer. the value we are summing up to.
@weights: list of positive integers.
### Friendly tip: This function can't solve the problem,
### you need more parameters to pass information for recursive functions.
### So, define another function!! Return the result from your new function!!
@return: List of all combinations that can add up to capacity.
'''
figure = []
ending = []
location = -1
knapsack(capacity, weights, location, figure, ending)
return ending
def knapsack(capacity, weights, location, figure, ending):
if location == len(weights):
return
else:
total = 0
for i in figure:
total = total + i
if capacity == total:
ending.append(figure)
return
if location < len(weights) - 1:
location = location + 1
newFigures = copy.deepcopy(figure)
newFigures.append(weights[location])
knapsack(capacity, weights, location, figure, ending)
knapsack(capacity, weights, location, newFigures, ending)
else:
knapsack(capacity, weights, location+1, figure, ending)
return ending
def main():
casts = [1, 2, 8, 4, 9, 1, 4, 5]
# order does not matter.
# [[9, 5], [9, 1, 4], [4, 1, 4, 5], [4, 9, 1], [8, 1, 5], [2, 8, 4], [2, 8, 4], [1, 9, 4], [1, 4, 4, 5], [1, 4, 9], [1, 8, 5], [1, 8, 1, 4], [1, 8, 4, 1]]
print(knapsack_driver(14, casts))
#main()
|
# twoOperandInstruction.py
# Author: Tanner Shephard
# Description: Decodes and holds data for any double operand instruction. Value
# is given as a number and then all relevant variables are written
# via shifts and masks
class twoOperandInstruction:
def __init__(self,instructionValue):
self.value = instructionValue
self.numOperands = 2
self.type = "twoOperand"
self.dstMode = (instructionValue>>3)&0x7
self.dstReg = instructionValue&0x7
self.srcMode = (instructionValue>>9)&0x7
self.srcReg = (instructionValue>>6)&0x7
self.opCode = (instructionValue>>12)&0x7
if(self.opCode == 6 or self.opCode == 14):
self.size = "word"
else:
if(instructionValue>>15):
self.size = "byte"
else:
self.size = "word"
if(self.opCode == 1):
self.mnemonic = "MOV"
elif(self.opCode == 6):
self.mnemonic = "ADD"
elif(self.opCode == 0o16):
self.mnemonic = "SUB"
elif(self.opCode == 2):
self.mnemonic = "CMP"
elif(self.opCode == 5):
self.mnemonic = "BIS"
elif(self.opCode == 4):
self.mnemonic = "BIC"
elif(self.opCode == 3):
self.mnemonic = "BIT"
else:
self.mnemonic = "ERROR"
def printValue(self):
print("Instruction in decimal: %s" %(self.value))
def printValueOct(self):
print("Instruction in octal: %s" %(oct(self.value)))
def printMnemonic(self):
print(self.mnemonic)
def getMnemonic(self):
return self.mnemonic
def getDstMode(self):
return self.dstMode
def getReg(self):
x = []
x.append(self.srcReg)
x.append(self.srcMode)
x.append(self.dstReg)
x.append(self.dstMode)
return x
def getNumOperands(self):
return self.numOperands
def getType(self):
return self.type
def getSize(self):
return self.size
def printInstruction(self):
print("%s %d, %d" %(self.mnemonic, self.dstReg, self.srcReg))
def printInstructionData(self):
x = 'W' if (self.size == "word") else 'B'
print("Opcode: %d, Op: %s, Src Reg: %d, Mode: %d, Dst Reg: %d, Mode: %d, Type: %s " %(self.opCode, self.mnemonic, self.srcReg, self.srcMode, self.dstReg, self.dstMode, x))
def test():
instr1 = 24576 # 060000 in octal add r0, r0
instr2 = 24705 # 060201 in octal add r1, r2
instr3 = 60089 # 165271 in octal sub r1 mode 7, r2 mode 5
i1 = twoOperandInstruction(instr1)
i2 = twoOperandInstruction(instr2)
i3 = twoOperandInstruction(instr3)
i1.printInstructionData()
i2.printInstructionData()
i3.printInstructionData()
|
import os
import pandas as pd
import sqlite3
def create_dataframe(db_filename):
"""
Creates a dataframe by concatenating the tables in the database specified
by db_filename, following the specific instructions in the homework.
"""
if not os.path.exists(db_filename):
raise ValueError(f"'{db_filename}' doesn't exist.")
conn = sqlite3.connect(db_filename)
sql = """
SELECT video_id, category_id, "ca" AS language FROM CAvideos
UNION
SELECT video_id, category_id, "de" AS language FROM DEvideos
UNION
SELECT video_id, category_id, "fr" AS language FROM FRvideos
UNION
SELECT video_id, category_id, "gb" AS language FROM GBvideos
UNION
SELECT video_id, category_id, "us" AS language FROM USvideos
;
"""
return pd.read_sql_query(sql, conn)
if __name__ == '__main__':
df = create_dataframe('../HW1-aenfield/class.db')
print(df.shape)
|
"""
Contains the querying interface.
Starting with :class:`~tinydb.queries.query` you can construct complex
queries:
>>> ((where('f1') == 5) & (where('f2') != 2)) | where('s').matches('^\w+$')
(('f1' == 5) and ('f2' != 2)) or ('s' ~= ^\w+$ )
Queries are executed by using the ``__call__``:
>>> q = where('val') == 5
>>> q({'val': 5})
True
>>> q({'val': 1})
False
"""
import re
__all__ = ('query',)
class AndOrMixin(object):
"""
A mixin providing methods calls '&' and '|'.
All queries can be combined with '&' and '|'. Thus, we provide a mixin
here to prevent repeating this code all the time.
"""
def __or__(self, other):
"""
Combines this query and another with logical or.
Example:
>>> (where('f1') == 5) | (where('f2') != 2)
('f1' == 5) or ('f2' != 2)
See :class:`~tinydb.queries.query_or`.
"""
return query_or(self, other)
def __and__(self, other):
"""
Combines this query and another with logical and.
Example:
>>> (where('f1') == 5) & (where('f2') != 2)
('f1' == 5) and ('f2' != 2)
See :class:`~tinydb.queries.query_and`.
"""
return query_and(self, other)
class query(AndOrMixin):
"""
Provides methods to do tests on dict fields.
Any type of comparison will be called in this class. In addition,
it is aliased to :data:`where` to provide a more intuitive syntax.
When not using any comparison operation, this simply tests for existence
of the given key.
"""
def __init__(self, key):
self._key = key
self._repr = 'has \'{0}\''.format(key)
def matches(self, regex):
"""
Run a regex test against a dict value.
>>> where('f1').matches('^\w+$')
'f1' ~= ^\w+$
:param regex: The regular expression to pass to ``re.match``
"""
return query_regex(self._key, regex)
def test(self, func):
"""
Run an user defined test function against a dict value.
>>> def test_func(val):
... return val == 42
...
>>> where('f1').test(test_func)
'f1'.test(<function test_func at 0x029950F0>)
:param func: The function to run. Has to accept one parameter and return a boolean.
"""
return query_custom(self._key, func)
def __eq__(self, other):
"""
Test a dict value for equality.
>>> where('f1') == 42
'f1' == 42
"""
self._value_eq = other
self._update_repr('==', other)
return self
def __ne__(self, other):
"""
Test a dict value for inequality.
>>> where('f1') != 42
'f1' != 42
"""
self._value_ne = other
self._update_repr('!=', other)
return self
def __lt__(self, other):
"""
Test a dict value for being lower than another value.
>>> where('f1') < 42
'f1' < 42
"""
self._value_lt = other
self._update_repr('<', other)
return self
def __le__(self, other):
"""
Test a dict value for being lower than or equal to another value.
>>> where('f1') <= 42
'f1' <= 42
"""
self._value_le = other
self._update_repr('<=', other)
return self
def __gt__(self, other):
"""
Test a dict value for being greater than another value.
>>> where('f1') > 42
'f1' > 42
"""
self._value_gt = other
self._update_repr('>', other)
return self
def __ge__(self, other):
"""
Test a dict value for being greater than or equal to another value.
>>> where('f1') >= 42
'f1' >= 42
"""
self._value_ge = other
self._update_repr('>=', other)
return self
def __invert__(self):
"""
Negates a query.
>>> ~(where('f1') >= 42)
not ('f1' >= 42)
See :class:`~tinydb.queries.query_not`.
"""
return query_not(self)
def __call__(self, element):
"""
Run the test on the element.
:param element: The dict that we will run our tests against.
:type element: dict
"""
if self._key not in element:
return False
try:
return element[self._key] == self._value_eq
except AttributeError:
pass
try:
return element[self._key] != self._value_ne
except AttributeError:
pass
try:
return element[self._key] < self._value_lt
except AttributeError:
pass
try:
return element[self._key] <= self._value_le
except AttributeError:
pass
try:
return element[self._key] > self._value_gt
except AttributeError:
pass
try:
return element[self._key] >= self._value_ge
except AttributeError:
pass
return True # _key exists in element (see above)
def _update_repr(self, operator, value):
""" Update the current test's ``repr``. """
self._repr = '\'{0}\' {1} {2}'.format(self._key, operator, value)
def __repr__(self):
return self._repr
def __hash__(self):
return hash(repr(self))
where = query
class query_not(AndOrMixin):
"""
Negates a query.
>>> ~(where('f1') >= 42)
not ('f1' >= 42)
"""
def __init__(self, cond):
self._cond = cond
def __call__(self, element):
"""
Run the test on the element.
:param element: The dict that we will run our tests against.
:type element: dict
"""
return not self._cond(element)
def __repr__(self):
return 'not ({0})'.format(self._cond)
class query_or(AndOrMixin):
"""
See :meth:`AndOrMixin.__or__`.
"""
def __init__(self, where1, where2):
self._cond_1 = where1
self._cond_2 = where2
def __call__(self, element):
"""
See :meth:`query.__call__`.
"""
return self._cond_1(element) or self._cond_2(element)
def __repr__(self):
return '({0}) or ({1})'.format(self._cond_1, self._cond_2)
class query_and(AndOrMixin):
"""
See :meth:`AndOrMixin.__and__`.
"""
def __init__(self, where1, where2):
self._cond_1 = where1
self._cond_2 = where2
def __call__(self, element):
"""
See :meth:`query.__call__`.
"""
return self._cond_1(element) and self._cond_2(element)
def __repr__(self):
return '({0}) and ({1})'.format(self._cond_1, self._cond_2)
class query_regex(AndOrMixin):
"""
See :meth:`query.regex`.
"""
def __init__(self, key, regex):
self.regex = regex
self._key = key
def __call__(self, element):
"""
See :meth:`query.__call__`.
"""
return bool(self._key in element
and re.match(self.regex, element[self._key]))
def __repr__(self):
return '\'{0}\' ~= {1} '.format(self._key, self.regex)
class query_custom(AndOrMixin):
"""
See :meth:`query.test`.
"""
def __init__(self, key, test):
self.test = test
self._key = key
def __call__(self, element):
"""
See :meth:`query.__call__`.
"""
return self._key in element and self.test(element[self._key])
def __repr__(self):
return '\'{0}\'.test({1})'.format(self._key, self.test)
|
"""
Splits large CSVs into multiple shards.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import argparse
import gzip
import pandas as pd
def parse_args(input_args=None):
parser = argparse.ArgumentParser()
parser.add_argument(
"--csv-file", required=1,
help="Name of input CSV file.")
parser.add_argument(
"--shard-size", required=1, type=int,
help="Number of shards to split file into.")
parser.add_argument(
"--out", required=1,
help="Root name of output CSV shards.")
parser.add_argument(
"--gzip-output", action="store_true",
help="Gzip the output.")
return parser.parse_args(input_args)
def shard_csv(input_file, shard_size, out_name, gzip_output):
"""Shard the csv file into multiple shards."""
compression = "gzip" if gzip_output else None
file_obj = None
try:
if input_file.endswith(".gz"):
file_obj = gzip.open(input_file)
else:
file_obj = open(input_file)
for shard_num, df_shard in enumerate(
pd.read_csv(input_file, index_col=0, chunksize=shard_size)):
suffix = "czv.gz" if gzip_output else "csv"
output_name = "%s_%d.%s" % (out_name, shard_num, suffix)
print("Writing output to %s" % output_name)
df_shard.to_csv(output_name, compression=compression)
finally:
if file_obj is not None:
file_obj.close()
def main():
args = parse_args()
input_file = args.csv_file
shard_size = args.shard_size
out_name = args.out
gzip_output = args.gzip_output
shard_csv(input_file, shard_size, out_name, gzip_output)
if __name__ == '__main__':
main()
|
from numpy import *
# input format : dot(transpose(w), x)
# w = (w0, w1, w2, ...)
# x = (1, x1, x2, ...)
def sigmoid(x):
return 1/(1+exp(-x))
def sigmoid_differential(x):
return x*(1-x)
# gradient descent
# activation function: f(x)
# cost function for pattern mode: J(w) = (y_i - f(dot(transpose(w), X_i)))^2
# partial differential respect to w: J'(w) = -2*error*output*(1-output)*x_i
# w(t): weights on t-th iteration
# w(t+1) = w(t) - learning rate*J'(w)
def calculate_gradient(y, x_vector, weight_vector, learning_rate):
sigmoid_output = sigmoid(dot(weight_vector.T, x_vector))
increment = -2*(y-sigmoid_output)*sigmoid_differential(sigmoid_output)
weight_vector -= learning_rate*increment
return weight_vector
def train_neural_network(data_matrix, labels, iterator_number):
training_data_size = shape(data_matrix)[0]
weight_vector_length = shape(data_matrix)[1]
weight_vector = 2 * random.random(weight_vector_length) - 1
for i in range(iterator_number):
for j in range(training_data_size):
data = array(data_matrix[j]).flatten()
weight_vector = calculate_gradient(data, labels[j], weight_vector, 0.5)
print "weight_vector: ", weight_vector
return weight_vector
def get_training_set():
data_matrix = mat([[1, 0, 0, 1],
[1, 1, 1, 1],
[1, 1, 0, 1],
[1, 0, 1, 1]])
labels = array([0, 1, 1, 0]).T
return data_matrix, labels
#input data format: array
def neural_network_classifier(input_data):
data_matrix, labels = get_training_set()
weight_vector = train_neural_network(data_matrix, labels, 40)
result = sigmoid(dot(weight_vector.T, input_data))
print "result : %.5f" % result
|
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: What is the output of the following snippet?
lst = [1, 2, 3, 4, 5]
# Insert in:
# Position: 1
# Value: 6
lst.insert(1, 6)
print("Insert ",lst)
# Delete 1st element
del lst[0]
print("Delete ",lst)
# Add (in final) value 1 at list
lst.append(1)
print("Append ", lst) # 6,2,3,4,5,1 |
# @Title: Creación de carreras de tortugas con PyGame
# @Description: En este programa se creará una competición de carreras de tortugas con la ayuda de la libreria
# pygame. Para ello, es necesario instalar el paquete, por defecto no lo está, para ello:
# > Tools
# >> Manage packages..
# >>> En la barra de 'Find package in PiPy' escribimos 'pygame' y damos a que lo busque
# >>>> Install
""" Esquema:
- class CreaciónDeClases:
- def __crearLasFuncionesNecesarias__:
- def __comprobarEventos:
- renderizar la pantalla:
"""
# @Author: Chunche
#
import pygame
import sys
import random
class Runner():
__customes = ("1","2","3","4","5",)
def __init__(self, x=0, y=0):
ixCustome = random.randint(0,4)
self.custome = pygame.image.load("img/{}.png".format(self.__customes[ixCustome]))
self.position = [x,y]
self.name = ""
def avanzar(self):
self.position[0] += random.randint(1,6)
class Game():
runners = []
__posY = (160,200,240,280)
__names = ("Nemo","Ninja", "Speedy Fast", "Octopus")
__startLine = -5
__finishLine = 620
def __init__(self):
# Creacion de atributos
self.__screen = pygame.display.set_mode((640,480))
self.__background = pygame.image.load("img/bg1.png")
pygame.display.set_caption("C@rrer@$ de Bich0$")
for i in range(4):
theRunner = Runner(self.__startLine,self.__posY[i])
theRunner.name = self.__names[i]
#self.runners = pygame.image.load("img/6.png")
self.runners.append(theRunner)
#runners.append(firstRunner)
#runners.append(Runner(self.__startLine, 240))
def close(self):
pygame.quit()
sys.exit()
def competir(self):
# x = 0
gameOver = False
while not gameOver:
# Comprobación de los eventos.
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = True
# Avance del corredor - Creamos el metodo para ello llamamos a avanzar()
for activeRunner in self.runners:
activeRunner.avanzar()
if activeRunner.position[0] >= self.__finishLine:
print ("{} win!".format(activeRunner.name))
gameOver = True
# Refresacar / renderizar la pantalla.
self.__screen.blit(self.__background, (0,0))
# Creacion de los 'n' corredores
for runner in self.runners:
self.__screen.blit(runner.custome, runner.position)
# Inicializacion de la pantalla
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.quit:
self.close()
pygame.quit()
sys.exit()
if __name__ == '__main__':
# Inicializamos el paquete
game = Game()
pygame.init() # Alternativa para versiones antiguas es: 'pygame.font.init()'
game.competir()
|
# anagrama('amor', 'roma')
def anagrama(p1, p2):
comparacionLetras = []
if len(p1) != len(p2): # recorer para comparar longitud de palabras
return False
for caracter1 in p1:
haPasado = False
for caracter2 in p2:
if caracter1 == caracter2 :
haPasado = True
comparacionLetras.append(True)
if not haPasado:
comparacionLetras.append(False)
if False in comparacionLetras:
return False
else:
return True
# comprobar en 2 direcciones :
def comprobarAnagrama(p1, p2):
return anagrama(p1, p2) and anagrama(p2, p1)
|
# @Title: Crear Termómetro Gráfico
# @Description: Creacion de un termometro con interfaz grafica de usuario,
#
# Nota: En los proyectos tkinter principalmente suelen poner la palabra 'root' como objeto principal de inicio de los programas,
# sin embargo, puedo llamarlo como quiera.
#
# @Version: 1.1
# @Author: Chunche
#
from tkinter import *
from tkinter import ttk
#
# El constructor no necesita el metodo 'self' realmente, pero es recomendable, como una <<Buena práctica de programacion>>, python no necesita este paso
# pero otros lenguajes de programación si lo necesitan para trabajar.
# Además, en esta librería por defecto crea un método al que llama 'root' con lo cual, la clase que creamos llama a éste por defecto.
#
class mainApp(Tk): # Hereda de Tk()
# Tamaño de la ventana a crear
#size = "640x480" # Tamaño por defecto de la pantalla
size = "1024x768"
def __init__(self):
# Hereda de la libreria tk y crea una pantalla 'creada para mi'
Tk.__init__(self)
# Instancias de tk modificadas
# Tamaño de la pantalla
self.geometry(self.size) # Llamo al método size declarado al inicio de la clase.
self.title("Mi primera ventana")
self.configure(bg = "lightblue")
def start(self):
self.mainloop() # Ciclo principal
if __name__ == '__main__':
app = mainApp()
# Creacion d ela ventana
app.start()
|
notas = (2,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10)
def contenido(lista,indice):
try:
resultado = lista[indice]
except:
resultado = None
return resultado
def longitud(lista):
indice = 0
while contenido (lista,indice) != None:
indice = indice +1
return indice
# Calculo de la media
suma = 0
longitudNotas = longitud(notas)
for indice in range(0, longitud(notas)): # Python usa un rango de la longitud total de la lista -1, que es lo que buscamos
suma = suma + notas[indice]
media = suma / longitud(notas)
# Imprimo resultado
print("Numero de elementos:", longitudNotas)
print("Nota total.........:", suma)
print("Nota Media.........:", media) |
aclNum = int(input("What is the IPv4 ACL number? "))
if aclNum >= 1 and aclNum <= 99:
print("This is a standard IPv4 ACL.")
elif aclNum >= 100 and aclNum <= 199:
print("This is an extended IPv4 ACL.")
else:
print("This is not a standard or extended IPv4 ACL.")
|
import ANSIEscapeSequences
entradas = {
'baby':{'cantidad':0,'precio':0},
'niño':{'cantidad':0,'precio':14},
'adulto':{'cantidad':0,'precio':23},
'jubilado':{'cantidad':0,'precio':18}
}
lineaPantalla = {'baby':4, 'niño':5,'jubilado':6,'adulto':7}
def tipoEntrada(miedad):
# Segun edad, el precio de la entrada
#
# Valores segun edad:
#
# de 0 años a 2 años = 0€
# de 3 años a 12 años = 14€
# de 13 años a 64 años = 23€
# de 65 años o más = 18€
#
if miedad > 0 and miedad <= 2:
tipo = 'baby'
elif miedad <= 12:
tipo = 'niño'
elif miedad < 65:
tipo = 'adulto'
else:
tipo = 'jubilado'
return tipo
def validaEdad(cadena):
# Comprueba que se pueda convertir en un numero entero y sea positivo
try:
n = int(cadena)
if n >= 0:
return True
return False
except:
return False
def pedirEdad():
ANSIEscapeSequences.clear()
ANSIEscapeSequences.locate(1,1)
edad = input("Ingrese la edad de la persona o marque 0 para salir: ")
while validaEdad(edad) == False:
ANSIEscapeSequences.locate(1,1)
print("Error Edad introducida inválida...Vuelva a intentarlo ")
edad = input("Ingrese la edad de la persona o marque 0 para salir: ")
edad = int(edad)
return edad
ANSIEscapeSequences.clear()
edad = pedirEdad()
precioTotal = 0
#linea = 4
while edad != 0:
#ANSIEscapeSequences.locate(linea,1)
tipo = tipoEntrada(edad)
entradas[tipo]['cantidad'] += 1
precio = entradas[tipo]['precio']
cantidad = entradas[tipo]['cantidad']
#linea += 1
precioTotal += precio
linea = lineaPantalla(tipo)
ANSIEscapeSequences.locate(linea,1)
print("Precio Entrada: {}€ x {}persona = {}€".format(precio,cantidad,precio*cantidad))
edad = pedirEdad()
linea += 4
ANSIEscapeSequences.locate(linea,10)
print ("============================")
print("Total: {}".format(precioTotal))
|
country = [
"Brazil",
"Russia",
"India",
"China",
"South Africa"
]
capitals = {
"Brazil": "Brasilia",
"Russia": "Moscow",
"India": "New Delhi",
"China": "Beijing",
"South Africa": [
"Pretoria",
"Cape Town",
"Bloemfontein"
]
}
print( country )
print( capitals )
print( capitals["South Africa"][1] )
"""
OUTPUT:
=========== RESTART: /home/allan/Dropbox/ETW-BP/list-dicts_sol.py ===========
['Brazil', 'Russia', 'India', 'China', 'South Africa']
{'South Africa': ['Pretoria', 'Cape Town', 'Bloemfontein'], 'India': 'New Delhi', 'Brazil': 'Brasilia', 'Russia': 'Moscow', 'China': 'Beijing'}
Cape Town
>>>
"""
|
# bloque de entrada
numero1 = float(input( "Número uno :")) / 10
numero2 = float(input( "Número dos :")) / 10
# bloque de procesos
suma = numero1 + numero2
resta = numero1 - numero2
producto = numero1 * numero2
division = numero1 / numero2
# bloque de salida de datos
print(" La suma de los valores es :" ,suma )
print( " La resta de los valores es :",round(resta, 2) )
print( " El producto de los valores es :",producto )
print( " La división de los valores es :",round( division, 2) )
|
#!/bin/python
import os
os.system("clear")
os.system("cls")
while True:
print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
income = float(input("Enter the annual income: "))
print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv \n")
base = 85528
#
# Calculating tax.
#
if income == -0:
print("Finished program")
break
elif income < base or income == base:
print("Calculamos el 18% de los ingresos")
tax = income*.18
print("El 18% de sus {:.02f} (ingresos) es {:.02f} (Pre-Tazas) ".format(income,tax))
print("Restamos los 556.02 de DF")
tax -= 556.02
tax = round(tax, 0)
if tax < 0:
tax = 0.0
print("The tax is: {:.02%} thalers".format(tax))
print("----------------------------------------------------------")
print("The tax is: ", tax, "thalers")
print("----------------------------------------------------------")
elif income > base:
# Excedente
surplus=(income-base)
print("Aplicamos el 32% sobre el excedente: ", surplus)
surplus *=.32
print("El 32% del extra es: ", surplus)
tax = surplus
print("Pre-Tazas: ", tax)
# print("La pre-taza {:.02f} con los DF de sus impuestos es: 14839.02".format(tax) )
tax += 14839.02
print("----------------------------------------------------------")
tax = round(tax, 0)
print("The tax is: ", tax, "thalers")
print("----------------------------------------------------------")
else:
print("Error in the income input")
|
# Creo una funcion que guarda las operaciones de comprobracion del anagrama
def isAnagram(p1,p2):
# Inicializo una lista que guarda las comparaciones de las letras
listaComparacionLetras = []
# Comparo la longitud de las palabras para que sean iguales, en numero de letras
if len(p1) != len(p2):
return False
# Inici un bucle anidado con la comparacion de las letras
for caracter1 in p1:
noAnadirFalse = False
for caracter2 in p2:
# Si no hay una igualdad entre las letras salta fuera
if caracter1 == caracter2:
noAnadirFalse = True
listaComparacionLetras.append(True)
if not noAnadirFalse:
listaComparacionLetras.append(False)
if False in listaComparacionLetras:
return False
else:
return True
|
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Ejercicio 5 de la seccion 3.1.3.10
myList = [1, 2, "in", True, "ABC"]
??? = input("¿Qué pongo? ")
print(1 ??? myList) # outputs True
print(" outputs True")
??? = input("¿Qué pongo? ")
print("A" ??? myList) # outputs True
print(" outputs True")
??? = input("¿Qué pongo? ")
print(3 ??? myList) # outputs True
print(" outputs True")
??? = input("¿Qué pongo? ")
print(False ??? myList) # outputs False
print(" outputs False")
??? = input("¿Qué pongo? ")tema |
precios = float(input("Introduzca precio : "))
unidades = float(input("Introduzca unidades de producto : "))
precioTotal = 0
totalUnidades = 0
_PRECIOS = 0
_UNIDADES = 1
def informaItem( precios, Unidades ):
item = dict()
item['precios'] = precios
item['unidades'] = unidades
return item
listaLineasFacturas = []
while precios > 0 or unidades > 0 :
costeTotal = precios * unidades
item = informaItem( precios, unidades )
listaLineasFacturas.append(item)
totalUnidades += unidades # totalUniades = TotalUnidades + unidades ( es lo mismo )
precioTotal += costeTotal
precios = float(input("Introduzca precio : "))
unidades = float(input("Introduzca unidades de producto : "))
# cadenaImpresion += str(precios) + " € -" + str(unidades) + " unidades - " + str(costeTotal) + " €\n "
# es = : cadenaImpresion += "{} € - {} unidades - {} €\n".format(precios,unidades,costeTotal)
for item in listaLineasFacturas:
print(item['precios'], " € -", item['unidades'], " unidades - Total : ",item['precios'] * item['unidades'], " € ")
print(" ")
print("Total factura : ",precioTotal)
print("Total de objetos : ",totalUnidades)
print(" \nTotal factura :\t{:.2f}\nTotal de objetos : \t{}".format(precioTotal, totalUnidades))
# .format formatea la salida , primera llamada al primer hueco {} y 2ª al segundo hueco {}
# \t{} la t es tabulador // {:.2f} : es el formato .2f es float y los decimales que se quieren |
import programaPantalla
def tipoEntrada(e):
if e > 0 and e <= 2:
tipo = 'bebe'
elif e <= 12:
tipo = 'niño'
elif e < 65:
tipo = 'adulto'
else:
tipo = 'jubilado'
return tipo
def validaEdad(cadena): # validar solo positivos
try:
n = int(cadena)
if n >= 0:
return True
return False
except:
return False
def pedirEdad():
edad = programaPantalla.Input("¿Que edad tienes? ", 1, 1) #esta linea sustituye a las 3 siguientes
# programaPantalla.locate(1,1)
# programaPantalla.clearLine()
# edad = input("¿Que edad tienes? ")
while validaEdad(edad) == False:
programaPantalla.Format(0,33,45)
programaPantalla.Print("Introduzca edad en número ",24, 1,True) #olocar el aviso de error abajo sin cambiar de linea
# programaPantalla.locate(24,1) # colocar el aviso de error abajo
# print("Introduzca edad en número ",end="")
programaPantalla.Reset()
edad = programaPantalla.Input("¿Que edad tienes? ", 1, 1)
programaPantalla.clearLine(24)
return int(edad)
def printScreen():
programaPantalla.clear()
programaPantalla.Print("Bebé.......: -", 4, 5) #sustituye las 2 inferiores
# programaPantalla.locate(4, 5)
# print("Bebé.......: -")
programaPantalla.Print("Infantil...: -", 5, 5)
programaPantalla.Print("Adulto.....: -", 6, 5)
programaPantalla.Print("Jubilado...: -", 7, 5)
programaPantalla.Format(1,37, 40)
programaPantalla.Print("Total...:",9, 8)
programaPantalla.Reset()
|
myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList) |
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import animation
lifes=[]
def play_life(a):
xmax, ymax = a.shape
b = a.copy()
for x in range(xmax):
for y in range(ymax):
n = np.sum(a[max(x - 1, 0):min(x + 2, xmax), max(y - 1, 0):min(y + 2, ymax)]) - a[x, y] # Definimos vecindad
if a[x, y]:
if n < 2 or n > 3:
b[x, y] = 0 # regla 1 and 3
elif n == 3:
b[x, y] = 1 # regla 4
# Sigue viva cuando hay 2 o tres células en su vecindad
return(b)
def play(size, times):
life = np.zeros((size, size), dtype=np.byte)
lifem = []
for x in range(size):
for y in range(size):
life[x,y]=np.random.binomial(1, 0.2)
for i in range(times):
life = play_life(life)
lifem.append(life.copy())
return lifem
def animate(i):
m = lifes[i]
out = plt.imshow(m, interpolation='nearest', cmap=plt.cm.gray)
return out
|
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Hipótenisis de Collatz
# Dice que un nº natural positivo distinto de cero, sí es:
# 1 - Un nº par
# + lo divido entre 2
# 2 - Un nº impar
# + lo multiplico x 3
# + y le sumo +1
# 3 - Y vuelvo a hacer lo mismo (Pasos 1 ó 2)
# El misterio está en que todos los nºs llegan a 1.
c0 = int(input("Write a number possitive: "))
loop = 0
for i in range (c0+1):
#print("........................................................................................................ ", i)
if c0 <= 0:
print(".............................................. Error")
print("Error in your input, data is not valied")
else:
#print("..............................................")
#print(" ", i)
#print("..............................................")
while c0 >= i:
if c0 % 2 == 0:
print("...............................................", loop, "Nº - Par")
c0 = c0/2
i += 1
loop +=1
print(" ===> " , int(c0))
else:
print("...............................................", loop, "Nº - Impar")
c0 = (3 * c0 + 1)
i += 1
loop +=1
print(" ===> " , int(c0))
print("Loops: ", i+1)
print("Steps: ", loop+1)
|
# Creamos una función para la validación de los datos de entrada
def esDecimal(numero):
try:
float(numero)
return True
except:
return False
# Entrada de parámetros:
B = input ("Base del triangulo: ")
if esDecimal(B):
# Guardamos y convertimos los valores de entrada.
b = float(B)
H = input ("Altura del triangulo: ")
if esDecimal(H):
# Guardamos y convertimos los valores de entrada.
h = float(H)
# Realizamos la operacion de cálculo.
area = ((b * h) / 2)
# Saco por pantalla el resultado.
print("Superficie del triángulo es: ", area)
else:
print(H,"<-- Debe ser un número. ")
quit()
else:
print(B,"<-- Debe ser un número. ")
quit()
# (algoritmo del triangulo)
# |
# (base)
# |
# (base = numero)
# |
# |----------------------|
# | |
# V V
# (error base) (altura)
# | |
# | (altura = numero)
# | |
# | |-------------------------|
# | (error altura) (A<-- base * altura / 2)
# | |
# | V
# | (A)
# | |
# L-------fin dle algoritmo)--------|
# |
# Funcion que nos indica el tiempo de ejecucion de cada una de las funciones del programa
import timeit
# Creo una funcion que guarda las operaciones de comprobracion del anagrama
def isAnagramE(p1,p2):
# Inicializo una lista que guarda las comparaciones de las letras
listaComparacionLetras = []
# Comparo la longitud de las palabras para que sean iguales, en numero de letras
if len(p1) != len(p2):
return False
# Inici un bucle anidado con la comparacion de las letras
for caracter1 in p1:
noAnadirFalse = False
for caracter2 in p2:
# Si no hay una igualdad entre las letras salta fuera
if caracter1 == caracter2:
noAnadirFalse = True
listaComparacionLetras.append(True)
if not noAnadirFalse:
listaComparacionLetras.append(False)
if False in listaComparacionLetras:
return False
else:
return True
# Comparo que haya coincidencia entre p1,p2 = p2,p1
def isAnagram(p1,p2):
return isAnagramE(p1,p2) and isAnagramE(p2,p1)
|
cadenaUnidades = input("Cantidad: ")
unidades = float(cadenaUnidades)
cadenaPrecio = input("Precio Unitario (€): ")
precio = float(cadenaPrecio)
totalItems = 0
precioTotal = 0
cadenaAImprimir= ""
while unidades > 0 and precio > 0:
totalUnitario = unidades * precio
#cadenaAImprimir += str(precio) + " € - " + str(unidades) + " Unidades - " + str(totalUnitario) + " € \n"
# cadenaAImprimir += "{}€ - {} unidades - {}€ \n".format(precio,unidades)
print(precio, " € - ", unidades, " Unidades - ", totalUnitario, "€")
totalItems += unidades
precioTotal += totalUnitario
cadenaUnidades = input(" Cantidad: ")
unidades = float(cadenaUnidades)
cadenaPrecio = input("Precio unitario (€) : ")
precio = float(cadenaPrecio)
#print(cadenaAImprimir)
print("------------------------------")
print("Total: ", precioTotal , " €")
print("Unidades: ",totalItems , " Items") |
#!/bin/python
import os
from datetime import date
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Continue function.
print(40*'·')
print(date.today())
print(40*'·')
largestNumber = -99999999
counter = 0
number = int(input("Enter a number or type -1 to end program: "))
while number != -1:
if number == -1:
continue
counter += 1
if number > largestNumber:
largestNumber = number
number = int(input("Enter a number or type -1 to end program: "))
if counter:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")
|
# Write a program to read through the mbox-short.txt
filehandle = open('mbox-short.txt')
distribution = dict()
# figure out the distribution by hour of the day for each of the messages.
for line in filehandle :
if line.startswith("From") and not line.startswith("From:") :
# You can pull the hour out from the 'From ' line by finding the time
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
time = line.split()[5]
# split the string a second time using a colon
hour = time.split(":")[0]
distribution[hour] = distribution.get(hour,0) + 1
# sort the dictionary by hour ascending
# create a list (which are sortable) to put the key value tuples into
listOfTuples = list()
for key, value in list(distribution.items()) :
listOfTuples.append((key, value))
listOfTuples.sort()
for key, value in listOfTuples :
print(key, value) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
""""
Initial Thoughts:
- palindrome reads the same forward and backwards
- need two pointers
- have to check first and last node and see if it's the same, and then keep moving inwards
Edge Cases:
- empty input
Possible Solutions:
- find out the half point of the linked list, reverse the second half
"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if(head):
#steady = head
curr = head
length = 0
even = 0
#finding the length of the linked list
while curr:
curr = curr.next
length = length + 1
if(length%2 ==0):
even = 1
halfpt = length//2
#setting curr back to the beggining
curr = head
#moving curr to halfway point of the list
while halfpt>0:
curr = curr.next
halfpt = halfpt -1
prev = curr
steady = curr.next
curr = curr.next
prev.next = None
dummy = head
#reverse the second half of the list
while steady:
steady = steady.next
curr.next = prev
prev = curr
curr = steady
if even==1:
while(prev):
if prev.val == dummy.val:
prev = prev.next
dummy = dummy.next
else:
return False
return True
else:
while(prev.next):
if prev.val == dummy.val:
prev = prev.next
dummy = dummy.next
else:
return False
return True
else:
return True
|
class node:
def __init__(self,value = None):
self.value = value
self.next = None
class linked_list:
def __init__(self):
self.head = node()
#this append will append this node to the end
def append(self,value):
new_node = node(value)
cur = self.head
while cur.next!=None:
cur = cur.next
cur.next = new_node
def display(self):
llist = []
elems = []
rnn = self.head
while rnn.next !=None:
rnn = rnn.next
# llist = llist + rnn.value
elems.append(rnn.value)
#print (llist)
print (elems)
def delete(self,index):
cur_index = 0
del_node = self.head
while del_node.next !=None:
last_node = del_node
del_node = del_node.next
if cur_index ==index:
last_node.next = del_node.next
return
cur_index = cur_index +1
new_n = linked_list();
new_n.display()
new_n.append(1)
new_n.append(2)
new_n.append(3)
new_n.append(8)
new_n.display()
new_n.delete(2)
new_n.display()
new_n.delete(2)
new_n.display()
|
# -*- coding: utf-8 -*-
#if文の条件には:
#else:
#pythonはindentを統一する必要がある
import numpy as np
def AND(x1, x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1*w1+ x2*w2
#tmp = np.sum(w*x)
if tmp <= theta:
return 0
elif tmp > theta:
return 1
print(AND(0,0))
def NAND(x1, x2):
x = np.array([x1,x2])
w = np.array([-0.5, -0.5])
b = 0.7
tmp = np.sum(x*w)+b
if tmp <= 0:
return 0
else:
return 1
def OR(x1, x2):
x = np.array([x1,x2])
w = np.array([1,1])
b = -0.1
tmp = np.sum(x*w)+b
if tmp <= 0:
return 0
else:
return 1
def XOR(x1 ,x2):
s1 = NAND(x1,x2)
s2 = OR(x1,x2)
y = AND(s1,s2)
return y
print(XOR(0,0))
print(XOR(1,1))
|
class Nodo():
def __init__(self, valor, izq=None, der=None):
self.valor=valor
self.izq=izq
self.der=der
class Variable():
def __init__ (self, nombre, valor):
self.Nombre=nombre
self.Valor=valor
def evaluar(arbol):
if arbol.valor == "+":
return (arbol.izq) + (arbol.der)
elif arbol.valor == "-":
return (arbol.izq) - (arbol.der)
elif arbol.valor == "*":
return (arbol.izq) * (arbol.der)
elif arbol.valor == "/":
return (arbol.izq) / (arbol.der)
return int(arbol.valor)
from Pila import *
def inicio():
pila=Pila()
pila2=Pila()
pila3=Pila()
print("ingrese vacio para Terminar")
while True:
m=raw_input("ingreso en post-orden:").split(" ")
k=len(m)
if m == '':
break
print("final")
if k == 0:
break
print("final")
for j in range(0, k):
y=m[j]
if(y=="="):
while len(pila2.items) != 0:
variable=pila2.desapilar()
pila3.apilar(variable)
print(variable.Nombre,"=",variable.Valor)
elif y in ["+", "-", "*", "/"]:
if(len(pila.items)>=2):
der=pila.desapilar()
izq=pila.desapilar()
nodo=Nodo(y, izq, der)
x=evaluar(nodo)
pila.apilar(x)
else:
print("estructura incorrecta")
else:
try:
y=int(y)
pila.apilar(y)
except:
if(m[j+1]=="="):
variable=Variable(y,pila.desapilar())
pila2.apilar(variable)
print("variable correcta")
else:
while len(pila2.items) != 0:
variable=pila2.desapilar()
pila3.apilar(variable)
if(y==variable.Nombre):
pila.apilar(variable.Valor)
while len(pila3.items)!= 0:
variable=pila3.desapilar()
pila2.apilar(variable)
print(pila.desapilar())
inicio()
|
#!/usr/local/bin/python3.8
import random
num=int(input("Please enter the number: "))
List=[]
def addfun(num):
count=0
while count < 5:
List.append(num)
num=num+1
count=count+1
print (List)
x=len(List)
con=str(List)
ran=random.randint(0,x-1)
print ("random num is: ",ran)
real=List[ran]
print (real)
List[ran]="_"
print (str(List))
turn=0
while turn <=2:
guenum=input("please guess the number: ")
if str(guenum) == str(real):
x=0
break
else:
turn=turn+1
x=1
if x == 0:
print ("You won")
elif x == 1:
print ("You loss")
addfun(num)
|
import sqlite3
conn = sqlite3.connect('test.sqlite') # 建立資料庫連線
cursor = conn.cursor() # 建立 cursor 物件
# 建立一個資料表
sqlstr='CREATE TABLE IF NOT EXISTS table01 \
("num" INTEGER PRIMARY KEY NOT NULL ,"tel" TEXT)'
cursor.execute(sqlstr)
# 新增一筆記錄
sqlstr='insert into table01 values(1,"02-1234567")'
cursor.execute(sqlstr)
conn.commit() # 主動更新
conn.close() # 關閉資料庫連 |
# # function input
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
# #function output
# [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")]
def dictInTupleOut(xyz):
dict_list = xyz.items()
return dict_list
# print (dictInTupleOut(my_dict))
def zipDict(list1, list2):
newDict = dict(zip(list1, list2))
return newDict
keys = ['a', 'b', 'c']
values = [1, 2, 3]
print (zipDict(keys, values)) |
myself = {"name": "Victor A.", "age":"27", "country of birth": "The United States",
"favorite language": "Python"}
def printMyself(dict):
for key, val in dict.items():
print ("My {} is {}".format(key, val))
printMyself(myself) |
import states
class Game:
def __init__(self, num_players: int, locations: list):
"""
Initialize the game.
Arguments:
- num_players: Number of players in this game.
- locations: An array of counts of controls in the locations.
"""
self.num_players = num_players
self.locations = locations
self.this_location_max = self.locations.pop()
self.this_location_remain = self.this_location_max
self.active_hero = None
def reveal_dark_arts(self):
"""
Reveals a dark arts card.
"""
# TODO
pass
def location_info(self):
"""
Returns the current location infomation.
Returns:
(remain, max) of this location.
"""
return self.this_location_remain, self.this_location_max
def update_state(self, state, args):
# TODO: Implement state update
# This will be a big function
"""
Responds to the given state. Notice that the state passed in may
trigger other states.
Arguments:
- state: the state to respond. It should be a function in states.py
"""
state(self, *args)
|
#By: Luis Febro
#Goal: Hangman game with a robot character. You have to find the right answer for each question before your robot end up being hung tragically.
#Date: 05/20/19
#Issues: if you guys know how to fix this box that appears at the beginning before it supossed to pop up, just let me know in the comments. If you are resolute of some other enhancements, I will be your ears. (=
from random import choice
print('')
print('=-' * 20)
print('{:-^30}'.format('HANGMAN GAME BY LUIS FEBRO'))
print('=-' * 20)
def body_hang(c):
body1 = body2 = body3 = body4 = body5 = body6 = ' '
if c == 0:
print('')
elif c == 1:
body1 = '(00)'
elif c == 2:
body1 = '(00)'
body2 = ' ||'
elif c == 3:
body1 = '(00)'
body2 = '||'
body3 = 'o--'
elif c == 4:
body1 = '(00)'
body2 = '||'
body3 = 'o--'
body4 = '--o'
elif c == 5:
body1 = '(00)'
body2 = '||'
body3 = 'o--'
body4 = '--o'
body5 = 'o/'
elif c == 6:
body1 = '(00)'
body2 = '||'
body3 = 'o--'
body4 = '--o'
body5 = 'o/'
body6 = ' \\o'
print('\n___________')
print('| |')
print(f'| {body1}')
print(f'| {body3}{body2}{body4}')
print(f'| {body5}{body6} ')
print('|')
print('|')
print('')
################################################################
# DATA BASE - QUESTIONS AND HIDDEN ANSWERS (DO NOT CHEAT HERE (; )
################################################################
# 5 questions (1st Hint keys followed by their respective Answers)
database = ['A brazilian City', 'Rio de Janeiro',
'A color', 'Yellow',
'A movie', 'Batman',
'A book', 'Harry Potter',
'An occupation', 'Programmer']
#choosing data
tips = choice(list(database[n] for n in range(0, len(database), 2))) #here we create only the tips data
answers = database[database.index(tips) + 1].upper()
hidden_ans = list(answers)
discovered_letters = []
print(f'\nKEY HINT: {tips}')
for l in range(0, len(hidden_ans)):
discovered_letters.append(' -- ')
cont = contover = amount = 0
print(f'The word has {len(hidden_ans)} letters. Lets get started!')
body_hang(contover)
print(' -- ' * len(hidden_ans), end = '')
while True:
user_letter = str(input('\nType a letter: ')).strip().upper()
if user_letter == '':
print("It seems like you didn't inserted a letter, pal")
continue
if user_letter[0] in '123456789':
print('Common!!! Numbers are not allowed...just letters')
continue
if len(user_letter) > 1:
print(f'Do you mean {user_letter[0]}, is it not? \nLets consider the first letter! (=')
user_letter = user_letter[0]
#user got one letter
if user_letter in discovered_letters:
print('You already put this letter. Try again!')
continue
if user_letter in hidden_ans:
body_hang(contover)
for l in range(0, len(hidden_ans)):
#inserting the letter into empty list and replacing ' -- '
if hidden_ans[l] == user_letter:
discovered_letters[l] = user_letter
cont += 1
#printing the traces
print(discovered_letters[l], end = ' ')
# user not got any letter
if cont == 0:
contover += 1
body_hang(contover)
print(' -- ' * len(hidden_ans), end = '')
# gameover condition
if contover == 6:
body_hang(contover)
print('\nGAME OVER!')
break
print('\nNope! ain\'t got this letter...Try again!')
# renewed for a new counting
# cont = 0
# results
print('\nYou guessed {} letters so far! '.format(cont))
print(f'LEFT: {6 - contover} TRIES...')
#Option to reveal word already with 4 traces left:
if discovered_letters.count(' -- ') <= 4:
final_word = ''.join(hidden_ans)
final_word_user = ' '
while final_word_user not in 'YN':
final_word_user = str(input('Do you already know the hidden word [Y/N]? ')).strip().upper()
if final_word_user == 'Y':
final_word_user = str(input('You can write over here: ')).strip().upper()
if final_word == final_word_user:
print('CONGRATS! YOU GOT IT!')
break
print('It seems not the right one...try again...')
if ' -- ' not in discovered_letters:
print('CONGRATS! YOU GOT IT!')
break
print('GAME IS OVER')
# NOTES:
# l means letters. this is requires in both for iteration
|
try:
no1 = int(input("1st Integer No :"))
no2 = int(input("2nd Integer No :"))
print("Sum = ", no1 + no2)
print("Div = ", no1 / no2)
except ValueError:
print("Only Integer's are allowed")
except ZeroDivisionError:
print("Cannot Divide By Zero")
else:
print("Sub = ", no1 - no2)
print("Mul = ", no1 * no2)
finally:
print("I am Final Statement")
print("Thanks") |
# Example on Global and local variables
a = 1000 # Global variable
def show():
print("I am show")
print(a)
b = 20 # Local Variale
print(b)
print("Sum = ",a+b)
print("Hi")
print(a)
show()
print(a)
print("Bye")
|
import random as ra
from pathlib import*
from turtle import*
def actscore(score,pseudo):
out=False
listevar=["a","b","c","d","e","f","g","h","i",'j']
liste=[1,2,3,4,5,6,7,8,9,10]
#print(score)
with open ("score.txt","r") as sco:
for i in range(10):
liste[i]=int(sco.readline()[:1])
with open ("score.txt","r") as sco:
for i in range(10):
listevar[i]=sco.readline()
with open ("score.txt","r") as sco:
for z in range(10):
if score>=liste[z] and out==False:
listevar.insert(z,str(score)+pseudo)
out=True
for i in range(len(listevar)):
if listevar[i][-1]=="\n":
listevar[i]=listevar[i][:-1]
with open ("score.txt","w") as sco:
for y in range(10):
sco.write(str(listevar[y])+"\n")
with open ("score.txt","r") as sco:
for i in range(len("score.txt")):
print(sco.readline(),end="")
return
|
def evaluate(root, facts):
assert root is not None
if root.value == '!':
return not evaluate(root.left, facts)
if root.value in ['|', '&']:
if root.value == '|':
return evaluate(root.left, facts) or evaluate(root.right, facts)
elif root.value == '&':
return evaluate(root.left, facts) and evaluate(root.right, facts)
return facts[root.value]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.