text stringlengths 37 1.41M |
|---|
#-*-coding:utf-8-*-
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def removeNthFromEnd(self,head,n):
res=ListNode(0)
res.next=head
tmp=res
for i in range(0,n):
head= head.next
while head!=None:
head=head.next
tmp=tmp.next
tmp.next=tmp.next.next
return res.next
|
#tictoctoe game implemantation
board=["-","-","-",
"-","-","-",
"-","-","-"]
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
game_still_going=True
winner=None
current_player="X"
def play_game():
display_board()
#loop for next turn
while game_still_going:
handle_turn(current_player)
check_if_game_over()
flip_player()
if winner=="X" or winner=="O":
print(winner + " is the winner")
elif winner==None:
print("Tie")
def handle_turn(player):
global position
print(player + " 's turn")
position=input("Choose position from 1-9: ")
valid=False
while not valid:
while position not in ["1","2","3","4","5","6","7","8","9"]:
position=input("Invalid input. Please select numbers b/w 0-9: ")
position=int(position)-1
if board[position]=="-":
valid=True
else:
print("place is already taken")
board[position]= player
display_board()
def check_if_game_over():
check_if_win()
check_if_tie()
def check_if_win():
global winner
row_winner=check_rows()
column_winner=check_columns()
diagonal_winner=check_diagonals()
if row_winner:
winner=row_winner
elif column_winner:
winner=column_winner
elif diagonal_winner:
winner=diagonal_winner
else:
winner=None
return
def check_rows():
global game_still_going
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
if row_1 or row_2 or row_3:
game_still_going = False
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
return
def check_columns():
global game_still_going
col_1 = board[0] == board[3] == board[6] != "-"
col_2 = board[1] == board[4] == board[7] != "-"
col_3 = board[2] == board[5] == board[8] != "-"
if col_1 or col_2 or col_3:
game_still_going = False
if col_1:
return board[0]
elif col_2:
return board[1]
elif col_3:
return board[2]
return
def check_diagonals():
global game_still_going
diag_1 = board[0] == board[4] == board[8] != "-"
diag_2 = board[6] == board[4] == board[2] != "-"
if diag_1 or diag_2:
game_still_going = False
if diag_1:
return board[0]
elif diag_2:
return board[6]
return
def check_if_tie():
global game_still_going
if "-" not in board:
game_still_going = False
return
def flip_player():
global current_player
if current_player == "X":
current_player ="O"
elif current_player == "O":
current_player = "X"
return
play_game() |
from datetime import datetime
hoje = datetime.today().year
ficha = dict()
ficha['nome'] = str(input('Nome: ')).title().strip()
nasc = int(input('Ano de nascimento: '))
ficha['idade'] = hoje - nasc
ficha['ctps'] = int(input('Carteira de Trabalho (0 se não tem): '))
if ficha['ctps'] != 0:
ficha['contratação'] = int(input('Ano de contração: '))
ficha['salário'] = int(input('Salário: R$'))
ficha['aposentadoria'] = 35 + ficha['contratação'] - nasc
print("-=" * 40)
for k, v in ficha.items():
print(f' --- {k} tem o valor {v}')
|
inicio = int(input('Digite o primeiro termo da sua Progressão Aritmética: '))
razao = int(input('Digite a razão da PA: '))
pa = inicio
termos = 0
cont = 1
mais = 10
while mais != 0:
termos = termos + mais
while cont <= termos:
print('{}'.format(pa), end=' => ')
pa = pa + razao
cont += 1
print('PAUSE')
mais = int(input('Deseja mostrar mais quantos termos? '))
print('='*35)
print('Foram apresentados {} termos da sua Progressão Aritmética.'.format(termos))
print('Programa encerrado com sucesso! Até mais!')
|
coleção = [[], []]
for c in range(1, 8):
num = int(input(f'Digite o {c}º valor: '))
if num % 2 == 0:
coleção[0].append(num)
else:
coleção[1].append(num)
print(f'Os valores pares digitados foram: {sorted(coleção[0])}')
print(f'Os valores impares digitados foram: {sorted(coleção[1])}') |
expressao = str(input('Digite um expressão matemática: '))
parentesis = []
for v in expressao:
if v == '(' or v == ')':
parentesis.append(v)
metade1 = []
metade2 = []
if len(parentesis) % 2 == 0:
for c in range(0, int(len(parentesis) / 2)):
metade1.append(parentesis[c])
for c in range(int(len(parentesis) / 2), len(parentesis)):
if parentesis[c] == ')':
metade2.append('(')
if metade1 == metade2:
print('Sua expressão é válida.')
else:
print('Esta expressão não é válida.')
else:
print('Esta expressão não é válida')
print(metade1)
print(metade2) |
lista = []
for c in range(0, 5):
new = int(input('Digite um valor: '))
if c == 0:
lista.append(new) or new > lista[-1]:
print('Adicionado a última posição.')
else:
pos = 0
while pos < len(lista):
if new <= lista[pos]:
lista.insert(pos, new)
print(f'Adicionado a posição {pos} da lista.')
break
pos += 1
print(f'Os valores digitados em ordem foram {lista}')
|
n = int(input('Digite um número para ver sua tabuada: '))
print('-'*12)
for c in range(0,10+1):
print('{} x {:2} = {}'.format(n,c,n*c))
print('-'*12) |
inicio = int(input('Digite o primeiro termo da sua PA? '))
razão = int(input('Digite um número: '))
pa = inicio
cont = 1
termos = 0
mais = 10
while mais != 0:
termos += mais
while cont <= termos:
print('{}'.format(pa), end=' => ')
pa = pa + razão
cont += 1
mais = int(input('Deseja mostrar mais termos? '))
print('FIM') |
d = int(input('Qual é a ditância da sua viagem em Km? '))
preço = d*0.5 if d<=200 else d*0.45
print('O preço da sua viagem é de R${:.2f}'.format(preço))
'''if d <=200:
preço = d*0.5
print('Sua passagem de {}Km custa {} reais. Boa viagem!'.format(d, preço))
else:
preço = d*0.45
print('Sua passagem de {}Km custa {} reais. Boa viagem!'.format(d, preço))'''
|
ficha = dict()
ficha['jogador'] = str(input('Nome do jogador: ')).title().strip()
partidas = int(input(f'Quantas partidas {ficha["jogador"]} jogou: '))
gols = []
for c in range(1, partidas + 1):
gols.append(int(input(f'Quantos gols fez na {c}ª partida? ')))
ficha['gols'] = gols[:]
ficha['total'] = sum(gols)
print('-=' * 40)
print(ficha)
print('-=' * 40)
for k, v in ficha.items():
print(f'O campo {k} tem o valor {v}')
print('-=' * 40)
print(f'O jogador {ficha["jogador"]} jogou {len(ficha["gols"])} partidas ')
for p, g in enumerate(ficha['gols']):
print(f' => Na partida {p + 1}, fez {g} gols')
print(f'Foi um total de {ficha["total"]} gols')
|
sair = False
while sair == False:
a = float(input('Entre com a primeira nota: '))
b = float(input('Entre com a segunda nota: '))
media = (a+b)/2
print('Sua média foi de {:.1f}'.format(media))
if media<5:
print('\033[0;31mREPROVADO\033[m')
elif 5<=media<7:
print('\033[32mRECUPERAÇÃO\033[m')
else:
print('\033[36mAPROVADO\033[m')
fim = str(input('Deseja sair?(s/n)'))
if fim == 's':
sair = True
|
from datetime import date
n = int(input('Que ano você quer analisar? Coloque 0 para analisar o ano atual: '))
if n == 0:
n = date.today().year
if n % 4 == 0 and n % 100 !=0 or n % 400 ==0:
print('O ano {} é bissexto.'.format(n))
else:
print('O ano {} não é bissexto.'.format(n))
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
"""CNN neural network to predict MNIST classes.
The network architecture are as follows:
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
FC 512 units ReLU
Softmax 10 units
Reaches the Accuracy of 94% after 900 epochs.
"""
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Parameters
learning_rate = 0.01
epochs = 200
batch_size = 100
display_step = 1
# Network Parameters
num_input = 784 # image shape= 28*28
num_classes = 10 # 0-9 digits
# x shape = [batch, height, width, channel]
# height and width for MNIST is 28x28 and since the images are grayscale the channel is 1
x = tf.placeholder("float", [None, 28, 28, 1])
y = tf.placeholder("float", [None, num_classes])
# train_X = data.train.images.reshape(-1, 28, 28, 1)
# test_X = data.test.images.reshape(-1,28,28,1)
def convolution(x, W, b, stride):
'''
convolution function
:param x: input tensor
:param W: connecting weight
:param b: bias
:param stride: number of steps for convolution
:return: relu output of the calculation of the convolution
'''
x = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool(x, k, stride):
'''
Maxpool function
:param x: input tensor
:param k: kernel size
:param stride: stride
:return: output of the maxpooling as a tensor
'''
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, stride, stride, 1], padding='SAME')
# Weights
weight_conv1 = tf.get_variable('wc1', shape=(5, 5, 1, 64))
weight_conv2 = tf.get_variable('wc2', shape=(5, 5, 64, 128))
weight_fc = tf.get_variable('wd', shape=(4 * 4 * 128, 500))
weight_out = tf.get_variable('wo', shape=(500, num_classes))
# Bias
bias_conv1 = tf.get_variable('B0', shape=64)
bias_conv2 = tf.get_variable('B1', shape=128)
bias_fc = tf.get_variable('B3', shape=500)
bias_out = tf.get_variable('B4', shape=10)
'''
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
64 Conv 5x5 stride=1 ReLU
Max Pooling 2x2 stride=2
FC 512 units ReLU
Softmax 10 units
'''
conv1 = convolution(x, weight_conv1, bias_conv1, stride=1)
conv1 = maxpool(conv1, k=2, stride=3)
conv2 = convolution(conv1, weight_conv2, bias_conv2, stride=1)
conv2 = maxpool(conv2, k=2, stride=3)
fc = tf.reshape(conv2, [-1, weight_fc.get_shape().as_list()[0]])
fc = tf.add(tf.matmul(fc, weight_fc), bias_fc)
fc = tf.nn.relu(fc)
out = tf.add(tf.matmul(fc, weight_out), bias_out)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(out, 1), tf.argmax(y, 1))
# calculate accuracy across all the given images and average them out.
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
train_loss = []
test_loss = []
train_accuracy = []
test_accuracy = []
summary_writer = tf.summary.FileWriter('./Output', sess.graph)
print('trainable params:')
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape()
# print(shape)
# print(len(shape))
variable_parameters = 1
for dim in shape:
# print(dim)
variable_parameters *= dim.value
# print(variable_parameters)
total_parameters += variable_parameters
print(total_parameters)
for i in range(epochs):
batch_x, batch_y = mnist.train.next_batch(batch_size)
batch_x = batch_x.reshape(-1, 28, 28, 1)
# Run optimization op (backprop).
# Calculate batch loss and accuracy
opt = sess.run(optimizer, feed_dict={x: batch_x,
y: batch_y})
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y})
print("Iter " + str(i) + ", Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
test_X, test_y = mnist.test.next_batch(batch_size)
test_X = test_X.reshape(-1, 28, 28, 1)
# Calculate accuracy for all 10000 mnist test images
test_acc, valid_loss = sess.run([accuracy, cost], feed_dict={x: test_X, y: test_y})
train_loss.append(loss)
test_loss.append(valid_loss)
train_accuracy.append(acc)
test_accuracy.append(test_acc)
print("Testing Accuracy:", "{:.5f}".format(test_acc))
print("Training Finished!")
|
def fizzBuzz(num):
if num <= 0:
return;
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
num -= 1
fizzBuzz(num)
fizzBuzz(35)
|
def bubbleSort(arr):
for i in range(len(arr) - 1):
for j in range(len(arr) - 1):
print(arr, arr[j], arr[j + 1])
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
return arr
print(bubbleSort([12, 1, 7, 5]))
|
import secrets
from string import digits, ascii_letters
#genereting normal functions
print(secrets.choice('Choos one from this string'.split()))
print(secrets.randbelow(1000))
print(secrets.randbits(16))
#genereting tokens
print(secrets.token_hex(32))
print(secrets.token_bytes(16))
print(secrets.token_urlsafe(32))
#genereting password
def genereting_pwd(length=8):
chars = digits + ascii_letters
return ''.join(secrets.choice(chars) for _ in range(length))
def genereting_sec_pwd(length=16, upper=3, digit=1):
if length<upper + digit + 1:
raise ValueError('Nice Try!')
while True:
pwd = genereting_pwd(length)
if any(c.islower() for c in pwd) and (sum(c.isupper() for c in pwd)) >= upper and (sum(c.isdigit() for c in pwd)) >= digit :
return pwd
print(genereting_pwd())
print(genereting_sec_pwd()) |
import unittest
from modules import calculator
class TestCalculator(unittest.TestCase):
def test_add_2_numbers(self):
self.assertEqual("The answer to 8 plus 4 is 12", add_2_numbers(8, 4)) |
alphabet = "abcdefghijklmnopqrstuvwxyz"
def alphabet_position(Char):
for i in range(len(alphabet)):
if Char == alphabet[i] or Char == alphabet[i].upper():
return i
def rotate_character(Char, Rot):
if Char.isalpha():
encrypted = ""
NewCharPos = alphabet_position(Char) + Rot
if NewCharPos <26:
encrypted += alphabet[NewCharPos]
else:
encrypted += alphabet[NewCharPos %26]
if Char.isupper():
return encrypted.upper()
else:
return encrypted
return Char
def encrypt(Msg, Rot):
FinalMsg = []
for i in range (len(Msg)):
for j in range(len(Msg[i])):
FinalMsg.append(rotate_character(Msg[i][j], Rot))
FinalMsg = "".join(FinalMsg)
return FinalMsg
|
# test cases
matrix1 = [
[1,2,3],
[4,5,6],
[7,8,9]
]
matrix2 = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24],
[25,26,27,28,29,30],
[31,32,33,34,35,36]
]
# algorithm
def rotate_matrix(matrix, n):
rotated = []
i = len(matrix) * n
x = 0
temp = []
for row in range(0, len(matrix) * n):
while(i):
if len(temp) == n:
rotated.insert(len(rotated), temp)
temp = []
x = 0
temp.insert(n, matrix[x].pop())
x += 1
i -= 1
rotated.insert(len(rotated), temp)
return rotated
# execution
if __name__ == "__main__":
rotate_matrix(matrix1, 3)
rotate_matrix(matrix2, 6)
|
def freq(n, text):
text = ''.join(i.lower() for i in text if i.isdigit() or i.isalpha()) #String preprocessing
no_dupls = set() #set to remove combination dupls
res_dct = dict() #dict with results
if len(text)==n: #specific case (N = text length)
res_dct[text]=1
for i in range(len(text)-n):
no_dupls.add(text[i:i+n])
for i in no_dupls:
res_dct[i]=text.count(i)
return sorted(res_dct.items(), key=lambda x:x[1], reverse=True) #sort by dict values.
#Tests
print(freq(1, "abracadabra"))
print(freq(2, "abracadabra"))
print(freq(2, "ab"))
print(freq(2, "abab"))
print(freq(3, "abracadabra"))
print(freq(2, "to be or not to be"))
|
# solve it_1
# import math
# x = 4
# y = 3
# z = 2
# w = (( x + y * z ) / ( x*y ))**z
# print (w)
#### OR
# v = ( x + y * z ) / ( x*y )
# result = math.pow(v,z)
# print(result)
# solve it_2
# x = input("Silakan masukkan angka berapapun: ") #meminta input dari user n disimpan di variable,
# #input dr user akan selalu string
# x = int(x) # ubah input dari user menjadi integer
# kuadrat = x**2 # hitung kuadrat input dr user
# kuadrat = int(kuadrat)
# print(f"Hasil kuadrat dari {x} adalah: {kuadrat}") # hasil kuadrat ditampilkan
# solve it 3
# 1 tahun = 360 hari, 1 bulan = 30 hari, 1 minggu 7 hari
# # Tentukan banyaknya hari
# days = 485
# # Tentukan jumlah tahun
# year = int(days / 360)
# # Sisa hari setelah diambil sekian tahun
# days = days % 360
# # Tentukan jumlah bulan
# month = int(days / 30)
# # Sisa hari setelah diambil sekian bulan
# days = days % 30
# # Tentukan jumlah minggu
# week = int(days / 7)
# Sisa hari setelah diambil sekian minggu
# days = days % 7
# print("Maka 485 hari terdiri dari:")
# print(f"{year} tahun")
# print(f"{month} bulan")
# print(f"{week} minggu")
# print(f"{days} hari")
############################
# number of days in terms of Years, Month, Weeks and Days
# DAYS_IN_WEEK = 7
# DAYS_IN_MONTH = 30
# # Function to find year, week, days
# def find( number_of_days ):
# # Assume that years is of 360 days
# year = int(number_of_days / 360)
# month = int((number_of_days % 360) / DAYS_IN_MONTH)
# week = int((number_of_days % 7) / DAYS_IN_WEEK)
# days = (number_of_days % 360) % DAYS_IN_MONTH
# print("years = ",year,
# "\nmonth =", month,
# "\nweeks = ",week,
# "\ndays = ",days)
# number_of_days = 485
# find(number_of_days)
#solve it 4
# andi/budi = 0.4
# andi + budi = 49
# andi = 49 - budi
# (49-budi) / budi = 0.4
# 49 - budi = 0.4*budi
# 49 = 1.4*budi
# budi = 49/1.4
# budi = 35
# andi = 49 - 35
# andi = 14
jumlah = 49
rasio = 0.4
andi = jumlah / (rasio + 1)
budi = jumlah - andi
print(andi)
print(budi)
# usia 2 th lagi
andi = andi + 2
budi = budi + 2
print(andi)
print(budi)
# solve it 5
# x = input("Silakan masukan kalimat: ")
# y = input ("Karakter apa yang ingin diketahui jumlahnya: ")
# result = x.count(y)
# print(f"Pada \"{x}\" terdapat karakter \"{y}\" sebanyak {result} buah")
# # solve it 6
v1 = 60
v2 = 40
s = 120
jam = 9
t = s / (v1+v2)
s1 = t*v1
s2 = t*v2
print (f"Waktu yang diperlukan {t} jam")
print (f"Jarak A ke titik C = {s1} km")
print (f"Jarak B ke titik C = {s2} km")
totalJam = int(t+jam)
minutes = int(t*60)%60
print(f"Maka akan bertemu di pukul {totalJam} lewat {minutes} menit")
|
numberOfGames = int(input())
results = [0] * numberOfGames
gameCounter = 0
while gameCounter != numberOfGames:
numberOfRounds = int(input())
player1 = 0
player2 = 0
roundCounter = 0
while roundCounter != numberOfRounds:
result = input()
if ((result == "P R") or (result == "S P") or (result == "R S")):
player1 += 1
if ((result == "R P") or (result == "P S") or (result == "S R")):
player2 += 1
roundCounter += 1
if player1 > player2:
results[gameCounter] = "Player 1"
elif player2 > player1:
results[gameCounter] = "Player 2"
else:
results[gameCounter] = "TIE"
gameCounter += 1
for result in results:
print(result) |
#program main
# use StringClass
# implicit none
#
# type(String_) :: string
word = "Hello "
print(word)
word = word + "world!"
print(word)
word = word + "world!" + word + "world!"
print(word)
x = word.lower()
print(x)
x = word.upper()
print(x) |
'''
Implemente as classes Pessoa e Aluno.
A classe Pessoa deve armazenar o nome da pessoa.
A classe Aluno deve herdar da classe Pessoa e armazena o ra e uma lista
com as notas de 5 atividades realizadas durante o semestre.
Os atributos das classes devem ser inicializados nos construtores.
A lista de notas do aluno deve ser inicializada como vazia.
A classe Aluno deve implementar os métodos:
cadastrar: recebe como entrada uma nota e a insere na lista de notas.
calcular_media: retorna a média aritmética das notas do aluno. Essa
média deve desconsiderar a nota mais baixa.
'''
# --------------------- IMPLEMENTE SEU CÓDIGO AQUI --------------------------
class Pessoa:
def __init__(self, nome):
self.nome = nome
class Aluno(Pessoa):
def __init__(self, ra, nome):
super().__init__(nome)
self.ra = ra
self.notas = []
def cadastrar(self, nota):
self.notas.append(nota)
def calcular_media(self):
self.notas.sort()
soma = self.notas[1] + self.notas[2] + self.notas[3] + self.notas[4]
return soma/4
# -------------- PROGRAMA PRINCIPAL (não deve ser alterado) -----------------
aluno1 = Aluno(123456, 'João')
aluno1.cadastrar(8.0)
aluno1.cadastrar(7.0)
aluno1.cadastrar(9.0)
aluno1.cadastrar(6.0)
aluno1.cadastrar(7.0)
print("Média:", aluno1.calcular_media()) # Média: 7.75
aluno2 = Aluno(123456, 'Maria')
aluno2.cadastrar(10.0)
aluno2.cadastrar(9.0)
aluno2.cadastrar(6.5)
aluno2.cadastrar(5.0)
aluno2.cadastrar(7.5)
print("Média:", aluno2.calcular_media()) # Média: 8.25
|
# Python program to code and decode with the help of fractions of lexicon of positive integers k<=n subdivided
# lexicographically by their prime factorization.
# Prime lexicon(lexicon): Whole set of positive integers k<=n subdivided lexicographically by their prime
# factorization, which contains set of multiples of a particular integer at a given resolution, in its fraction.
# Reference: https://oeis.org/A336533
import math
eng = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", " "]
def text_int(s, l): # convert text to number
n = 0
s = list(s)
c = 0
for i in range(len(s)):
n += (len(l) + 1) ** i * (l.index(s[i]) + 1)
return n
def int_text(n, l): # convert number to text
s = ""
while n > len(l):
s += l[n % (len(l) + 1) - 1]
n //= len(l) + 1
s += l[n - 1]
return s
def is_prime(n): # return True if input is prime
if n <= 1:
return False
if n == 2 or n == 3 or n == 5:
return True
if n % 2 == 0 or n % 3 == 0 or n % 5 == 0:
return False
max_div = math.floor(math.sqrt(n))
for i in range(3, 1 + max_div, 2):
if n % i == 0:
return False
return True
def nth_prime(n): # return n-th prime number
c = -1
i = 1
while n != c:
if is_prime(i):
c += 1
i += 1
else:
i += 1
return i - 1
def next_prime(n): # return smallest prime >= n
i = 2
c = 0
while i < n:
i = nth_prime(c)
c += 1
return i
def integer_fractionOfLexicon(num): # return at which fraction of lexicon are set of multiples of an integer
numberLexicalFraction = 1
seenFraction = 0
prime = 2
total = 1
if num == 1:
return 1
while num > 1:
total *= prime
seenFraction *= prime
numberLexicalFraction *= prime
if num % prime == 0:
num //= prime
numberLexicalFraction //= prime
else:
seenFraction += numberLexicalFraction // prime
numberLexicalFraction -= numberLexicalFraction // prime
prime = next_prime(prime + 1)
seenFraction += numberLexicalFraction
return seenFraction / total
def fractionOfLexicon_integer(fraction, resolution):
# return the integer which its set of multiples are at the given fraction of lexicon for given resolution
seenFraction = 0
prime = 1
unseenFraction = 1
numberLexicalFraction = 0
extract = 1
counter = 0
if fraction == 1:
return 1
if 0 < fraction < 1 and 0 < resolution < 1:
while not (seenFraction - resolution < fraction < seenFraction + resolution):
counter += 1
if counter > 5000:
return "error"
if fraction > seenFraction:
prime = next_prime(prime + 1)
numberLexicalFraction = unseenFraction / prime
seenFraction += numberLexicalFraction
unseenFraction -= numberLexicalFraction
if seenFraction - resolution < fraction < seenFraction + resolution:
extract *= prime
return extract
if fraction < seenFraction:
seenFraction -= numberLexicalFraction
unseenFraction = numberLexicalFraction
numberLexicalFraction /= prime
unseenFraction -= numberLexicalFraction
seenFraction += numberLexicalFraction
extract *= prime
extract *= prime
return extract
else:
return fractionOfLexicon_integer(float(input("\nEnter positive value <=1 for fraction:\n ")),
float(input("\nEnter positive value <=1 for resolution:\n ")))
def prog(): # main program
state = input(
"\n\"cn\" to code numbers\n\"dn\" to decode numbers\n\"ct\" to code texts\n\"dt\" to decode texts\nEnter: ")
if state.lower() == "cn":
s = int(input("\nType an integer:\n "))
num = integer_fractionOfLexicon(s)
resolution = 1 / 10
if num != "error":
while s != fractionOfLexicon_integer(num, resolution):
if resolution < 1 / 10 ** 16:
print("Try smaller input, it takes too long!")
return prog()
else:
resolution /= 2
print("\nFraction of lexicon:", num, "\nResolution:", resolution)
else:
print("Try smaller input, takes too long!")
return prog()
if state.lower() == "dn":
num = float(input("\nEnter fraction of lexicon:\n "))
resolution = float(input("\nEnter resolution:\n "))
print("\nOriginal number: ", fractionOfLexicon_integer(num, resolution))
if state.lower() == "ct":
s = input("\nEnter text (a few english characters plus space):\n ")
num = integer_fractionOfLexicon(text_int(s, eng))
resolution = 1 / 10
if num != "error":
while s != int_text(fractionOfLexicon_integer(num, resolution), eng):
if resolution < 1 / 10 ** 16:
print("Try smaller input, it takes too long!")
return prog()
else:
resolution /= 2
print("\nFraction of lexicon:", num, "\nResolution:", resolution)
else:
print("Try smaller input, it takes too long!")
return prog()
if state.lower() == "dt":
num = float(input("\nEnter fraction of lexicon:\n "))
resolution = float(input("\nEnter resolution:\n "))
print("\nOriginal text: ", int_text(fractionOfLexicon_integer(num, resolution), eng))
while True:
prog()
# https://oeis.org/wiki/User:Mohammad_Saleh_Dinparvar , SEP 6 2020
|
"""
Used to allow for function and their arguments to be stored.
"""
__all__ = ["Task"]
class Task:
"""
Class used to store function that will be executed
args:
func : the function that will be executes
callback : function that will run when processing has started and finished, callback("STARTED", "taskname"), if None will not run any
task_name : the name of the task which will be used in the callback
args : any arguments that will be passed in the function
kwargs : any kwargs that will be passed in the function
"""
def __init__(self, func, callback=None, task_name="", args=(), kwargs={}):
self.__func = func
self.__callback = callback
self.__task_name = task_name
self.__args = args
self.__kwargs = kwargs
@property
def callback(self):
return self.__callback
@callback.setter
def callback(self, newcallback):
if callable(newcallback) or newcallback == None:
self.__callback = newcallback
else:
raise TypeError("new callback value must be callable or None")
def execute(self):
"""
Executes the task
"""
if callable(self.__callback):
self.__callback("STARTED", self.__task_name)
self.__func(*self.__args, **self.__kwargs)
self.__callback("FINISHED", self.__task_name)
else:
self.__func(*self.__args, **self.__kwargs)
|
import pandas as pd
from sklearn.impute import KNNImputer
def knn(data=None, columns=None, k=3, inplace=False):
"""Performs k-nearest neighbors imputation on the data. The k nearest
neighbors or each subject with missing data are chosen and the average
of their values is used to impute the missing value. The operation can be
applied to all columns, by leaving the parameter columns empty, or to
selected columns, passed as an array of strings.
:param data: The data on which to perform the k-nearest neighbors
imputation.
:type data: pandas.DataFrame
:param columns: Columns on which to apply the operation.
:type columns: array-like, optional
:param k: The number of neighbors to which the subject with missing
values should be compared
:type k: int, default 3
:param inplace: If True, do operation inplace and return None.
:type inplace: bool, default False
:return: The series or dataframe with NA values imputed, or
None if inplace=True.
:rtype: pandas.DataFrame or None
:raises: TypeError, ValueError
"""
# Check if data is a dataframe:
if not isinstance(data, pd.DataFrame):
raise TypeError('The data has to be a DataFrame.')
# Assign a reference or copy to res, depending on inplace:
if inplace:
res = data
else:
res = data.copy()
# The KNNImputer removes all columns that contain only empty values.
# Therefore, we save those values in order to add them later (otherwise
# problems would occur with dataframes that contain such columns:
empty_column_names = res.columns[res.isna().all()]
empty_column_indices = [
res.columns.get_loc(column_name) for column_name in empty_column_names]
empty_column_values = res.loc[:, res.isna().all()]
# Perform KNN:
knn_out_array = KNNImputer(n_neighbors=k).fit_transform(data)
knn_out = pd.DataFrame(knn_out_array)
# Add empty columns back and set indices of knn_out:
for i, empty_column_name in enumerate(empty_column_names):
knn_out.insert(
empty_column_indices[i], empty_column_name,
empty_column_values.iloc[:, i])
knn_out.columns = res.columns
knn_out.index = res.index
# Treatment for a whole dataframe:
if columns is None:
res.loc[:, :] = knn_out
# Treatment for selected columns of a dataframe:
else:
for column in columns:
if column not in data.columns:
raise ValueError(
'\'' + column + '\' is not a column of the data.')
col_loc = data.columns.get_loc(column)
res[column] = knn_out.iloc[:, col_loc]
# Return the imputed data, or None if inplace:
if inplace:
return None
else:
return res
|
import unittest
from imputena import knn
from test.example_data import *
class TestKNN(unittest.TestCase):
# Positive tests ----------------------------------------------------------
def test_KNN_returning(self):
"""
Positive test
data: Correct data frame (example_df)
The data frame (example_df) contains 2 NA values.
knn() should impute all of them.
Checks that the original data frame remains unmodified and that the
returned data frame contains no NA values.
"""
# 1. Arrange
df = generate_example_df()
# 2. Act
df2 = knn(df)
# 3. Assert
self.assertEqual(df.isna().sum().sum(), 2)
self.assertEqual(df2.isna().sum().sum(), 0)
def test_KNN_inplace(self):
"""
Positive test
data: Correct data frame (example_df)
The data frame (example_df) contains 2 NA values.
knn() should impute both of them.
Checks that the data frame contains no NA values after the operation.
"""
# 1. Arrange
df = generate_example_df()
# 2. Act
knn(df, inplace=True)
# 3. Assert
self.assertEqual(df.isna().sum().sum(), 0)
def test_KNN_columns(self):
"""
Positive test
data: Correct data frame (example_df)
columns: ['x']
The data frame (example_df) contains 2 NA values.
knn() should impute 1 of them.
Checks that the original data frame remains unmodified and that the
returned data frame contains 1 NA value.
"""
# 1. Arrange
df = generate_example_df()
# 2. Act
df2 = knn(df, columns=['x'])
# 3. Assert
self.assertEqual(df.isna().sum().sum(), 2)
self.assertEqual(df2.isna().sum().sum(), 1)
def test_KNN_k(self):
"""
Positive test
data: Correct data frame (example_df)
k: 1
The data frame (example_df) contains 2 NA values.
knn() should impute both of them.
Checks that the original data frame remains unmodified and that the
returned data frame contains no NA values.
"""
# 1. Arrange
df = generate_example_df()
# 2. Act
df2 = knn(df, k=1)
# 3. Assert
self.assertEqual(df.isna().sum().sum(), 2)
self.assertEqual(df2.isna().sum().sum(), 0)
# Negative tests ----------------------------------------------------------
def test_KNN_wrong_type(self):
"""
Negative test
data: array (unsupported type)
Checks that the function raises a TypeError if the data is passed as
an array.
"""
# 1. Arrange
data = [2, 4, np.nan, 1]
# 2. Act & 3. Assert
with self.assertRaises(TypeError):
knn(data)
def test_KNN_wrong_column(self):
"""
Negative test
data: Correct data frame (example_df)
columns: ['x', 'a'] ('a' is not a column of example_df)
Checks that the function raises a ValueError if one of the specified
columns doesn't exist in the data.
"""
# 1. Arrange
df = generate_example_df()
# 2. Act
df2 = knn(df, columns=['x'])
# 2. Act & 3. Assert
with self.assertRaises(ValueError):
knn(df, columns=['x', 'a'])
|
import pandas as pd
from sklearn import linear_model
from sklearn.exceptions import ConvergenceWarning
import logging
import warnings
def logistic_regression(
data=None, dependent=None, predictors=None, regressions='available',
inplace=False):
"""Performs logistic regression imputation on the data. First, the
regression equation for the dependent variable given the predictor
variables is computed. For this step, all rows that contain a missing
value in either the dependent variable or any of the predictor variable
is ignored via pairwise deletion. Then, missing valued in the dependent
column in imputed using the regression equation. If, in the same
row as a missing value in the dependent variable the value for any
predictor variable is missing, a regression model based on all available
predictors in calculated just to impute those values where the
predictor(s) are missing. This behavior can be changed by assigning to
the parameter regressions the value 'complete'. In this case, rows in
which a predictor variable is missing do not get imputed. If the parameter
predictors is omitted, all variables other than the dependent are used as
predictors.
:param data: The data on which to perform the logistic regression
imputation.
:type data: pandas.DataFrame
:param dependent: The dependent variable in which the missing values
should be imputed.
:type dependent: String
:param predictors: The predictor variables on which the dependent variable
is dependent.
:type predictors: array-like, optional
:param regressions: If 'available': Impute missing values by modeling a
regression based on all available predictors if some predictors have
missing values themselves. If 'complete': Only impute with a
regression model based on all predictors and leave missing values in
rows in which some predictor value is missing itself unimputed.
:type regressions: {'available', 'complete'}, default 'available'
:param inplace: If True, do operation inplace and return None.
:type inplace: bool, default False
:return: The dataframe with logistic regression imputation performed for
the incomplete variable or None if inplace=True.
:rtype: pandas.DataFrame or None
:raises: TypeError, ValueError
"""
# Check if data is a dataframe:
if not isinstance(data, pd.DataFrame):
raise TypeError('The data has to be a DataFrame.')
# Check if the dependent variable is actually a column of the dataframe:
if dependent not in data.columns:
raise ValueError(
'\'' + dependent + '\' is not a column of the data.')
# If predictors is None, all variables except for the dependent one are
# considered predictors:
if predictors is None:
predictors = list(data.columns)
predictors.remove(dependent)
# Check if each of the predictor variables is actually a column of the
# dataframe:
for column in predictors:
if column not in data.columns:
raise ValueError(
'\'' + column + '\' is not a column of the data.')
# Assign value to do_available_regressions
if regressions == 'available':
do_available_regressions = True
elif regressions == 'complete':
do_available_regressions = False
else:
raise ValueError(regressions + 'could not be understood')
# Assign a reference or copy to res, depending on inplace:
if inplace:
res = data
else:
res = data.copy()
# Predictor combination sets and lists
limited_predictors_combs = set()
predictors_combs_done = []
predictors_combs_todo = [tuple(predictors)]
# Perform the operation:
while len(predictors_combs_todo) > 0:
# Select iteration predictors
it_predictors = predictors_combs_todo.pop(0)
# Log iteration beginning:
logging.info('Applying regression imputation with predictors: ' + str(
it_predictors))
# Perform iteration:
res.loc[:, :] = logistic_regression_iter(
res, dependent, list(it_predictors),
limited_predictors_combs)
# Update predictor combinations done and to do
predictors_combs_done.append(it_predictors)
if do_available_regressions:
predictors_combs_todo = list(
set(limited_predictors_combs) - set(predictors_combs_done))
# Log iteration end:
logging.info('Predictor combinations done: ' + str(
predictors_combs_done))
logging.info('Predictor combinations to do: ' + str(
predictors_combs_todo))
# Return dataframe is the operation is not to be performed inplace:
if not inplace:
return res
def logistic_regression_iter(
data, dependent, predictors, limited_predictors_combs):
"""Auxiliary function that performs (simple or multiple) logistic
regression imputation on the data, for the dependent column only. In rows
that contain a missing value for any predictor variable, the value of the
dependent variable does not get imputed. The operation is always
performed on a copy of the data, which is returned.
:param data: The data on which to perform the logistic regression
imputation.
:type data: pandas.DataFrame
:param dependent: The dependent variable in which the missing values
should be imputed.
:type dependent: String
:param predictors: The predictor variables on which the dependent variable
is dependent.
:type predictors: array-like
:param limited_predictors_combs: Reference to the set which contains all
limited predictor combinations that are necessary to use because
some predictor had a missing value in some row.
:type limited_predictors_combs: set
:return: A copy of the dataframe with logistic regression imputation
performed for the incomplete variable.
:rtype: pandas.DataFrame o None
"""
# Perform pairwise deletion before calculating the regression
data_pairwise_deleted = data.copy()
variables = predictors.copy()
variables.append(dependent)
data_pairwise_deleted.dropna(subset=variables, inplace=True)
# Calculate the regression:
x = data_pairwise_deleted[predictors]
y = data_pairwise_deleted[dependent]
model = linear_model.LogisticRegression()
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=ConvergenceWarning)
model.fit(x, y)
# Implementation using apply:
return data.apply(
lambda row: get_imputed_row(
row, dependent, predictors, model, limited_predictors_combs),
axis=1, result_type='broadcast')
def get_imputed_row(
row, dependent, predictors, model, limited_predictors_combs):
"""Auxiliary function that receives a row of a DataFrame and returns the
same row. If the row contains a missing value for the dependent variable,
it gets imputed according to the regression model.
:param row: The row for which the missing value should be imputed
:type row: pandas.Series
:param dependent: The dependent variable for which the row might contain a
missing value
:type dependent: String
:param predictors: The predictor variables on which the dependent variable
is dependent.
:type predictors: array-like
:param model: The logistic regression model.
:type model: sklearn.linear_model._logistic.LogisticRegression
:param limited_predictors_combs: Reference to the set which contains all
limited predictor combinations that are necessary to use because
some predictor had a missing value in some row.
:type limited_predictors_combs: set
:return: The row, with the missing value imputed if it contains one.
:rtype: pandas.Series
"""
res = row.copy()
if pd.isnull(res[dependent]):
# Check whether there are predictors for which the value is NA
na_predictors = tuple(
row[predictors][row[predictors].isnull()].index.to_list())
# If the row contains NA values for one or several predictors,
# add the combination of predictors to na_predictor_combs, in order
# to perform regression without them:
if na_predictors != ():
limited_predictors = tuple(set(predictors) - set(na_predictors))
# Add the limited_predictors to the set only if the combination
# isn't empty:
if limited_predictors != ():
limited_predictors_combs.add(limited_predictors)
# If the row doesn't contain missing values for any predictor, impute:
else:
value = model.predict(row[predictors].values.reshape(1, -1))
res[dependent] = value[0]
return res
|
import pandas as pd
def interpolation(
data=None, method='linear', direction='both', columns=None,
inplace=False):
"""Performs linear, quadratic, or cubic interpolation on a series or a
data frame. If the data is passed as a dataframe, the operation can be
applied to all columns, by leaving the parameter columns empty, or to
selected columns, passed as an array of strings.
:param data: The data on which to perform the interpolation.
:type data: pandas.Series or pandas.DataFrame
:param method: The interpolation model to use.
:type method: {'linear', 'quadratic', 'cubic'}, default 'linear'
:param direction: Direction in which to interpolate values when the
interpolation method is linear.
:type direction: {'forward', 'backward', 'both'}, default 'both'
:param columns: Columns on which to apply the operation.
:type columns: array-like, optional
:param inplace: If True, do operation inplace and return None.
:type inplace: bool, default False
:return: The series or dataframe with NA values interpolated, or
None if inplace=True.
:rtype: pandas.Series, pandas.DataFrame, or None
:raises: TypeError, ValueError
"""
# Check that data is a series or dataframe:
if not (isinstance(data, pd.Series) or isinstance(data, pd.DataFrame)):
raise TypeError('The data has to be a Series or DataFrame.')
# Raise a ValueError if columns are selected for a Series:
if isinstance(data, pd.Series) and columns is not None:
raise ValueError('Columns can only be selected if the data is a '
'DataFrame.')
# Assign a reference or copy to res, depending on inplace:
if inplace:
res = data
else:
res = data.copy()
# kwargs for the pandas interpolate() function:
int_kwargs = {'limit_direction': direction}
# Treatment for a whole DataFrame or a Series:
if columns is None:
if inplace:
data.interpolate(method=method, inplace=True, **int_kwargs)
else:
res = data.interpolate(method=method, inplace=False, **int_kwargs)
# Treatment for selected columns:
else:
for column in columns:
# Raise error if the column name doesn't exist in the data:
if column not in data.columns:
raise ValueError(
'\'' + column + '\' is not a column of the data.')
res[column] = res[column].interpolate(
method=method, inplace=False, **int_kwargs)
# Return the imputed data, or None if inplace:
if inplace:
return None
else:
return res
|
from stack_092 import Stack
def matcher(line):
s = Stack()
for char in line:
if char == "(" or char == "{" or char == "[":
s.push(char)
elif char == ")" or char == "}" or char == "]":
try:
if not s.is_empty:
return False
elif char == ")" and s.top() == "(":
s.pop()
elif char == "}" and s.top() == "{":
s.pop()
elif char == "]" and s.top() == "[":
s.pop()
else:
return False
except:
return False
return s.is_empty()
|
#!/usr/bin/env python
import sys
def pas(s):
tot = 0
a = []
for c in s:
if c.isdigit():
a.append("dig")
if c.islower():
a.append("low")
if c.isupper():
a.append("up")
if c != " ":
if not c.isalnum():
a.append("oth")
a.pop(len(a) - 1)
if "dig" in a:
tot = tot + 1
if "low" in a:
tot = tot + 1
if "up" in a:
tot = tot + 1
if "oth" in a:
tot = tot + 1
return tot
def main():
for line in sys.stdin:
print(pas(line))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import sys
from math import pi
def pie(r):
m = str(r)
n = "{:." + m + "f}"
return(n.format(pi))
def main():
print(pie(sys.argv[1]))
if __name__ == '__main__':
main()
|
from six.moves import input
import random
def main():
word_list, answer_list, word_dict, wrong_list = [], [], {}, []
with open('word.db') as f:
for line in f.readlines():
line_list = line.strip().split()
if len(line_list) < 2:
pass
else:
word = line_list[0]
answer = ' '.join(line_list[1:])
word_dict[word] = answer
word_list.append(word)
answer_list.append(answer)
print("---------------------- Usage ----------------------")
print("Choose the one which is the synonym of given word.\n")
print("Enter 1, 2, 3, or 4 to provide your answer, or enter")
print("ENTER to get result directly if you don't know what")
print("the given word means.\n")
print("Enter q to exit.")
print("-----------------------------------------------------")
quit_flag = False
while True:
if quit_flag:
break
pick_one = random.choice(word_list)
print(">>> " + pick_one)
choice_list = random.sample(answer_list, 3)
choice_list.append(word_dict[pick_one])
random.shuffle(choice_list)
print(choice_list)
while True:
user_answer = input("Answer? >>>")
if user_answer == 'q':
quit_flag = True
break
if user_answer.isdigit():
user_answer = int(user_answer)
if choice_list[user_answer - 1] == word_dict[pick_one]:
print("[Correct!]")
else:
print("[Wrong] Answer is: ", word_dict[pick_one])
wrong_list.append(pick_one)
break
elif not user_answer:
print("[Wrong] Answer is: ", word_dict[pick_one])
wrong_list.append(pick_one)
break
else:
user_answer = input(
"[Warning] Answer should in [1, 2, 3, 4]! Retry >>>")
print("")
with open('wrong_note.db', 'a') as f:
to_write = [w + ' ' + word_dict[w] + '\n' for w in wrong_list]
f.writelines(to_write)
print("Wrong answers has been saved in ./wrong_note.db")
if __name__ == '__main__':
main()
|
import csv
import numpy as numpy
from messytables import CSVTableSet, type_guess, types_processor, headers_guess, headers_processor, offset_processor
tinyint_min = 0
tinyint_max = 255
smallint_min = -32768
smallint_max = 32767
int_min = -2147483648
int_max = 2147483647
bigint_min = -9223372036854775808
bigint_max = 9223372036854775807
real_min = -3.4E+38
real_max = 3.4E+38
float_min = -1.7E+308
float_max = 1.7E+308
def get_row_count(file_name): # counts the rows in the csv file
try:
# opens the csv file being used as a reading file
with open(file_name, 'r') as csv_file:
# sets the file to the reader variable
reader = csv.reader(csv_file)
row_number = 0
# each row in the csv file is a list. The row variable counts for each list (or row)
for row in reader:
# adds 1 to the row number each time a new row is counted by the for loop
row_number += 1
# closes the csv file
csv_file.close()
# returns the number of rows (not including the header)
return row_number - 1
except Exception:
# makes sure that if the row count fails, the rest of the functions still work
print("Row Count Unavailable")
def get_column_count(file_name): # counts the columns in the csv file
try:
with open(file_name, 'r') as csv_file:
reader = csv.reader(csv_file)
# goes to the first row of the csv file
first_row = next(reader)
csv_file.close()
# counts each item in a single row list (which is the number of columns)
return len(first_row)
except Exception:
# makes sure that if the col count fails, rest of the functions still works
print("Column Count Unavailable")
def get_column_names(file_name): # gives the name of the columns in the csv file in an array
try:
with open(file_name, 'r') as csv_file:
reader = csv.reader(csv_file)
# the first row is the header, next goes to the next row which is the first one here
header = next(reader)
# array is not native to python, this converts the list to an array
header_array = numpy.array(header)
csv_file.close()
# returns the array of column names
return header_array
except Exception:
# makes sure that if the col name fails, rest of the functions still works
print("Column Names Unavailable")
def get_column_pytypes(file_name): # gives the python data types of each column
try:
# The messytables module helps us get accurate python data types through the following:
# opens the csv file in read binary mode
file_table = open(file_name, "rb")
# Next, we load the file into a table set and assign that table set under the "table_types" variable:
table_types = CSVTableSet(file_table)
# Since a table set is a set of multiple tables, we create our table:
column_types = table_types.tables[0]
# We save the first row (headers) under the offset and headers variables
offset, headers = headers_guess(column_types.sample)
# We tell the table that the first row is under the headers variable
column_types.register_processor(headers_processor(headers))
# Then we tell the table that the rest of the content is under the offset variable
# We add one to begin with the content and not the header
column_types.register_processor(offset_processor(offset + 1))
# Next, we guess the data types of each column in the table
# strict=True means that a type will still be guessed even if parsing fails for a cell in the column
types = type_guess(column_types.sample, strict=True)
# We apply the data types to each column of the table
column_types.register_processor(types_processor(types))
# stores the number of headers (or columns essentially)
header_length = len(headers)
datatype_list = [] # creates the data type list
# the for loop will be used to iterate through the first column (0) to the last one (header_length)
for current_col in range(0, header_length):
# We convert the current type of 'messytables.type' to a string so that we can write to it
types[current_col] = str(types[current_col])
# messytables uses the type Decimal instead of the python type float:
if types[current_col] == 'Decimal': # if the data type of a column is called "Decimal"
types[current_col] = "Float" # change the name of that data type to be called "Float"
# we use a string to indicate which header contains which type
type_assignment = f"{headers[current_col]} : {types[current_col]}"
# appends the type_assignment for each column into the list
datatype_list.append(type_assignment)
# converts the list to an array
datatype_array = numpy.array(datatype_list)
file_table.close()
# returns the array with all the data types
return datatype_array
except Exception:
# makes sure that if the types fails, rest of the functions still works
print("Python Datatypes Unavailable")
def get_sql_types(file_name):
try:
with open(file_name, 'r') as csv_file:
# The following block of code uses the messytables module and is explained in the get_column_types function:
file_table = open(file_name, "rb")
table_types = CSVTableSet(file_table)
column_types = table_types.tables[0]
offset, headers = headers_guess(column_types.sample)
column_types.register_processor(headers_processor(headers))
column_types.register_processor(offset_processor(offset + 1))
types = type_guess(column_types.sample, strict=True)
column_types.register_processor(types_processor(types))
# creates a lambda that checks if the string being passed is ascii or unicode
# by checking if the string is the same as it would be if it was encoded
# since ascii is 1 byte and Unicode is 2 bytes, this checks if they are the same length
is_ascii = lambda s: len(s) == len(s.encode())
# gives the number of columns
column_length = len(headers)
# creates list
sql_list = []
# iterates through the first to last column
for current_col in range(0, column_length):
# We convert the current type of 'messytables.type' to a string so that we can write to it
types[current_col] = str(types[current_col])
if types[current_col] == 'Bool': # if the data type is a Bool
types[current_col] = 'Bit' # change name to "Bit"
if types[current_col] == 'String': # if the data type is a String
reader = csv.reader(csv_file)
# variable that will be used to prevent the header from being a part of the column
header_check = False
# variable that will be used to switch between VarChar and NVarChar
nvarchar_check = False
# variable that will be used to find the longest string within each column
char_length = 0
# restarts the file from the very start for each new string column
csv_file.seek(0)
# for each row in the column
for row in reader:
# if not the header
if header_check:
# if past longest string is less than length of current
if char_length < len(row[current_col]):
# change the longest length to the current string length
char_length = len(row[current_col])
# if the current string is in ascii
if is_ascii(row[current_col]):
# if no previous strings were unicode in current column
if not nvarchar_check:
# change name to "VarChar(max length)"
types[current_col] = f'VarChar({char_length})'
# if any previous string was unicode in current column
elif nvarchar_check:
# change name to 'NVarChar(max length)"
types[current_col] = f'NVarChar({char_length})'
# if the current string is in unicode
elif not is_ascii(row[current_col]):
# change name to 'NCharVar(max length)"
types[current_col] = f'NVarChar({char_length})'
# make sure the column is identified as NVarChar
nvarchar_check = True
header_check = True # checks that the header has been passed
# if the data type is an Integer
if types[current_col] == 'Integer':
reader = csv.reader(csv_file)
# variable that will be used to prevent the header from being a part of the column
header_check = False
# variable that will be used to switch between each sql int type
int_check = 0
# restarts the file from the very start for each new string column
csv_file.seek(0)
for row in reader:
# if not the header
if header_check:
# We convert the current type of 'messytables.type' to an int so that we can write to it
row[current_col] = int(row[current_col])
# if the current int is between the minimum and maximum value of tinyint
if tinyint_min <= row[current_col] <= tinyint_max:
# if no other numbers in the column go past the same values
if int_check == 0:
# change name to TinyInt
types[current_col] = 'TinyInt'
if smallint_min <= row[current_col] < tinyint_min \
or tinyint_max < row[current_col] <= smallint_max:
# if no other numbers in the column go past the same values
if int_check <= 1:
# change name to 'SmallInt'
types[current_col] = 'SmallInt'
int_check = 1
if int_min <= row[current_col] < smallint_min \
or smallint_max < row[current_col] <= int_max:
# if no other numbers in the column go past the same values
if int_check <= 2:
# change name to 'Int'
types[current_col] = 'Int'
int_check = 2
if bigint_min <= row[current_col] <= int_min \
or int_max < row[current_col] <= bigint_max:
# change name to 'BigInt'
types[current_col] = 'BigInt'
# remain BigInt even if future numbers in column are smaller
int_check = 3
header_check = True # iterates through the column
# if the data type is 'Decimal'
if types[current_col] == 'Decimal':
reader = csv.reader(csv_file)
# variable that will be used to prevent the header from being a part of the column
header_check = False
# variable that will be used to switch between Real and Float
float_check = False
# restarts the file from the very start for each new string column
csv_file.seek(0)
for row in reader:
# if not the header
if header_check:
# We convert the current type of 'messytables.type' to a string so that we can write to it
row[current_col] = float(row[current_col])
# if current float in column is between these values
if real_min <= row[current_col] <= real_max:
# if no previous float in column has exceeded these boundaries
if not float_check:
# Change name to 'Real'
types[current_col] = 'Real'
if float_min <= row[current_col] < real_min or real_max < row[current_col] <= float_max:
# change name to 'Float'
types[current_col] = 'Float'
float_check = True
header_check = True # checks if header has been reached yet
# assigns each sql type to each header in a string
sql_names = f"{headers[current_col]} : {types[current_col]}"
# appends the header + type string into list
sql_list.append(sql_names)
# converts list into an array
sql_array = numpy.array(sql_list)
csv_file.close()
file_table.close()
# returns the array of sql types
return sql_array
except Exception:
# makes sure that if the sql types fails, rest of the functions still works
print("SQL Types Unavailable")
|
def check_name(name):
if str(name).isalpha():
return True
else:
return False
def check_mail(email):
if '@' in email:
return True
else:
return False
if __name__ == '__main__':
name = input('Please enter your name: ')
if check_name(name):
email = input('Please enter your mail: ')
if check_mail(email):
print('welcome')
else:
print('you input invalid mail')
else:
print('you input invalid name') |
import math
e = 2.71828
def fungsi(x):
x = float((e**x) - (4*x))
return x
def fungsiturunan(x):
x = float((e**x) - (4))
return x
x = float(input('Masukkan nilai awal = '))
error = float(input('Masukkan nilai error = '))
perulangan = int(input('Masukkan maksimal pengulangan = '))
iterasi = 0
selisih = error+1
while iterasi <= perulangan and selisih>error :
iterasi += 1
f_2 = x - (fungsi(x)/fungsiturunan(x))
selisih = math.fabs(f_2 - x)
x = f_2
print("Iterasi ke = ",iterasi,", x = ",f_2, ", f(",f_2,") = ",fungsi(f_2),", selisih = ",error)
if iterasi <= perulangan:
print("Perulangan Mencapai Batas Maksimal dengan hasil = ", f_2)
else :
print("Toleransi tidak terpenuhi")
|
For this challenge, you need to take a matrix as an input from the stdin , transpose it and print the resultant matrix to the stdout.
Input Format
A matrix is to be taken as input from stdin. On first line you need to tell that how many rows and columns your matrix need to have and these values should be separated by space. Below lines will represent the elements of the matrix where each line will represent the row of the matrix.
Constraints
1 < (n,m) < 100
Output Format
Print the resultant matrix to the stdout where each line should represent each row and values in the row should be separated by a space.
dim = list(map(int, input().split()))
m = dim[0]
n = dim[1]
matrix1 = []
for i in range(m):
matrix1.append(list(map(int, input().split())))
matrix = [ [ 0 for i in range(m) ] for j in range(n) ]
for i in range(m):
for j in range(n):
matrix[j][i] = matrix1[i][j]
for i in range(n):
if i == n-1:
print(" ".join(str(x) for x in matrix[i]), end = "")
else:
print(" ".join(str(x) for x in matrix[i]))
|
For this challenge, you need to take number of elements as input on one line and array elements as an input on another line and find the second largest array element and print that element to the stdout.
Input Format
In this challenge, you will take number of elements as input on one line and array elements which are space separated as input on another line.
Constraints
1 < = n < = 100000
1 < = a[i] < = 10^9
Output Format
You will print the second largest element to the stdout.
def main():
n = input()
array = input().split(" ")
array = map(int, array)
array1 = []
for i in array:
array1.append(int(i))
second_last = sorted(array1)[-2]
print(second_last, end = "")
main()
|
import multiprocessing
import ctypes
class SharedMemoryString(object):
'''
Shared Memory Value that lets you work with a mutable string
>>> shared_string = SharedMemoryString(
max_size=1024,
default='hello',
)
>>> with shared_string.get_lock():
... shared_string.set('New Value')
>>> with shared_string.get_lock():
... shared_string.get() == 'New Value'
'''
def __init__(self, max_size, default='', encoding=u'utf-8', lock=True):
'''
max_size: The max_size of the array in bytes. (Immutable)
default: Starting value for the string
encoding: encoding string as accepted by .encode() / .decode()
'''
self.max_size = max_size
self.encoding = encoding
# The shared data goes here
if lock is True:
self._lock = multiprocessing.RLock()
elif lock is not False:
self._lock = lock
else:
self._lock = None
self._stored_size = multiprocessing.RawValue(
ctypes.c_int,
0,
)
self._data = multiprocessing.RawArray(
ctypes.c_char,
max_size,
)
# For faster access
self._memory = memoryview(self._data)
with self._lock:
self.set(default)
def __len__(self):
'''
Returns the length of the currently stored string.
* Remember to lock the underlying data if you want consistency
'''
return self._stored_size.value
def __getitem__(self, slice_info):
'''
Supports slicing.
* Remember to lock the underlying data if you want consistency
'''
return bytes(
self._memory
# First we chop it to the "used" bytes
[:self._stored_size.value]
# Then we actually slice on that
[slice_info]
).decode(self.encoding)
def __setitem__(self, slice_info, value):
'''
Supports slice assignment, affects the underlying memory directly.
* Remember to lock the underlying data if you want consistency
This will ONLY affect only affect the currently used memory.
If you wish to write outside of those bounds use .resize() first
'''
if isinstance(slice_info, int):
self._data[slice_info] = value.encode(self.encoding)
return
elif slice_info.step is None or slice_info.step >= 0:
if slice_info.stop is None or slice_info.stop >= self._stored_size.value:
stop = self._stored_size.value
elif slice_info.stop < 0:
stop = max(self._stored_size.value - slice_info.stop, 0)
else:
stop = slice_info.stop
if slice_info.start is None or slice_info.start >= 0:
start = slice_info.start
else:
start = max(self._stored_size.value - slice_info.start, 0)
else:
# Reverse slice, our start is the actual stop
if slice_info.start is None or slice_info.start >= self._stored_size.value:
start = self._stored_size.value - 1
elif slice_info.start < 0:
start = max(self._stored_size.value - slice_info.start, 0)
else:
start = slice_info.start
if slice_info.stop is None or slice_info.stop >= 0:
stop = slice_info.stop
else:
stop = max(self._stored_size.value - slice_info.stop, 0)
data = value.encode(self.encoding)
(
self._data
# First we chop it to the "used" bytes
# [:self._stored_size.value]
# Then we actually slice on that
[start:stop:slice_info.step]
) = data
# (ctypes.c_char * len(data)).from_buffer(data)
def __iadd__(self, value):
'''
Adds an extra string at the end of the existing one
* If there isn't enough space, new data gets cut off
'''
value = value[:self.max_size - self._stored_size.value]
data = value.encode(self.encoding)
self._data[self._stored_size.value:self._stored_size.value + len(data)] = data
self._stored_size.value = self._stored_size.value + len(data)
return self
def resize(self, size=None):
'''
Changes the currently used size, without changing the data.
* Enlarging the size will not reset any trailing bytes
* Useful for using slice assignment to mess with out-of-bounds data
* Remember to lock the underlying data if you want consistency
This cannot change the max_size
'''
if size > self.max_size:
raise ValueError("SharedMemoryString Cannot resize past max-size")
elif size < 0:
raise ValueError("SharedMemoryString Cannot resize to a negative size")
self._stored_size.value = size
def set(self, value):
'''
Copies in a string value, replacing the current data
* If there isn't enough space, it gets cut off
* This won't zero out any remaining data
'''
value = value[:self.max_size]
data = value.encode(self.encoding)
self._data[:len(data)] = data
self._stored_size.value = len(data)
def get(self):
''' Gets the underlying string value '''
# Grab just the useful data
return bytes(self._memory[:self._stored_size.value]).decode(self.encoding)
def get_lock(self):
''' Returns the lock guarding this SharedMemory object '''
return self._lock
if __name__ == '__main__':
shared_data = SharedMemoryString(
max_size=16,
default='Hello',
encoding='ascii',
)
assert shared_data.get() == 'Hello', "Should respects `default` value"
assert len(shared_data) == 5, "`default` should set size"
shared_data.set('1234567890abcdef')
assert shared_data.get() == '1234567890abcdef', "Should allow full-data use"
assert len(shared_data) == 16, "Maxing should set size"
# --------------------------------------------------------------------------
# +=
shared_data.set('merge')
shared_data += ' me'
assert shared_data.get() == 'merge me', "+= appends data"
assert len(shared_data) == 8, "appending should update size"
# --------------------------------------------------------------------------
# Overflows
shared_data.set('1234567890abcdefg')
assert shared_data.get() == '1234567890abcdef', "Should throws out extra data"
assert len(shared_data) == 16, "Overflows shouldn't mess up the size"
shared_data += 'other'
assert shared_data.get() == '1234567890abcdef', "+= should throw out extra data"
assert len(shared_data) == 16, "Overflows shouldn't mess up the size"
shared_data.set('1234567890')
shared_data += '123456789'
assert shared_data.get() == '1234567890123456', "+= appends as much as it can"
assert len(shared_data) == 16, "Overflows shouldn't mess up the size"
over_shared = SharedMemoryString(
max_size=4,
default='apple',
encoding='ascii',
)
assert over_shared.get() == 'appl', "default should also check for overflow"
assert len(over_shared) == 4, "Overflows shouldn't mess up the size"
# --------------------------------------------------------------------------
# Resizing
shared_data.set('wonderfull')
assert len(shared_data) == 10, "Assigning should change size"
shared_data.resize(5)
assert shared_data.get() == 'wonde', "Resizing should lop off data"
assert len(shared_data) == 5, "Resizing should change length"
shared_data.resize(7)
assert shared_data.get() == 'wonderf', "Resizing should bring back data"
assert len(shared_data) == 7, "Resizing should change length"
shared_data.set('hello')
try:
shared_data.resize(1024)
except ValueError:
pass
else:
assert False, "Resizing past max-size should raise an error"
assert len(shared_data) == 5, "bad resizing shouldn't mess with size"
try:
shared_data.resize(-1)
except ValueError:
pass
else:
assert False, "Resizing to negative should raise an error"
assert len(shared_data) == 5, "bad resizing shouldn't mess with size"
# --------------------------------------------------------------------------
# Slicing
shared_data.set('1234567890abcdef')
assert shared_data[:] == '1234567890abcdef'
assert shared_data[:5] == '12345'
assert shared_data[3:] == '4567890abcdef'
assert shared_data[:-1] == '1234567890abcde'
assert shared_data[:-10] == '123456'
assert shared_data[-12:-10] == '56'
assert shared_data[-1:-10:-1] == 'fedcba098'
assert shared_data[3:1:-1] == '43'
assert shared_data[::-2] == 'fdb08642'
assert shared_data[::2] == '13579ace'
# Slicing should respect the current size
shared_data.set('apple')
assert shared_data[:] == 'apple'
assert shared_data[3:] == 'le'
assert shared_data[3:10000] == 'le'
assert shared_data[::2] == 'ape'
assert shared_data[::-1] == 'elppa'
assert shared_data[:-10:] == ''
assert shared_data[:-2:] == 'app'
assert shared_data[-3::] == 'ple'
assert shared_data[-20:-3:] == 'ap'
assert shared_data[3:1:-1] == 'lp'
# Assignment slicing
shared_data[:] = 'cheer'
assert shared_data.get() == 'cheer'
assert len(shared_data) == 5, "assign shouldn't mess with size"
shared_data[0] = 's'
assert shared_data.get() == 'sheer'
assert len(shared_data) == 5, "assign shouldn't mess with size"
try:
shared_data[:] = 'overflow'
shared_data.resize(1024)
except ValueError:
pass
else:
assert False, "Assigning past the size should error out"
try:
shared_data[1:3] = 'a'
shared_data.resize(1024)
except ValueError:
pass
else:
assert False, "Assigning not enough characters should error out"
shared_data[:2:-1] = 'aa'
assert shared_data.get() == 'sheaa'
shared_data[:2:] = 'aa'
assert shared_data.get() == 'aaeaa'
shared_data[::-1] = 'elppa'
assert shared_data.get() == 'apple'
shared_data[::-2] = '___'
assert shared_data.get() == '_p_l_'
shared_data[1::2] = '..'
assert shared_data.get() == '_._._'
shared_data.resize(16)
assert shared_data.get() == '_._._67890abcdef', "Old data shouldn't have been affected"
shared_data.set('12345')
shared_data[10] = 'a'
assert shared_data.get() == '12345', 'You can assign past the array'
import time
def _test_async():
def reader(shared):
counter = 0
while True:
counter += 1
with shared.get_lock():
print(shared[1:])
# print(shared.get())
time.sleep(0.01)
def writer(shared):
counter = 0
while True:
with shared.get_lock():
# shared[6:] = '{:<2}'.format(counter % 100)
shared.set('Hello ')
shared += '{}'.format(counter % 100)
counter += 1
time.sleep(0.01)
shared_data = SharedMemoryString(
max_size=1024,
default='Hello ',
encoding='ascii',
)
read_process = multiprocessing.Process(
target=reader,
kwargs={
'shared': shared_data,
},
)
read_process.start()
time.sleep(0.2)
write_process = multiprocessing.Process(
target=writer,
kwargs={
'shared': shared_data,
},
)
write_process.start()
read_process.join()
write_process.join()
|
# Demonstrate the usage of namdtuple objects
import collections
def main():
# TODO: create a Point namedtuple
Point = collections.namedtuple("Point", "a b")
point1 = Point(3, 4)
point2 = Point("alon", "bar")
print(point1, point2)
print(point2.b)
# TODO: use _replace to create a new instance
point1 = point1._replace(a = 30)
print(point1)
if __name__ == "__main__":
main()
|
class Solution:
def isValid(self, s: str) -> bool:
if s == "":
return True
stack = []
pairs = {"(": ")", "{": "}", "[": "]"}
for char in s:
if char in pairs:
stack.append(char)
else:
if not stack:
return False
else:
last = stack.pop()
if pairs[last] != char:
return False
if stack:
return False
else:
return True
|
#!python
from trie import Trie, TrieNode
import unittest
class TrieTest(unittest.TestCase):
def test_init(self):
tree = Trie()
assert tree.size == 0
assert tree.is_empty() is True
tree.insert('hello')
tree.search('hello') == 'hello'
tree.search('state') == None
def test_init_with_list(self):
tree = Trie([('North Dakota'), ('North Carolina')])
assert tree.height() == 14
assert tree.size == 20
assert tree.root.children[hash('n') % 26].word == 'North Dakota'
assert tree.root.children[hash('n') % 26].children[hash('o') % 26].children[hash('r') % 26].word == 'North Dakota'
assert tree.is_empty() is False
def test_search(self):
tree = Trie([('cat'), ('catholic'), ('catch')])
assert tree.search('ca') == 'cat'
tree.insert('cup')
assert tree.search('cath') == 'catholic'
assert tree.search('cu') == 'cup'
tree.insert('catch')
print(tree.search('catch'))
assert tree.search('catch') == 'catch'
tree.insert('catholicism')
assert tree.search('catholic') == 'catholic'
assert tree.search('zoo') == None
|
name = input("Enter your name: ")
number = input("Enter how many times you want to see it: ")
print (str(name) * int(number))
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
device_ids = [0, 1]
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
# self.conv1 = nn.Conv2d(1, 32, 5)
self.features = nn.Sequential(
nn.Conv2d(1,32,9), nn.ELU(),
nn.MaxPool2d((2,2)), nn.Dropout(p=0.1),
nn.Conv2d(32,64,7), nn.ELU(),
nn.MaxPool2d((2,2)), nn.Dropout(p=0.2),
nn.Conv2d(64,128,5), nn.ELU(),
nn.MaxPool2d((2,2)), nn.Dropout(p=0.3),
nn.Conv2d(128,256,3), nn.ELU(),
nn.MaxPool2d((2,2)), nn.Dropout(p=0.4)
)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
self.classifier = nn.Sequential(
nn.Linear(256 * 10 * 10, 136 * 10), nn.ELU(),nn.Dropout(p=0.5),
nn.Linear(136 * 10, 136 * 10), nn.ReLU(),nn.Dropout(p=0.6),
nn.Linear(136 * 10, 136)
)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
# a modified x, having gone through all the layers of your model, should be returned
return x
|
'''
this program is used to check if postal codes are valid and sees where
the postal codes come from
'''
#importing functions
from postal import formatCode
from postal import getProvince
from postal import isValid
'''
formatted = formatCode("m 5P1j 4")
print(formatted)
province = getProvince("M5P 1J4")
print(province)
province = getProvince("D5P 1J4")
print(province)
print(isValid("M5R 1J4"))
print(isValid(" m 5 P 1 j 4"))
print(isValid("M5P1J"))
print(isValid("m5p114"))
'''
#helper function to help check if postal codes are valid
def helper(code):
if isValid(formatCode(code)) == False:
print("'" + code + "' is improper code")
return
print("'" + code + "' properly formatted is " + formatCode(code))
print("it belongs to " + getProvince(formatCode(code)))
#test cases
helper(" ")
helper("")
helper("M5M q1j")
helper("M4M1L4")
helper("1K2 L4M")
helper("m5M 1p2")
helper("t2t 4 f2")
helper("D2E 1l4") |
'''This program is used to create a pyramid made out of the desired symbol and height'''
#this function is used to create the list of triangles and then print it
def createTriangularNumber(termNumber, symbol):
#Establishing the variables required.
triangleNumber = 1
triangleList = []
#loops until there are as many triangles as desired
while triangleNumber <= termNumber:
#creating local variables for each round of triangle making
triangleForThisRound = ""
numberOfSymbolsThisRound = 1
#this loops actually creates the triangle
while numberOfSymbolsThisRound <= triangleNumber:
thisRoundAddition = " "*(triangleNumber-numberOfSymbolsThisRound) + (symbol + " ")*numberOfSymbolsThisRound + "\n"
triangleForThisRound += thisRoundAddition
numberOfSymbolsThisRound += 1
#adds an additional triangle to the entire list
triangleNumber += 1
triangleList.append(triangleForThisRound)
#loop to print out all the triangles
index = 0
while index < len(triangleList):
print(triangleList[index])
index += 1
#activating the program
createTriangularNumber(4, "*") |
def reverse(word):
word = word.lower()
reversedWord = ""
index = len(word) - 1
while index != -1:
if word[index] not in ["a","e","i","o","u"]:
reversedWord += word[index]
index -= 1
print(reversedWord)
reverse("Ihunderbolt") |
'''Reads a bunch of data from a text file. Allows the user to input a upper and lower bound
and takes all the numbers in the text file that meets though criteria. After retreiving
those numbers, it will return the average of all the numbers in the specified range
'''
#function that allows the user to input their desired file, and the boundaries they want
def fileReader(file, low, high):
#checks if the ranges entered are valid
if low >= high:
print("Your specified ranges are not valid")
exit()
#opens the file, establishes some variables and starts reading the file
fileObject = open(file + ".txt",'r')
line = fileObject.readline()
sumOfNumbers = 0
numbersAdded = 0
#while loops that continues running until the end of the txt file
while line != "":
#checks if the line fits inside the specified ranges
if float(line) >= low and float(line) <= high:
#some operations that helsp me calculate the average of the numbers
sumOfNumbers += float(line)
numbersAdded += 1
print("Data point: " + line + " added")
#allows the loop to check the next line
line = fileObject.readline()
#prints out the calculated average and the results of the calculator
print("The data in the range (",low,",",high,") have an average:", round(sumOfNumbers/numbersAdded,2))
#closes the file
fileObject.close()
#allows the user to input their file name that they want to access and the boundaries
file = input("Enter file name: ")
low = float(input("Enter the low boundary: "))
high = float(input("Enter the high boundary: "))
#starts up the function with the specified variables
fileReader(file,low,high) |
'''A program to allow the user to input a wavelength in nanometers
and then have a program output the corresponding colour in the
visible spectrum
'''
#import the library to change the colour of the text
from colorama import init, Fore, Back
init()
#function that accepts a wavelength number and then outputs the corresponding colour
def getColor(number):
if number < 380:
return "unknown"
elif number < 450:
return "Violet"
elif number < 495:
return "Blue"
elif number < 570:
return "Green"
elif number < 590:
return "Yellow"
elif number < 620:
return "Orange"
elif number < 750:
return "Red"
else:
return "unknown"
#helps me make the last colour of the output the corresponding color to make it easier for the user to understand the output
def colorHelper(colour):
if colour == "unknown":
print("The colour for the light with lambda = ", waveLength, "nm is", Back.WHITE, getColor(waveLength))
elif colour == "Violet":
print("The colour for the light with lambda = ", waveLength, "nm is", Fore.MAGENTA, getColor(waveLength))
elif colour == "Blue":
print("The colour for the light with lambda = ", waveLength, "nm is", Fore.BLUE, getColor(waveLength))
elif colour == "Green":
print("The colour for the light with lambda = ", waveLength, "nm is", Fore.GREEN, getColor(waveLength))
elif colour == "Yellow":
print("The colour for the light with lambda = ", waveLength, "nm is", Fore.YELLOW, getColor(waveLength))
elif colour == "Orange":
print("The colour for the light with lambda = ", waveLength, "nm is", Back.YELLOW, getColor(waveLength))
elif colour == "Red":
print("The colour for the light with lambda = ", waveLength, "nm is", Fore.RED, getColor(waveLength))
#allows the user to enter the wavelength they want to calculate colour with
waveLength = float(input("Enter the wave length: "))
#activated the helper to allows for the answer to be printed
colorHelper(getColor(waveLength)) |
'''
This program is used to allow a user to create a file and write stuff in the file
'''
#allows the user to input the name that they want to name the new file
fileName = input("Enter the file name: ")
#allows the user to input a line of text to put into the file
textInFile = input("Enter a one line text: ")
#add the ".txt" so that the user's file name works
fileNameWithExtension = fileName + ".txt"
#Create a file object that the user will be accessing
fileObject = open(fileNameWithExtension,'w')
#write the string from the user into the beginning of the file
fileObject.write(textInFile)
#close the file
fileObject.close()
print("The content \"" + textInFile +"\",\nhas been successfully saved in the file " + fileNameWithExtension) |
'''
Allows the user to input variables to solve a linear quadratic system
'''
#Function to more easily check the value of a variable and will output an error if the variable is invalid
def inputChecker(letter):
value = input("Enter the value of parameter " + letter + ": ")
if value == "":
print("The values of your parameter are invalid!")
exit()
return float(value)
#easy way for the program to find the y value after finding valid x values
def yValueSolver(m,d,x):
return m*x + d
#prints out the header for the user
print("This calculator solves a linear quadratic system.\
\ny=ax^2+bx+c\
\ny=mx+d")
#allows the user to input a
a = input("Enter the value of parameter a: ")
#checks if a is valid and then gives an error if it isn't
if a == "0" or a == "":
print("The values of your parameter are invalid!")
exit()
#allows the user to input values
b = inputChecker("b")
c = inputChecker("c")
m = inputChecker("m")
d = inputChecker("d")
#Creating new variables so I can use the Quadratic formula with these numbers
letterA = float(a)
letterB = b - m
letterC = c - d
#Creating the discriminant variable to make it clear what I am doing and because I use this variable often
discriminant = letterB**2 - 4 * letterA * letterC
#When the discriminant is below 0, there are no solutions for the system and the program replies as such
if discriminant < 0:
print("There is no solution for this linear quadratic system")
exit()
#when the discriminate is 0, there is only one answer. This if loop helps the program find that single point
if discriminant == 0:
solutionX = -letterB/2/letterA
solutionY = yValueSolver(m,d,solutionX)
print("The solution of your linear quadratic system is: \
\n(x , y) = (" + str(solutionX) + " , " + str(solutionY) + ")")
#in other words, whenever the discriminant is positive, there are two answers to the system and this loop finds it
else:
solutionX1 = (-letterB + discriminant**0.5)/2/letterA
solutionY1 = yValueSolver(m,d,solutionX1)
solutionX2 = (-letterB - discriminant**0.5)/2/letterA
solutionY2 = yValueSolver(m,d,solutionX2)
print("The solution of your linear quadratic system are:" + \
"\n(x1 , y1) = (" + str(solutionX1) + " , " + str(solutionY1) + ")" + \
"\n(x2 , y2) = (" + str(solutionX2) + " , " + str(solutionY2) + ")")
|
"""
Course: CSE 251
Lesson Week: 02 - Team Activity
File: team.py
Author: Brother Comeau
Purpose: Playing Card API calls
"""
from datetime import datetime, timedelta
import threading
import requests
import json
# # Include cse 251 common Python files
# import os, sys
# sys.path.append('../../code')
# from cse251 import *
class Request_thread(threading.Thread):
def __init__(self, url):
# Call the Thread class's init function
threading.Thread.__init__(self)
self.url = url
self.response = {}
def run(self):
response = requests.get(self.url)
# Check the status code to see if the request succeeded.
if response.status_code == 200:
self.response = response.json()
else:
print('RESPONSE = ', response.status_code)
class Deck:
def __init__(self, deck_id):
self.id = deck_id
self.reshuffle()
self.remaining = 52
def reshuffle(self):
req = Request_thread(rf'https://deckofcardsapi.com/api/deck/{self.id}/shuffle/')
req.start()
req.join()
def draw_card(self):
req = Request_thread(rf'https://deckofcardsapi.com/api/deck/{self.id}/draw/')
req.start()
req.join()
if req.response != {}:
self.remaining = req.response['remaining']
return req.response['cards'][0]['code']
else:
return ''
def cards_remaining(self):
return self.remaining
def draw_endless(self):
if self.remaining <= 0:
self.reshuffle()
return self.draw_card()
if __name__ == '__main__':
# TODO - run the program team_get_deck_id.py and insert
# the deck ID here. You only need to run the
# team_get_deck_id.py program once. You can have
# multiple decks if you need them
deck_id = 'ENTER ID HERE'
deck = Deck(deck_id)
for i in range(55):
card = deck.draw_endless()
print(i, card, flush=True)
print()
|
"""
Course: CSE 251
Lesson Week: 06
File: assignment.py
Author: <Your name here>
Purpose: Processing Plant
Instructions:
- Implement the classes to allow gifts to be created.
"""
import random
import multiprocessing as mp
import os.path
import time
# Include cse 251 common Python files - Don't change
import os, sys
sys.path.append('../../code') # Do not change the path.
from cse251 import *
CONTROL_FILENAME = 'settings.txt'
BOXES_FILENAME = 'boxes.txt'
# Settings consts
MARBLE_COUNT = 'marble-count'
CREATOR_DELAY = 'creator-delay'
BAG_COUNT = 'bag-count'
BAGGER_DELAY = 'bagger-delay'
ASSEMBLER_DELAY = 'assembler-delay'
WRAPPER_DELAY = 'wrapper-delay'
# No Global variables
class Bag():
""" bag of marbles - Don't change for the 93% """
def __init__(self):
self.items = []
def add(self, marble):
self.items.append(marble)
def get_size(self):
return len(self.items)
def __str__(self):
return str(self.items)
class Gift():
""" Gift of a large marble and a bag of marbles - Don't change for the 93% """
def __init__(self, large_marble, marbles):
self.large_marble = large_marble
self.marbles = marbles
def __str__(self):
marbles = str(self.marbles)
marbles = marbles.replace("'", "")
return f'Large marble: {self.large_marble}, marbles: {marbles[1:-1]}'
class Marble_Creator(mp.Process):
""" This class "creates" marbles and sends them to the bagger """
colors = ('Gold', 'Orange Peel', 'Purple Plum', 'Blue', 'Neon Silver',
'Tuscan Brown', 'La Salle Green', 'Spanish Orange', 'Pale Goldenrod', 'Orange Soda',
'Maximum Purple', 'Neon Pink', 'Light Orchid', 'Russian Violet', 'Sheen Green',
'Isabelline', 'Ruby', 'Emerald', 'Middle Red Purple', 'Royal Orange', 'Big Dip O’ruby',
'Dark Fuchsia', 'Slate Blue', 'Neon Dark Green', 'Sage', 'Pale Taupe', 'Silver Pink',
'Stop Red', 'Eerie Black', 'Indigo', 'Ivory', 'Granny Smith Apple',
'Maximum Blue', 'Pale Cerulean', 'Vegas Gold', 'Mulberry', 'Mango Tango',
'Fiery Rose', 'Mode Beige', 'Platinum', 'Lilac Luster', 'Duke Blue', 'Candy Pink',
'Maximum Violet', 'Spanish Carmine', 'Antique Brass', 'Pale Plum', 'Dark Moss Green',
'Mint Cream', 'Shandy', 'Cotton Candy', 'Beaver', 'Rose Quartz', 'Purple',
'Almond', 'Zomp', 'Middle Green Yellow', 'Auburn', 'Chinese Red', 'Cobalt Blue',
'Lumber', 'Honeydew', 'Icterine', 'Golden Yellow', 'Silver Chalice', 'Lavender Blue',
'Outrageous Orange', 'Spanish Pink', 'Liver Chestnut', 'Mimi Pink', 'Royal Red', 'Arylide Yellow',
'Rose Dust', 'Terra Cotta', 'Lemon Lime', 'Bistre Brown', 'Venetian Red', 'Brink Pink',
'Russian Green', 'Blue Bell', 'Green', 'Black Coral', 'Thulian Pink',
'Safety Yellow', 'White Smoke', 'Pastel Gray', 'Orange Soda', 'Lavender Purple',
'Brown', 'Gold', 'Blue-Green', 'Antique Bronze', 'Mint Green', 'Royal Blue',
'Light Orange', 'Pastel Blue', 'Middle Green')
def __init__(self):
mp.Process.__init__(self)
# TODO Add any arguments and variables here
def run(self):
'''
for each marble:
send the marble (one at a time) to the bagger
- A marble is a random name from the colors list above
sleep the required amount
Let the bagger know there are no more marbles
'''
pass
class Bagger(mp.Process):
""" Receives marbles from the marble creator, then there are enough
marbles, the bag of marbles are sent to the assembler """
def __init__(self):
mp.Process.__init__(self)
# TODO Add any arguments and variables here
def run(self):
'''
while there are marbles to process
collect enough marbles for a bag
send the bag to the assembler
sleep the required amount
tell the assembler that there are no more bags
'''
class Assembler(mp.Process):
""" Take the set of marbles and create a gift from them.
Sends the completed gift to the wrapper """
marble_names = ('Lucky', 'Spinner', 'Sure Shot', 'The Boss', 'Winner', '5-Star', 'Hercules', 'Apollo', 'Zeus')
def __init__(self):
mp.Process.__init__(self)
# TODO Add any arguments and variables here
def run(self):
'''
while there are bags to process
create a gift with a large marble (random from the name list) and the bag of marbles
send the gift to the wrapper
sleep the required amount
tell the wrapper that there are no more gifts
'''
class Wrapper(mp.Process):
""" Takes created gifts and wraps them by placing them in the boxes file """
def __init__(self):
mp.Process.__init__(self)
# TODO Add any arguments and variables here
def run(self):
'''
open file for writing
while there are gifts to process
save gift to the file with the current time
sleep the required amount
'''
def display_final_boxes(filename, log):
""" Display the final boxes file to the log file - Don't change """
if os.path.exists(filename):
log.write(f'Contents of {filename}')
with open(filename) as boxes_file:
for line in boxes_file:
log.write(line.strip())
else:
log.write_error(f'The file {filename} doesn\'t exist. No boxes were created.')
def main():
""" Main function """
log = Log(show_terminal=True)
log.start_timer()
# Load settings file
settings = load_json_file(CONTROL_FILENAME)
if settings == {}:
log.write_error(f'Problem reading in settings file: {CONTROL_FILENAME}')
return
log.write(f'Marble count = {settings[MARBLE_COUNT]}')
log.write(f'settings["creator-delay"] = {settings[CREATOR_DELAY]}')
log.write(f'settings["bag-count"] = {settings[BAG_COUNT]}')
log.write(f'settings["bagger-delay"] = {settings[BAGGER_DELAY]}')
log.write(f'settings["assembler-delay"] = {settings[ASSEMBLER_DELAY]}')
log.write(f'settings["wrapper-delay"] = {settings[WRAPPER_DELAY]}')
# TODO: create Pipes between creator -> bagger -> assembler -> wrapper
# TODO create variable to be used to count the number of gifts
# delete final boxes file
if os.path.exists(BOXES_FILENAME):
os.remove(BOXES_FILENAME)
log.write('Create the processes')
# TODO Create the processes (ie., classes above)
log.write('Starting the processes')
# TODO add code here
log.write('Waiting for processes to finish')
# TODO add code here
display_final_boxes(BOXES_FILENAME, log)
# TODO Log the number of gifts created.
if __name__ == '__main__':
main()
|
"""
Course: CSE 251
Lesson Week: 05
File: assignment.py
Author: <Your name>
Purpose: Assignment 05 - Factories and Dealers
Instructions:
- Read the comments in the following code.
- Implement your code where the TODO comments are found.
- No global variables, all data must be passed to the objects.
- Only the included/imported packages are allowed.
- Thread/process pools are not allowed
- You are not allowed to use the normal Python Queue object. You must use Queue251.
- the shared queue between the threads that are used to hold the Car objects
can not be greater than MAX_QUEUE_SIZE
"""
from datetime import datetime, timedelta
import time
import threading
import random
# Include cse 251 common Python files
import os, sys
sys.path.append('../../code') # Do not change the path.
from cse251 import *
# Global Consts
MAX_QUEUE_SIZE = 10
SLEEP_REDUCE_FACTOR = 5000
# NO GLOBAL VARIABLES!
class Car():
""" This is the Car class that will be created by the factories """
# Class Variables
car_makes = ('Ford', 'Chevrolet', 'Dodge', 'Fiat', 'Volvo', 'Infiniti', 'Jeep', 'Subaru',
'Buick', 'Volkswagen', 'Chrysler', 'Smart', 'Nissan', 'Toyota', 'Lexus',
'Mitsubishi', 'Mazda', 'Hyundai', 'Kia', 'Acura', 'Honda')
car_models = ('A1', 'M1', 'XOX', 'XL', 'XLS', 'XLE' ,'Super' ,'Tall' ,'Flat', 'Middle', 'Round',
'A2', 'M1X', 'SE', 'SXE', 'MM', 'Charger', 'Grand', 'Viper', 'F150', 'Town', 'Ranger',
'G35', 'Titan', 'M5', 'GX', 'Sport', 'RX')
car_years = [i for i in range(1990, datetime.now().year)]
def __init__(self):
# Make a random car
self.model = random.choice(Car.car_models)
self.make = random.choice(Car.car_makes)
self.year = random.choice(Car.car_years)
# Sleep a little. Last statement in this for loop - don't change
time.sleep(random.random() / (SLEEP_REDUCE_FACTOR))
# Display the car that has was just created in the terminal
self.display()
def display(self):
print(f'{self.make} {self.model}, {self.year}')
class Queue251():
""" This is the queue object to use for this assignment. Do not modify!! """
def __init__(self):
self.items = []
self.max_size = 0
def get_max_size(self):
return self.max_size
def put(self, item):
self.items.append(item)
if len(self.items) > self.max_size:
self.max_size = len(self.items)
def get(self):
return self.items.pop(0)
class Factory(threading.Thread):
""" This is a factory. It will create cars and place them on the car queue """
def __init__(self):
self.cars_to_produce = random.randint(200, 300) # Don't change
def run(self):
# TODO produce the cars, the send them to the dealerships
# TODO wait until all of the factories are finished producing cars
# TODO "Wake up/signal" the dealerships one more time. Select one factory to do this
pass
class Dealer(threading.Thread):
""" This is a dealer that receives cars """
def __init__(self):
pass
def run(self):
while True:
# TODO handle a car
# Sleep a little - don't change. This is the last line of the loop
time.sleep(random.random() / (SLEEP_REDUCE_FACTOR + 0))
def run_production(factory_count, dealer_count):
""" This function will do a production run with the number of
factories and dealerships passed in as arguments.
"""
# TODO Create semaphore(s)
# TODO Create queue
# TODO Create lock(s)
# TODO Create barrier(s)
# This is used to track the number of cars receives by each dealer
dealer_stats = list([0] * dealer_count)
# TODO create your factories, each factory will create CARS_TO_CREATE_PER_FACTORY
# TODO create your dealerships
log.start_timer()
# TODO Start all dealerships
time.sleep(1) # make sure all dealers have time to start
# TODO Start all factories
# TODO Wait for factories and dealerships to complete
run_time = log.stop_timer(f'{sum(dealer_stats)} cars have been created')
# This function must return the following - Don't change!
# factory_stats: is a list of the number of cars produced by each factory.
# collect this information after the factories are finished.
return (run_time, car_queue.get_max_size(), dealer_stats, factory_stats)
def main(log):
""" Main function - DO NOT CHANGE! """
runs = [(1, 1), (1, 2), (2, 1), (2, 2), (2, 5), (5, 2), (10, 10)]
for factories, dealerships in runs:
run_time, max_queue_size, dealer_stats, factory_stats = run_production(factories, dealerships)
log.write(f'Factories : {factories}')
log.write(f'Dealerships : {dealerships}')
log.write(f'Run Time : {run_time:.4f}')
log.write(f'Max queue size : {max_queue_size}')
log.write(f'Factor Stats : {factory_stats}')
log.write(f'Dealer Stats : {dealer_stats}')
log.write('')
# The number of cars produces needs to match the cars sold
assert sum(dealer_stats) == sum(factory_stats)
if __name__ == '__main__':
log = Log(show_terminal=True)
main(log)
|
def Color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (red << 16) | (green << 8) | blue
class _LED_Data(object):
"""Wrapper class which makes a SWIG LED color data array look and feel like
a Python list of integers.
"""
def __init__(self, size):
self.size = size
self.data = [0 for _ in range(size)]
def __getitem__(self, pos):
"""Return the 24-bit RGB color value at the provided position or slice
of positions.
"""
# Handle if a slice of positions are passed in by grabbing all the values
# and returning them in a list.
if isinstance(pos, slice):
return [self.data[n] for n in range(*pos.indices(self.size))]
# Else assume the passed in value is a number to the position.
else:
return self.data[pos]
def __setitem__(self, pos, value):
"""Set the 24-bit RGB color value at the provided position or slice of
positions.
"""
# Handle if a slice of positions are passed in by setting the appropriate
# LED data values to the provided values.
if isinstance(pos, slice):
index = 0
for n in range(*pos.indices(self.size)):
self.data[n] = value[index]
index += 1
# Else assume the passed in value is a number to the position.
else:
self.data[pos] = value
return value
def __str__(self) -> str:
return "".join(str(v and 1 or "-") for v in self.data)
class PixelStrip(object):
def __init__(self, num, pin, freq_hz=800000, dma=10, invert=False,
brightness=255, channel=0, strip_type=None, gamma=None):
"""Class to represent a SK6812/WS281x LED display. Num should be the
number of pixels in the display, and pin should be the GPIO pin connected
to the display signal line (must be a PWM pin like 18!). Optional
parameters are freq, the frequency of the display signal in hertz (default
800khz), dma, the DMA channel to use (default 10), invert, a boolean
specifying if the signal line should be inverted (default False), and
channel, the PWM channel to use (defaults to 0).
"""
# Grab the led data array.
self._led_data = _LED_Data(num)
self._length = num
# Set a has inited flag
self._is_initialized = False
self.brightness = brightness
def setGamma(self, gamma):
assert self._is_initialized
if type(gamma) is list and len(gamma) == 256:
self._gamma = gamma
def begin(self):
"""Initialize library, must be called once before other functions are
called.
"""
self._is_initialized = True
def show(self):
"""Update the display with the data from the LED buffer."""
assert self._is_initialized
def setPixelColor(self, n, color):
"""Set LED at position n to the provided 24-bit color value (in RGB order).
"""
assert self._is_initialized
self._led_data[n] = color
def setPixelColorRGB(self, n, red, green, blue, white=0):
"""Set LED at position n to the provided red, green, and blue color.
Each color component should be a value from 0 to 255 (where 0 is the
lowest intensity and 255 is the highest intensity).
"""
assert self._is_initialized
self.setPixelColor(n, Color(red, green, blue, white))
def getBrightness(self):
assert self._is_initialized
return self.brightness
def setBrightness(self, brightness):
"""Scale each LED in the buffer by the provided brightness. A brightness
of 0 is the darkest and 255 is the brightest.
"""
assert self._is_initialized
self.brightness = brightness
def getPixels(self):
"""Return an object which allows access to the LED display data as if
it were a sequence of 24-bit RGB values.
"""
assert self._is_initialized
return self._led_data
def numPixels(self):
"""Return the number of pixels in the display."""
assert self._is_initialized
return self._length
def getPixelColor(self, n):
"""Get the 24-bit RGB color value for the LED at position n."""
assert self._is_initialized
return self._led_data[n]
def getPixelColorRGB(self, n):
assert self._is_initialized
def c():
return None
setattr(c, 'r', self._led_data[n] >> 16 & 0xff)
setattr(c, 'g', self._led_data[n] >> 8 & 0xff)
setattr(c, 'b', self._led_data[n] & 0xff)
return c
# Shim for back-compatibility
class Adafruit_NeoPixel(PixelStrip):
pass
|
# Calculating pi to the nth decimal using the Madhava-Leibniz Series
from math import sqrt
print "This program can approximate pi to up to 10 decimal places."
decimal_places = int(raw_input("Enter the number of decimal places for pi: "))
if decimal_places > 10:
raise RuntimeError("This program approximates pi to up to and including 10 decimal places.")
def madhava_leibniz(n):
total = 0
for i in range(n+10):
total += ((-1./3.)**i)/(2.*i+1)
#print total
return sqrt(12) * total
print "Pi to %d decimal places is %.10f." % (decimal_places, madhava_leibniz(decimal_places)) |
from collections import OrderedDict
class LRU_Cache:
def __init__(self, capacity = 5):
assert capacity >= 1, "Capacity should be at least 1."
self.dict = OrderedDict()
self.capacity = capacity
self.size = 0
def get(self, key):
if self.dict.get(key):
self.dict.move_to_end(key)
return self.dict.get(key)
else:
return -1
def set(self, key, value):
if self.dict.get(key):
self.dict[key] = value
self.dict.move_to_end(key)
else:
if self.size < self.capacity:
self.dict[key] = value
self.size += 1
else:
self.dict.popitem(last=False)
self.dict[key] = value
test1_cache = LRU_Cache(5)
test1_cache.set(1, 1)
test1_cache.set(2, 2)
test1_cache.set(3, 3)
test1_cache.set(4, 4)
print(test1_cache.get(1)) # returns 1
print(test1_cache.get(2)) # returns 2
print(test1_cache.get(9)) # returns -1 because 9 is not present in the cache
test1_cache.set(5, 5)
test1_cache.set(6, 6)
print(test1_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry
test2_cache = LRU_Cache(1)
test2_cache.set(1, 1)
test2_cache.set(2, 2)
print(test2_cache.get(1)) # returns -1 because the cache reached it's capacity and 1 was the least recently used entry
print(test2_cache.get(2)) # returns 2
test3_cache = LRU_Cache(5)
test3_cache.set(1, 1)
print(test3_cache.get(2)) # returns -1
test3_cache.set(1, 11111)
print(test3_cache.get(1)) # overriding a value, returns 11111
test3_cache = LRU_Cache(0) # gives an error, because cache should has at least capacity of 1.
|
class Node:
def __init__(self, data = None):
self.data = data
self.left = None
self.right = None
self.parent = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self,item):
if self.root == None:
self.root = Node(item)
else:
self._insert(item, self.root)
def _insert(self, item, cur):
if item < cur.data:
if cur.left == None:
cur.left = Node(item)
cur.left.parent = cur
else:
self._insert(item, cur.left)
elif item > cur.data:
if cur.right == None:
cur.right = Node(item)
cur.right.parent = cur
else:
self._insert(item, cur.right)
else:
print("Node '" + str(item) + "' already exists")
def view(self):
if self.root != None:
self._view(self.root)
def _view(self, cur):
if cur != None:
self._view(cur.left)
print(str(cur.data))
self._view(cur.right)
def height(self):
if self.root != None: #For Leetcode this was just root
return self._height(self.root, 0) #For Leetcode this was just root
else:
return 0
def _height(self, cur, cur_height):
if cur == None: return cur_height #For Leetcode this remained just cur
left_height = self._height(cur.left, cur_height + 1)
right_height = self._height(cur.right, cur_height + 1)
return max(left_height, right_height)
def find(self, item):
if self.root != None:
return self._find(item, self.root)
else:
return None
def _find(self, item, cur):
if item == cur.data:
return cur.data
elif item < cur.data and cur.left != None:
return self._find(item, cur.left)
elif item > cur.data and cur.right != None:
return self._find(item, cur.right)
def search(self, item):
if self.root != None:
return self._search(item, self.root)
else:
return False
def _search(self, item, cur):
if item == cur.data:
return True
elif item < cur.data and cur.left != None:
return self._search(item, cur.left)
elif item > cur.data and cur.right != None:
return self._search(item, cur.right)
return False
tree = BinaryTree()
tree.insert(10)
tree.insert(2)
tree.insert(8)
tree.insert(4)
tree.insert(6)
tree.insert(99)
tree.insert(5)
print("The following is the ordered print out:")
tree.view()
tree.insert(2) # Prexisiting
print("Tree height is: " + str(tree.height()))
print("Looking for node '5', found: " + str(tree.find(5)))
print("Looking for node '11', found: " + str(tree.find(11)))
print("Is '5' in the list? " + str(tree.search(5)))
print("Is '11' in the list? " + str(tree.search(11)))
|
class SelectionSort:
def ascending(self, array):
sortedArray = []
while array != []:
lowest = array.pop(self.getLowest(array))
sortedArray.append(lowest)
print(sortedArray)
def getLowest(self, array):
lowest = array[0]
for i in array:
if i < lowest:
lowest = i
return array.index(lowest)
sort = SelectionSort()
array = [6,4,2,8,40,0,5,9,1]
sort.ascending(array) |
def reverseWords(string):
array = string.split()
reverse = " ".join(array[::-1])
return(reverse)
string = "A surprise to be sure but a welcome one"
print(reverseWords(string)) |
#https://www.kaggle.com/c/amazon-employee-access-challenge/forums/t/4797/starter-code-in-python-with-scikit-learn-auc-885
""" Amazon Access Challenge Starter Code
These files provide some starter code using
the scikit-learn library. It provides some examples on how
to design a simple algorithm, including pre-processing,
training a logistic regression classifier on the data,
assess its performance through cross-validation and some
pointers on where to go next.
Paul Duan <email@paulduan.com>
"""
from __future__ import division
import numpy as np
from sklearn import (metrics, cross_validation, linear_model, preprocessing)
SEED = 42 # always use a seed for randomized procedures
def load_data(filename, use_labels=True):
"""
Load data from CSV files and return them as numpy arrays
The use_labels parameter indicates whether one should
read the first column (containing class labels). If false,
return all 0s.
"""
# load column 1 to 8 (ignore last one)
data = np.loadtxt(open("data/" + filename), delimiter=',',
usecols=range(1, 9), skiprows=1)
if use_labels:
labels = np.loadtxt(open("data/" + filename), delimiter=',',
usecols=[0], skiprows=1)
else:
labels = np.zeros(data.shape[0])
return labels, data
def save_results(predictions, filename):
"""Given a vector of predictions, save results in CSV format."""
with open(filename, 'w') as f:
f.write("id,ACTION\n")
for i, pred in enumerate(predictions):
f.write("%d,%f\n" % (i + 1, pred))
def main():
"""
Fit models and make predictions.
We'll use one-hot encoding to transform our categorical features
into binary features.
y and X will be numpy array objects.
"""
model = linear_model.LogisticRegression(C=3) # the classifier we'll use
# === load data in memory === #
print "loading data"
y, X = load_data('train.csv')
y_test, X_test = load_data('test.csv', use_labels=False)
# === one-hot encoding === #
# we want to encode the category IDs encountered both in
# the training and the test set, so we fit the encoder on both
encoder = preprocessing.OneHotEncoder()
encoder.fit(np.vstack((X, X_test)))
X = encoder.transform(X) # Returns a sparse matrix (see numpy.sparse)
X_test = encoder.transform(X_test)
# if you want to create new features, you'll need to compute them
# before the encoding, and append them to your dataset after
# === training & metrics === #
mean_auc = 0.0
n = 10 # repeat the CV procedure 10 times to get more precise results
for i in range(n):
# for each iteration, randomly hold out 20% of the data as CV set
X_train, X_cv, y_train, y_cv = cross_validation.train_test_split(
X, y, test_size=.20, random_state=i*SEED)
# if you want to perform feature selection / hyperparameter
# optimization, this is where you want to do it
# train model and make predictions
model.fit(X_train, y_train)
preds = model.predict_proba(X_cv)[:, 1]
# compute AUC metric for this CV fold
fpr, tpr, thresholds = metrics.roc_curve(y_cv, preds)
roc_auc = metrics.auc(fpr, tpr)
print "AUC (fold %d/%d): %f" % (i + 1, n, roc_auc)
mean_auc += roc_auc
print "Mean AUC: %f" % (mean_auc/n)
# === Predictions === #
# When making predictions, retrain the model on the whole training set
model.fit(X, y)
preds = model.predict_proba(X_test)[:, 1]
filename = raw_input("Enter name for submission file: ")
save_results(preds, filename + ".csv")
if __name__ == '__main__':
main()
|
def yes_or_no(question):
'Asks a question and returns True or False according to the answer.'
while True:
answer = input(question)
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
print('I dont understand, answer yes or no.')
print(yes_or_no('Do you want to continue? '))
if yes_or_no('Do you want to play a game? '):
print('OK! But first, you have got to program it!')
else:
print('Pity.')
|
birth_number = input('Zadej svoje rodné číslo, prosím. ')
#fce analytující formát rč
def format(birth_number):
intak = int(birth_number[:6])
intak2 = int(birth_number[-4:])
if len(str(intak)) == 6 and birth_number[6] == '/' and len(str(intak2)) == 4:
return True
else:
return False
print(format(birth_number))
#dělitelné jedenácti
def eleven(birth_number):
if birth_number % 11 == 0:
return True
else:
return False
#vrátí datum narození ve formátu třech čísel - 08, 07, 97
#def date_of_birth(birth_number):
# day = birth_number[4:5]
# month = int(birth_number[2:3])
# year = int(birth_number[0:1])
# return date_of_birth(birth_number)
#print(date_of_birth(birth_number))
|
from math import ceil, sqrt
from itertools import zip_longest
def cipher_text(plain_text):
plain_text = _cleanse(plain_text)
square_size = int(ceil(sqrt(len(plain_text))))
square = _chunks_of(plain_text, square_size)
return ' '.join([''.join(column)
for column in zip_longest(*square, fillvalue=' ')])
def _cleanse(text):
"""Lowercase a string and remove punctuation and whitespace
"""
return ''.join([character for character in text
if character.isalnum()]).lower()
def _chunks_of(text, num):
if len(text) <= num:
return [text]
return [text[:num]] + _chunks_of(text[num:], num)
|
def find(search_list, value):
low = 0
high = len(search_list) - 1
while low <= high:
middle = (low + high) // 2
if search_list[middle] > value:
high = middle - 1
elif search_list[middle] < value:
low = middle + 1
else:
return middle
raise ValueError('value not in array')
|
# -*- coding: utf-8 -*-
from collections import Counter
from threading import Lock, Thread
from time import sleep
from queue import Queue
TOTAL_WORKERS = 3 # Maximum number of threads chosen arbitrarily
class LetterCounter:
def __init__(self):
self.lock = Lock()
self.value = Counter()
def add_counter(self, counter_to_add):
self.lock.acquire()
try:
self.value = self.value + counter_to_add
finally:
self.lock.release()
def count_letters(queue_of_texts, letter_to_frequency, worker_id):
while not queue_of_texts.empty():
sleep(worker_id + 1)
line_input = queue_of_texts.get()
if line_input is not None:
letters_in_line = Counter(idx for idx in line_input.lower() if idx.isalpha())
letter_to_frequency.add_counter(letters_in_line)
queue_of_texts.task_done()
if line_input is None:
break
def calculate(list_of_texts):
queue_of_texts = Queue()
for line in list_of_texts:
queue_of_texts.put(line)
letter_to_frequency = LetterCounter()
threads = []
for idx in range(TOTAL_WORKERS):
worker = Thread(target=count_letters, args=(queue_of_texts, letter_to_frequency, idx))
worker.start()
threads.append(worker)
queue_of_texts.join()
for _ in range(TOTAL_WORKERS):
queue_of_texts.put(None)
for thread in threads:
thread.join()
return letter_to_frequency.value
|
NUMERAL_MAPPINGS = (
(1000, 'M'), (900, 'CM'),
(500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'),
(5, 'V'), (4, 'IV'),
(1, 'I')
)
def roman(number):
result = ''
for arabic_num, roman_num in NUMERAL_MAPPINGS:
while number >= arabic_num:
result += roman_num
number -= arabic_num
return result
|
def sum_of_multiples(limit, multiples):
return sum(value for value in range(limit)
if any(value % multiple == 0
for multiple in multiples
if multiple > 0))
|
def steps(number):
if number <= 0:
raise ValueError('Only positive integers are allowed')
step_count = 0
while number > 1:
if is_odd(number):
number = number * 3 + 1
else:
number = number / 2
step_count += 1
return step_count
def is_odd(number):
return number % 2 == 1
|
class Node:
def __init__(self, value, succeeding=None, previous=None):
self.value = value
self.succeeding = succeeding
self.prev = previous
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __len__(self):
return self.length
def __iter__(self):
current_node = self.head
while current_node:
yield (current_node.value, current_node.succeeding, current_node.prev)
current_node = current_node.succeeding
def delete(self, to_delete):
if self.length == 0:
raise ValueError("Value not found")
found = False
node = self.head
for value, succeeding, prev in self:
if value == to_delete:
if prev:
node.prev.succeeding = succeeding
else:
self.head = succeeding
if succeeding:
node.succeeding.prev = prev
else:
self.tail = prev
found = True
self.length -= 1
break
node = node.succeeding
if not found:
raise ValueError("Value not found")
def push(self, value):
new_node = Node(value)
if not self.head:
self.head = self.tail = new_node
else:
new_node.prev = self.tail
self.tail.succeeding = new_node
self.tail = new_node
self.length += 1
def pop(self):
node = self.tail
if self.length == 0:
raise IndexError("List is empty")
if node is None or node.prev is None:
self.head = self.tail = None
else:
self.tail = self.tail.prev
self.tail.succeeding = None
self.length -= 1
return node.value
def shift(self):
if self.length == 0:
raise IndexError("List is empty")
node = self.head
if node is None or node.succeeding is None:
self.head = self.tail = None
else:
self.head = self.head.succeeding
self.head.prev = None
self.length -= 1
return node.value
def unshift(self, value):
new_node = Node(value)
if not self.head:
self.head = self.tail = new_node
else:
new_node.succeeding = self.head
self.head.prev = new_node
self.head = new_node
self.length += 1
|
"""Functions for creating, transforming, and adding prefixes to strings."""
def add_prefix_un(word):
"""Take the given word and add the 'un' prefix.
:param word: str - containing the root word.
:return: str - of root word prepended with 'un'.
"""
pass
def make_word_groups(vocab_words):
"""Transform a list containing a prefix and words into a string with the prefix followed by the words with prefix prepended.
:param vocab_words: list - of vocabulary words with prefix in first index.
:return: str - of prefix followed by vocabulary words with
prefix applied.
This function takes a `vocab_words` list and returns a string
with the prefix and the words with prefix applied, separated
by ' :: '.
For example: list('en', 'close', 'joy', 'lighten'),
produces the following string: 'en :: enclose :: enjoy :: enlighten'.
"""
pass
def remove_suffix_ness(word):
"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""
pass
def adjective_to_verb(sentence, index):
"""Change the adjective within the sentence to a verb.
:param sentence: str - that uses the word in sentence.
:param index: int - index of the word to remove and transform.
:return: str - word that changes the extracted adjective to a verb.
For example, ("It got dark as the sun set.", 2) becomes "darken".
"""
pass
|
"""Functions for implementing the rules of the classic arcade game Pac-Man."""
def eat_ghost(power_pellet_active, touching_ghost):
"""Verify that Pac-Man can eat a ghost if he is empowered by a power pellet.
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - can the ghost be eaten?
"""
return power_pellet_active and touching_ghost
def score(touching_power_pellet, touching_dot):
"""Verify that Pac-Man has scored when a power pellet or dot has been eaten.
:param touching_power_pellet: bool - is the player touching a power pellet?
:param touching_dot: bool - is the player touching a dot?
:return: bool - has the player scored or not?
"""
return touching_power_pellet or touching_dot
def lose(power_pellet_active, touching_ghost):
"""Trigger the game loop to end (GAME OVER) when Pac-Man touches a ghost without his power pellet.
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - has the player lost the game?
"""
return not power_pellet_active and touching_ghost
def win(has_eaten_all_dots, power_pellet_active, touching_ghost):
"""Trigger the victory event when all dots have been eaten.
:param has_eaten_all_dots: bool - has the player "eaten" all the dots?
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - has the player won the game?
"""
return has_eaten_all_dots and not lose(power_pellet_active, touching_ghost)
|
class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
def equal_id(self):
return self.record_id == self.parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def validate_record(record):
if record.equal_id() and record.record_id != 0:
raise ValueError('Only root should have equal record and parent id.')
if not record.equal_id() and record.parent_id >= record.record_id:
raise ValueError("Node parent_id should be smaller than it's record_id.")
def BuildTree(records):
parent_dict = {}
node_dict = {}
ordered_id = sorted(idx.record_id for idx in records)
for record in records:
validate_record(record)
parent_dict[record.record_id] = record.parent_id
node_dict[record.record_id] = Node(record.record_id)
root_id = 0
root = None
for index, record_id in enumerate(ordered_id):
if index != record_id:
raise ValueError('Record id is invalid or out of order.')
if record_id == root_id:
root = node_dict[record_id]
else:
parent_id = parent_dict[record_id]
node_dict[parent_id].children.append(node_dict[record_id])
return root
|
from collections import defaultdict
class School:
def __init__(self):
self.db = {}
self.add = []
def added(self):
result = self.add[:]
self.add = []
return result
def add_student(self, name, grade):
if not self.db.get(name, 0):
self.db[name] = grade
self.add.append(True)
else:
self.add.append(False)
def roster(self, grade=0):
grades_roster = defaultdict(list)
for key, value in self.db.items():
grades_roster[value].append(key)
if grade:
return sorted(grades_roster[grade])
else:
working_list = (sorted(grades_roster[key]) for key in sorted(grades_roster.keys()))
return [element for item in working_list for element in item]
def grade(self, grade_number):
return sorted(self.roster(grade_number))
|
def convert(number):
"""
Converts a number to a string according to the raindrop sounds.
"""
result = ''
if number % 3 == 0:
result += 'Pling'
if number % 5 == 0:
result += 'Plang'
if number % 7 == 0:
result += 'Plong'
if not result:
result = str(number)
return result
|
"""Functions to keep track and alter inventory."""
def create_inventory(items):
"""Create a dict that tracks the amount (count) of each element on the `items` list.
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
inventory = {}
add_items(inventory, items)
return inventory
def add_items(inventory, items):
"""Add or increment items in inventory using elements from the items `list`.
:param inventory: dict - dictionary of existing inventory.
:param items: list - list of items to update the inventory with.
:return: dict - the inventory updated with the new items.
"""
for item in items:
inventory.setdefault(item, 0)
inventory[item] += 1
return inventory
def decrement_items(inventory, items):
"""Decrement items in inventory using elements from the `items` list.
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory with items decremented.
"""
for item in items:
if item in inventory:
inventory[item] = max(inventory[item] - 1, 0)
return inventory
def remove_item(inventory, item):
"""Remove item from inventory if it matches `item` string.
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory with item removed. Current inventory if item does not match.
"""
if item in inventory:
inventory.pop(item)
return inventory
def list_inventory(inventory):
"""Create a list containing all (item_name, item_count) pairs in inventory.
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""
output = []
for item in sorted(inventory.items()):
if item[1] > 0:
output.append(item)
return output
|
while True:
h, w = map(int, raw_input().split(' '))
if h == w and h == 0:
break
for a in range(h):
print '#' + '.#'[a == 0 or a == h - 1] * (w - 2) + '#'
print
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 09:53:48 2020
@author: ictd
"""
class Book():
def __init__(self,title,author,pages):
self.title=title
self.author=author
self.pages=pages
def __str__(self):
return "Title: {}\nAuthor: {}\nPages:{}".format(self.title,self.author,self.pages)
book=Book('class concepts','jose',200)
print(book)
|
# Default imports
import pandas as pd
data = pd.read_csv('data/house_prices_multivariate.csv')
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import f_regression
# Write your solution here:
def percentile_k_features(df, k=20):
X = df.drop(labels=['SalePrice'], axis=1)
y = df.SalePrice
feat_selector = SelectPercentile(score_func=f_regression, percentile=k)
X_transformed = feat_selector.fit_transform(X,y)
# print '(Before f_regression and SelectKPercentile) Predictor rows {} and columns {}'.format(X.shape[0],X.shape[1])
# print '(After f_regression and SelectKPercentile) Predictor rows {} and columns {}'.format(X_transformed.shape[0],X_transformed.shape[1])
# print 'Selected {} columns post the f_regression and SelectKPercentile'.format(X_transformed.shape[1])
sel_params_index = feat_selector.get_support(indices=True)
sel_params_scores = feat_selector.scores_[sel_params_index]
sel_params = X.columns[sel_params_index].values
# Get the indices as per the scores sorted in descending order
sort_indices = sel_params_scores.argsort()[::-1]
# Using the above indices sort the columns/features selected by our SelectPercentile
lst = sel_params[sort_indices].tolist()
return lst
|
'''
This file contains functions to collect and save 3D scan data as well as visualize it on a heatmap.
'''
import serial
import matplotlib.pyplot as plt
import numpy as np
import time
import pandas as pd
import seaborn as sns
# data collection params
pan_i = 40
pan_f = 130
pan_interval = 5
tilt_i = 50
tilt_f = 130
tilt_interval = 10
pan_len = int((pan_f-pan_i)/pan_interval) + 1
tilt_len = int((tilt_f-tilt_i)/tilt_interval) + 1
# set up serial communication, comment this out if not connected to arduino
ser = serial.Serial('COM4',9600)
ser.close()
ser.open()
def read_ser_data():
''' Reads data from serial and parses each line into the following format:
[x, y, sharp_ir_val_inches]
'''
ser_data = ser.readline().decode()
parsed_ser_data = [int(x) for x in ser_data.split()]
return parsed_ser_data
def collect_data():
''' Performs a 3D scan and save outputs in a csv file.
'''
with open("heatmap_data_with_labels.csv", 'w') as fd:
fd.write("Pan,Tilt,Inches\n")
# find total number of points
num_pts = pan_len*tilt_len
# collect data
for i in range(num_pts):
# wait for a bit
time.sleep(0.001)
# fetch new serial data
ser_data = read_ser_data()
print(ser_data)
# append to csv
with open("heatmap_data_with_labels.csv", 'a') as fd:
fd.write(f"{ser_data[0]},{ser_data[1]},{ser_data[2]}\n")
def plot_existing_data():
''' Create heatmap from existing data.
'''
df = pd.read_csv('heatmap_data_with_labels.csv',header=0)
# turn columns into matrix and perform transformations for plotting
df = pd.pivot_table(df, index='Tilt', columns='Pan', values='Inches')
df = df.sort_index(axis=0, level=1, ascending=False)
df = df.sort_index(axis=1, level=1, ascending=False)
# plot heatmap
ax = sns.heatmap(df)
plt.show()
if __name__ == "__main__":
# collect_data()
plot_existing_data() |
#list,set comprehension
my_list=[char for char in "Hello World"]
my_list2=[num for num in range(0,100)]
my_list3=[num**2 for num in range(1,11)]
my_list4=[num**2 for num in range(1,11) if num%2==0] #list=[param for param in iterable condition]
print(my_list)
print(my_list2)
print(my_list3)
print(my_list4)
#dictionary comprehension
simple_dict={
"a":1,
"b":2
}
my_dict={k:v**2 for k,v in simple_dict.items() if v%2==0}
print(my_dict)
my_dict1={num:num*2 for num in [1,2,3,4,5]}
print(my_dict1)
some_list=["a","b","c",'b',"d","m","n","n"]
duplicate=list(set(x for x in some_list if some_list.count(x)>1 ))
print(duplicate)
list5=[1,2,3,4,5]
my_list5=[item**3 for item in list5 if item>2]
print(my_list5)
|
#!/usr/bin/env python3
#
# output.py
# Author: Patrick Bannister
# Output and formatting for results of L7R dice Monte Carlo
# simulations.
#
class TextOutput:
def __init__(self, stream, step=5, bins=15, delimiter='\t', show_mutator_value=True):
self.stream = stream
self.step = step
self.bins = bins
self.delimiter = delimiter
self.show_mutator_value = show_mutator_value
def header(self):
bin_numbers = [i * self.step for i in range(1, self.bins)]
header = '\t{}'.format('\t'.join([str(n) for n in bin_numbers]))
if (self.show_mutator_value):
header += '\tMutator Value'
return header
def format_simulation(self, simulation):
'''
format_simulation(simulation) -> str
simulation (Simulation): a simulation that will be printed as a row
Returns a delimited string showing the results of a simulation.
'''
# compute probabilities for each bin
probabilities = []
for i in range(1, self.bins):
probabilities.append(sum(simulation.results[i:self.bins]) / simulation.trials)
# format data
label = '{}k{}'.format(simulation.rolled, simulation.kept)
probabilities_str = self.delimiter.join(['{:.2f}'.format(p) for p in probabilities])
fields = [label]
fields.extend(['{:.2f}'.format(p) for p in probabilities])
# Optionally include mutator value
if (self.show_mutator_value):
mutator_value = simulation.mutator_value / simulation.trials
fields.append('{:.2f}'.format(mutator_value))
# return delimited row
return self.delimiter.join(fields)
def write(self, simulations):
'''
write(simulations) -> str
simulations (list of Simulation): simulations to format
Returns a delimited string hat should be formatted
'''
simulations.sort()
self.stream.write(self.header() + '\n')
prev_rolled = 0
for simulation in simulations:
if (simulation.rolled != prev_rolled):
self.stream.write('\n')
prev_rolled = simulation.rolled
self.stream.write(self.format_simulation(simulation) + '\n')
|
from math import cos, radians, sin
class Point:
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __iter__(self):
yield self.x
yield self.y
def __getitem__(self, index):
return tuple(self)[index]
@staticmethod
def distance(p1, p2):
dx = p2.x - p1.x
dy = p2.y - p1.y
return (dx ** 2 + dy ** 2) ** 0.5
@staticmethod
def rotate(point, angle):
rotated_x = cos(radians(angle)) * point[0] - sin(radians(angle)) * point[1]
rotated_y = sin(radians(angle)) * point[0] + cos(radians(angle)) * point[1]
return Point(rotated_x, rotated_y)
|
"""This module implements the UART_Port class which talks to bioloid
devices using a UART on the pyboard.
"""
import stm
from pyb import UART
class UART_GPIO_Port:
"""Implements a port which can send or receive commands with a bioloid
device using the pyboard UART class. This class assumes that there is
an active HIGH GPIO line used to indicate transmitting (i.e. connected
to something like an external 74AHCT1G126)
"""
def __init__(self, uart_num, baud, control_pin, rx_buf_len=64):
self.uart = UART(uart_num)
self.control_pin = control_pin
self.baud = 0
self.rx_buf_len = 0
self.set_parameters(baud, rx_buf_len)
base_str = 'USART{}'.format(uart_num)
if not hasattr(stm, base_str):
base_str = 'UART{}'.format(uart_num)
self.uart_base = getattr(stm, base_str)
def any(self):
return self.uart.any()
def read_byte(self):
"""Reads a byte from the bus.
This function will return None if no character was read within the
designated timeout (set when we call self.uart.init).
"""
byte = self.uart.readchar()
if byte >= 0:
return byte
def set_parameters(self, baud, rx_buf_len):
"""Sets the baud rate and the read buffer length.
Note, the pyb.UART class doesn't have a method for setting the baud
rate, so we need to reinitialize the uart object.
"""
if baud != self.baud or rx_buf_len != self.rx_buf_len:
self.baud = baud
self.rx_buf_len = rx_buf_len
# The max Return Delay Time is 254 * 2 usec = 508 usec. The default
# is 500 usec. So using a timeout of 2 ensures that we wait for
# at least 1 msec before considering a timeout.
self.uart.init(baudrate=baud, timeout=2, read_buf_len=rx_buf_len)
def write_packet(self, packet_data):
"""Writes an entire packet to the serial port."""
_write_packet(self.uart_base, packet_data, len(packet_data), self.control_pin.gpio() & 0x7fffffff, self.control_pin.pin())
TXE_MASK = const(1 << 7)
TC_MASK = const(1 << 6)
@micropython.asm_thumb
def disable_irq():
cpsid(i)
@micropython.asm_thumb
def enable_irq():
cpsie(i)
@micropython.viper
def _write_packet(uart_base: int, data: ptr8, data_len: int, gpio_base: int, pin: int):
pin_mask = int(1 << pin)
# Enable the external transmit buffer by setting the GPIO line high
gpio_BSRR = ptr16(gpio_base + stm.GPIO_BSRR)
gpio_BSRR[0] = pin_mask
uart_SR = ptr16(uart_base + stm.USART_SR)
uart_DR = ptr16(uart_base + stm.USART_DR)
# Send the data
for idx in range(data_len):
# Wait for the Transmit Data Register to be Empty
while uart_SR[0] & TXE_MASK == 0:
pass
if idx == data_len - 1:
# We disable interrupts from the beginning of the last character
# until we drop the GPIO line (i.e. about 1 character time) in
# order to assure that the GPIO gets lowered as soon as possible
# after the last character gets sent.
disable_irq()
uart_DR[0] = data[idx]
# Wait for Transmit Complete (i.e the last bit of transmitted data has
# left the shift register)
while uart_SR[0] & TC_MASK == 0:
pass
# Disable the external transmit buffer by setting the GPIO line low
# The time from the end of the stop bit to the falling edge of the
# GPIO is about 0.25 usec
gpio_BSRR[1] = pin_mask
enable_irq()
|
# Problem Set 4B
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
import string
import copy
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
'''
print("Loading word list from file...")
# inFile: file
inFile = open(file_name, 'r')
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.extend([word.lower() for word in line.split(' ')])
print(" ", len(wordlist), "words loaded.")
return wordlist
def is_word(word_list, word):
'''
Determines if word is a valid word, ignoring
capitalization and punctuation
word_list (list): list of words in the dictionary.
word (string): a possible word.
Returns: True if word is in word_list, False otherwise
Example:
>>> is_word(word_list, 'bat') returns
True
>>> is_word(word_list, 'asdf') returns
False
'''
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in word_list
def get_story_string():
"""
Returns: a story in encrypted text.
"""
f = open("story.txt", "r")
story = str(f.read())
f.close()
return story
### END HELPER CODE ###
WORDLIST_FILENAME = 'words.txt'
class Message(object):
def __init__(self, text):
self.message_text = text
self.valid_words = load_words(WORDLIST_FILENAME)
def get_message_text(self):
#由于strings对象不可变,可以不拷贝直接返回
return self.message_text
def get_valid_words(self):
#深拷贝副本保护源列表
return copy.deepcopy(self.valid_words)
def build_shift_dict(self, shift):
dict_low = dict(zip(string.ascii_lowercase, string.ascii_lowercase[shift:] + string.ascii_lowercase[:shift]))
dict_high = dict(zip(string.ascii_uppercase, string.ascii_uppercase[shift:] + string.ascii_uppercase[:shift]))
dict_high.update(dict_low) #合并
return dict_high
def apply_shift(self, shift):
# 利用self.build_shift_dict方法得到映射字典
dict_map = self.build_shift_dict(shift)
# 题目要求忽略的标点符号
symbols = " !@#$%^&*()-_+={}[]|\:;'<>?,./\""
# 根据偏移获取要求的加密字符串,特殊符号不偏移
result = ''
for letter in self.get_message_text():
if letter in symbols:
result = result + letter #直接拼接
else:
result = result + dict_map[letter] #偏移后拼接
return result
class PlaintextMessage(Message):
def __init__(self, text, shift):
#继承的父类要进行初始化
Message.__init__(self, text)
#偏移量
self.shift = shift
# 调用继承来的build_shift_dict函数得到映射表
self.encryption_dict = self.build_shift_dict(shift)
# 调用继承来apply_shift得到加密后的字符串
self.message_text_encrypted = self.apply_shift(shift)
def get_shift(self):
return shift
def get_encryption_dict(self):
#深拷贝保护源字典
return copy.deepcopy(self.encryption_dict)
def get_message_text_encrypted(self):
return self.message_text_encrypted
def change_shift(self, shift):
#利用修改后的shift重新初始化类对象
self.__init__(self.get_message_text(), shift)
class CiphertextMessage(Message):
def __init__(self, text):
Message.__init__(self, text)
def decrypt_message(self):
# 最好的偏移量
best_shift = 0
# 最多合法的单词数
max_words = 0
# 解密后最好的字符串
best_msg = ''
# 遍历0-25个偏移量
for i in range(26):
num = 0 #偏移i单位的匹配单词数
temp = self.apply_shift(i) #偏移i单位的解密字符串
'''
将所有单词都分割出来,此处只处理正常语法的message,也就是词与词之间必有空格
若要将类似 hello,world 这种词与词之间没有空格而只有标点符号的字符串需要import re,用re里的方法,此处不考虑这种情况
'''
temp_list = temp.split()
# 计算合法单词数
for word in temp_list:
if is_word(self.get_valid_words(), word):
num += 1
# 如果这个偏移量得到的单词数,比当前最大的还大就改变
if num > max_words:
max_words = num
best_shift = i
best_msg = temp
# 如果合法单词数等于全部单词数,直接返回
if num == len(temp_list):
break
return (best_shift, best_msg)
if __name__ == '__main__':
# #Example test case (PlaintextMessage)
test ="abc,bcd,efg!aaa sss"
plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
#
# #Example test case (CiphertextMessage)
ciphertext = CiphertextMessage('jgnnq') #正确语法下,词与词之间必有空格
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())
# Example test case (PlaintextMessage)
plaintext = PlaintextMessage('I am very happy', 2)
print('Expected Output: K co xgta jcrra')
print('Actual Output:', plaintext.get_message_text_encrypted())
# Example test case (CiphertextMessage)
ciphertext = CiphertextMessage('K co xgta jcrra')
print('Expected Output:', (24, 'I am very happy'))
print('Actual Output:', ciphertext.decrypt_message())
# Example test case (PlaintextMessage)
plaintext = PlaintextMessage('I am so sad', 10)
print('Expected Output: S kw cy ckn')
print('Actual Output:', plaintext.get_message_text_encrypted())
# Example test case (CiphertextMessage)
ciphertext = CiphertextMessage('S kw cy ckn')
print('Expected Output:', (16, 'I am so sad'))
print('Actual Output:', ciphertext.decrypt_message())
#TODO: WRITE YOUR TEST CASES HERE
#TODO: best shift value and unencrypted story
|
#Classes to contruct and manipulate Graphs
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
class Vertex:
def __init__(self):
self.color = 'white'
self.d = float('inf')
self.p = None
self.name = None
#BFS(Cormen)
def bfs(G,source):
source.color = 'gray'
source.d = 0
source.p = None
Q = []
enqueue(Q,source)
while len(Q) != 0:
u = dequeue(Q)
for v in G.graph[u]:
if v.color == 'white':
v.color = 'gray'
v.d = u.d + 1
v.p = u
enqueue(Q,v)
u.color = 'black'
#Function to print a path between two vertices
def path_printer(s, v):
if s==v:
print(s.name)
else:
path_printer(s, v.p)
print(v.name)
#Functions to manipulate the Queue
def enqueue(Q,v):
Q.append(v)
def dequeue(Q):
return Q.pop(0)
s,a,b,c,d,e,f,g,h,i = Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex()
#Just to make easy to print the path
s.name = 's'
a.name = 'a'
b.name = 'b'
c.name = 'c'
d.name = 'd'
e.name = 'e'
f.name = 'f'
g.name = 'g'
h.name = 'h'
i.name = 'i'
G = Graph()
G.addEdge(s, a)
G.addEdge(s, d)
G.addEdge(s, g)
G.addEdge(a, s)
G.addEdge(a, b)
G.addEdge(a, c)
G.addEdge(b, a)
G.addEdge(c, a)
G.addEdge(d, e)
G.addEdge(d, f)
G.addEdge(d, s)
G.addEdge(e, d)
G.addEdge(f, d)
G.addEdge(g, h)
G.addEdge(g, i)
G.addEdge(g, s)
G.addEdge(h, g)
G.addEdge(i, g)
bfs(G,s)
path_printer(s,i) |
a=int(input("Enter a value"))
i=0
while(i<a):
print("Hello")
i=i+1
|
""" When the values in a dictionary are collections (lists, dicts, etc.) then in
this case, the value (an empty list or dict) must be initialized the first time
a given key is used. While this is relatively easy to do manually,
the defaultdict type automates and simplifies these kinds of operations.
A defaultdict works exactly like a normal dict, but it is initialized with a
function (“default factory”) that takes no arguments and provides the default
value for a nonexistent key.
A defaultdict will never raise a KeyError. Any key that does not exist gets the
value returned by the default factory.
"""
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Mike'] = 'Butter Scotch'
ice_cream['John'] = 'Strawberry'
print(ice_cream)
print(ice_cream['David'])
""" Output
defaultdict(<function <lambda> at 0x7f4d052daa60>, {'John': 'Strawberry', 'Mike': 'Butter Scotch'})
Vanilla
"""
"""
In the next example, we start with a list of states and cities. We want to build a
dictionary where the keys are the state abbreviations and the values are lists of all
cities for that state. To build this dictionary of lists, we use a defaultdict with a
default factory of list. A new list is created for each new key.
"""
city_list = [('TX','Austin'), ('TX','Houston'), ('NY','Albany'), ('NY', 'Syracuse'),('NY', 'Buffalo'),
('NY', 'Rochester'), ('TX', 'Dallas'), ('CA','Sacramento'), ('CA', 'Palo Alto'), ('GA', 'Atlanta')]
cities_by_state = defaultdict(list)
for state, city in city_list:
cities_by_state[state].append(city)
print(cities_by_state)
""" Output
defaultdict(<class 'list'>, {'GA': ['Atlanta'], 'TX': ['Austin', 'Houston', 'Dallas'],
'NY': ['Albany', 'Syracuse', 'Buffalo', 'Rochester'], 'CA': ['Sacramento', 'Palo Alto']})
"""
|
# Define a function
def say_hello():
# block belonging to the function.
print('Hello World')
# End of function
say_hello() # call the function
say_hello() # call the function again
# OUTPUT
# python functions_basics.py
# Hello World
# Hello World
|
#!/usr/bin/env python3
proto = ["ssh", "http", "https"]
protoa = ["ssh", "http", "https"]
print(proto)
print(proto[1])
proto.extend('dns') #this line will add d, n and s
protoa.extend('dns') #this line will add d, n and s
print(proto)
proto2 = [22, 80, 443, 53 ] #a list of common ports
proto.extend(proto2) #pass proto 2 as an argument to the extend method
print (proto)
protoa.append(proto2) #pass proto 2 as an argument to the append method
print (protoa)
|
class Parent:
def __new__(cls, val):
return super(Parent, cls).__new__(cls)
def __init__(self, val):
self.val = val + 1
class Child(Parent):
def __new__(cls, val):
return super(Child, cls).__new__(cls, val)
def __init__(self, val):
self.val += 1
c = Child(1)
print(c)
print(c.val) |
import urllib2, urllib, json
baseurl = "https://query.yahooapis.com/v1/public/yql?"
place=raw_input ("Enter the location\n")
x=str(place)
k=0
print "your choice of location for weather forecasting is "+x
yql_query = '''select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=" '''+x+''' ")'''
yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json"
print "Retrieving data from ",yql_url
result = urllib2.urlopen(yql_url).read()
data = json.loads(result)
info=json.dumps(data,indent=4)
#print info
print data["query"]["results"]["channel"]["description"]
#print " Forecasted temperature for next few days in "+x+" is:"
while k<=8:
z=((int(data["query"]["results"]["channel"]["item"]["forecast"][k]["high"])-32)*5)/9
y=((int(data["query"]["results"]["channel"]["item"]["forecast"][k]["low"])-32)*5)/9
i=data["query"]["results"]["channel"]["item"]["forecast"][k]["date"]
conditions=data["query"]["results"]["channel"]["item"]["forecast"][k]["text"]
print "Date:",i
print "Maximum:", z
print "Minimum:", y
print "Conditions:",conditions
k=k+1
|
# Flood fill algorithm
# to create an example with
def makeGrid(width, height):
d = {}
for row in range(height):
for col in range(width):
d[(row, col)] = '.'
return d
rowSize, colSize = 5, 5
grid = makeGrid(rowSize, colSize)
# directions N, NE, E, SE, S, SW, W, NW
dirRow = [-1, -1, 0, 1, 1, 1, 0, -1]
dirCol = [0, 1, 1, 1, 0, -1, -1, -1]
def floodfill(row, col, c1, c2): # start row, start col, start char, end char
if row < 0 or row >= rowSize or col < 0 or col >= colSize: # out of bounds check
return 0
if grid[(row, col)] != c1: # check if current cell is start char
return 0
count = 1 # for counting filled cells
grid[(row, col)] = c2 # fill this cell
for d in range(8): # call recursively in every direction
count += floodfill(row + dirRow[d], col + dirCol[d], c1, c2)
return count # total number of filled cells
print(grid) # initial grid
# .....
# .....
# .....
# .....
# .....
print(floodfill(1, 1, '.', 'f')) # -> 25 cells filled
print(grid) # filled grid
# fffff
# fffff
# fffff
# fffff
# fffff
|
# Dynamic programming coin change problem
def coin_change(coins, n):
"""
Returns the minimum amount of coins to get the sum of n.
Recursive solution.
coins is a tuple or list
n is the sum to get
"""
values = {} # cached results
def solve(x):
if x < 0:
return float("inf")
elif x == 0:
return 0
elif x in values:
return values[x]
best = float("inf")
for c in coins:
best = min(best, solve(x - c) + 1)
values[x] = best
return best
return solve(n)
def coin_change2(coins, n):
"""
Returns the minimum amount of coins to get the sum of n.
Iterative solution.
coins is a tuple or list
n is the sum to get
"""
v = [0] * (n + 1)
def iterative():
for x in range(1, len(v)):
v[x] = float("inf")
for c in coins:
if x - c >= 0:
v[x] = min(v[x], v[x - c] + 1)
return v
return iterative()[n]
def coin_change3(coins, n):
"""
Returns the minimum amount of coins and the solution to get the sum of n
as a tuple -> (minimum amount (int), solution (list of ints))
Iterative solution.
coins is a tuple or list
n is the sum to get
"""
v = [0] * (n + 1)
first = [0] * (n + 1)
for x in range(1, len(v)):
v[x] = float("inf")
for c in coins:
if x - c >= 0 and v[x - c] + 1 < v[x]:
v[x] = v[x - c] + 1
first[x] = c
result = v[n]
solution = []
while n > 0:
solution.append(first[n])
n -= first[n]
return result, solution
def count_ways(coins, n):
"""
Return the count of possible ways to get a sum of n with coins.
coins is a tuple or list
n is the sum to get
"""
ways = [1] + [0] * n
for c in coins:
for i in range(c, n + 1):
ways[i] += ways[i - c]
return ways[n]
N = 11
COINS = (1, 3, 4)
print(coin_change(COINS, N)) # -> 3
print(coin_change2(COINS, N)) # -> 3
print(coin_change3(COINS, N)) # -> (3, [3, 4, 4])
print(count_ways(COINS, N)) # -> 9
|
# Goldbach's conjecture
from d18_sieve_of_eratosthenes import eratosthenes
from d03_binary_search import binary_search
def prime_sum(n, primes):
"""Return two primes that add up to n."""
if n <= 2 or n % 2 != 0:
return
i = 0
while primes[i] <= n / 2:
difference = n - primes[i]
if binary_search(primes, difference)[0]:
return f"{primes[i]} + {difference} = {n}"
i += 1
print(prime_sum(4, eratosthenes(10000))) # 2 + 2 = 4
print(prime_sum(64, eratosthenes(10000))) # 3 + 61 = 64
print(prime_sum(720, eratosthenes(10000))) # 11 + 709 = 720
|
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
# Example
#
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
a = self
while a.next != None:
print(str(a.val))
a = a.next
print(str(a.val))
def addTwoNumbers(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
l1 and l2 may not have the same length, but either way the result will have at
most n + 1 node.
so we just iterate the l1,l2 and add the value, if the value >=10, make sure add the 1 to the next node.
"""
rlist = ListNode(0)
rlist_cp,l1_cp,l2_cp = rlist,l1,l2
carry = 0
while l1_cp != None or l2_cp != None:
x1 = l1_cp.val if l1_cp != None else 0
x2 = l2_cp.val if l2_cp != None else 0
curVal = x1 + x2 + carry
carry = 1 if curVal >=10 else 0
rlist_cp.next = ListNode(curVal % 10)
if(l1_cp != None):
l1_cp = l1_cp.next
if(l2_cp != None):
l2_cp = l2_cp.next
rlist_cp = rlist_cp.next
if(carry>0):
rlist_cp.next = ListNode(carry)
return rlist.next
rlist = addTwoNumbers(ListNode(4),ListNode(8))
rlist.__str__()
|
from typing import Any
class ClassUtilities:
"""Classes utilities."""
@staticmethod
def merge_dataclasses(*args) -> Any:
"""Merge two or more dataclasses.
Adapted solution from:
https://stackoverflow.com/questions/9667818/python-how-to-merge-two-class
Args:
args: dataclasses to merge
Raises:
ValueError: dataclasses of different types were passed
Returns:
Any: the merged dataclass
"""
if len({arg.__class__.__name__ for arg in args}) > 1:
raise ValueError(
'Merge of non-homogeneous entries no allowed.'
)
data = {}
for entry in args:
data.update(
ClassUtilities.__remove_none_values(
vars(entry) # noqa: WPS421
)
)
return args[-1].__class__(**data)
@staticmethod
def __remove_none_values(data: dict) -> dict:
clear_data: dict = {}
for key, value in data.items():
if value is not None:
clear_data[key] = value
return clear_data
|
class car(object):
"""
This class creates instance of cars
"""
def __init__(self,c,m):
self.company = c
self.mileage = m
def salutation(self):
print(f"The {self.company} car mileage is about {self.mileage} kmpl")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.