text stringlengths 37 1.41M |
|---|
total = mil = menor = 0
cont = 0
barato = ' '
print('-'*30)
print('LOJA SUPER BARATÃO')
print('-'*30)
while True:
nome = str(input('nome do produto: '))
preco = float(input('preço do produto: $'))
cont +=1
total+= preco
if preco > 1000:
mil+=1
if cont == 1 or preco < menor:
menor = preco
barato = nome
continuar = ' '
while continuar not in 'sn':
continuar = str(input('quer continuar?: '))
if continuar == 'n':
break
print('-'*30, 'FIM DO PROGRAMA!', '-'*30)
print(f'o total gasto na compra foi {total}$')
print(f'{mil} produtos custam mais de mil reais')
print(f'o produto mais barato foi o(a) {barato} que custa {menor}$')
|
import math
n = float(input('digite um numero: '))
t = math.trunc(n)
print('o número {} tem a parte inteira {}'.format(n, t))
|
sexo = ''
while sexo != 'm' and sexo != 'f':
sexo = str(input('qual o sexo da pessoa? M/F?: ')).lower()
if sexo != 'm' and sexo != 'f':
print('sexo inexistente, SEU PORRA!')
print('por favor, digite novamento o sexo')
print('FIM')
|
def leiadinheiro(msg):
"""
formata um valor(em dinheiro) com as características do REAL
:param msg: recebe a string
:return: retorna o numero float
"""
valido = False
while not valido:
entrada = str(input(msg)).replace('.',',').strip()
if entrada.isalpha() or entrada == '':
print(f'\033[0;31mERRO: \"{entrada}\" é um preço inválido\033[m')
else:
valido = True
return float(entrada)
def leiaInt(num):
"""
função que verifica se um numero é inteiro
ou não.
:param num: recebe uma string
:return: a variável 'numero', que é convertido para um numero inteiro
"""
while True:
try:
numero = int(input(num))
except (TypeError, ValueError):
print('\033[0;31mERRO! digite um número inteiro válido!\033[m')
continue
else:
return numero
def cores(nome):
"""
função para colori os textos mais facilmente.
:param nome: recebe o nome da cor
:return: o codigo da cor que está dentro de um dicionário, através da variavel 'v'
"""
cor = dict()
cor = {'padrao': '\033[m', 'vermelho':'\033[31m', 'branco':'\033[30m',
'verde':'\033[32m', 'amarelo':'\033[33m', 'azul':'\033[34m',
'roxo': '\033[35m', 'azul02':'\033[36m', 'cinza':'\033[37m'}
for k, v in cor.items():
if nome == k:
return v |
import math
numero = float(input('digite o valor de um ângulo: '))
s = math.sin(math.radians(numero))
c = math.cos(math.radians(numero))
t = math.tan(math.radians(numero))
print('o seno de {} é {:.2f}'.format(numero,s))
print('o cosseno de {} é {:.2f}'.format(numero,c))
print('a tangente de {} é {:.2f}'.format(numero,t))
|
s = float(input('qual o seu salario?: '))
a = ((s*15)/100) + s
print('o seu salrio era {} R$, com 15% de aumento fica {} R$'.format(s, a))
|
def main():
empId = int(input("Enter an employee id (00000):"))
if (empId == 82500):
empName = "Helene Mukoko"
elif (empId == 92746):
empName = "Raymond Kuomo"
elif (empId == 54080):
empName = "Henry Larson"
else:
empName = "Unknown"
print("Id # ", empId," The employees name is, ", empName)
weeklyTime = float(input("Enter the weekly time:"))
hourlySalary = float(input("Enter the hourly salary:"))
if (weeklyTime > 40):
regularTime = 40
overTime = weeklyTime - regularTime
regularPay = regularTime * hourlySalary
overtimePay = overTime * hourlySalary * 1.5
netpay = overtimePay + regularPay
else:
regularTime = weeklyTime
overTime = 0
regularPay = regularTime + hourlySalary
overtimePay = 0
netpay = overtimePay + regularPay
print("--------------------------Employee Payroll-------------------------------")
print("Employee number:", empId)
print("Employee name:", empName)
print("Hourly salary:", hourlySalary)
print("Weekly Time:", weeklyTime)
print("Regular Pay:", regularPay)
print("Overtime Pay:", overtimePay)
print("Net Pay:", netpay)
main()
|
def main():
lines = readFile()
writeFile(lines)
def readFile():
fname = input("Enter a filename: ")
fp = open(fname, 'r')
lines = fp.readlines()
fp.close()
return lines
def writeFile(data):
fp = open('output','a')
for i in range(0, len(data), 1):
fp.write(str(i) + ' ' + data[i])
fp.close()
main()
|
from List import *
def main():
numbers = ArrayToList(eval(input("Enter an array of numbers: ")))
print(reverse(numbers))
def reverse(items):
return rhelper(None,items)
def rhelper(t,s):
if (s == None):
return t
else:
return rhelper(join(head(s),t),tail(s))
main()
|
import sys
def main():
rows = int(sys.argv[1])
cols = int(sys.argv[2])
mode = sys.argv[3]
# Mode = 'recursive' or 'iterative'
mode = sys.argv[3]
mat = createMatrix(rows,cols,mode)
print(mat)
def createMatrix(r,c,m):
if (m == 'recursive'):
return recursiveMatrix(r,c)
elif (m == 'iterative'):
return iterativeMatrix(r,c)
else:
print("ERROR!")
return
def iterativeMatrix(r,c):
mat = []
for i in range(0,r,1):
mat += [iterativeRow(c)]
return mat
def iterativeRow(c):
row = []
for i in range(0,c,1):
row += [0]
return row
def recursiveMatrix(r,c):
if (r == 0):
return mat
else:
row = recursiveRow(c,[])
return recursiveMatrix(rows-1,cols,mat+[row])
def recursiveRow(c,arr):
if(c ==0):
return arr
else:
return recursiveRow(c-1,arr+[0])
main()
|
def main():
`
arr = [[1,2,3],[4,5,6],[7,8,9]]
# Iterating over the rows
for i in range(0,len(arr),1):
# Iterating over the columns
for j in range(0,len(arr[i]),1):
print(arr[i][j], end= ' ')
print()
sums = sumOfColumns(arr)
print("Sums:", sums)
Diag = sumDiag(arr)
print(Diag)
def sumOfColumns(arr):
sums = []
for j in range(0, len(arr), 1):
s = 0
for i in range(0, len(arr), 1):
s += arr[i][j]
sums += [s]
def sumDiag(arr):
i = 0
while(i<len(arr)):
s = 0
j = 0
while(j<len(arr[i])):
if(i ==j):
s += arr[i][j]
j+=1
i+=1
main()
|
import sys
def main():
matrix = eval(sys.argv[1])
compute(matrix)
pi(matrix)
def compute(matrix):
count = sum(matrix[0])
for i in range( 1, len(matrix), 1):
count += matrix[i][len(matrix[i]) - 1]
print("The sum of the first row and last column is",count)
def sum(items):
total = 0
for i in range(0, len(items),1):
total += items[i]
return total
def pi(matrix):
count = 0
for i in range(0, len(matrix), 1):
for j in range(0, len(matrix[i]),1):
if ( (matrix[i][0] * matrix[i][1]) <= 1):
count += 1
pi = (count / len(matrix)) * 4
print(pi)
main()
|
import sys
from List import *
def main():
strings = ArrayToList(sys.argv[1:])
print("The second longest string is, ",secondLongest(strings))
def secondLongest(data):
longest = head(data)
second = 0
while (data != None):
if (len(head(data)) > len(longest)):
second = longest
longest = head(data)
data = tail(data)
return second
main()
|
ax=input()
b=ax.isalpha()
if(b==True):
print("Alphabet")
else:
print("No")
|
n=int(input())
if(n>0):
print("Positive")
elif(n<0):
print("Negative")
elife(n==0):
print("Zero")
else:
print("enter a valid number")
|
import sys
import pyautogui
import argparse
from datetime import datetime
# validate the given argument to ensure it is an integer.
def numeric_val(duration):
if not duration.isnumeric():
raise argparse.ArgumentTypeError('Input Error. Expected a numeric value for duration. Found "{}"'
.format(duration))
try:
return int(duration)
except Exception as e:
raise argparse.ArgumentTypeError("""Couldn't parse the value passed into integer. Value passed is "{}" """
.format(duration))
# convert seconds to day, hour, minutes and seconds
def get_formatted_time(duration):
days = int(duration // (24 * 3600))
duration = duration % (24 * 3600)
hours = int(duration // 3600)
duration %= 3600
minutes = int(duration // 60)
duration %= 60
seconds = duration
return f"{days} Day(s) {hours} Hours(s) {minutes} minute(s) and {seconds:.2f} seconds(s)"
# brains of the operation. after every interval seconds, it performs an ALT-TAB operation to keep the machine awake
# for duration specified.
def keep_awake(duration, interval):
print('Keeping your computer awake for {}'.format(get_formatted_time(duration)))
start_time = datetime.now()
try:
while True:
if (datetime.now() - start_time).total_seconds() > duration:
end_time = datetime.now()
print(f'System has been awake since {start_time} until {end_time} for a total duration of {get_formatted_time((end_time - start_time).total_seconds())}')
sys.exit(0)
pyautogui.sleep(interval)
pyautogui.hotkey('altleft', 'tab')
current_time = datetime.now()
print(f'Operation performed at {current_time}. Duration elapsed is {get_formatted_time((current_time - start_time).total_seconds())}')
except Exception as e:
print("Unable to keep the system awake")
print(e)
pyautogui.alert('KeepAwake Stopped. Please check the console output...')
sys.exit(2)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-duration', default=3600, help='Duration to be awake in seconds', type=numeric_val)
parser.add_argument('-interval', default=60, help='Interval at which operation to be performed', type=numeric_val)
args = parser.parse_args()
keep_awake(args.duration, args.interval)
|
'''
Module handles and manipulates all requests that are sqlite specific
List of methods:
get_tables_names
get_columns_names
get_column_data
'''
from data.dbhelpers.Sqlite import Sqlite
import logging
def get_tables_names(target, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None):
'''
Parameters
----------
target : string, target file or database to retrieve tables from
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
list, default None
Contains the names of the tables associated with the specific database
'''
df = Sqlite().read_query_dataframe(target, 'select * from sqlite_master', index_col=index_col,
coerce_float=coerce_float, params=params, parse_dates=parse_dates,
chunksize=chunksize)
if df is None:
logging.warning('Query returned an empty DataFrame. Returning None')
return None
else:
tables_df = df[df['type'] == 'table']
return tables_df.name.values.tolist()
def get_columns_names(target, table, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None):
'''
:param target:
:param table:
:param index_col:
:param coerce_float:
:param params:
:param parse_dates:
:param chunksize:
:return:
'''
df = Sqlite().read_query_dataframe(target, 'pragma table_info(\'{}\')'.format(table), index_col=index_col, coerce_float=coerce_float, params=params,
parse_dates=parse_dates, chunksize=chunksize)
return df.name.values.tolist()[1:]
def get_columns_data(target, table, columns, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None):
if isinstance(columns, str):
columns_string = columns
logging.info('Provided columns as string: ' + columns)
elif isinstance(columns, list):
columns_string = ",".join(columns)
logging.info('Provided columns as list, each element of the list is considered as a separate column of the query'
': ' + columns)
df = Sqlite().read_query_dataframe(target, 'select {} from {}'.format(columns_string, table), index_col=index_col,
coerce_float=coerce_float, params=params,
parse_dates=parse_dates, chunksize=chunksize)
return df.values.tolist() |
from address import Address
class Person:
def __init__(self, first, last, dob, phone, address):
self.first_name = first
self.last_name = last
self.date_of_birth = dob
self.phone = phone
self.addresses = []
# Using isinstance to check if the address entered is the correct format or an instance of the Address class from Address.py
if address is isinstance(address, Address):
self.addresses.append(address)
elif isinstance(address, list):
for entry in address:
if not isinstance(entry, Address):
raise Exception("Invalid Address...") # Not sure what he's using here to raise the Exception. Have to look it up later
self.addresses = address
else:
raise Exception("Invalid Address...")
def add_address(self, address):
if not isinstance(address, Address):
raise Exception("Invalid Address...")
self.addresses.append(address) |
#!/usr/bin/env python
import sys
import sqlite3
class mySqlite:
""" Constructor le paso el nombre de la base de datos """
def __init__ (self,baseDatos):
self.con = None
self.tabs = {"nombreTabs":[],"idTabs":[],"pathIcono":[]}
self.programas = {"ejecucion":[],"descripcion":[],"pathIcono":[]}
""" Realizo la conexion de la base de datos"""
try:
self.con = sqlite3.connect(baseDatos)
self.cursor = self.con.cursor()
except sqlite3.Error, e:
print "Error : %s" % e.args[0]
sys.exit(1)
""" Devuelvo la informacion de los tabs en un
diccionario
"""
def obtenerTabs(self):
try:
self.cursor.execute ("SELECT idTabs,nombre,pathIcono FROM tabs ORDER BY idTabs")
self.datos = self.cursor.fetchall()
except sqlite3.Error, e:
print "Error al acceder a los datos: %s" % e.args[0]
sys.exit(1)
for datos in self.datos:
self.tabs["idTabs"].append(datos[0])
self.tabs["nombreTabs"].append(datos[1])
self.tabs["pathIcono"].append(datos[2])
return self.tabs
""" Devuelvo la informacion de los tabs en un
diccionario
"""
def obtenerProgramas(self,id):
sql="SELECT ejecucion,descripcion,pathIcono,label FROM programas WHERE idTabs=%d ORDER BY idTabs,idProgramas" % (id)
self.programas = {"ejecucion":[],"descripcion":[],"pathIcono":[],"label":[]}
try:
self.cursor.execute (sql)
self.datos = self.cursor.fetchall()
except sqlite3.Error, e:
print "Error al acceder a los datos: %s" % e.args[0]
sys.exit(1)
#print self.datos
if len(self.datos) > 0:
for datos in self.datos:
self.programas["ejecucion"].append(datos[0])
self.programas["descripcion"].append(datos[1])
self.programas["pathIcono"].append(datos[2])
self.programas["label"].append(datos[3])
return self.programas
else:
return []
""" Cierro la base de datos """
def cerrarBase(self):
self.con.close()
|
#importando bibliotecas necessárias para funcionamento do código
import sys #modulo nativo do python para algumas variáveis usadas ou mantidas pelo interpretador
from PyQt5 import QtCore, QtGui, QtWidgets #framework em C++ para o desenvolvimento da UI
import random #gerador de números pseudo-aleatórios
import time #usado para análise do tempo de execução de para organizador
_translate = QtCore.QCoreApplication.translate #método para tradução
#método de organizador bolha
def bubble_sort(lista):
for percorrer_lista in range(len(lista) - 1, 0, -1):
for indice in range(percorrer_lista):
if lista[indice] > lista[indice + 1]:
lista[indice], lista[indice + 1] = lista[indice + 1], lista[indice]
return lista
#método organizador de seleção
def selection_sort(lista):
for indice in range(0, len(lista) - 1):
valor_minimo = indice
for indice_posterior in range (indice + 1, len(lista)):
if (lista[indice_posterior] < lista[valor_minimo]):
valor_minimo = indice_posterior
lista[indice],lista[valor_minimo] = lista[valor_minimo],lista[indice]
return lista
#método organizador de inserção
def insertion_sort(lista):
for indice in range(0,len(lista)):
valor_indice = lista[indice]
indice_anterior = indice - 1
while indice_anterior >= 0 and lista[indice_anterior] > valor_indice:
lista[indice_anterior + 1] = lista[indice_anterior]
indice_anterior -= 1
lista[indice_anterior + 1] = valor_indice
return lista
#método organizador nativo do python
def sort(lista):
lista.sort()
return lista
#função criada para facilitar o manejo das listas
def Listas(n):
lista_aleatoria = random.sample(range(0, n), n) #gerador de funções pseudo-aleatórias com a biblioteca random
global lista_bubble, lista_selection, lista_insertion, lista_func_sort #Essas listas foram definidas como globais para uso fora da função
#As listas são cópias da lista_aleatoria para evitar póssiveis erros
lista_bubble = lista_aleatoria.copy()
lista_selection = lista_aleatoria.copy()
lista_insertion = lista_aleatoria.copy()
lista_func_sort = lista_aleatoria.copy()
#função criada para melhor organização da medição de tempo e organização das listas
def execucao_orcanizadores(Listas):
global tempo_bubble, tempo_selection, tempo_insertion, tempo_sort #o tempo de execução foi definido como global para utilização fora da função
#utilizando a função time.time(), pegamos o tempo de execução do programa no momento em que chamamos a função
ini = time.time()
bubble_sort(lista_bubble)
fim = time.time()
tempo_bubble = str(round(fim - ini, 7))
#a variável foi definida como uma string pois o pyqt5 exige que para mostrar um número em seus label's, o mesmo seja uma str
#foi utilizado o round() com 7 casas decimais para melhor leitura do tempo de execução no programa
#subtraindo o tempo de execução de depois e antes da função do organizador, temos o tempo de execução daquela função
ini = time.time()
selection_sort(lista_selection)
fim = time.time()
tempo_selection = str(round(fim - ini, 7))
ini = time.time()
insertion_sort(lista_insertion)
fim = time.time()
tempo_insertion = str(round(fim - ini, 7))
ini = time.time()
sort(lista_func_sort)
fim = time.time()
tempo_sort = str(round(fim - ini, 7))
#criação da UI
class Ui_MainWindow(object):
#inicializando a interface
def setupUi(self, MainWindow):
#MainWindow
MainWindow.setObjectName("MainWindow")#definindo o nome do objeto para a janela principal
MainWindow.resize(432, 283)#tamanho da interface
#centralwidget
self.centralwidget = QtWidgets.QWidget(MainWindow)#definindo método para localização dos Widget
self.centralwidget.setObjectName("centralwidget")#nome do objeto de localização
#Titulo
self.Titulo = QtWidgets.QLabel(self.centralwidget)#definindo o Widget "Titulo" como um label
self.Titulo.setGeometry(QtCore.QRect(20, 20, 391, 31))#coordenadas(x,y) e tamanho(largura,altura) do Widgets "Titulo"
font = QtGui.QFont()#definindo "font" como uma fonte
font.setFamily("Arial")#definindo a família da "font" para "Arial"
font.setPointSize(20)#tamanho da fonte
self.Titulo.setFont(font)#definindo "Titulo" para utilizar a fonte "font"
self.Titulo.setObjectName("Titulo")#nome do objeto
#cemElementos
self.cemElementos = QtWidgets.QPushButton(self.centralwidget)#definindo o Widget "cemElementos" como um botão
self.cemElementos.setGeometry(QtCore.QRect(30, 60, 101, 23))#coordenadas(x,y) e tamanho(largura,altura) do botão "cemElementos"
self.cemElementos.clicked.connect(self.cemElementos_clicked)#método definido quando o botão "cemElementos" for pressionado
self.cemElementos.setObjectName("cemElementos")#nome do objeto
#milElementos
self.mil_elementos = QtWidgets.QPushButton(self.centralwidget)
self.mil_elementos.setGeometry(QtCore.QRect(160, 60, 111, 23))
self.mil_elementos.clicked.connect(self.milElementos_clicked)
self.mil_elementos.setObjectName("mil_elementos")
#dezMilElementos
self.dezMilElementos = QtWidgets.QPushButton(self.centralwidget)
self.dezMilElementos.setGeometry(QtCore.QRect(300, 60, 101, 23))
self.dezMilElementos.clicked.connect(self.dezMilelementos_clicked)
self.dezMilElementos.setObjectName("dezMilElementos")
#Bubble
self.Bubble = QtWidgets.QLabel(self.centralwidget)
self.Bubble.setGeometry(QtCore.QRect(30, 130, 141, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
self.Bubble.setFont(font)
self.Bubble.setObjectName("Bubble")
#Selection
self.Selection = QtWidgets.QLabel(self.centralwidget)
self.Selection.setGeometry(QtCore.QRect(30, 160, 141, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
self.Selection.setFont(font)
self.Selection.setObjectName("Selection")
#Tempo_execucao
self.Tempo_execucao = QtWidgets.QLabel(self.centralwidget)
self.Tempo_execucao.setGeometry(QtCore.QRect(150, 100, 141, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
self.Tempo_execucao.setFont(font)
self.Tempo_execucao.setObjectName("Tempo_execucao")
#Insertion
self.Insertion = QtWidgets.QLabel(self.centralwidget)
self.Insertion.setGeometry(QtCore.QRect(30, 190, 141, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
self.Insertion.setFont(font)
self.Insertion.setObjectName("Insertion")
#sort
self.sort = QtWidgets.QLabel(self.centralwidget)
self.sort.setGeometry(QtCore.QRect(30, 220, 151, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
self.sort.setFont(font)
self.sort.setObjectName("sort")
#menubar e statusbar
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 432, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#caso o botao "cemElementos" seja clickado
def cemElementos_clicked(self):
self.Titulo.setText("100 elementos: ") #definindo o label "Titulo" para "100 elementos: "
#definindo o n com valor 100 para funcionamento das funções responsáveis pelos organizadores
n=100
Listas(n)
execucao_orcanizadores(Listas)
#atualizando a mensagem mostrada pelos label's para assim mostrar o tempo de execução de cada organizador
self.Bubble.setText(_translate("MainWindow", "Bubble: "+ tempo_bubble))
self.Selection.setText(_translate("MainWindow", "Selection: "+ tempo_selection))
self.Insertion.setText(_translate("MainWindow", "Insertion: "+ tempo_insertion))
self.sort.setText(_translate("MainWindow", "Sort() :"+ tempo_sort))
#caso o botão "milElementos" seja clickado
def milElementos_clicked(self):
self.Titulo.setText("1000 elementos: ")
n= 1000
Listas(n)
execucao_orcanizadores(Listas)
self.Bubble.setText(_translate("MainWindow", "Bubble: "+ tempo_bubble))
self.Selection.setText(_translate("MainWindow", "Selection: "+ tempo_selection))
self.Insertion.setText(_translate("MainWindow", "Insertion: "+ tempo_insertion))
self.sort.setText(_translate("MainWindow", "Sort() :"+ tempo_sort))
#caso o botão "dezMilElementos" seja clickado
def dezMilelementos_clicked(self):
self.Titulo.setText("10000 elementos: ")
n= 10000
Listas(n)
execucao_orcanizadores(Listas)
self.Bubble.setText(_translate("MainWindow", "Bubble: "+ tempo_bubble))
self.Selection.setText(_translate("MainWindow", "Selection: "+ tempo_selection))
self.Insertion.setText(_translate("MainWindow", "Insertion: "+ tempo_insertion))
self.sort.setText(_translate("MainWindow", "Sort() :"+ tempo_sort))
#definindo as mensagens mostradas pelos label's e botões em primeiro momento
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Organizadores"))
self.Titulo.setText(_translate("MainWindow", "Escolha o tamanho de sua lista:"))
self.cemElementos.setText(_translate("MainWindow", "100 elementos"))
self.mil_elementos.setText(_translate("MainWindow", "1000 elementos"))
self.dezMilElementos.setText(_translate("MainWindow", "10000 elementos"))
#main
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)#define "app" como o cache
MainWindow = QtWidgets.QMainWindow()#define a MainWindow com as funções criqadas anteriormente
ui = Ui_MainWindow()#define "ui" como a janela criada
ui.setupUi(MainWindow)#inicializa a UI
MainWindow.show() #mostra a UI criada
sys.exit(app.exec_())#finaliza o algorítmo caso o usuário clique no "X" para fechar a janela
|
# Modules
import os
import csv
# Path to collect data from the Resources folder
poll_csv = os.path.join("Poll.csv")
# Create lists and initialize variables
total_votes = 0
candidate_list = []
vote_count = []
Winner_Vote_Count = 0
# Read in the CSV file
with open(poll_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
# read in the header data
header = next(csvreader)
# for loop
for row in csvreader:
# Count the total number of votes using increment feature
total_votes += 1
#Creating a list of unique candidates
if(row[2] not in candidate_list):
candidate_list.append(row[2])
vote_count.append(0)
#Getting the Index in candidate list
candidate_index = candidate_list.index(row[2])
#Using the same Index to increment count of votes for the candidate
vote_count[candidate_index] += 1
# print the good stuff
print("---(>'-')> <('-'<) ^('-')^ v('-')v(>'-')>")
print("ELECTION RESULTS")
print("---(>'-')> <('-'<) ^('-')^ v('-')v(>'-')>")
print("-----------------------------------------")
print(f"Total Votes: {total_votes}")
print("-----------------------------------------")
# finding out winner and winner percentage
for x in range(len(candidate_list)):
vote_percent = round((vote_count[x]/total_votes)*100,3)
print(f"{candidate_list[x]}: {vote_percent}% ({vote_count[x]})")
print("-----------------------------------------")
Winner_Vote_Count = max(vote_count)
Winner = candidate_list[vote_count.index(Winner_Vote_Count)]
print(f"Winner: {Winner}")
print("-----------------------------------------")
# output text file
import os
text_output = os.path.join("..", "Analysis",'PyPoll_Analysis.txt')
with open(text_output,'w') as text:
text.write("\n---(>'-')> <('-'<) ^('-')^ v('-')v(>'-')>")
text.write("\nELECTION RESULTS")
text.write("\n---(>'-')> <('-'<) ^('-')^ v('-')v(>'-')>")
text.write(f"\nTotal Votes: {total_votes}")
text.write("\n-----------------------------------------")
for x in range(len(candidate_list)):
vote_percent = round((vote_count[x]/total_votes)*100,3)
text.write(f"\n{candidate_list[x]}: {vote_percent}% ({vote_count[x]})")
text.write("\n-----------------------------------------")
text.write(f"\nWinner: {Winner}")
text.write("\n-----------------------------------------")
text.close()
|
import gym
import numpy as np
env = gym.make("MountainCar-v0") #environment has 3 actions you can take
# 0 = go left, 1 = no accel, 2 = go right
env.reset()
#resets the environment each time the program runs
# to the agent, it does not matter what these values represent
print(env.observation_space.high) #highest value for all the observations possible, state space
print(env.observation_space.low) #lowest value for all the observations possible
print(env.action_space.n) #how many actions you can take
DISCRETE_OS_SIZE = [20]*len(env.observation_space.high)
# the range between low value -1.2, -0.07 and high value 0.6, 0.07 will now be chunked into 20 buckets aka 20 discrete values instead
# of infinitely continous range that would take forever to create
discrete_os_win_size = (env.observation_space.high - env.observation_space.low)/DISCRETE_OS_SIZE
print(discrete_os_win_size)
q_table = np.random.uniform(low = -2, high = 0, size = (DISCRETE_OS_SIZE) + [env.action_space.n]) #rewards given, 20 by 20 table of discrete observations,
# contains every combo of observations we might find, every combo of position and velocity
# Now, need values for every single action possible
# [env.action.space.n] creates a 20 by 20 by 3 table, every combo of environment states, random q value in each of those cells
print(q_table.shape)
print(q_table)
done = False
while not done: #while True, allows us to step through the environment
action = 2 #the car will always take the action of moving to the right
new_state, reward, done, _ = env.step(action) #every time we step with an action, we get a new state (position and velocoty), a reward for that
#action
print(reward, new_state) #change continous values to discrete values (every possible combination to 8 decimal places is crazy)
env.render()
env.close()
|
#To find if the file exists, path of file, if given path is file or a directory.
import os
from os import path
import datetime
from datetime import date, time, timedelta
import time
def main():
print(os.name) #Prints the os name
#Output:
#nt
#CHECKING FILE'S EXISTENSE, IF THE PATH IS A FILE PATH OR A DIRECTORY PATH
print("Item exists? : "+str(path.exists("D:/Coding/files/textfile1.txt")))
print("Item is a file? : "+str(path.isfile("D:/Coding/files/textfile1.txt")))
print("Item is a directory? : "+str(path.isdir("D:/Coding/files/textfile1.txt")))
#Output:
#Item exists? : True
#Item is a file? : True
#Item is a directory? : False
# TO FIND THE REAL PATH, SPLITTING NAME FROM THE REAL PATH OF FILE
print("Item path : "+str(path.realpath("D:/Coding/files/textfile1.txt")))
print("Item path and name : "+str(path.split("D:/Coding/files/textfile1.txt")))
print("Item realpath and name : "+str(path.split(path.realpath("D:/Coding/files/textfile1.txt"))))
filepath,filename=path.split("D:/Coding/files/textfile1.txt")
print("File path : "+filepath)
print("File name : "+filename)
filepath,filename=path.split(path.realpath("D:/Coding/files/textfile1.txt"))
print("File path : "+filepath)
print("File name : "+filename)
#Output:
#Item path : D:\Coding\files\textfile1.txt
#Item path and name : ('D:/Coding/files', 'textfile1.txt')
#Item realpath and name : ('D:\\Coding\\files', 'textfile1.txt')
#File path : D:/Coding/files
#File name : textfile1.txt
#File path : D:\Coding\files
#File name : textfile1.txt
#TO GET MODIFICATION TIME
t=time.ctime(path.getmtime("D:/Coding/files/textfile1.txt")) #First way
print(t)
print("Modification Time : "+str(datetime.datetime.fromtimestamp(path.getmtime("D:/Coding/files/textfile1.txt")))) #Second way
#Output:
#Sat Jan 5 20:49:49 2019
#Modification Time : 2019-01-05 20:49:49.635641
#TO GET THE TIME SINCE THE MODIFICATION WAS DONE
td=datetime.datetime.now()-datetime.datetime.fromtimestamp(path.getmtime("D:/Coding/files/textfile1.txt"))
print("Time since modification : "+str(td)) #Modification time
print("Time since modification in seconds : "+str(td.total_seconds())+" seconds") #Modification time in seconds
#Output:
#Time since modification : 17:48:27.520957
#Time since modification in seconds : 64107.520957 seconds
if __name__=="__main__":
main() |
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that
# tells them the year that they will turn 100 years old.
#Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.
class Age:
def age100(self):
addyears=100
self.age=input("Enter your current age : ")
self.nm=input("Enter your name : ")
self.age=int(self.age) #converted the input from string to int
self.age+=addyears
print("Your age after 100 years will be : ", self.age)
print("Your name will remain same : ", self.nm)
def multiplePrints(self):
timesinput=int(input("Enter the number times you want to print : "))
i=0
while i<timesinput:
print(self.age)
i+=1
print("\n"*2)
classobj=Age()
classobj.age100()
classobj.multiplePrints()
|
def main():
x=0
#while loop
while(x<5):
print(x)
x=x+1
print("")
for i in range(1,5):
print(i)
print("")
#range(x) gives the values 0 to x-1
#range(x,y) gives the values x to y-1
#Now, for loop over collection
days=["mon","tue","wed","thurs","fri","sat","sun"]
for i in days:
print(i)
print("")
#using break can continue statements
for i in range(1,10):
if(i==8): break #runs from 1 to 4 on 5 it will break
# break causes this for loop to break and fall to the next block
# of statement
if(i==5): continue #will skip 5 and then continue with the loop
print(i)
print("")
days=["mon","tue","wed","thurs","fri","sat","sun"]
for i,d in enumerate(days): #enumerate() gives the index thus this
# will give index along with the values of the days array
print(i,d)
#for loop does not generally uses index variable for loops
#however it can use loop counter if needed
if __name__=="__main__":
main()
|
# -*- coding: utf-8 -*-
M, N = map(int, input().split())
graph = {}
visited = {}
for _ in range(N):
name1, _, name2 = input().split()
try:
graph[name1].append(name2)
except KeyError:
graph[name1] = [name2]
if not name2 in graph:
graph[name2] = []
visited[name1] = False
visited[name2] = False
def toposort(graph: dict, visited: dict, curr=None, order=[]) -> list:
if curr == None:
for name in graph.keys():
if not visited[name]:
toposort(graph, visited, name, order)
return order
visited[curr] = True
for adj in graph[curr]:
if not visited[adj]:
toposort(graph, visited, adj, order)
order.append(curr)
return order
def dfs(graph, visited, curr):
if visited[curr]:
return
visited[curr] = True
for adj in graph[curr]:
dfs(graph, visited, adj)
def disjoint(graph, visited, order) -> int:
res = 0
for name in order:
if not visited[name]:
res += 1
dfs(graph, visited, name)
return res
toposorted = toposort(graph, visited.copy())
for name in toposorted:
for adj in graph[name]:
graph[adj].append(name)
print(disjoint(graph, visited.copy(), reversed(toposorted)))
|
# -*- coding: utf-8 -*-
inversions = 0
def merge(arr1, arr2):
global inversions
mid = len(arr1)
sz = len(arr1) + len(arr2)
merged = [0 for _ in range(sz)]
arr1.append(float('inf'))
arr2.append(float('inf'))
i = 0
j = 0
for idx in range(sz):
if arr1[i] <= arr2[j]:
merged[idx] = arr1[i]
i += 1
else:
merged[idx] = arr2[j]
j += 1
inversions += mid - i
return merged
def mergesort(arr):
if len(arr) == 1:
return arr
mid = len(arr) // 2
left = mergesort(arr[:mid])
right = mergesort(arr[mid:])
return merge(left, right)
n = int(input())
while n > 0:
arr = list(map(int, input().split()))
inversions = 0
mergesort(arr)
print(inversions)
n = int(input())
|
# -*- coding: utf-8 -*-
_ = input()
nums = sorted(map(int, input().split()), reverse=True)
half = sum(nums) // 2
acum = 0
for coin, num in enumerate(nums, start=1):
acum += num
if acum > half:
print(coin)
break
|
import matplotlib.pyplot as plt
import numpy as np
def show_curve(ys, title):
"""
plot curlve for Loss and Accuacy
Args:
ys: loss or acc list
title: loss or accuracy
"""
x = np.array(range(len(ys)))
y = np.array(ys)
plt.plot(x, y, c='b')
plt.axis()
plt.title('{} curve'.format(title))
plt.xlabel('epoch')
plt.ylabel('{}'.format(title))
plt.show() |
def find_fraction(summ):
if summ < 3:
return False
if summ%2 != 0:
a = summ/2
else:
a = summ/2 - 1
b = summ - a
flag = True
while flag:
if b % a == 0:
break
if a % (b % a) != 0 or (b % a) == 1:
flag = False
else:
a = a - 1
b = b + 1
return (a, b)
print find_fraction(2) # False
print find_fraction(3) # (1, 2)
print find_fraction(10) # (3, 7)
print find_fraction(62) # (29, 33)
print find_fraction(150000001) # (75000000, 75000001)
|
def str_to_int(a):
return [int(i) for i in list(a)]
def read_input():
with open("input.txt", 'r') as f:
algo_name = f.readline()
n = int(f.readline().strip())
p = int(f.readline().strip())
data = list(map(str_to_int, f.read().split()))
return (n, p, data)
|
#데이터 프레임에 함수적용
frame = pd.DataFrame(np.random.randn(4,3), columns = list('bde'),
index = ['Utah', 'Ohio', 'Texas', 'Oregon'])
frame
np.abs(frame)
print(frame)
def f(x):
return pd.Series([x.min(), x.max()], index=['min','max'])
frame.apply(f)
print(frame)
format = lambda x:"%.2f"%x
frame.applymap(format)
print(frame)
|
import matplotlib.pyplot as plt
years = [1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2000, 2002, 2006, 2010, 2014]
medals = [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 3, 2, 1, 5, 0, 13, 10, 3, 1]
plt.plot(years, medals, color=(255/255, 100/255, 100/255), linewidth=6.0)
plt.ylabel("Number of Bronze Medals")
plt.xlabel("Number of Years")
plt.title("Women's mens bronze medals - 1924-2014", pad=20)
plt.show() |
import random
import quiz_common
words = { }
# ask the user for quiz type
print("Quiz Types: sat, spanish")
quiz_type = input("Enter quiz type: ")
data_files_path = quiz_type + "/"
# randomly select a file
random_file_num = random.randrange(1,3)
random_file_num = str(random_file_num)
word_file = data_files_path + "quiz" + random_file_num + ".csv"
quiz_common.read_data_from_file(words, word_file)
random_answer = quiz_common.random_key(words)
random_question = words[random_answer]
user_answer = input("Word for " + random_question + ": ")
if (user_answer == random_answer):
print("correct")
else:
print ("incorrect") |
import cv2
import math
import numpy
import os
from PIL import Image, ImageDraw
def rotatePoints(origin, point, angle):
"""Rotate a point by a given angle around a given origin."""
# Taken from https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python
angle = math.radians(angle)
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy
image = Image.open('rot.jpg')
imw,imh = image.size
center = (imw/2, imh/2)
w = 100
h = 100
t = 100
l = imw/2-w/2
b = t+h
r = l+w
sqpoly = [(t,l), (t,r), (b,r), (b,l)]
draw = ImageDraw.Draw(image)
#draw.polygon(sqpoly, outline='red')
for rot in range(20, 360, 30):
sqpoly_rot = []
for point in sqpoly:
rotx,roty = rotatePoints(center, point, rot)
sqpoly_rot.append((rotx, roty))
draw.polygon(sqpoly_rot, outline='white')
image.show() |
# _*_ coding: utf-8 _*_
"""
LSTM prediction
考虑时间维度,以一天为周期输入分钟数
"""
import math
import numpy as np
import time
from keras.layers.core import Dense,Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from sklearn.metrics import mean_squared_error
from lstm_pre import data_pre
str=10
#设置时间刻度
if(str==1):
X_train,X_test,y_train,y_test,y_scale=data_pre(1)
elif(str==5):
X_train,X_test,y_train,y_test,y_scale=data_pre(5)
elif(str==10):
X_train,X_test,y_train,y_test,y_scale=data_pre(10)
if(str==1):
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(1, 2)))
model.add(Dropout(0.2))
model.add(LSTM(64))
model.add(Dropout(0.2))
model.add(Dense(1, activation='relu'))
start = time.time()
model.compile(loss='mse', optimizer='adam')
model.fit(X_train, y_train, batch_size=72, epochs=100, validation_split=0.1, verbose=1)
print("Compliation Time : ", time.time() - start)
print('存入模型中')
# model.save('model_1_multime.h5')
model.save('model_1(2).h5')
elif(str==5):
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(1, 3)))
model.add(Dropout(0.2))
model.add(LSTM(64))
model.add(Dropout(0.2))
model.add(Dense(1, activation='relu'))
start = time.time()
model.compile(loss='mse', optimizer='adam')
model.fit(X_train, y_train, batch_size=64, epochs=500, validation_split=0.1, verbose=1)
print("Compliation Time : ", time.time() - start)
print('存入模型中')
model.save('model_5_multime(11).h5')
elif(str==10):
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(1, 3)))
model.add(Dropout(0.1))
model.add(LSTM(64))
model.add(Dropout(0.1))
model.add(Dense(1, activation='relu'))
start = time.time()
model.compile(loss='mse', optimizer='adam')
model.fit(X_train, y_train, batch_size=64, epochs=500, validation_split=0.1, verbose=1)
print("Compliation Time : ", time.time() - start)
print('存入模型中')
model.save('model_10_web&temp(5).h5')
# score =model.evaluate(X_train,y_train)
# print('Score:{}'.format(score))
y_hat1 =model.predict(X_train)
y_hat1 = y_scale.inverse_transform(y_hat1)
y_train = y_scale.inverse_transform(y_train)
train_rmse = math.sqrt(mean_squared_error(y_train,y_hat1))
print('Train Score:%.6f RMSE'%(train_rmse))
mape1 = np.mean(np.abs((y_train-y_hat1)/y_train))*100
print('Train MAPE:%.3f' % mape1)
y_hat2 =model.predict(X_test)
y_hat2 = y_scale.inverse_transform(y_hat2)
y_test1 = y_scale.inverse_transform(y_test)
test_rmse = math.sqrt(mean_squared_error(y_test1[:-1],y_hat2[1:]))
print('Test Score:%.6f RMSE'%(test_rmse))
mape2 = np.mean(np.abs((y_test1[:-1]-y_hat2[1:])/y_test1[:-1]))*100
print('Test MAPE:%.3f' % mape2)
y_hat3 =model.predict(X_test)
y_hat3= y_scale.inverse_transform(y_hat3)
y_test2 = y_scale.inverse_transform(y_test)
test_rmse = math.sqrt(mean_squared_error(y_test2,y_hat3))
print('Test2 Score:%.6f RMSE'%(test_rmse))
mape2 = np.mean(np.abs((y_test2-y_hat3)/y_test2))*100
print('Test2 MAPE:%.3f' % mape2) |
import random
import string
from words import words
from hangman_drawing import user_lives
def get_valid_word(words):
word = random.choice(words)
while '-' in word or ' ' in word:
word = random.choice(words)
return word.upper()
def hangman():
lives = 6
word = get_valid_word(words)
word_letters = set(word) #letters of the word chosen
alphabet = set(string.ascii_uppercase)
used_letters = set()
#taking input
while len(word_letters) > 0 and lives > 0:
print("you have "+ str(lives) + "lives" + "you've guessed these letters " +' ' .join(used_letters))
word_list = [letter if letter in used_letters else '-' for letter in word]
print("current word: " + ','.join(word_list))
user_input = input("guess a letter: ").upper()
#checking user input validity
if user_input in alphabet - used_letters:
used_letters.add(user_input)
if user_input in word_letters: #guessing the correct letter
word_letters.remove(user_input)
else: #guessing the wrong letter
lives = lives - 1
print("letter is not in the word, try again")
print(" you have " + str(lives) + "lives remaining")
user_lives(lives)
elif user_input in used_letters:
print("you've already guessed this letter, try again")
else:
print("invalid character, try again")
if lives == 0:
print("too bad, better luck next time! The word was: "+ word)
else:
print("you've guess the word " + word)
print("you're winner!!!!")
hangman()
|
# BLOKUSFUNCTIONS.PY
# Functions useful for the other classes
import numpy as np
def findExtremes(points):
"""Return the minimum and maximum x and y from a 2xn array of points."""
xmin = xmax = points[0,0]
ymin = ymax = points[1,0]
for i in range(0, points[0].size):
curx = points[0,i]
cury = points[1,i]
if curx < xmin:
xmin = curx
if curx > xmax:
xmax = curx
if cury < ymin:
ymin = cury
if cury > ymax:
ymax = cury
return (xmin, xmax, ymin, ymax)
def toBoolArray(points):
"""Return a 2d boolean array in the shape of the provided 2xn point array."""
#Get min and max x and y
xmin, xmax, ymin, ymax = findExtremes(points)
# Find width and height
width = xmax - xmin + 1
height = ymax - ymin + 1
# Make 'blank' 2d boolean array (all false) of correct size
shape = np.zeros((height, width), dtype = bool)
# Switch appropriate points to True
for i in range(0, points[0].size):
shape[points[1,i] - ymin][points[0,i] - xmin] = True
return shape
def splitCornerArray(corners):
"""Return a list containing views of each 2x2 corner in a 2x2n array of corners"""
# NOTE: these will change as the piece moves! Make a copy to save them
rtn = list()
numCorners = corners[0].size/2
for i in range(0, numCorners):
cur = corners[:,2*i:2*(i+1)]
rtn.append(cur)
return rtn
|
from math import sin, cos
import random
class Polecart:
# state variables
theta = 0.00
thetaVel = 0.0
thetaAcc = 0.0
x = 0.0 #pole position.
y = 0.0
xVel = 0.0
xAcc = 0.0
gravity = -9.81
massCart = 1.0
massPole = 0.1
totalMass = massCart+massPole
poleLen = 0.5 # this is half of the poles actual length (measured from bottom to center)
force = 10 # this will either be +- 10 newtons
#cart variables:
cartW, cartH = 40, 40
#pole positions.
poleX1, poleY1 = x , y #bottom point attatched to the cart.
poleX2, poleY2 = poleX1, poleY1 - poleLen
trackLimit = 2.4 # the cart is only allowed to travel +- 2.4 meters from the center
poleFail = 0.523599 # the pole can go 30 degrees from level before the test is failed
currentTime = 0.00 # this will mostly be used for analytics
tau = 0.0045 # this will be the time jump each tick
def __init__(self, randomize=True):
if(randomize):
self.theta = random.uniform(0.05, 0.25) * random.choice([-1, 1])
self.thetaVel = random.uniform(0.05, 0.15) * random.choice([-1, 1])
# print(self.theta, self.thetaVel)
else:
self.theta = 0.01
self.thetaVel = 0.03
#calculate the new position of the pole's points.
def _calculatePolePos(self):
#update the attatched pole position to be equal to the x and y of the main cart body.
self.poleX1, self.poleY1 = self.x, self.y
#convert polar coordinates to cartesian coordinates.
self.poleX2 = self.poleX1 + (self.poleLen * sin(self.theta))
self.poleY2 = self.poleY1 - (self.poleLen * cos(self.theta))
# the complete run function
# takes the action and updates game variables as necessary
def run(self, action):
if action == 0:
self.force = 0
elif action > 0:
self.force = 10
else:
self.force = -10
# do things
# calculate the angular acceleration
self.thetaAcc = (-self.gravity*sin(self.theta) + cos(self.theta)*
((-self.force-self.massPole*self.poleLen*(self.thetaVel**2)*sin(self.theta))/self.totalMass))
self.thetaAcc /= self.poleLen*((4/3)-(self.massPole*cos(self.theta)**2)/self.totalMass)
# calculate the cart acceleration
self.xAcc = (self.force+self.massPole*self.poleLen*
((self.thetaVel**2)*sin(self.theta)-self.thetaAcc*cos(self.theta))) / self.totalMass
# update the 4 variables using the time tau
# should tau be a set 0.02 seconds?
self.x += self.tau * self.xVel
self.xVel += self.tau * self.xAcc
self.theta += self.tau * self.thetaVel
self.thetaVel += self.tau * self.thetaAcc
# update the current time and pole positions.
#self.currentTime += self.tau
self._calculatePolePos()
def hasLost(self):
result = False
if abs(self.theta) > self.poleFail:
#print("theta greater than limit", self.theta, ">", self.poleFail)
result = True
elif abs(self.x) > self.trackLimit:
#print("x greater than limit", self.x, ">", self.trackLimit)
result = True
#print("result = ", result)
return result
|
# One Time Pad encryption
# an encrypting technique used to to shift every character of a message according to a one time pad (or just a radnom sequence)
# I've encorporated my own random function into the algorithm
import datetime
alphabet = ['i', 'l', 'o', 'v', 'e', 'k', 'a', 'n', 'b', 'r', 'u', 'g', 'm', 'h', 'c', 'p', 'q', 'j', 's', 't', 'f',
'd', 'z', 'y', 'x', 'w', ' ']
def caesar(letter,key):
i = 0
for l in alphabet:
if l == letter:break
i = i+1
global akey
akey = i + key
if akey > 26:
while akey > 26:
akey = akey - 27
cypher = alphabet[akey]
return cypher
def randkey(length): # custom random sequence generator (not perfect)
now = datetime.datetime.now()
list1 = []
keyy = []
x = 0
ctr = 0
mask = 0xff
while (ctr <= mask):
nnn = now.microsecond
coeff = now.second
if x == 1: # I added this because 1^n is still 1
k = coeff + coeff * nnn
k = k & mask
else:
k = coeff * x ^ 3 + nnn * x ^ 2 + x + nnn
k = k & mask
if k not in list1:
list1.append(k)
ctr += 1
x += 1
ctr1 = 0
counter = 0
while (ctr1 < mask) and counter < length:
if list1[ctr1] != 0 :
keyy.append(list1[ctr1])
ctr1 += 1
counter += 1
return keyy
def vermund(word):
emsg = []
counter = 0
ctr = 0
wordletters = []
for l in word:
wordletters.append(l)
global keylist #gets OTP
keylist = randkey(len(word))
while counter < len(word):
emsg.append(caesar(wordletters[ctr],keylist[ctr]))
ctr += 1
counter += 1
return emsg
#====================User Interface=========================================
def user():
wordy = str(input("\nEnter message to encrypt\n\n"))
product = vermund(wordy)
wordd = ''.join(product)
print("\n",wordd,"\n")
print("Key: ")
return keylist
while 25 == 25:
print(user())
|
__author__ = 'Ruslanas'
from graphics.vector import Vec3
from tkinter import *
root = Tk()
canvas = Canvas(root, width=100, height=100)
canvas.pack()
vec = Vec3(0, 50, 0)
origin = Vec3(50, 50, 0)
for i in range(12):
canvas.create_line(origin.x, origin.y, (origin + vec).x, (origin + vec).y)
vec.rotate_z(30)
mainloop()
|
a = 1
for i in range(9):
a = (a + 1) * 2
print(a)
for i in range(3):
print(' ', end=' ')
for a in range(i):
print('*')
sum= 0
for b in range(1, 20):
sum = ((b+1)/b)+sum
print(sum)
|
a = int(input("enter number1 :"))
b = int(input("enter number2 :"))
c = int(input("enter number3 :"))
if(a>b and a>c):
print(a," is largest")
else:
if(b>c):
print(b," is largest")
else:
print(c," is largest")
|
'''
Finds k-th smallest element in the array arr.
'''
#########################################################################
from random import randrange
def find_kth(arr, k, start=0, end=None):
if not end:
end = len(arr) -1
pivot_ridx = randrange(start, end)
pivot = arr[pivot_ridx]
pivot_idx = _partition(arr, start, end, pivot_ridx)
if pivot_idx + 1 == k:
return pivot
elif pivot_idx + 1 > k:
return find_kth(arr, k, start, pivot_idx)
else:
return find_kth(arr, k, pivot_idx, end)
def _partition(arr, start, end, pivot_idx):
pivot = arr[pivot_idx]
arr[end], arr[pivot_idx] = arr[pivot_idx], arr[end]
inc_idx = start
for i in range(start, end):
if arr[i] <= pivot:
arr[inc_idx], arr[i] = arr[i], arr[inc_idx]
inc_idx += 1
arr[end], arr[inc_idx] = arr[inc_idx], arr[end]
return inc_idx
#########################################################################
''' Verification test '''
if __name__ == "__main__":
from random import shuffle, randint
from time import clock
from heapq import nsmallest
for l in range(1, 7):
arr = list(range(1, 10**l))
k = randint(1, len(arr))
shuffle(arr)
start = clock()
assert k == find_kth(arr, k)
print('find_kth for length 10 ^', l , '; k =', k, clock() - start)
start = clock()
n = nsmallest(k, arr)[k-1]
assert n == k
print('heapq for length 10 ^', l , ': k =', k, clock() - start) |
import os
import openpyxl
def calculate_water_usage(work_book, work_sheet_names, row_num):
"""
2か月ごとの水道使用量を取得
"""
# 初期処理
work_sheet = work_book.get_sheet_by_name(work_sheet_names[0])
# 水道使用量リスト
sum_of_water_usage_per_one_month = []
water_usage_per_one_month = [0]
"""
index 0 : 3 月
1 : 4 月
2 : 5 月
3 : 6 月
.
11 : 2 月
12 : 3 月
"""
water_usage_per_two_month = []
"""
index 0 : 4~5 月
1 : 6~7 月
2 : 8~9 月
3 : 10~11 月
4 : 12~1 月
5 : 2~3 月
"""
# 各月までの累計水道使用量を取得
for i in range(13):
cell_num = work_sheet.cell(row=row_num,column=i+3).value
sum_of_water_usage_per_one_month.append(cell_num)
# 各月の累計使用量を取得
for i in range(1,13):
result = (sum_of_water_usage_per_one_month[i] - sum_of_water_usage_per_one_month[i-1])
water_usage_per_one_month.append(result)
# 2か月ごとの累計使用量を取得
for i in range(1,13,2):
result = (water_usage_per_one_month[i] + water_usage_per_one_month[i+1])
water_usage_per_two_month.append(result)
# 戻り値
return water_usage_per_two_month
def calculate_sum_water_fee(work_book, work_sheet_names, water_usage_list):
"""
2か月ごとの水道料金を取得
"""
# 初期処理
work_sheet = work_book.get_sheet_by_name(work_sheet_names[1])
water_fee_list = []
# 水道料金マスタから水道料金を取得
for i in range(6):
for j in range(6,236):
water_usage = work_sheet.cell(row=j,column=1).value
if water_usage == water_usage_list[i]:
water_fee_list.append(work_sheet.cell(row=j,column=4).value)
break
return water_fee_list
def water_charge_statement_create(work_book,
work_sheet_names,
row_num,
water_usage_list,
water_fee_list):
"""
帳票作成
"""
# 初期処理
work_sheet1 = work_book.get_sheet_by_name(work_sheet_names[0])
work_sheet3 = work_book.get_sheet_by_name(work_sheet_names[2])
# 部屋番号取得
room_num = work_sheet1.cell(row=row_num,column=1).value
# 氏名取得
room_owner = work_sheet1.cell(row=row_num,column=2).value
# 帳票作成
work_sheet3.cell(row=5,column=2).value = str(room_num) + '号'
work_sheet3.cell(row=5,column=3).value = str(room_owner) + '様'
work_sheet3.cell(row=7,column=4).value = work_sheet_names[0]
sum_price = 0
sum_minus_price = 0
for i in range(6):
work_sheet3.cell(row=10+i,column=3).value = water_usage_list[i]
work_sheet3.cell(row=10+i,column=4).value = water_fee_list[i]
# 差引額
work_sheet3.cell(row=10+i,column=6).value = water_fee_list[i] - int(work_sheet3.cell(row=10+i,column=5).value)
# 合計水道料金保存
sum_price = sum_price + water_fee_list[i]
# 合計差引額保存
sum_minus_price = sum_minus_price + int(work_sheet3.cell(row=10+i,column=6).value)
# 差額
price_diff = sum_minus_price - int(work_sheet3.cell(row=22,column=3).value)
if price_diff > 0:
work_sheet3.cell(row=22,column=5).value = '▲' + "{:,}".format(price_diff)
elif price_diff == 0:
work_sheet3.cell(row=22,column=5).value = '0'
elif price_diff < 0:
work_sheet3.cell(row=22,column=5).value = "{:,}".format(abs(price_diff))
# 請求額・返金額
if price_diff >= 0:
work_sheet3.cell(row=26,column=4).value = '請求額'
work_sheet3.cell(row=26,column=5).value = price_diff
elif price_diff < 0:
work_sheet3.cell(row=26,column=4).value = '返金額'
work_sheet3.cell(row=26,column=5).value = abs(price_diff)
# 名前を付けて保存
work_book.save(f'{work_sheet_names[0]}/{room_num} {room_owner}.xlsx')
def report_print():
"""
帳票印刷
"""
pass
#----------------------------------#
# main 処理
#----------------------------------#
def main():
book_name = 'water_fee_table.xlsx'
try:
# ワークブック取得
work_book = openpyxl.load_workbook(book_name)
# ワークシート取得
work_sheet_names = work_book.get_sheet_names()
"""
work_sheet[0] : H__年度
work_sheet[1] : 水道料金マスタ
work_sheet[2] : 印刷テンプレート
"""
# 今年度帳票保存ディレクトリ作成
os.mkdir(work_sheet_names[0])
# 初期処理
work_sheet = work_book.get_sheet_by_name(work_sheet_names[0])
max_row = work_sheet.max_row - 1
# 一人ずつ帳票作成
for row_num in range(2,max_row+2):
# 水道使用量計算
water_usage_list = calculate_water_usage(work_book, work_sheet_names, row_num)
# 水道使用料計算
water_fee_list = calculate_sum_water_fee(work_book, work_sheet_names, water_usage_list)
# 水道使用量・水道料金明細ファイル作成
water_charge_statement_create(work_book,
work_sheet_names,
row_num,
water_usage_list,
water_fee_list)
# 帳票印刷
report_print()
except:
assert False, '処理が中止されました。'
finally:
work_book.close
if __name__ == '__main__':
main()
|
import psycopg2
import time
import serial
def main():
banco = Banco('projects','arduinoproject','postgres','banco')
# Cria conexao:
banco.connection();
banco.insertDataInto(table='environment', description='soil')
banco.selectAllDataFrom(table='environment')
class Banco:
"""Database class. Use this class to create connection e execute CRUD
commands on a database.
Parameters
----------
database : String
Database name.
schema : type
Schema which the tables are stored.
user : String
User's username to access to database.
password : type
User's password to access the database.
port : int
Port number which the database uses.
host : type
Database host address.
"""
def __init__(self, database, schema, user, password, port=5432, host='localhost'):
self.database = database
self.schema = schema
self.user = user
self.password = password
self.port = port
self.host = host
self.con = None
self.cur = None
self.query = None
def connection(self):
"""Creates connection with the database using the specified parameter at
the class constructor.
Returns
-------
void
"""
try:
self.con = psycopg2.connect(database=self.database,
user=self.user,
password=self.password,
host=self.host,
port=self.port)
self.cur = self.con.cursor()
except (Exception, psycopg2.DatabaseError) as error:
print("exception: " + str(error))
def insertDataInto(self, table, **kwargs):
"""Inserts data into a table using the parameters as fields and it's
values as data to be inserted.
Parameters
----------
table : String
Table which the data will be inserted.
**kwargs : String
Fields and values to be inserted in the table. Use the template
fieldName='value' to pass the columns and values. Ilimited number of
parameters allowed here.
Returns
-------
void
"""
fields = []
values = []
unknownValues = []
self.query = "INSERT INTO " + self.schema + "." + table
for key in kwargs:
# Table's fields
fields.append(key);
# Table's values
values.append(kwargs[key])
# Placeholders
unknownValues.append("%s")
# Reversing to keep fields and values in the right order
fields.reverse()
values.reverse()
# Converting the lists in string
knownFields = ", ".join(fields)
placehold = ', '.join(unknownValues)
if(len(values) == 1): # Case only one value is inserted
self.cur.execute("INSERT INTO " + self.schema + "." + table + "(" + knownFields + ") VALUES ('" + str(values[0]) + "')")
else:
knownValues = tuple(values)
self.query = "INSERT INTO " + self.schema + "." + table + "(" + knownFields + ") VALUES(" + placehold + ")"
print(self.query)
print(knownValues)
self.cur.executemany(self.query, knownValues)
self.con.commit()
def selectDataFrom(self, table):
"""Selects one row data from the specified table.
Parameters
----------
table : String
Table name which data will be fetched.
Returns
-------
String
Value fetched from the query.
"""
self.cur.execute('SELECT * FROM ' + self.schema + '.' + table)
data_output = self.cur.fetchone();
print(data_output)
return data_output
def selectAllDataFrom(self, table):
"""Selects all data from the specified table.
Parameters
----------
table : String
Table name which data will be fetched.
Returns
-------
String tuple
Values fetched from the query. Each tuple represents a row.
"""
self.cur.execute('SELECT * FROM ' + self.schema + '.' + table)
rows = self.cur.fetchall()
for row in rows:
print row
return rows
def closeConnecetion(self):
"""Closes the connection.
Returns
-------
void
"""
self.con.close()
def updataDataFrom(self, table):
pass
# TODO: Create update method
def deleteDataFrom(self, table):
pass
# TODO: Create delet method
if __name__ == "__main__":
main()
|
def main():
hieght = int(input("Enter Hieght: "))
for i in range(0,hieght):
for j in range(0,i+1):
print("*",end= "" )
print("")
if __name__ == "__main__":
main() |
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
"""
They key to make this efficient as possible is to reduce the number of
times we check if an integer is a factor of the input number.
Number Theory:
Composite Number has Prime Factor not Greater Than its Square Root
We will only check until the square root of the input integer , and add 1
for it to be included.
e.g for x in range(1,int(sqrt(input_int))+1)
The resulting list will only give you the result of factors not greater
than the square root of the input integer. To get the other factors , divide
each of the elements on the first list with the input integer. Compare the two list
and add criteria to remove any duplicate and elements equal to the input integer
"""
if num < 0:
return False
limit = int(num ** 0.5) + 1
sqrt_list = [(x if x != num else 0) for x in range(1,limit) if num % x == 0]
sqrt_factor_list = [(num / x if x != num / x and x != 1 else 0) for x in sqrt_list if x != 0]
return ((sum(sqrt_list) + sum(sqrt_factor_list)) == num) if num > 0 else False |
#!/usr/bin/env python
# HW04_ex08_11
# The following functions are all intended to check whether a string contains
# any lowercase letters, but at least some of them are wrong. For each function,
# describe what the function actually does (assuming that the parameter is a
# string).
# Do not merely paste the output as a counterexample into the documentation
# string, explain what is wrong.
################################################################################
# Body
def any_lowercase1(s):
"""if the first letter of the string is uppercase, this returns FALSE becuase the first
time through the IF condition is not met, so it goes on to the ELSE statement which
automatically returns FALSE.
"""
for c in s:
if c.islower():
return True
else:
return False
print c
def any_lowercase2(s):
"""isn't this just checking if the string 'c' is lowercase? which it always will be because
it is given as lower. If you change it to 'C'.islower() then it always returns FALSE. The
only time this doesn't return TRUE is if there are no characters in the string..
"""
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
"""this just returns TRUE or FALSE for whether or not the last character in the string is
uppercase or lowercase.
"""
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
"""I don't understand this one.
"""
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
"""as it goes through the letters, as soon as it gets to an uppercase letter
it returns FALSE. therefore it is looking for any upper, not any lower
"""
for c in s:
if not c.islower():
return False
return True
################################################################################
def main():
# Remove print("Hello World!") and for each function above that is wrong,
# call that function with a string for which the function returns
# incorrectly.
print any_lowercase5("thisstring")
print any_lowercase5("ThisstringmessesupthefunCtion")
if __name__ == '__main__':
main() |
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:zhoukaiyin
"""
# n的阶乘
def getFactorial(n):
if n==1:
return 1
return n*getFactorial(n-1)
# 求字符串所有子序列
def printAllSubsquence(test, i, res):
if i == len(test):
print(res)
return
printAllSubsquence(test, i+1, res)
printAllSubsquence(test, i+1, res + test[i])
printAllSubsquence(["b","c","d"],0,"") |
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:zhoukaiyin
"""
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:zhoukaiyin
"""
#时间复杂度太高
def lengthOfLongestSubstring(s: str) -> int:
min = 0
string = ""
for i in range(1,len(s)+1):
for j in range(len(s)-i+1):
lis = s[j:j+i]
if len(lis)==len(set(lis)) and len(lis)>min:
min = len(lis)
string = lis
print(string)
#窗口问题:
def lengthOfLongestSubstring_new(s: str) -> int:
"""
维护一个队列,该队列中不存在重复项,当新加入的为
重复项则通过remove从左往右删除来使得该重复项不再存在
:param s:
:return:
"""
if not s:return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len+=1
while s[i] in lookup:
lookup.remove(s[left])
left+=1
cur_len-=1
if cur_len > max_len:max_len=cur_len
lookup.add(s[i])
return max_len
|
# -*- coding: utf-8 -*-
__author__ = "Anshul Kapoor(10456388)| " \
"Pranay Singh(10455251) | " \
"Himanshu Bishnoi(10451752)"
"""
J&M 3rd Exercise 11.1
"""
from stat_parser import Parser
import nltk
moby_dick = nltk.corpus.gutenberg.raw('melville-moby_dick.txt')
sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
sentences = sent_tokenizer.tokenize(moby_dick)
def find_longest_sentence():
longest_sentence = ""
word_count = 0
for sent in sentences:
w = len(nltk.tokenize.word_tokenize(sent))
if w > word_count:
word_count = w
longest_sentence = sent
# print("longest sentence: \n" + longest_sentence)
return longest_sentence
def main():
""" Main function which is used as an interface """
parser = Parser()
sentence = "Book the cooks who cook the books."
longest_sentence = find_longest_sentence()
print(parser.parse(sentence))
if __name__ == '__main__':
main()
|
def sum(num):
if(num==0):
return 0
else:
return (num%10) + sum(num//10)
def main():
num=int(input("Enter the number : "))
ret=sum(num)
print("Sum is : ",ret)
if (__name__=="__main__"):
main() |
import math
def area_triangle(side1, side2, side3):
"""Returns the area of a triangle with the given side lengths."""
# Uses Heron's formula
s = (float(side1) + side2 + side3) / 2
return math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
print area_triangle(3, 4, 5)
|
#-*-coding:utf-8-*-
import pilas
import piedra_espacial
import random
#import contador_de_vidas
from grilla import Jeison
class Estado:
"Representa un estado dentro del juego."
def actualizar(self):
pass #tienes que sobrescribir este metodo...
class Jugando(Estado):
"Representa el estadop de juego."
def __init__(self,juego,nivel):
self.nivel=nivel
self.juego=juego
self.juego.crear_piedras(cantidad=nivel*3)
#Cada segundo le avisa al estado que cuente.
pilas.mundo.agregar_tarea(1,self.actualizar)
def actualizar(self):
if self.juego.ha_eliminado_todas_las_piedras():
self.juego.cambiar_estado(Iniciando(self.juego,self.nivel+1))
return False
return True
class Iniciando(Estado):
"Estado que indica que el juego ha comenzado."
def __init__(self,juego,nivel):
self.texto = pilas.actores.Texto("Nivel %d" %(nivel))
self.texto.escala = 0.1
self.texto.escala = [1]
self.texto.rotacion = [360]
self.nivel = nivel
self.texto.color = pilas.colores.negro
self.contador_de_segundos = 0
self.juego = juego
pilas.mundo.agregar_tarea(1,self.actualizar)
def actualizar(self):
self.contador_de_segundos +=1
if self.contador_de_segundos >2:
self.juego.cambiar_estado(Jugando(self.juego,self.nivel))
self.texto.eliminar()
return False
return True #para que el contador siga trabajando.
class Pierde_Vida(Estado):
def __init__(self,juego):
self.contador_de_segundos= 0
self.juego = juego
juego.cambiar_estado(PierdeTodoElJuego(juego))
def actualizar(self):
self.contador_de_segundos +=1
if self.contador_de_segundos >2:
self.juego.crear_grilla()
return False
return True
class PierdeTodoElJuego(Estado):
def __init__(self,juego):
#muestra el mensaje "has perdido"
pilas.avisar(u"Perdiste!, pulsa Esc para volver al menu principal")
saludo = pilas.actores.Texto(u"Perdiste!!")
# Realiza una animacion
saludo.escala = 0.1
saludo.escala = [1]
saludo.rotacion = [360]
def cuando_pulsa_tecla(self,*k,**kw):
import escena_menu
pilas.cambiar_escena(escena_menu.EscenaMenu())
def actualizar(self):
pass
class Juego(pilas.escena.Base):
"la escena que te permite controlarlo y jugar"
def __init__(self):
pilas.escena.Base.__init__(self)
def iniciar(self):
pilas.fondos.Fondo("fondo.jpg")
self.pulsa_tecla_escape.conectar(self.cuando_pulsa_tecla_escape)
self.piedras = []
self.crear_personaje()
self.cambiar_estado(Iniciando(self,1))
self.puntaje= pilas.actores.Puntaje(x=280 , y=220 ,color=pilas.colores.negro)
def cambiar_estado(self,estado):
self.estado = estado
def crear_personaje(self):
uachin = Jeison()
uachin.escala = 1.5
uachin.aprender(pilas.habilidades.SeMantieneEnPantalla)
uachin.definir_enemigos(self.piedras,self.cuando_explota_asteroide)
self.colisiones.agregar(uachin,self.piedras,self.restar_vida)
def cuando_explota_asteroide(self):
self.puntaje.aumentar(1)
def cuando_pulsa_tecla_escape(self,*k,**kw):
"regresa al menu principal."
import escena_menu
pilas.cambiar_escena(escena_menu.EscenaMenu())
def restar_vida(self,uachin,piedra):
"responde a la colision entre la nave y la piedra."
uachin.eliminar()
self.cambiar_estado(Pierde_Vida(self))
def crear_piedras(self,cantidad):
"genera una cantidad especifica de marcianos en el escenario."
fuera_de_la_pantalla = [-600,-650,-700,-750,-800]
tamanos = ['grande','media','chica']
for x in range(cantidad):
x= random.choice(fuera_de_la_pantalla)
y= random.choice(fuera_de_la_pantalla)
t= random.choice(tamanos)
piedra_nueva= piedra_espacial.PiedraEspacial(self.piedras,x=random.randrange(-320, 320),y=240,tamano=t)
piedra_nueva.imagen = pilas.imagenes.cargar("piedra_grande.png")
self.piedras.append(piedra_nueva)
def ha_eliminado_todas_las_piedras(self):
return len(self.piedras)==0
|
1 - Faça um Programa que peça dois números e imprima o maior deles.
2 - Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido.
3 - Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
* Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro
* Triângulo Equilátero: três lados iguais
* Triângulo Isósceles: quaisquer dois lados iguais
* Triângulo Escaleno: três lados diferentes |
# -*- coding: utf-8 -*-
# Se listarmos os números menores que 10 e que são múltiplos de 3 e de 5, temos 3, 5, 6 e 9.
# A soma desse múltiplos é 23
# Descubra a soma de todos os múltiplos de 3 e de 5 e que são menores que 1000
limite = 1000
total = 0
for i in range(0, limite):
if i % 3 == 0:
total = total + i
elif i % 5 == 0:
total = total + i
print(total) |
# -*- coding: utf-8 -*-
# O código abaixo imprime o somatório dos números da lista
# Por que ele está dando erro?
# Como podemos corrigir?
lista = [ "0", 1, 2, "3", 4 ]
total = 0
for elemento in lista:
total = total + elemento
print(total) |
numbers = []
def even():
for num in range(1,51):
if num % 2 == 0:
numbers.append(num)
print(numbers)
return numbers
even() |
import random # For generating random numbers
import sys # We will use sys.exit to exit the program
import pygame
from pygame.locals import * # Basic pygame imports
from tkinter import *
# Global Variables for the game
SCREENWIDTH = 320
SCREENHEIGHT = 560
GROUNDY = SCREENHEIGHT * 0.84 #base.png 84% height
GAME_SPRITES = {} #images used in game
GAME_SOUNDS = {} #sounds used in game
#initialising the images rendered in the game
class images:
def __init__(self):
self.Playerimg=[('gallery/sprites/bird.png',25),('gallery/sprites/bull-big.png',45), ('gallery/sprites/smile1.png',60),
('gallery/sprites/smile2.png',60), ('gallery/sprites/smile3.png',60), ('gallery/sprites/smile7.png',60)] #list of tuples containing avatar images and their base values
self.Pipeimg = ['gallery/sprites/pipe.png'] #list of different obstacle images
def playerimg_base(self):
"""
Returns the image of avatar that player chose
"""
return self.Playerimg[1]
def pipeimg(self):
"""
Returns a random image of obstacle
"""
return random.choice(self.Pipeimg)
img=images()
BASE=img.playerimg_base()[1] #the base of the avatar
BACKGROUND= 'gallery/sprites/background.png'
PIPE= img.pipeimg()
#added queue data structure to points on the basis of FIFO rule
class Point_Queue:
def __init__(self):
self.queue=[]
def __len__(self):
return len(self.queue)
def enqueque(self,score):
"""
Add points to queue list
"""
self.score=score
self.queue.append(self.score)
def dequeue(self):
"""
Remove points from queue list
"""
point=self.queue.pop(0)
return point
def traverse(self):
"""
To display the pointes collected by the user
"""
x=1
for points in self.queue:
statement= 'The score of round '+str(x)+' is: '+str(points)+'!'
x+=1
return statement
class Buffalo_Wing:
scorequeue=Point_Queue()
def __init__(self):
self.PLAYER= img.playerimg_base()[0]
self.crash_avatar=['gallery/sprites/smile5.png','gallery/sprites/smile4.png']
self.FPS = 32 #frames per second
self.SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) #initialise screen
GAME_SPRITES['message'] =pygame.image.load('gallery/sprites/message.png').convert_alpha()
#This will be the main point from where game will start
pygame.init() #Initialize all pygame's modules
self.FPSCLOCK = pygame.time.Clock() #to control fps
pygame.display.set_caption('BUFFALO WINGS')
#adding keys values to dictionary
GAME_SPRITES['numbers'] = (
pygame.image.load('gallery/sprites/0.png').convert_alpha(),
pygame.image.load('gallery/sprites/1.png').convert_alpha(),
pygame.image.load('gallery/sprites/2.png').convert_alpha(),
pygame.image.load('gallery/sprites/3.png').convert_alpha(),
pygame.image.load('gallery/sprites/4.png').convert_alpha(),
pygame.image.load('gallery/sprites/5.png').convert_alpha(),
pygame.image.load('gallery/sprites/6.png').convert_alpha(),
pygame.image.load('gallery/sprites/7.png').convert_alpha(),
pygame.image.load('gallery/sprites/8.png').convert_alpha(),
pygame.image.load('gallery/sprites/9.png').convert_alpha(),
) #key-value pair with tuple as the value
#conv alpha = optimises images for faster blitting
GAME_SPRITES['message'] =pygame.image.load('gallery/sprites/message.png').convert_alpha()
GAME_SPRITES['base'] =pygame.image.load('gallery/sprites/base.png').convert_alpha()
GAME_SPRITES['pipe'] =(pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(), 180),
pygame.image.load(PIPE).convert_alpha()
) #two elements in tuple, to rotate the pipe
GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert()
GAME_SPRITES['player'] = pygame.image.load(self.PLAYER).convert_alpha()
# Game sounds
GAME_SOUNDS['die'] = pygame.mixer.Sound('gallery/audio/die.wav')
GAME_SOUNDS['hit'] = pygame.mixer.Sound('gallery/audio/hit.wav')
GAME_SOUNDS['point'] = pygame.mixer.Sound('gallery/audio/point.wav')
GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('gallery/audio/swoosh.wav')
GAME_SOUNDS['wing'] = pygame.mixer.Sound('gallery/audio/wing.wav')
self.welcomeScreen() #Shows welcome screen to the user until a button is pressed
self.mainGame() #This is the main game function
def welcomeScreen(self):
"""
Shows welcome images on the screen
"""
self.playerx = int(SCREENWIDTH/5) #adds the bird at the 1/5th of screen self.width
self.playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2) #makes the avatar centre position, (total height- avatar pic height)/2
self.messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width())/2)
self.messagey = int(SCREENHEIGHT*0.01)
self.basex = 0 #the base image is always on 0 of x
while True:
for event in pygame.event.get(): #monitors all button clicks
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE): #eiter clicks on cross or esc key
pygame.quit()
sys.exit()
#KEYDOWN refers to a keyboard key pressed
# If the user presses space or up key, start the game for them
elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP):
return #according to func call, return will start game
else:
self.SCREEN.blit(GAME_SPRITES['background'], (0, 0))
self.SCREEN.blit(GAME_SPRITES['player'], (self.playerx, self.playery))
self.SCREEN.blit(GAME_SPRITES['message'], (self.messagex,self.messagey))
self.SCREEN.blit(GAME_SPRITES['base'], (self.basex, GROUNDY))
pygame.display.update() #runs all the blits
self.FPSCLOCK.tick(self.FPS)
def mainGame(self):
"""
The main game function
"""
self.score = 0
#adjusting inital position of birdy
self.playerx = int(SCREENWIDTH/5)
self.playery = int(SCREENWIDTH/2)
self.basex = 0
# Create 2 pipes for blitting on the screen
#the pipes move, the bird doesn't (illusion)
self.newPipe1 = self.getRandomPipe()
self.newPipe2 = self.getRandomPipe()
#List of upper pipes
self.upperPipes = [
{'x': SCREENWIDTH+200, 'y':self.newPipe1[0]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':self.newPipe2[0]['y']},
]
#List of lower pipes
self.lowerPipes = [
{'x': SCREENWIDTH+200, 'y':self.newPipe1[1]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':self.newPipe2[1]['y']},
]
self.pipeVelX = -4 #velocity of pipes moving backwards
self.playerVelY = -9 #velocity of bird falling down
self.playerMaxVelY = 10 #max up arrow/space velocity
self.playerMinVelY = -8
self.playerAccY = 1 #acceleration while falling
self.playerFlapAccv = -8 #velocity while flapping
self.playerFlapped = False # It is true only when the bird is flapping
#game loop
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if self.playery > 0: #birdy is above ground
self.playerVelY = self.playerFlapAccv #birdy goes up
self.playerFlapped = True
GAME_SOUNDS['wing'].play() #plays sound
#This function will return true if the player is crashed
self.crashTest = self.isCollide(self.playerx, self.playery, self.upperPipes, self.lowerPipes)
if self.crashTest:
Buffalo_Wing.scorequeue.enqueque(self.score)
print(f"Your score is {self.score}")
return
#check for score
self.playerMidPos = self.playerx + GAME_SPRITES['player'].get_width()/2 #getting birdy centre position
#if birdy centre passes pipe == point + 1
for pipe in self.upperPipes:
self.pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2
if self.pipeMidPos<= self.playerMidPos < self.pipeMidPos +4:
self.score +=1
GAME_SOUNDS['point'].play()
if self.score>5:
self.incSpeed()
if self.playerVelY <self.playerMaxVelY and not self.playerFlapped:
self.playerVelY += self.playerAccY
#if user clicks up/space once, then crashes lateron
if self.playerFlapped:
self.playerFlapped = False
self.playerHeight = GAME_SPRITES['player'].get_height()
self.playery = self.playery + min(self.playerVelY, GROUNDY - self.playery - self.playerHeight) #the min returns 0, so the birdy stays on ground
#move pipes to the left
for upperPipe , lowerPipe in zip(self.upperPipes, self.lowerPipes): #zip creates subsets of two values from each list (x,y)
upperPipe['x'] += self.pipeVelX
lowerPipe['x'] += self.pipeVelX
# Add a new pipe when the first is about to cross the leftmost part of the screen
if 0<self.upperPipes[0]['x']<5:
self.newpipe = self.getRandomPipe()
self.upperPipes.append(self.newpipe[0])
self.lowerPipes.append(self.newpipe[1])
# if the pipe is out of the screen, remove it
if self.upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
self.upperPipes.pop(0)
self.lowerPipes.pop(0)
# Lets blit our sprites now
self.SCREEN.blit(GAME_SPRITES['background'], (0, 0))
for upperPipe, lowerPipe in zip(self.upperPipes, self.lowerPipes):
self.SCREEN.blit(GAME_SPRITES['pipe'][0], (upperPipe['x'], upperPipe['y']))
self.SCREEN.blit(GAME_SPRITES['pipe'][1], (lowerPipe['x'], lowerPipe['y']))
self.SCREEN.blit(GAME_SPRITES['base'], (self.basex, GROUNDY))
self.SCREEN.blit(GAME_SPRITES['player'], (self.playerx, self.playery))
self.myDigits = [int(x) for x in list(str(self.score))]
self.width = 0
for digit in self.myDigits:
self.width += GAME_SPRITES['numbers'][digit].get_width()
Xoffset = (SCREENWIDTH - self.width)/2
for digit in self.myDigits:
self.SCREEN.blit(GAME_SPRITES['numbers'][digit], (Xoffset, SCREENHEIGHT*0.12))
Xoffset += GAME_SPRITES['numbers'][digit].get_width()
pygame.display.update()
self.FPSCLOCK.tick(self.FPS)
def incSpeed(self):
"""
To increase the speed with respect to increasing score
"""
if self.score>=6 and self.score<10:
self.FPS = 32+8 #frames per second
elif self.score>10 and self.score<15:
self.FPS = 32+12
elif self.score>15 and self.score<20:
self.FPS = 32+18
elif self.score>20:
self.FPS = 32+20
return
def isCollide(self,playerx, playery, upperPipes, lowerPipes):
"""
Collison conditions with ground and obstacles
"""
self.playerx=playerx
self.playery=playery
self.upperPipes=upperPipes
self.lowerPipes=lowerPipes
if self.playery> GROUNDY - BASE or self.playery<0:
GAME_SOUNDS['hit'].play()
if BASE != 25 and BASE != 45 :
self.PLAYER='gallery/sprites/smile6.png'
GAME_SPRITES['player'] = pygame.image.load(self.PLAYER).convert_alpha()
self.SCREEN.blit(GAME_SPRITES['player'], (self.playerx, self.playery))
pygame.display.update()
return True
for pipe in self.upperPipes:
self.pipeHeight = GAME_SPRITES['pipe'][0].get_height()
if(self.playery < self.pipeHeight + pipe['y'] and abs(self.playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()):
GAME_SOUNDS['hit'].play()
if BASE != 25 and BASE != 45 :
self.PLAYER=random.choice(self.crash_avatar)
GAME_SPRITES['player'] = pygame.image.load(self.PLAYER).convert_alpha()
self.SCREEN.blit(GAME_SPRITES['player'], (self.playerx, self.playery))
pygame.display.update()
return True
for pipe in self.lowerPipes:
if (self.playery + GAME_SPRITES['player'].get_height() > pipe['y']) and abs(self.playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width():
GAME_SOUNDS['hit'].play()
if BASE != 25 and BASE != 45 :
self.PLAYER=random.choice(self.crash_avatar)
GAME_SPRITES['player'] = pygame.image.load(self.PLAYER).convert_alpha()
self.SCREEN.blit(GAME_SPRITES['player'], (self.playerx, self.playery))
pygame.display.update()
return True
return False
def getRandomPipe(self):
"""
Generate positions of two pipes(one bottom straight and one top rotated ) for blitting on the screen
"""
self.pipeHeight = GAME_SPRITES['pipe'][0].get_height() #accessing 0th index of tuple value from dict
self.offset = SCREENHEIGHT/3 #space for bird to pass
self.y2 = self.offset + random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 *self.offset)) #generates a random # between specified range
self.pipeX = SCREENWIDTH + 10
self.y1 = self.pipeHeight - self.y2 + self.offset
self.pipe = [
{'x': self.pipeX, 'y': -self.y1}, #upper Pipe, neg because inverted
{'x': self.pipeX, 'y': self.y2} #lower Pipe
]
return self.pipe
'''This class displays the total score to the user'''
class Score(Frame):
def __init__(self,master):
Frame.__init__(self,master)
Frame.config(self,width=150,height=200,bg="cyan")
self.master=master
self.score= 0
self.depends=str()
self.master.title("BUFFALO WINGS")
self.scoreque=Buffalo_Wing.scorequeue
self.buttons()
self.pack()
'''this function holding conditions on the basis of score'''
def condition(self):
for rounds in range(self.scoreque.__len__()):
indiv_score = self.scoreque.dequeue()
self.score=self.score+indiv_score
statement= 'The score of round '+str(rounds+1)+' is: '+str(indiv_score)+'!'
self.depends=self.depends+'\n'+str(statement)
if self.score>=25:
self.depends=self.depends+'\n'+"WELL PLAYED! with a great total score of "+str(self.score)
elif self.score>=20:
self.depends=self.depends+'\n'+"Nicely played! with a total score of " + str(self.score)
elif self.score>=15:
self.depends=self.depends+'\n'+"Good! your total score is "+ str(self.score)
elif self.score>=10:
self.depends=self.depends+'\n'+"Average! your total score is "+ str(self.score)
elif self.score<5:
self.depends=self.depends+'\n'+"Poorly played! your total score is "+ str(self.score)
'''to display the buttons'''
def buttons(self):
self.condition()
self.message2 = Label(self, text=self.depends ,width=50
,height=15,font=25,bg="green",fg='white')
self.Order2 = Button(self, text='CLOSE',height=5,width=10,
font=6,bg="red",fg='yellow' ,command=self.terminate)
self.Order2.pack(side='right',fill=Y)
self.Order3 = Button(self, text='PLAY AGAIN',height=3,width=10,
font=6,bg="lightblue",fg='purple' ,command=self.play_again)
self.Order3.pack(side="left",fill=Y)
self.message2.pack(fill=X)
''' A terminate button'''
def terminate(self):
self.master.destroy() #current game window destroy
'''If the user wants to play again'''
def play_again(self):
self.master.destroy()
objB=Buffalo_Wing()
stages()
def stages():
"""
Generate 5 chances of the player
"""
BACKGROUNDlist=[('gallery/sprites/bg1.png')] #list of different backgrounds
chances=0
while chances <2 :
if obj.crashTest==True:
global BACKGROUND
BACKGROUND=BACKGROUNDlist[0]
chances+=1
objB=Buffalo_Wing()
else:
high=Tk()
high.geometry('600x200+350+100')
high.resizable(0,0)
high.attributes("-topmost",True)
a=Score(high)
high.mainloop()
obj=Buffalo_Wing()
stages()
|
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
if a+b>c and a+c>b and b+c>a:
print(a, b, c)
print("triangle exists")
else:
print("triangle does not exist")
|
#1 Task.
#Вводится строка.
# Если в строке больше символов в нижнем регистре - вывести все в нижнем,
#если больше в верхнем - вывести все в верхнем,
#если поровну - вывести в противоположных регистрах.
s = input ("1. Enter a string: ")
s1 = s * 2
template_1 = "Some string {0}\nSome edited string {1}"
count_l = count_u = 0
for i in s:
if i.islower ():
count_l += 1
elif i.isupper ():
count_u += 1
print ("Upper case = ", count_u, "Lower case = ",count_l)
if count_l > count_u:
print (s.lower())
elif count_l < count_u:
print (s.upper())
else:
print (s.swapcase())
print (template_1.format (s, s1))
#2 Task
#Вводится строка.
#Если в строке каждое слово начинается с заглавной буквы, тогда
#добавить в начало строки 'done. '.
#Иначе заменить первые 5 элементов строки на 'draft: '.
# (можно использовать метод replace и/или конкатенацию строк + срезы)
s = input ("2. Enter a string: ")
s1 = s * 2
t = "done."
if s.istitle ():
print (t + s)
else:
print (s.replace (s [:5],"draft"))
print (template_1.format (s, s1))
#3 Task
#Если длина строки больше 20, то обрезать лишние символы до 20.
#Иначе дополнить строку символами '@' до длины 20.
#(можно использовать метод ljust либо конкатенацию и дублирование (+ и *))
#После выполнения кажого пункта выводить результат типа:
#1. Исходная строка: "some string".
#Результат: "some edited string".
# (Использовать форматирование строк f, format либо %)
s = input ("3. Enter a string: ")
s1 = s * 2
if len (s) > 20:
s = s [:21]
print (s)
else:
print (s.ljust (20, "@"))
print (template_1.format (s, s1))
|
year = int(input("year: "))
leap = 366
usual = 365
if year % 4 !=0:
print("Quantity of days: ", usual)
elif year % 4 == 0:
print("leap year:", leap)
elif year % 100 !=0:
print("leap year:", leap)
elif year % 400 != 0:
print("leap year:", leap)
else:
pass |
import copy
a=[[1,2,3,4],[4,5,6,7]]
b=copy.deepcopy(a)
print("a and b before modify")
print(a)
print(b)
a[0][1]=10
print("a and b after modify. b was obtain as a copy of a")
print(a)
print(b) |
# 3. List - contain set of elements, defined in [], can be set of nums, strings or combination
list_numbers = [12, 34, 23, 56, 45645, 234, 7862]
list_language = ["English", "Malay", "Mandarin", "Tamil"]
list_numbs_language = [34, 76, 54, "Python", "Java", "C++"]
# Concatenation
output = list_numbers + list_language
print("Concatenation of 2 list =", output)
# Index
print("Index 0 =", list_numbers[0]) # Only list in index 0
print("Index 0 to 4 =", list_numbers[0:5]) # print from index 0 to 5 excluding index 5
print("Everything with step of 2 =", list_language[::2]) # every 2
print("Reversing list =", list_language[::-1]) # reverse the list
# Change index 0 with other numbers
list_numbers[0] = 1000
print("Updated list =", list_numbers)
|
# 4) read using csv library
# Advantage : each line will be converted to list automatically
import csv
# fobj is file object used for reading any kind of file
with open("realestate.csv", "r") as fobj:
# converting file object to csv object
reader = csv.reader(fobj)
for line in reader:
print(line)
|
import os
print("Current directory =", os.getcwd())
print("Current username :", os.getlogin())
# list all the files
for file in os.listdir():
print(file)
# files from D:
for file in os.listdir("D:\\"):
print(file)
# delete file in the directory
# os.remove("put the file name")
# # delete extension files in current directory
# for file in os.listdir():
# if file.endswith(".docx") and os.path.isfile(file)
# os.remove(file)
#
# os.mkdir("testdir")
#
# # program to create 100 directories in the below format
# for val in range(1, 101):
# os.mkdir("dir" + str(val))
#
# os.chdir(path)
#
# for val in range(1, 101)
# os.rmdir("dir" + str(val))
# create empty file in python
# fobj = open("abcd.txt", "w"):
# fobj.close()
# display ONLY directories
for file in os.listdir():
if os.path.isdir(file):
print("This is a directory ", file)
# display ONLY file
for file in os.listdir():
if os.path.isfile(file):
print("This is a file ", file) |
def CurrentBoard(Board):
print("\n", Board.get("0"),"|",Board.get("1"),"|",Board.get("2"),
"\n---+---+---\n",Board.get("3"),"|",Board.get("4"),"|",Board.get("5"),
"\n---+---+---\n",Board.get("6"),"|",Board.get("7"),"|",Board.get("8"))
def NewBoard():
i = 0
Board = {}
while i < 9:
Board[str(i)] = i
i += 1
return Board
def CheckWinner(Board):
if Board.get(str(0)) == Board.get(str(1)) == Board.get(str(2)):
return Board.get(str(0))
elif Board.get(str(3)) == Board.get(str(4)) == Board.get(str(5)):
return Board.get(str(3))
elif Board.get(str(6)) == Board.get(str(7)) == Board.get(str(8)):
return Board.get(str(6))
elif Board.get(str(0)) == Board.get(str(3)) == Board.get(str(6)):
return Board.get(str(0))
elif Board.get(str(1)) == Board.get(str(4)) == Board.get(str(7)):
return Board.get(str(1))
elif Board.get(str(2)) == Board.get(str(5)) == Board.get(str(8)):
return Board.get(str(2))
elif Board.get(str(0)) == Board.get(str(4)) == Board.get(str(8)):
return Board.get(str(0))
elif Board.get(str(6)) == Board.get(str(4)) == Board.get(str(2)):
return Board.get(str(6))
else:
return "False"
def ReadPlay(Board):
while True:
play = input("Introduza a sua jogada (0-8): ")
if int(play) not in (0, 1, 2, 3, 4, 5, 6, 7, 8):
print("Jogada Invalida (Não introduziu um numero de 0 a 8).")
continue
if Board.get(play) not in (0, 1, 2, 3, 4, 5, 6, 7, 8):
print("Espaço ocupado.")
continue
else:
return play
def Play(Board,Position, Symbol):
Board[Position] = Symbol
|
#coding:utf-8
import urllib2,json
import city
def ctq():
name = raw_input('你想查询哪个城市的天气:')
bianma = city.city.get(name)
if bianma:
try:
url='http://www.weather.com.cn/data/cityinfo/%s.html' % bianma
result=urllib2.urlopen(url)
html=result.read()
html=json.loads(html)
info=html['weatherinfo']
print name
print info['weather']
print info['temp1']+'~'+info['temp2']
except:
print '查询失败!'
else:
print '请输入正确的城市!'
if __name__ == "__main__":
ctq() |
from datetime import datetime
def string_to_bool(string):
if string in ('f', 'F', 'false', 'False', 0):
return bool(False)
elif string in ('t', 'T', 'true', 'True', 1):
return bool(true)
else:
print("Please use true or false values.")
class TestClass:
""" test class to show effect of change attribute method """
def __init__(self):
self.a = 1
self.b = False
self.c = 'string'
self.d = 4.2
def setAtrib(self, index, value):
""" from the dict keys of attributes gained from vars() creates a list for an indexable way to set attributes"""
keys = list(vars(self).keys()) # creates list of keys
key = keys[index] # with index gain key value
vars(self)[key] = value # with key value set attribute to arguement value
def change_attribute_enhanced(self, index, value):
keys = list(vars(self).keys())
key = keys[index]
if type(vars(self)[key]) == type(int()):
vars(self)[key] = int(value)
elif type(vars(self)[key]) == type(bool()):
vars(self)[key] = string_to_bool(value)
elif type(vars(self)[key]) == type(datetime(1,1,1)):
try:
tempDatetime = datetime.strptime(value, '%m/%d/%Y %H:%M')
vars(self)[key] = tempDatetime
except Exception as err:
print("There is an issue: {}".format(err))
elif type(vars(self)[key]) == type(str()):
if type(value) == type(str()):
vars(self)[key] = value
else:
print("What are you try to do? Don't recognize that variable type.")
classObj = TestClass()
print(vars(classObj))
print(classObj.d)
#classObjKeys = list(vars(classObj).keys())
#key = classObjKeys[2]
#vars(classObj)[key] = 20
classObj.change_attribute_enhanced(3, '8/20/2020 9:38')
print(classObj.d)
print(vars(classObj))
|
def leaderof_array(arr):
for i in range(len(arr)):
flag = False
for j in range(i+1,len(arr)):
if arr[i] <= arr[j]:
flag = True
break
if flag == False:
print(arr[i],end=" ")
arr = [7,10,4,10,6,5,2]
print(leaderof_array(arr))
# naive approach Time complexity = 0(n**2)
# Space complexity = 0(1)
def leaderof_array1(arr):
l1 = []
last_index = len(arr)-1
current_leader = arr[last_index]
l1.append(current_leader)
for i in range(last_index-1,-1,-1):
if current_leader < arr[i]:
current_leader = arr[i]
l1.append(current_leader)
print(l1[::-1])
arr = [7,10,4,10,6,5,2]
print(leaderof_array1(arr))
# better approach Timw Complexity = 0(n)
# space Complexity = 0(n)
|
import math
def check_prime(number):
if number <=1:
return False
if number == 2:
return True
for i in range(2,number):
if number%i ==0:
return False
return True
def check_prime1(number):
if(number<=1):
return False
if number ==2:
return True
for i in range(2,int(math.sqrt(number))+1):
if number % i==0:
return False
return True
def check_prime2(number):
if(number<=1):
return False
if(number==2 or number==3):
return True
if(number%2 ==0 or number%3 ==0):
return False
for i in range(5,number,6):
if number%i ==0 or number%(i+2) ==0: # check with ith number and i+2th number
return False
return True
print(check_prime2(29))
|
def middle_linkedlist(self):
method 1
if self.head == None:
print("No element")
else:
llist = self.head
count = 0
while llist:
count = count+1
llist = llist.next
llist1 = self.head
for i in range(count//2):
llist1 = llist1.next
return llist1.data
# method2
if self.head == None:
print("No element")
else:
slow = self.head
fast = self.head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
return slow.data
|
def givensubarraySumzero(arr):
for i in range(len(arr)):
curry_sum = 0
for j in range(i,len(arr)):
curry_sum += arr[j]
if curry_sum == 0:
return True
return False
def givensubarraySumzero1(arr):
result = set()
prefix_sum = 0
for i in range(len(arr)):
prefix_sum +=arr[i]
if prefix_sum in result:
return "Yes"
if prefix_sum == 0:
return "Yes"
result.add(prefix_sum)
return "No"
arr = [1,4,-13,-3,16,5]
print(givensubarraySumzero1(arr))
|
## GCD of the number of the navie approach.
def gcd_number(num,num1):
result = min(num,num1)
while(result>0):
if num%result ==0 and num1%result == 0:
break;
result = result-1
return result
print(gcd_number(2,4))
## Time complexitity = 0(min(num,num1))
## GCD of the number using Eucliclean algorithm.
def gcd(num,num1):
if(num1 == 0):
return num
else:
return gcd(num1,num%num1)
print(gcd(7,10))
|
def compute_power(number,number1):
result =1
for i in range(number1):
result = result*number
return result
def compute_power1(number,number1):
if number1 == 0:
return 1
temp = compute_power1(number,number1//2)
temp = temp*temp
if(number1 %2 ==0):
return temp
else:
return temp*number
print(compute_power1(2,3))
|
def factorial(num):
if num==0 or num==1:
return 1
else:
return num*factorial(num-1)
print(factorial(5))
def fibonacci_number(num):
if num == 0:
return 0
if num ==1:
return 1
return fibonacci_number(num-1)+fibonacci_number(num-2)
print(fibonacci_number(3))
|
def peak_element(arr):
low =0
high = len(arr)-1
n = len(arr)-1
while low <= high:
mid = (low+high)//2
if (mid==0 or arr[mid-1]<arr[mid]) and (mid==n or arr[mid]> arr[mid+1]):
return arr[mid]
elif mid >0 and arr[mid-1] > arr[mid]:
high = mid-1
else:
first = mid+1
return -1
arr = [5,10,20,15,7]
print(peak_element(arr))
|
def transpose_matrix(arr,r,c):
for i in range(0,r):
for j in range(i+1,c):
arr[i][j],arr[j][i] = arr[j][i],arr[i][j]
return arr
arr = [[1,2,3],[4,5,6],[7,8,9]]
print(transpose_matrix(arr,3,3))
|
n=int(input("Enter the value :"))
for i in range(1,6):
m=n*i
print(m)
|
n=[1,2,3,4,5]
sum=0
k=2
for i in range(0,k):
sum=sum+n[i]
print(sum)
|
x=int(input("Enter the year :"))
if(x%4==0):
print(x,"is a leap year")
else:
print(x,"is not a leap year")
|
#
# @lc app=leetcode.cn id=306 lang=python3
#
# [306] 累加数
#
# https://leetcode.cn/problems/additive-number/description/
#
# algorithms
# Medium (38.16%)
# Likes: 374
# Dislikes: 0
# Total Accepted: 44.1K
# Total Submissions: 115.6K
# Testcase Example: '"112358"'
#
# 累加数 是一个字符串,组成它的数字可以形成累加序列。
#
# 一个有效的 累加序列 必须 至少 包含 3 个数。除了最开始的两个数以外,序列中的每个后续数字必须是它之前两个数字之和。
#
# 给你一个只包含数字 '0'-'9' 的字符串,编写一个算法来判断给定输入是否是 累加数 。如果是,返回 true ;否则,返回 false 。
#
# 说明:累加序列里的数,除数字 0 之外,不会 以 0 开头,所以不会出现 1, 2, 03 或者 1, 02, 3 的情况。
#
#
#
# 示例 1:
#
#
# 输入:"112358"
# 输出:true
# 解释:累加序列为: 1, 1, 2, 3, 5, 8 。1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
#
#
# 示例 2:
#
#
# 输入:"199100199"
# 输出:true
# 解释:累加序列为: 1, 99, 100, 199。1 + 99 = 100, 99 + 100 = 199
#
#
#
# 提示:
#
#
# 1 <= num.length <= 35
# num 仅由数字(0 - 9)组成
#
#
#
#
# 进阶:你计划如何处理由过大的整数输入导致的溢出?
#
#
# @lc code=start
class Solution:
def validate(self, a: int, b: int, remaining: str) -> bool:
print(f"validating {a=} {b=} {remaining}")
vals = [a, b]
while remaining:
last_two_sum = vals[-1] + vals[-2]
last_two_sum_str = str(last_two_sum)
if not remaining.startswith(last_two_sum_str):
return False
remaining = remaining[len(last_two_sum_str) :]
vals.append(last_two_sum)
return True
def isAdditiveNumber(self, num: str) -> bool:
# 前两个数字决定了后面的序列,首先排列出所有可能性
# 前两个数字的长度相加必定 < len(num)
total_length = len(num)
fst_start = 0
for fst_end in range(0, total_length - 2): # 至少预留两个数字位给 2th 3rd
fst_num = int(num[fst_start : fst_end + 1])
second_start = fst_end + 1
for second_end in range(second_start, total_length - 1): # 至少预留1个数字位给 3rd
second_num = int(num[second_start : second_end + 1])
if self.validate(fst_num, second_num, num[len(f"{fst_num}{second_num}") :]):
return True
return False
# @lc code=end
|
#
# @lc app=leetcode.cn id=81 lang=python3
#
# [81] 搜索旋转排序数组 II
#
# https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/description/
#
# algorithms
# Medium (41.20%)
# Likes: 639
# Dislikes: 0
# Total Accepted: 171.2K
# Total Submissions: 415.4K
# Testcase Example: '[2,5,6,0,0,1,2]\n0'
#
# 已知存在一个按非降序排列的整数数组 nums ,数组中的值不必互不相同。
#
# 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转 ,使数组变为 [nums[k],
# nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始
# 计数)。例如, [0,1,2,4,4,4,5,6,6,7] 在下标 5 处经旋转后可能变为 [4,5,6,6,7,0,1,2,4,4] 。
#
# 给你 旋转后 的数组 nums 和一个整数 target ,请你编写一个函数来判断给定的目标值是否存在于数组中。如果 nums 中存在这个目标值
# target ,则返回 true ,否则返回 false 。
#
# 你必须尽可能减少整个操作步骤。
#
#
#
# 示例 1:
#
#
# 输入:nums = [2,5,6,0,0,1,2], target = 0
# 输出:true
#
#
# 示例 2:
#
#
# 输入:nums = [2,5,6,0,0,1,2], target = 3
# 输出:false
#
#
#
# 提示:
#
#
# 1 <= nums.length <= 5000
# -10^4 <= nums[i] <= 10^4
# 题目数据保证 nums 在预先未知的某个下标上进行了旋转
# -10^4 <= target <= 10^4
#
#
#
#
# 进阶:
#
#
# 这是 搜索旋转排序数组 的延伸题目,本题中的 nums 可能包含重复元素。
# 这会影响到程序的时间复杂度吗?会有怎样的影响,为什么?
#
#
#
#
#
# @lc code=start
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> bool:
# ll, ..., max, min, ..., rr
l = 0
r = len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target or nums[l] == target or nums[r] == target:
return True
# l mid r
# mid == l
# 1 1 1 -> ??
# 2 2 1 -> left sorted
# mid > l
# 1 2 1 -> left sorted
# mid < l
# 2 1 2 -> right sorted
# 2 1 1 -> right sorted
# 只能利用有序部分判定
if nums[l] == nums[mid] == nums[r]:
l += 1
r -= 1
elif nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return False
# @lc code=end
|
#
# @lc app=leetcode.cn id=590 lang=python3
#
# [590] N叉树的后序遍历
#
# https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/description/
#
# algorithms
# Easy (72.93%)
# Likes: 61
# Dislikes: 0
# Total Accepted: 20.8K
# Total Submissions: 28.5K
# Testcase Example: '[1,null,3,2,4,null,5,6]'
#
# 给定一个 N 叉树,返回其节点值的后序遍历。
#
# 例如,给定一个 3叉树 :
#
#
#
#
#
#
#
# 返回其后序遍历: [5,6,3,2,4,1].
#
#
#
# 说明: 递归法很简单,你可以使用迭代法完成此题吗?
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
ret = []
if not root:
return ret
q = [root]
while q:
i = q.pop()
ret.append(i.val)
q.extend(i.children)
return ret[::-1]
# @lc code=end
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if not length:
return -1
if target < nums[0]:
i = length-1
while i > 0 and target < nums[i] and nums[i-1] < nums[i]:
i -= 1
if target == nums[i]:
return i
else:
return -1
else:
i = 0
while i < length-1 and target > nums[i] and nums[i+1] > nums[i]:
i += 1
if target == nums[i]:
return i
else:
return -1
|
# -- coding: utf-8 --
import string
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
unique_letters = [l for l in string.ascii_lowercase if s.count(l)==1]
unique_index = [s.index(l) for l in unique_letters]
return min(unique_index) if unique_index else -1
|
# -- coding: utf-8 --
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
stack = [(root, 0)]
while stack:
item, current_sum = stack.pop()
if not item.left and not item.right:
if current_sum + item.val == sum:
return True
continue
if item.left:
stack.append((item.left, current_sum + item.val))
if item.right:
stack.append((item.right, current_sum + item.val))
return False
|
# -- coding: utf-8 --
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def build_link_str(self, prefix, val):
if prefix:
return '%s->%s' % (prefix, val)
else:
return str(val)
def binaryTreePaths(self, root, prefix=''):
"""
:type root: TreeNode
:rtype: List[str]
"""
all_paths = []
if root is None:
return all_paths
if root.left is None and root.right is None:
all_paths.append(self.build_link_str(prefix, root.val))
return all_paths
if root.left:
all_paths.extend(self.binaryTreePaths(root.left, self.build_link_str(prefix, root.val)))
if root.right:
all_paths.extend(self.binaryTreePaths(root.right, self.build_link_str(prefix, root.val)))
return all_paths
|
# -- coding: utf-8 --
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
max_positive_value = 2**31-1
min_negative_value = -2**31
int_val = []
starrted = False
for char in str:
if char.isspace():
if starrted:
break
else:
continue
elif char in ['+', '-'] and not starrted:
int_val.append(char)
starrted = True
elif char.isdigit():
int_val.append(char)
starrted = True
else:
break
try:
ret = int(''.join(int_val))
except Exception:
ret = 0
if min_negative_value > ret:
return min_negative_value
elif ret > max_positive_value:
return max_positive_value
else:
return ret
|
# -- coding: utf-8 --
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
result = [False] * 2 + [True] * (n - 2)
for i in range(2, int(n ** 0.5) + 1):
if result[i]:
result[i**2:n:i] = [False] * len(result[i**2:n:i])
return sum(result)
|
#str=input("please provide any of the string:")
#if ele in range len(str): #kindom king
#k=str[0]
#for ele in range(len(str)):
#print(str.replace(str[0],'@',5))
def change_char(str1):
char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
|
class User:
__name = ''
__email = ''
def __init__(self, name, email):
self.__name = name
self.__email = email
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_email(self, email):
self.__email = email
def get_email(self):
return self.__email
def info(self):
return 'Users name is {} and email is {}.'.format(self.__name, self.__email)
'''
maksym = User('Maksym', 'maksym@mail.com')
print(maksym.get_email())
print(maksym.info())
os = open('test.txt', 'a+')
os.write('\nUser name: ' + maksym.get_name())
os.write('\nUser email: ' + maksym.get_email())
os.close()
'''
class Customer(User):
def __init__(self, name, email, balance):
self.__name = name
self.__email = email
self.__balance = balance
super(Customer, self).__init__(name, email)
def set_balance(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def about(self):
return '{} has a balance of {}$ and can be contacted at {}.'.format(self.__name, self.__balance, self.__email)
maksym = Customer('Maksym', 'max@gmail.com', 5400)
maksym.set_name('Max')
maksym.set_email('maksym@mail.com')
maksym.set_balance(2600)
#print(maksym.about())
class Worker():
pass
bob = Worker()
bob.name = 'Tim'
#print(bob.name)
class Employee():
num_of_emps = 0
raise_amount = 1.04
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
self.email = fname + '.' + lname + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.fname, self.lname)
def apply_raise(self):
#self.pay = int(self.pay * Employee.raise_amount)
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amt(cls, amount):
#pass
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
fname, lname, pay = emp_str.split('-')
return cls(fname, lname, pay)
#first argument not 'self' and not 'cls'
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
dan = Employee('Dan', 'Conelly', 50000)
tim = Employee('Tim', 'Filen', 70000)
#print(dan.email)
#print(dan.fullname())
#print(Employee.fullname(dan))
'''
print(dan.pay)
Employee.apply_raise(dan)
print(dan.pay)
'''
#print(Employee.raise_amount)
'''
print(Employee.__dict__)
print('***************************')
print(dan.__dict__)
'''
#Employee.raise_amount = 1.07
#dan.raise_amount = 1.02
'''
Employee.set_raise_amt(1.09)
print(Employee.raise_amount)
print(dan.raise_amount)
print(dan.raise_amount)
'''
#print(dan.__dict__)
#print(Employee.num_of_emps)
emp_str_1 = 'Will-Smith-70000'
emp_str_2 = 'Kim-Johnsson-50000'
emp_str_1 = 'Brad-Karlsson-40000'
#print(emp_str_1.split('-'))
fname, lname, pay = emp_str_1.split('-')
emp_1 = Employee(fname, lname, pay)
new_emp_1 = Employee.from_string(emp_str_1)
#print(new_emp_1.__dict__)
import datetime
my_date = datetime.date(2018, 4, 6)
#print(my_date)
#print(Employee.is_workday(my_date))
my_date1 = '2018-08-08'
#print(my_date1.weekday())
#repr(dan)
|
def merge_sort(s):
if len(s)<2:
return(s)
else:
left=merge_sort(s[:len(s)//2])
right=merge_sort(s[len(s)//2:])
return(merge(left,right))
def merge(left,right):
i,j = 0,0
result=[]
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
if i==len(left): result.extend(right[j:])
if j==len(right): result.extend(left[i:])
return(result)
|
"""
Forms.py:
This will handle user authenticationagainst our DB
"""
from django import forms
from django.contrib.auth.models import User
from accounts.models import Profile
# This class will be responsible for handling the registration of a new user
class UserRegisterForm(forms.ModelForm):
"""
password1: The users password to enter initially
password2: The users password re-entered
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput)
class Meta:
"""
model: The user model
fields: The fields we wish to provide the user with for registration/sign-up
"""
model = User
fields = ('username', 'first_name', 'last_name', 'email')
def clean_password2(self):
"""
clean_password: Here we check if the second password matches the first password
entered, if they do not match we return a validation error message to the user
"""
clean_pwd_data = self.cleaned_data
if clean_pwd_data['password1'] != clean_pwd_data['password2']:
raise forms.ValidationError('Sorry, the passwords do not match!')
return clean_pwd_data['password2']
def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].required = True
self.fields["first_name"].required = False
self.fields["last_name"].required = False
self.fields["email"].required = True
self.fields["password1"].required = True
self.fields["password2"].required = True
# This class will be responsible for handling the user login
class UserLoginForm(forms.Form):
"""
username: The users name input field
password: The users password input field
We use the widget here to display the passwords HTML input, it includes a
type="password" attr
"""
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class EditUserForm(forms.ModelForm):
"""
EditUserForm(forms.ModelForm):
Handle the users details so they can edit them
"""
class Meta:
"""
model: the User model
fields: allow users to edit first and last names as well as email address
"""
model = User
fields = ('first_name', 'last_name', 'email')
class EditProfileForm(forms.ModelForm):
"""
EditProfileForm(forms.ModelForm):
We want to allow the user to edit their profile
so we provide a form
"""
class Meta:
"""
model: UserProfile model
fields: allows the user to edit their dob and profile image
"""
model = Profile
fields = (
'personal_site_url',
'date_of_birth',
'about_me',
'fave_game',
'facebook_url',
'github_url',
'twitter_url',
'google_plus_url',
'youtube_url',
'profile_image',
)
|
# Author: Kishon Diaz
# Date: 02/7/2014
# File: volume_and_surface.py
# Description: This is a program to calculate the volume and surface area of a sphere
"""
ALGORITHM: The pseudocode description for how the program performs its tasks.
Write as many lines as necessary in this space to describe the
method selected to solve the problem at hand.
1. Print a welcome statement.
2. Ask the user to input their name.
3. Call the greet() function to update the visitor count and print
a statement to greet the user.
4. Print an exit statement.
5. End the program
"""
# IMPORT STATEMENTS
import math
# GLOBAL VARIABLES
message = "Please enter a number or Q to quit, R to restart\n"
errorMessage = "Please Follow the prompt or Q to quit, R to restart\n"
rightAnswer = "Program will now start over\n"
# FUNCTIONS
def oper():
print("This is a program to calculate the volume and surface area of a sphere \n")
choice=input("Enter A for Area or V for Volume and Q to quit: ")
if choice == "A"or choice == "a":
area()
elif choice == "V" or choice == "v":
volume()
elif choice =="q" or choice == "Q":
end()
else:
if(choice != correctinput):
if choice != "A" or choice != "a":
correctinput()
elif choice != "V" or choice != "v":
correctinput()
if(choice != "Q" or choice != "q"):
repeat()
elif (choice == "Q" or choice == "q"):
end()
def volume():
rad = input("Enter a number value for the volume: ")
#x = eval(rad)
#vol = 4/3*math.pi*x**3
#print("The Volume of the Sphere is: ",vol)
while True:
if rad == "":
print(message)
#return 0
return volume()
elif rad == "q" or rad == "Q":
end()
elif rad == "r" or rad == "R":
oper()
try:
n = float(rad)
if n < 1:
print(message)
return volume()
elif n > 1:
rad = float(rad)
vol = 4/3*math.pi*rad**3
print(vol)
print(rightAnswer)
oper()
else:
break
except ValueError:
#Well i tried == to catch the ValueError but for some reason != seems to work
#Please explain i cant figure it out is it something to do with ValueError
value = rad
if(value != ""):
print(errorMessage)
return volume()
elif(value != ValueError):
return volume()
#return n
def area():
rad = input("Enter a number value for the area: ")
#thisArea = 4*math.pi*rad**2
#print("The Area of the Sphere is: ", thisArea)
while True:
if rad == "":
print(message)
return area()
elif rad == "q" or rad == "Q":
end()
elif rad == "r" or rad == "R":
oper()
try:
n = int(rad)
if n < 1:
print(message)
return area()
elif n > 1:
rad = int(rad)
thisArea = 4*math.pi*rad**2
print(thisArea)
print(rightAnswer)
oper()
else:
break
except ValueError:
#Well i tried == to catch the ValueError but for some reason != seems to work
#Please explain I cant figure it out is it something to do with ValueError
value = rad
if(value != ""):
print(errorMessage)
return area()
elif(value != ValueError):
return area()
def end():
cont = input("Are you sure you want to quit yes or No press Y or N: \n")
#ending = quit(input("The program has ended"))
#quitting = ending
if cont == "n" or cont == "N":
oper()
elif cont == "y" or cont == "Y":
ending = quit(input("The program has ended \n"))
end()
exit
#else:
#ending = quit(input("The program has ended"))
#end()
#exit()
def correctinput():
print("Please choose from the prompt! \n")
def repeat():
while True:
oper()
# MAIN FUNCTION
def main():
oper()
main()
|
# Author: Kishon Diaz
# Date: 02/16/2014
# File: futureValuehw4.py
# Description: Brief This is a revised future vaule caluation program
# just the required code for the homework
"""
ALGORITHM:
"""
# IMPORT STATEMENTS
# GLOBAL VARIABLES
# FUNCTIONS
# MAIN FUNCTION
def main():
print("This is a revised future vaule caluation program")
numValue = float(input("enter in the amount of "+
"money you want to invest:$"))
apr = float(input("Enter in decmials percent of intrest:%"))
yR = int(input("Enter in the amount of years you want to "+
"predict to:"))
yR = yR +1
print("Year "," " ," Value")
for i in range(yR):
numValue = numValue *(1 + apr)
rnumVale = round(numValue,2)
print("Yr:"+ str(i)+" "+"Total: "+ "${:.2f}".format(rnumVale))
main()
|
''' Author: Catherine Boothman
Student Number: D12127081
Graphical User Interface for user to input new inventory items to the system. '''
# --------------------------------------------------- First GUI ---------------------------------------------------
# First screen allows the user to either load a .csv file containg a number of new stock items
# or manually add either a Book Item or a CD Item via a button for each one
# tkinter is one of the few modules where it is not only safe to import everything but it is recommended
from Tkinter import *
# file browser to get filename of .csv file to load
from tkFileDialog import askopenfilename
from CDItem import *
from BookItem import *
from StockRepository import *
import datetime
import random
from StockException import stockExsitsException
# ----------------------------------------------- Defined Functions -----------------------------------------------
def addStockToDB():
# get text entries to add stock item
client = cliName.get()
# add a book
if (client != "") and (txtABT.get() != "") and (txtABA.get() != ""):
title = txtABT.get()
author = txtABA.get()
date = txtABD.get()
if date == "":
date = datetime.datetime.now().strftime("%d-%m-%Y")
genre = txtABG.get()
if genre == "":
genre = "undefined"
numOfCopies = txtABN.get()
pricePerUnit = txtABP.get()
warehouseNum = txtABW.get()
if warehouseNum == "":
warehouseNum = random.randint(1,5)
bookParam1 = [client, title, author, date, genre, numOfCopies, pricePerUnit, warehouseNum]
book1 = BookItem(bookParam1)
manageBook = StockRepository()
manageBook.enterStock(book1)
bookID = book1.getUniqueID()
storeCost = book1.calcStorageCost()
print "%s book item added to stock with ID of %d at a cost of %.2f" %(title, bookID, storeCost)
# add a CD
if (client != "") and (txtACT.get() != "") and (txtACA.get() != ""):
title = txtACT.get()
artist = txtACA.get()
date = txtACD.get()
if date == "":
date = datetime.datetime.now().strftime("%d-%m-%Y")
genre = txtACG.get()
if genre == "":
genre = "undefined"
numOfCopies = txtACN.get()
pricePerUnit = txtACP.get()
warehouseNum = txtACW.get()
if warehouseNum == "":
warehouseNum = random.randint(1,5)
cdParam1 = [client, title, artist, date, genre, numOfCopies, pricePerUnit, warehouseNum]
cd1 = CDItem(cdParam1)
manageCD = StockRepository()
manageCD.enterStock(cd1)
cdID = cd1.getUniqueID()
storeCost = cd1.calcStorageCost()
print "%s cd item added to stock with ID of %d, with a cost of %.2f" %(title, cdID, storeCost)
def removeStockFromDB():
client = cliName.get()
# the idea here is that using the client name and the cd / book title and creator the id is looked up
# if more than one instance exist just one is deleted
# remove a book
if (client != "") and (txtRBT.get() != "") and (txtRBA.get() != ""):
title = txtRBT.get()
author = txtRBA.get()
# default vlaues for to test if the have been updated
bookID = 0
# open the csv file to look up the book item
try:
stockFile = open("BuyNLargeStock.csv", "rU")
except IOError:
print "No database to delete stock from"
else:
# get rid of header line
headerLine = stockFile.readline()
for line in stockFile:
line = line.strip("\n")
params = line.split(",")
stockID = int(params[0])
stockClient = params[1]
stockTitle = params[2]
stockAuthor = params[3]
stockFlag = params[10]
if (client == stockClient) and (stockTitle == title) and (author == stockAuthor) and (stockFlag != "deleted"):
# stock exists to be deleted
bookID = stockID
date = params[4]
genre = params[5]
numOfCopies = int(params[6])
pricePerUnit = float(params[7])
warehouseNum = int(params[8])
# create item if it exsits
if bookID != 0:
bookParam = [client, title, author, date, genre, numOfCopies, pricePerUnit, warehouseNum]
book2 = BookItem(bookParam)
book2.updateUniqueID(bookID)
manageBook = StockRepository()
manageBook.deleteStock(book2)
print "Book deleted from stock"
else:
try:
raise stockExsitsException("buynlargeGUI.removeStockFromDB()")
except stockExsitsException:
print "Book item does not exist to remove from database"
# remove a cd
if (client != "") and (txtRCT.get() != "") and (txtRCA.get() != ""):
title = txtRCT.get()
artist = txtRCA.get()
# default vlaues for to test if the have been updated
cdID = 0
# open the csv file to look up the book item
try:
stockFile = open("BuyNLargeStock.csv", "rU")
except IOError:
print "No database to delete stock from"
else:
# get rid of header line
headerLine = stockFile.readline()
for line in stockFile:
line = line.strip("\n")
params = line.split(",")
stockID = int(params[0])
stockClient = params[1]
stockTitle = params[2]
stockArtist = params[3]
stockFlag = params[10]
if (client == stockClient) and (stockTitle == title) and (artist == stockArtist) and (stockFlag != "deleted"):
# stock exists to be deleted
cdID = stockID
date = params[4]
genre = params[5]
numOfCopies = int(params[6])
pricePerUnit = float(params[7])
warehouseNum = int(params[8])
# create item if it exsits
if cdID != 0:
cdParam = [client, title, author, date, genre, numOfCopies, pricePerUnit, warehouseNum]
cd2 = BookItem(bookParam)
cd2.updateUniqueID(bookID)
manageCD = StockRepository()
manageCD.deleteStock(cd2)
print "CD deleted from stock"
else:
try:
raise stockExsitsException("buynlargeGUI.removeStockFromDB()")
except stockExsitsException:
print "CD item does not exist to remove from database"
# ------------------------------------------- End of Defined Functions --------------------------------------------
# main window GUI (mWin)
mWin = Tk()
# get screen size
w = mWin.winfo_screenwidth()
h = mWin.winfo_screenheight()
w = (w / 100) * 90
h = (h / 100) * 90
# parameters of mWin
mWin.title("Buy N Large Stock Management")
# mWin.geometry("%dx%d" %(w,h))
# invisible frame to hold other frames and attach scrollbars too
frmMain = Frame(mWin, height = 300)
# client name selection from list box
cliName = StringVar(mWin)
comList = ["CD WoW", "Books Unlimited", "New Media"]
lblClient = Label(frmMain, text = "Select Company:")
opmClient = OptionMenu(frmMain, cliName, "CD WoW", "Books Unlimited", "New Media")
# -------------- Add Stock ---------------
# frame for adding stock
frmAddStock = LabelFrame(frmMain, text = "Add Stock", labelanchor = "nw")
fAS = frmAddStock
# frame to manually add a book item
frmAddBook = LabelFrame(fAS, text = "Manually Add Book Item", labelanchor = "n")
fAB = frmAddBook
# entry requirements to add a book
lblABT = Label(fAB, text = "Book Title")
lblABA = Label(fAB, text = "Author")
lblABD = Label(fAB, text = "Published Date")
lblABG = Label(fAB, text = "Genre")
lblABN = Label(fAB, text = "Number of Copies")
lblABP = Label(fAB, text = "Price Per Unit")
lblABW = Label(fAB, text = "Warehouse Number")
# manual entry text boxes
txtABT = Entry(fAB, width = 15)
txtABA = Entry(fAB, width = 15)
txtABD = Entry(fAB, width = 15)
txtABG = Entry(fAB, width = 15)
txtABG.insert(0,"Fiction")
txtABN = Entry(fAB, width = 15)
txtABN.insert(0,1)
txtABP = Entry(fAB, width = 15)
txtABP.insert(0,9.99)
txtABW = Entry(fAB, width = 15)
# frame to manulally add a CD item
frmAddCD = LabelFrame(fAS, text = "Manually Add CD Item", labelanchor = "n")
fAC = frmAddCD
# entry requirement labels to add a CD
lblACT = Label(fAC, text = "CD Title")
lblACA = Label(fAC, text = "Artist")
lblACD = Label(fAC, text = "Date Released")
lblACG = Label(fAC, text = "Genre")
lblACN = Label(fAC, text = "Number of Copies")
lblACP = Label(fAC, text = "Price Per Unit")
lblACW = Label(fAC, text = "Warehouse Number")
# manual entry text boxes
txtACT = Entry(fAC, width = 15)
txtACA = Entry(fAC, width = 15)
txtACD = Entry(fAC, width = 15)
txtACG = Entry(fAC, width = 15)
txtACN = Entry(fAC, width = 15)
txtACN.insert(0,1)
txtACP = Entry(fAC, width = 15)
txtACP.insert(0,9.99)
txtACW = Entry(fAC, width = 15)
# Add Stock Button
btnAddStock = Button(fAS, text = "Add Stock Items", width = 15, height = 2, command = addStockToDB)
# -------------- Remove Stock ---------------
# frame for removing stock
frmRemoveStock = LabelFrame(frmMain, text = "Remove Stock", labelanchor = "nw")
fRS = frmRemoveStock
# frame to manually remove a book item
frmRemoveBook = LabelFrame(fRS, text = "Manually Remove Book Item", labelanchor = "n")
fRB = frmRemoveBook
# entry requirements to remove a book
lblRBT = Label(fRB, text = "Book Title")
lblRBA = Label(fRB, text = "Author")
# manual removal text boxes
txtRBT = Entry(fRB, width = 15)
txtRBA = Entry(fRB, width = 15)
# frame to manulally remove a CD item
frmRemoveCD = LabelFrame(fRS, text = "Manually Remove CD Item", labelanchor = "n")
fRC = frmRemoveCD
# entry requirement labels to remove a CD
lblRCT = Label(fRC, text = "CD Title")
lblRCA = Label(fRC, text = "Artist")
# manual removel text boxes
txtRCT = Entry(fRC, width = 15)
txtRCA = Entry(fRC, width = 15)
# Remove Stock Button
btnRemoveStock = Button(fRS, text = "Remove Stock Items", width = 15, height = 2, command = removeStockFromDB)
# -------------- Pack Widgets ---------------
# pack all widgets into the main window
# main frame to hold everything
frmMain.grid(column = 0, row = 0)
# client name selection
lblClient.grid(column = 0, row = 0, sticky = E, padx = 5, pady = 10)
opmClient.grid(column = 1, row = 0, sticky = W, padx = 5, pady = 10)
# add stock section
fAS.grid(column = 0, row = 1, columnspan = 2, padx = 10, pady = 10)
# add a book manually
fAB.grid(column = 0, row = 0, columnspan = 3, padx = 5, pady = 10)
# labels for manual book entry
lblABT.grid(column = 0, row = 0, padx = 5, pady = 5)
lblABA.grid(column = 1, row = 0, padx = 5, pady = 5)
lblABD.grid(column = 2, row = 0, padx = 5, pady = 5)
lblABG.grid(column = 3, row = 0, padx = 5, pady = 5)
lblABN.grid(column = 4, row = 0, padx = 5, pady = 5)
lblABP.grid(column = 5, row = 0, padx = 5, pady = 5)
lblABW.grid(column = 6, row = 0, padx = 5, pady = 5)
# text entry for manual book entry
txtABT.grid(column = 0, row = 1, padx = 5, pady = 5)
txtABA.grid(column = 1, row = 1, padx = 5, pady = 5)
txtABD.grid(column = 2, row = 1, padx = 5, pady = 5)
txtABG.grid(column = 3, row = 1, padx = 5, pady = 5)
txtABN.grid(column = 4, row = 1, padx = 5, pady = 5)
txtABP.grid(column = 5, row = 1, padx = 5, pady = 5)
txtABW.grid(column = 6, row = 1, padx = 5, pady = 5)
# add a CD manually
fAC.grid(column = 0, row = 2, columnspan = 3, padx = 5, pady = 10)
# labels for manual CD entry
lblACT.grid(column = 0, row = 0, padx = 5, pady = 5)
lblACA.grid(column = 1, row = 0, padx = 5, pady = 5)
lblACD.grid(column = 2, row = 0, padx = 5, pady = 5)
lblACG.grid(column = 3, row = 0, padx = 5, pady = 5)
lblACN.grid(column = 4, row = 0, padx = 5, pady = 5)
lblACP.grid(column = 5, row = 0, padx = 5, pady = 5)
lblACW.grid(column = 6, row = 0, padx = 5, pady = 5)
# manual entry text boxes
txtACT.grid(column = 0, row = 1, padx = 5, pady = 5)
txtACA.grid(column = 1, row = 1, padx = 5, pady = 5)
txtACD.grid(column = 2, row = 1, padx = 5, pady = 5)
txtACG.grid(column = 3, row = 1, padx = 5, pady = 5)
txtACN.grid(column = 4, row = 1, padx = 5, pady = 5)
txtACP.grid(column = 5, row = 1, padx = 5, pady = 5)
txtACW.grid(column = 6, row = 1, padx = 5, pady = 5)
# Add Stock Button
btnAddStock.grid(column = 1, row = 3, padx = 5, pady = 10)
# remove stock section
fRS.grid(column = 0, row = 2, columnspan = 2, padx = 10, pady = 10)
# remove a book manually
fRB.grid(column = 0, row = 0, padx = 5, pady = 10)
# labels for manual book removal
lblRBT.grid(column = 0, row = 0, padx = 5, pady = 5)
lblRBA.grid(column = 1, row = 0, padx = 5, pady = 5)
# text entry for manual book removal
txtRBT.grid(column = 0, row = 1, padx = 5, pady = 5)
txtRBA.grid(column = 1, row = 1, padx = 5, pady = 5)
# remove a CD manually
fRC.grid(column = 1, row = 0, padx = 5, pady = 10)
# labels for manual CD removal
lblRCT.grid(column = 0, row = 0, padx = 5, pady = 5)
lblRCA.grid(column = 1, row = 0, padx = 5, pady = 5)
# manual removal text boxes
txtRCT.grid(column = 0, row = 1, padx = 5, pady = 5)
txtRCA.grid(column = 1, row = 1, padx = 5, pady = 5)
# Remove Stock Button
btnRemoveStock.grid(column = 0, row = 1, columnspan = 2, padx = 5, pady = 10)
# start main window when program runs
mWin.mainloop()
|
#lists
def add_all(t):
"""Add all the numbers in t and return the sum"""
total = 0
for x in t:
total += x
return total
# Exercise 4
def is_anagram(s, t):
"""return True if s and t are anagrams"""
u = list(s)
v = list(t)
return u.sort() == v.sort()
|
import random
class Player():
def __init__(self,name):
self.name = name
self.wins = 0
self.losses = 0
self.ties = 0
def __str__(self):
return f"\n{self.name}\n{self.wins} - {self.losses} - {self.ties}\n"
def addResult(self, result):
if result == 1:
self.wins += 1
elif result == 0:
self.ties += 1
elif result == -1:
self.losses += 1
def get_random_rps():
rps = ["r", "p", "s"]
return rps[random.randrange(0,3)]
def eval_rps(player_cmd, computer_cmd):
if player_cmd == "r":
if computer_cmd == "p":
return -1
elif computer_cmd == "s":
return 1
elif computer_cmd == "r":
return 0
elif player_cmd == "p":
if computer_cmd == "p":
return 0
elif computer_cmd == "s":
return -1
elif computer_cmd == "r":
return 1
elif player_cmd == "s":
if computer_cmd == "p":
return 1
elif computer_cmd == "s":
return 0
elif computer_cmd == "r":
return -1
choice_dictionary = {"r": "rock", "p": "paper", "s": "scissors"}
p = Player(input("What is your name? "))
while True:
agent_choice = get_random_rps()
print(p)
cmd = input("-> ")
if cmd == "q":
break
elif cmd == "r" or cmd == "p" or cmd == "s":
result = eval_rps(cmd, agent_choice)
print(f"You chose {choice_dictionary[cmd]}")
print(f"Computer chose {choice_dictionary[agent_choice]}")
p.addResult(result)
if result == 1:
print("You win!")
elif result == 0:
print("Tie")
else:
print("You lose")
else:
print("I did not understand that command.") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.