text
stringlengths 37
1.41M
|
---|
a=int(input("Enter number: "))
z=""
for x in range(a+1):
for y in range(x+1):
z=z+str(object=y)
print (z)
z=""
|
'''
Summary: This program is mainly for parsing the url/html and get its content(title,meta,h1)
Author: Srivatsan Ananthakrishnan
Reference links: http://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup/
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
'''
import urllib.request
import requests
from bs4 import BeautifulSoup
def parse_html(url):
req= requests.get(url) #get the url request
soup = BeautifulSoup(req.text,"lxml") #parse it through BeautifulSoup
#1. get title
title_content = soup.title.string #get the title string/content
#2. get metatags
meta_content = ""
for meta_tag in soup.findAll("meta"): #find if meta occurs in the soup content, if so, get the content of that
meta_con = meta_tag.get("content",None)
if meta_con != None:
meta_content += meta_con + " "
#3. Get h1 tags
h1_tag_content = None
for h1_tag in soup.find_all("h1"): #find if h1 tag occurs in the soup, if it is there, get its content
h1_tag_content = h1_tag.string
return title_content, meta_content, h1_tag_content;
if __name__ == '__main__':
print("This file can only be imported!")
|
"""
Test the parse_env module.
"""
import unittest
from .. import parse_env
class ParseEnvTest(unittest.TestCase):
"""Test the parse_env functions."""
def test_env_as_int__not_set(self) -> None:
"""env value not set"""
self.assertEqual(
-10,
parse_env.env_as_int({}, 'tuna', -10),
)
def test_env_as_int__not_int(self) -> None:
"""env value not an int"""
self.assertEqual(
100,
parse_env.env_as_int({'tuna': 'fish'}, 'tuna', 100),
)
def test_env_as_int__int(self) -> None:
"""env value is an int"""
self.assertEqual(
123,
parse_env.env_as_int({'koi': '123'}, 'koi', 5),
)
def test_env_as_float__not_set(self) -> None:
"""env value not set"""
self.assertEqual(
-10.5,
parse_env.env_as_float({}, 'tuna', -10.5),
)
def test_env_as_float__not_float(self) -> None:
"""env value not a float"""
self.assertEqual(
100.9,
parse_env.env_as_float({'tuna': 'fish'}, 'tuna', 100.9),
)
def test_env_as_float__float(self) -> None:
"""env value is a float"""
self.assertEqual(
123.4,
parse_env.env_as_float({'koi': '123.4'}, 'koi', 5),
)
def test_env_as_bool__not_set(self) -> None:
"""env value is not set"""
self.assertTrue(
parse_env.env_as_bool({}, 'bat', True),
)
def test_env_as_bool__not_true_or_false(self) -> None:
"""env value is set to non-boolean value"""
self.assertTrue(
parse_env.env_as_bool({'bat': 'wing'}, 'bat', True),
)
def test_env_as_bool__true(self) -> None:
"""env value is set to a true value."""
self.assertTrue(
parse_env.env_as_bool({'bat': 'TRUE'}, 'bat', False),
)
def test_env_as_bool__false(self) -> None:
"""env value is set to a false value"""
self.assertFalse(
parse_env.env_as_bool({'bat': 'off'}, 'bat', True),
)
|
se1=input("Enter the first sequence::")
se2=input("Enter the second sequence::")
seq1=list(se1)
seq2=list(se2)
def find_identity(a,b):
gap(a,b)
print(a)
print(b)
score=0
length=len(a)
total_elements=len(a)*len(b)
for i in range(0,length):
for j in range(0,length):
if (a[i]==b[j]):
score=score+1
identity=(score/total_elements)*100
print("Matching Score::",score)
print("Identity of the sequences::",identity)
def gap(a,b):
if(len(a)==len(b)):
print()
else:
k=int(input("enter the position to insert gap:"))
if(len(a)<len(b)):
a.insert(k,'-')
else:
b.insert(k,'-')
return(a,b)
find_identity(seq1,seq2)
|
import operator
def read_until_number(prompt):
original = prompt
while True:
try:
return int(input(prompt))
except Exception:
prompt = "Incorrect number. please " + original
pass
def read_until_operation(prompt):
original = prompt
while True:
operator = input(prompt)
if operator in "+-*/^":
return operator
else:
prompt = "Incorrect operator. please " + original
num1 = read_until_number("Select first number: ")
num2 = read_until_number("Select second number: ")
operation = read_until_operation("Select operation: ")
ops = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.itruediv,
"^": operator.pow}
print(f"{num1}{operation}{num2} = {ops[operation](num1, num2)}")
|
# executemany() method
# import the sqlite3 library
import sqlite3
# create a new database it the database doesn't aleady exist
with sqlite3.connect("new.db") as conn:
# get the cursor object used to execute SQL commands
c = conn.cursor()
c.execute("SELECT city, state, population from population")
# retrieve all records from the query
rows = c.fetchall()
# output the rows to the screen, row by row
for r in rows:
print r[0],r[1],r[2]
|
from math import factorial
n = int(input("Digite um número inteiro para cálculo do fatorial: "))
f = factorial(n)
print("O fatorial de",n,"é",f)
|
n = 10
while n > 0:
lista = [n]
n = n + 10
lista.append(n)
print(lista)
tam = len(lista) - 1
n = int(input("Digite 0 para decrescentar a lista:"))
while tam >= 0:
print(lista[tam], end=", ")
tam = tam - 1
|
"""Generate Markov text from text files."""
from random import choice
import sys
def open_and_read_file(*file_paths):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
raw_text = ""
for file_path in file_paths[0]:
# your code goes here
with open(file_path) as origin_text:
raw_text += origin_text.read()
return raw_text
def make_chains(text_string, n):
"""Take input text as string; return dictionary of Markov chains.
A chain will be a key that consists of a tuple of (word1, word2)
and the value would be a list of the word(s) that follow those two
words in the input text.
For example:
>>> chains = make_chains("hi there mary hi there juanita")
Each bigram (except the last) will be a key in chains:
>>> sorted(chains.keys())
[('hi', 'there'), ('mary', 'hi'), ('there', 'mary')]
Each item in chains is a list of all possible following words:
>>> chains[('hi', 'there')]
['mary', 'juanita']
>>> chains[('there','juanita')]
[None]
"""
chains = {}
# created tokenized list of words
words = text_string.split()
# iterate through first through second to last word
for i in range(len(words) - (n-1)):
# create tuple for word[i] and word[i +1]
new_key = tuple(words[i: (i + n)])
if (i + n) < len(words):
new_val = words[i + n]
else:
new_val = None
# add as key to chains dictionary
if chains.get(new_key) is None:
chains[new_key] = [new_val]
else:
chains[new_key].append(new_val)
return chains
def make_text(chains, n):
"""Return text from chains."""
words = list(choice(chains.keys()))
# choose random key, cast tuple as list
while words[0][0].isupper() is False:
words = list(choice(chains.keys()))
# while loop until value == None
test_key = tuple(words)
while words[-1] is not None:
new_word = choice(chains[test_key])
# append a random value from chains[key] to words[]
words.append(new_word)
test_key = tuple(words[-n:])
words = words[: -1]
#print words
# convert list to string
return " ".join(words)
def make_paragraphs(all_text):
""" Creates paragraphs within text."""
input_path = sys.argv[1:]
def run_all_functions(file_paths, n):
"""Calls all functions in order to create markov chain text from source(s)."""
input_text = open_and_read_file(file_paths)
chains = make_chains(input_text, n)
return make_text(chains, n)
random_text = run_all_functions(input_path, 3)
print random_text
# Open the file and turn it into one long string
# print input_text
# Get a Markov chain
#print chains
# Produce random text
|
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
if new_val is None:
return
node = None
def create_node():
nonlocal node
node = Node(new_val)
create_node()
if self.root.value is None:
self.root = node
return
def insert_node(node, node_to_add):
if type(node) is BST:
if new_val < node.root.value:
if node.root.left is None:
node.root.left = node_to_add
else:
insert_node(node.root.left, node_to_add)
else:
if node.root.right is None:
node.root.right = node_to_add
else:
insert_node(node.root.right, node_to_add)
else:
if new_val < node.value:
if node.left is None:
node.left = node_to_add
else:
insert_node(node.left, node_to_add)
else:
if node.right is None:
node.right = node_to_add
else:
insert_node(node.right, node_to_add)
insert_node(self, node)
def search(self, find_val):
root = self.root
def search_node(node, find_val):
if type(node) is BST:
if node.root.value is find_val:
return True
if node.root.left is not None:
search_node(node.left, find_val)
if node.root.right is not None:
search_node(node.right, find_val)
else:
if node.value is find_val:
return True
if node.left is not None:
search_node(node.left, find_val)
if node.right is not None:
search_node(node.right, find_val)
return False
return search_node(root, find_val)
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
pass
# Check search
# Should be True
print(tree.search(2))
# Should be False
print(tree.search(6))
|
# Prints helloworld
def printHelloWorld():
print "Hello World"
def printSum(a,b):
return (a+b)
def main():
printHelloWorld()
x = printSum(3,5)
print x
y = printSum(4,9)
print y
if __name__ == '__main__':
main()
|
"""
CTEC 121
<your name>
<assignment/lab name>
<assignment/lab description
"""
""" IPO template
Input(s): list/description
Process: description of what function does
Output: return value and description
"""
def main():
# section 1
'''
# define a string
myStr = "Hello World"
print()
print(myStr)
print(myStr[6])
print(myStr[len(myStr)-1])
print(myStr[10])
#print(myStr[11])
print(myStr[0])
print(myStr[-1])
print(myStr[-5])
print(myStr[-len(myStr)])
word1 = "Hello"
word2 = "World"
myStr2 = word1 + " " + word2
print(myStr2)
myStr3 = word1 + word2
print(myStr3)
print(myStr2[6:len(myStr2)])
'''
# section 2
'''
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
n = int(input("Enter a month number (1 - 12): "))
pos = (n-1) * 3
print(pos)
# slice to get abbreviation
monthAbr = months[pos:pos+3]
print(monthAbr)
print(months[(n-1)*3:(n-1)*3+3])
# lists
# create an empty list
myList1 = []
print("myList1:", myList1)
myList2 = [1, 2, 3, 4]
print("myList2:", myList2)
myList3 = [42, "fourty-two", 3.14]
print("myList3:", myList3)
print("third element of myList2:", myList2[2])
# initialization example
for i in range(1,6):
myList1.append(i)
print("myList1:", myList1)
# illistrate insert()
myList1.insert(2, 3.14)
print("myList1:", myList1)
# illistrate sort()
myList1.sort()
print("myList1:", myList1)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
n = int(input("Enter a month number (1-12): "))
print(months[n-1])
print("A:", ord('A'))
print("97:", chr(97))
myStr = "text \n"
print("*", myStr, "*", sep="")
print()
myStr = myStr.rstrip()
print("*", myStr, "*", sep="")
myStr = "CamelCase"
print(myStr)
s1 = myStr.upper()
print(s1)
s2 = myStr.lower()
print(s2)
myStr = "Mary had a little lamb"
myList = myStr.split()
'''
print()
main() |
# -*- coding: utf-8 -*-
count = input() # 몇번 정수 입력 할것인지 ?
inputData=[] #
for data in range(0,count): # count만큼 반복할 것.
isHoemoonin = 1
scanData = input()
inputData.insert(data,scanData)
for scanData in inputData:
for notation in range(2,65):
s=[]
a=scanData
while a > 0:
a,r = divmod(a,notation)
if (r>9):
r=chr(ord('a')+r-10)
s.insert(0,str(r))
else :
s.insert(0,str(r))
compareDigitNumber=len(s)-1
while compareDigitNumber!=len(s)/2+len(s)%2-2:
if s[len(s)-compareDigitNumber-1]==s[compareDigitNumber]:
isHoemoonin=1
compareDigitNumber=compareDigitNumber-1
else :
isHoemoonin=0
break
if (isHoemoonin):
print isHoemoonin
break
elif notation==64 and isHoemoonin==False:
print isHoemoonin
|
total = input("How much was the bill? ")
total = float(total)
service = input("How was the service?: (Good, Fair, or Bad) ")
if service == "Good":
tip = total * 0.20
if service == "Fair":
tip = total * 0.15
if service == "Bad":
tip = total * 0.10
totalBill = ("Your total including tip comes to: ")
print(totalBill)
print(total + tip)
|
name = input("What is your name? ")
print("Hello,".upper(),name.upper())
total = len(name)
print("Your name has".upper(), total, "letters in it!".upper())
|
nums = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
new_nums = list(filter(lambda x: x > 0, nums))
print("Positive numbers in the list: ",new_nums)
|
import random
import string
users = []
#Random string generator
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
#Email verifyer
def email_verify(email):
if '@' and '.' not in email:
return False
else:
return True
print("Welcome to Hng tech")
first_name = input("First Name: ")
last_name = input("Last Name: ")
email = input("Email Address: ")
while email_verify(email)==False:
email = input("Not a valid email address! Try again\nEmail Address: ")
password = first_name[:2]+last_name[:2]+randomString(5)
print("Your Password: "+password)
ask = input("Do you like the password? please reply 'yes' or 'no'.\n")
if ask.lower() != 'yes':
password = input("Please input your preferred password (not less than 7 characters:\n")
while len(password) < 7:
password = input("Improper password length, please input your password again (not less than 7 characters)\n")
user = {'fn':first_name, 'ln':last_name, 'em':email, 'pw':password,}
print("Your information:\n\tFirst Name: "+user['fn']+"\n\tLast Name: "+user['ln']+"\n\tEmail: "+user['em']+"\n\tPassword: "+user['pw'])
users.append(user)
print(users)
|
'''
for i in range (5):
word=(input('введите слово: '))
a=len(word)
print (a)
'''
'''
kol=int(input('kolichestvo'))
for i in range (kol):
num=int(input('vvedite chislo: '))
if num>0:
print('bolshe')
elif num<0:
print('menshe')
else:
print (0)
'''
'''
a=0
for i in word: #letter, i - просто переменные
#print(letter)
#print('---')
#print (letter*3)
print (i,a)
a+=1
print(a)
print ('--'*10)
#print(word[1])
#print (word[0])
print(len(word))
print(word[len(word)-1])
print (word[-4])
'''
'''
a=0
for i in word: #letter, i - просто переменные
#print(letter)
#print('---')
#print (letter*3)
if a%2!=0:
print(i)
a+=1
'''
#print(word[2:4]) #обращение к 2-м переменным, не включая второе
#print(word[3:]) с третье буквы до конца
#print(word[3:-1])
#print(word[-2:2])
#print(word[::2]) с шагом два
#print(word[-5:-1])
#part=word[3:6]
#print(word[:3]+'!'+part+'!'+word[6:])
#a=0
#for i in range(3,20,2):
#if i>10 and i%2!=0:
#print (i**2)
'''
a=0
for k in range (word+1):
a+=k
print (a)
print(a)
'''
'''
for i in range(10):
print()
print(i, end=' ') #выводит на той же строке
if i == 8:
continue
print (i**2)
print('end')
'''
'''
i=2
while i**2<=100:
print(i, i**2)
i+=1
print (i)
'''
|
def temp(celsius):
msg1 = " degree Celsius are "
msg2 = " degrees Fahrenheit."
result = (celsius * 9/5) +32
return str(celsius) + msg1 + str(result) + msg2
temp_in_celc = input("Enter a temperature in degrees Celsius: ")
Fahrenheit_result = temp(float(temp_in_celc))
print(Fahrenheit_result) |
# Si scriva un programma che calcoli il volume
# di un cubo o di una sfera in base ad una
# scelta effettuata dall'utente. Se l'utente sceglie di
# calcolare il volume di un cubo, il programma
# chiederà l'input del relativo lato,
# altrimenti chiederà il raggio della sfera.
import math
print( "Calcolo del volume di un cubo o di una sfera" )
print( "1 - cubo, 2 - sfera" )
scelta = input( "? " )
scelta = int( scelta ) # cast esplicito
if scelta == 1 :
lato = input( "Lato del cubo : ")
lato = int( lato )
volume = lato**3
print( "Il cubo di lato", lato, "ha volume", volume )
elif scelta == 2 :
raggio = input( "Raggio della sfera : ")
raggio = int( raggio ) #cast esplicito
volume = 4.0 / 3.0 * math.pi * raggio**3
print( "La sfera di raggio", raggio, "ha volume", volume )
else :
print( "Numero non valido" )
|
from typing import Generator
from bartpy.bartpy.tree import Tree
class Initializer(object):
"""
The abstract interface for the tree initializers.
Initializers are responsible for setting the starting values of the model, in particular:
- structure of decision and leaf nodes
- variables and values used in splits
- values of leaf nodes
Good initialization of trees helps speed up convergence of sampling
Default behaviour is to leave trees uninitialized
"""
def initialize_tree(self, tree: Tree) -> None:
#print("enter bartpy/bartpy/initializers/initializer.py Initializer initialize_tree")
pass
#print("-exit bartpy/bartpy/initializers/initializer.py Initializer initialize_tree")
def initialize_trees(self, trees: Generator[Tree, None, None]) -> None:
#print("enter bartpy/bartpy/initializers/initializer.py Initializer initialize_trees")
for tree in trees:
self.initialize_tree(tree)
#print("-exit bartpy/bartpy/initializers/initializer.py Initializer initialize_trees")
|
# coding=utf-8
import matplotlib.pyplot as plt
x_value = list(range(0, 1001))
y_value = [x**3 for x in x_value]
plt.plot(x_value, y_value, linewidth=5)
# 设置图表的标题
plt.title('Test1', fontsize=20)
# 设置x轴的参数名称
plt.xlabel('value', fontsize=14)
# 设置y轴的参数名称
plt.ylabel('Cube of Value', fontsize=14)
# 设置刻度的大小
plt.show()
|
#coding=utf-8
class A:
#类的变量,可以通过类访问
num=1
a=A()
b=A()
print a.num
a.num=2
print a.num
print b.num
A.num=5
print a.num
print b.num
a.age=1
print a.age
print '*'*50
#构造函数
class A:
def __init__(self):
#这个num是实例化才有
self.num=1
a=A()
print a.num
help(classmethod) |
from PIL import Image
import pytesseract
from difflib import SequenceMatcher
import PyPDF2
from OCR import OCR
class PyTess(OCR):
"""
This class is for the use of scanned documents.
"""
def __init__(self,url):
"""
The constructor for PyTess class.
Parameters:
url (string): The path to the chosen jpg file.
"""
super(PyTess, self).__init__(url)
pytesseract.pytesseract.tesseract_cmd = self.OCR_path
self.url = url
def read_text(self):
"""
The function to extract text from the chosen jpg file.
Returns:
output: If the OCR is able to extract text from the image, it will return this text. Otherwise it will give off an error message.
"""
output = pytesseract.image_to_string(Image.open(self.url))
if(output == ''):
output = "Are you sure this is a scanned document?\n Because I couldn't find any text in this image."
return output
def compare(self,pdf_file):
"""
The function to extract and compare text from the chosen pdf file, the chosen pdf file has to be the same documents as the scanned image, otherwise you should use the function read_text().
Parameters:
pdf_file (string): the path to the chosen pdf file for comparison.
Returns:
percentage: the percentage of the correlation between the pdf and jpg file. The higher the output the higher the correlation.
"""
print(pdf_file)
#string of the read text from the file picture
output = pytesseract.image_to_string(Image.open(self.url))
if(output == ''): return("Are you sure this is a scanned document?\n Because I couldn't find any text in this image.")
else:
print("Text was found on the image, now converting the pdf file.")
# read original file
pdfFileObj = open(pdf_file, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
content_of_page = pageObj.extractText() # convert text from the pdf file to a Python string
#compare the found text to the original file
m = SequenceMatcher(None, content_of_page, output)
percentage = float(m.ratio()) * 100
return percentage
|
"""
All sorts of bandit problem environments go here.
"""
import numpy as np
from Ranger import Range
from ai.environments import MDP, Domain
class Bandit(MDP):
"""
The simplest multi-armed bandit problem.
"""
def __init__(self, n_arms=2, distributions=None):
super().__init__(states=None, actions=Domain(domain=Range.closed(1, int(n_arms))))
self.n_arms = int(n_arms)
if distributions is not None:
assert len(distributions) == self.n_arms
self._distributions = None
self._probabilities = None
self.distributions = distributions
@property
def distributions(self):
return self._distributions
@distributions.setter
def distributions(self, value):
import collections
from functools import partial
value = np.random.uniform(0, 1, size=self.n_arms) if value is None else value
if not isinstance(value, collections.Iterable):
raise ValueError
self._distributions = []
self._probabilities = []
for element in value:
if isinstance(element, float):
self._distributions.append(partial(np.random.choice,
a=[0, 1], size=1, replace=False, p=[element, 1 - element]))
self._probabilities.append(element)
elif callable(element):
self._distributions.append(element)
self._probabilities.append(None)
else:
raise ValueError
def reward(self, action):
if not self.actions.contains(action):
raise ValueError
return self.distributions[action[0]-1]()[0]
def transition(self, action):
"""
This problem has no concept of state. Just calculate reward and return (None, reward)
:param action:
:return: (None, reward)
"""
return self.reward(action)
if __name__ == '__main__':
bandit = Bandit()
rewards = np.asarray([bandit.reward(bandit.actions.sample()) for _ in range(10)])
print(rewards.sum())
|
import unittest
def fib(n):
#Error handle
if n < 0:
print("Please Enter a correct input")
#base case
elif n == 1:
return 0
#base cases
elif n == 1 or n == 2:
return 1
#recursive return
else:
return (fib(n-1)+fib(n-2))
#Simple factorial function
def factorial(n):
f = 1
for i in range(1, n+1):
f = f * i
return f
|
from datetime import datetime
def main2():
monthsnobi = {"Enero": 31, "Febrero": 28, "Marzo": 31, "Abril": 30, "Mayo": 31, "Junio": 30, "Julio": 31,
"Agosto": 31, "Septiembre": 30, "Octubre": 31, "Noviembre": 30, "Diciembre": 31}
monthssibi = {"Enero": 31, "Febrero": 29, "Marzo": 31, "Abril": 30, "Mayo": 31, "Junio": 30, "Julio": 31,
"Agosto": 31, "Septiembre": 30, "Octubre": 31, "Noviembre": 30, "Diciembre": 31}
actual_date = datetime.now()
years = actual_date.year - birthdaydt.year
birthdaydtyear = birthdaydt.year
days = 0
months = 0
while birthdaydtyear != actual_date.year:
if birthdaydtyear % 4 == 0:
days += sum(monthssibi.values())
months += 12
else:
days += sum(monthsnobi.values())
months += 12
birthdaydtyear += 1
print(days, months)
def main():
actual_date = datetime.now()
difference = actual_date - birthdaydt
if birthdaydt > actual_date:
print("Introduce una fecha válida")
else:
print("Tiene {} años, {} meses y {} días de vivo".format(int(difference
.days / 365), int(difference.days / 30),
int(difference.days)))
print("Tu día de cumpleaños es el {}".format(birthdaydt.strftime("%m/%d")))
birthday = input("Dime tu fecha de nacimiento (formato YYYY-MM-DD) ")
try:
birthdaydt = datetime.strptime(birthday, "%Y-%m-%d")
main()
main2()
except ValueError:
print("Introduce una fecha válida")
|
frase_del_usuario = input("Dime una frase: ")
vocales = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]
numero_aparicion = 1
for letra in frase_del_usuario:
if letra in vocales:
frase_del_usuario = frase_del_usuario.replace(letra, str(numero_aparicion), 1)
numero_aparicion += 1
print(frase_del_usuario)
|
clase = "simon perro"
respuesta = input("Darwin es un sendo zamuro?")
if respuesta == "si":
print("Zenda Rata")
else:
respuesta == "no"
print("Claro el nunca haria tal cosa")
|
def rayitas_de_una_string(string):
string_rayitas = ""
for letra in string:
string_rayitas += "-"
return string_rayitas
frase_usuario = input("Dime una frase: ")
print(rayitas_de_una_string(frase_usuario))
|
def FindIntersection(strArr):
matches = []
for number in strArr[0]:
if number.isdigit():
if number not in matches:
for number2 in strArr[1]:
if number2.isdigit() and number2 == number:
matches.append(number)
# code goes here
return matches
# keep this function call here
print(FindIntersection(input("")))
|
lista_numeros = []
respuesta_usuario = ""
print("Escribir -Finalizar- para detener el programa")
while not respuesta_usuario == "Finalizar":
respuesta_usuario = (input("Dime un número"))
if not respuesta_usuario == "Finalizar":
lista_numeros.append(int(respuesta_usuario))
print("Número añadido")
for indice in range(len(lista_numeros)):
numero = int(lista_numeros[indice])
if numero % 3 == 0 and numero % 5 == 0:
lista_numeros[indice] = "Bazinga"
elif numero % 3 == 0:
lista_numeros[indice] = "Fizz"
elif numero % 5 == 0:
lista_numeros[indice] = "Buzz"
else:
lista_numeros[indice] = "No múltiplo de 2 ni 3"
print(lista_numeros) |
import os
import csv
import numpy as np
csvpath = os.path.join('Resources', 'budget_data.csv')
dates = []
total = []
list_of_changes = []
initial_change = [0]
with open(csvpath, newline= '') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
dates.append(row[0])
total.append(int(row[1]))
total_profit = sum(total)
total_months = len(dates)
for i in range(1, len(total)):
changes_profit_loss = total[i]-total[i-1]
list_of_changes.append(int(changes_profit_loss))
average_difference = round(np.mean(list_of_changes),2)
zipped_list = initial_change + list_of_changes
months_profit_change_dict = dict(zip(dates, zipped_list))
max_value = max(zip(months_profit_change_dict.values(), months_profit_change_dict.keys()))
min_value = min(zip(months_profit_change_dict.values(), months_profit_change_dict.keys()))
print(f"Financial Analysis")
print("---------------------")
print(f"Total Months:",total_months)
print(f"Total: $",total_profit)
print(f"Average Change: $",average_difference)
print(f"Greatest Increase in Profits: $",max_value)
print(f"Greatest Decrease in Profits: $",min_value)
output_file = os.path.join('Resources', 'budget_data_final.txt')
with open(output_file, "w") as file:
file.write(f"Financial Analysis")
file.write("\n")
file.write("---------------------")
file.write("\n")
file.write(f"Total Months: " + str(total_months))
file.write("\n")
file.write(f"Total: $" + str(total_profit))
file.write("\n")
file.write(f"Average Change: $" + str(average_difference))
file.write("\n")
file.write(f"Greatest Increase in Profits: $" + str(max_value))
file.write("\n")
file.write(f"Greatest Decrease in Profits: $" + str(min_value))
file.write("\n")
|
import psycopg2
#function to create table
def create_table():
#Step1: Connecting to Database
conn=psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>")
#Step2: Create cursor object to access the rows in database
cur=conn.cursor()
#Step3: SQL Query
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, qty INTEGER, price FLOAT)")
#Step4: Commit changes to the database
conn.commit()
#Step5: Close the connection
conn.close()
#function to insert data into table
def insert(item, qty, price):
conn = psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES(%s,%s,%s)",(item,price,item)) #use this format to prevent SQL Injection
conn.commit()
conn.close()
#function to view the table
def view():
conn = psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows=cur.fetchall()
conn.close()
return rows
#function to delete an entry in the table
def delete(item):
conn = psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>")
cur = conn.cursor()
cur.execute("DELETE FROM store WHERE item=%s", (item,))
conn.commit()
conn.close()
#function to update an entry in the table
def update(qty,price,item):
conn = psycopg2.connect("dbname='<database_name>' user='<user_name>' password=<> host=<> port=<>")
cur = conn.cursor()
cur.execute("UPDATE store SET qty=%s, price=%s WHERE item=%s", (qty,price,item))
conn.commit()
conn.close()
|
####################################
# 58.1 Списковое включение
cubes = [i**3 for i in range(5)]
print(cubes)
####################################
####################################
# 58.2 Списковое включение
evens = [i**2 for i in range(10) if i**2 % 2 == 0]
print(evens)
####################################
####################################
# 58.3 Списковое включение
even = [2*i for i in range(10**100)]
####################################
|
####################################
# 36.1 Комментарии
x = 365
y = 7
# this is a comment
print(x % y) # find the remainder
# print (x // y)
# another comment
####################################
####################################
# 36.2 Строки документации
def shout(word):
"""
Print a word with an
exclamation mark following it.
"""
print(word + "!")
shout("spam")
####################################
|
####################################
# 21.1 Инструкции else
x = 4
if x == 5:
print("Yes")
else:
print("No")
####################################
####################################
# 21.2 Инструкции else
num = 3
if num == 1:
print("One")
else:
if num == 2:
print("Two")
else:
if num == 3:
print("Three")
else:
print("Something else")
####################################
####################################
# 21.3 Инструкции elif
num = 3
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
else:
print("Something else")
####################################
|
########################
# Решение задачи 1.1 'Ваша первая программа':
print('Python is fun')
########################
########################
# Решение задачи 3.2 'Заморозка Мозга!':
print((23+27+18)*2)
########################
########################
# Решение задачи 6.2 'Учебники для Учеников':
print(76 % ((18+19)*2))
########################
########################
# Решение задачи 8 'Проект по кодингу (Возведение в степень)':
print(0.01 * (2 ** 30))
########################
|
########################
# Решение задачи 65.3 'Лямбда-функции':
x = int(input())
y = (lambda z: z**3)(x)
print(y)
########################
########################
# Решение задачи 66.1 'Сколько им будет лет?':
y = [1995, 2004, 2019, 1988, 1977, 1902]
r = list(map(lambda x: 2050-x, y))
print(r)
########################
########################
# Решение задачи 66.2 'Фильтры':
names = ["David", "John", "Annabelle", "Johnathan", "Veronica"]
res = list(filter(lambda x: len(x) > 5, names))
print(res)
########################
########################
# Решение задачи 67.3 'Генератор-разделитель':
########################
|
####################################
# 45.1 Вызов исключений
print(1)
raise ValueError
print(2)
####################################
####################################
# 45.2 Вызов исключений
name = "123"
raise NameError("Invalid name!")
####################################
####################################
# 45.3 Вызов исключений
try:
num = 5 / 0
except:
print("An error occurred")
raise
####################################
|
class FontTypes:
class Font:
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = self.default_lowercase
self.uppercase_symbols = self.default_uppercase
def upper(self, text):
for i in range(len(self.lowercase_symbols)):
text = text.replace(self.lowercase_symbols[i], self.uppercase_symbols[i])
return text
def lower(self, text):
for i in range(len(self.lowercase_symbols)):
text = text.replace(self.uppercase_symbols[i], self.lowercase_symbols[i])
return text
def transform(self, text):
for i in range(len(self.default_lowercase)):
text = text.replace(self.default_lowercase[i], self.lowercase_symbols[i])
for i in range(len(self.default_uppercase)):
text = text.replace(self.default_uppercase[i], self.uppercase_symbols[i])
return text
class Italic(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = '𝘲𝘸𝘦𝘳𝘵𝘺𝘶𝘪𝘰𝘱𝘢𝘴𝘥𝘧𝘨𝘩𝘫𝘬𝘭𝘻𝘹𝘤𝘷𝘣𝘯𝘮1234567890'
self.uppercase_symbols = '𝘘𝘞𝘌𝘙𝘛𝘠𝘜𝘐𝘖𝘗𝘈𝘚𝘋𝘍𝘎𝘏𝘑𝘒𝘓𝘡𝘟𝘊𝘝𝘉𝘕𝘔1234567890'
class Bold(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = '𝐪𝐰𝐞𝐫𝐭𝐲𝐮𝐢𝐨𝐩𝐚𝐬𝐝𝐟𝐠𝐡𝐣𝐤𝐥𝐳𝐱𝐜𝐯𝐛𝐧𝐦𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗𝟎'
self.uppercase_symbols = '𝐐𝐖𝐄𝐑𝐓𝐘𝐔𝐈𝐎𝐏𝐀𝐒𝐃𝐅𝐆𝐇𝐉𝐊𝐋𝐙𝐗𝐂𝐕𝐁𝐍𝐌𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗𝟎'
class BoldItalic(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = '𝙦𝙬𝙚𝙧𝙩𝙮𝙪𝙞𝙤𝙥𝙖𝙨𝙙𝙛𝙜𝙝𝙟𝙠𝙡𝙯𝙭𝙘𝙫𝙗𝙣𝙢1234567890'
self.uppercase_symbols = '𝙌𝙒𝙀𝙍𝙏𝙔𝙐𝙄𝙊𝙋𝘼𝙎𝘿𝙁𝙂𝙃𝙅𝙆𝙇𝙕𝙓𝘾𝙑𝘽𝙉𝙈1234567890'
class Handwritting(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = '𝓆𝓌𝑒𝓇𝓉𝓎𝓊𝒾𝑜𝓅𝒶𝓈𝒹𝒻𝑔𝒽𝒿𝓀𝓁𝓏𝓍𝒸𝓋𝒷𝓃𝓂𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫𝟢'
self.uppercase_symbols = '𝒬𝒲𝐸𝑅𝒯𝒴𝒰𝐼𝒪𝒫𝒜𝒮𝒟𝐹𝒢𝐻𝒥𝒦𝐿𝒵𝒳𝒞𝒱𝐵𝒩𝑀𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫𝟢'
class HandwrittingBold(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = '𝓺𝔀𝓮𝓻𝓽𝔂𝓾𝓲𝓸𝓹𝓪𝓼𝓭𝓯𝓰𝓱𝓳𝓴𝓵𝔃𝔁𝓬𝓿𝓫𝓷𝓶1234567890'
self.uppercase_symbols = '𝓠𝓦𝓔𝓡𝓣𝓨𝓤𝓘𝓞𝓟𝓐𝓢𝓓𝓕𝓖𝓗𝓙𝓚𝓛𝓩𝓧𝓒𝓥𝓑𝓝𝓜1234567890'
class Vaporwave(Font):
def __init__(self):
self.default_lowercase = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.default_uppercase = self.default_lowercase.upper()
self.lowercase_symbols = 'qwertyuiopasdfghjklzxcvbnm1234567890'
self.uppercase_symbols = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890'
class Text:
def __init__(self, fontType: FontTypes.Font, text: str):
self.font = fontType()
self.text = self.font.transform(text)
@property
def uppercase(self):
return self.font.upper(self.text)
@property
def lowercase(self):
return self.font.lower(self.text)
@property
def underlined(self):
return '̲'.join(list(self.text))
@property
def double_underlined(self):
return '̳'.join(list(self.text))
@property
def crossed(self):
return '̷'.join(list(self.text))
@property
def through(self):
return '̶'.join(list(self.text))
def set_text(self, new_text):
self.text = self.font.transform(new_text)
def __str__(self):
return self.text
def __repr__(self):
return self.text |
#dates are very compicated
from datetime import datetime
current_date=datetime.now()
print("Today is "+str(current_date))
print("Day:"+str(current_date.day))
print("Month:"+str(current_date.month))
print("Year:"+str(current_date.year))
#how to write birthdays
birthday=input("enter your birthday:dd/mm/yyyy ")
birthday_date=datetime.strptime(birthday, "%d/%m/%Y")
print("birthday:"+str(birthday_date))
|
from Node import Node
from symbolTable import TIPO_DATO as Type
class Instruccion:
'''This is an abstract class'''
class Imprimir(Instruccion):
'''
Esta clase representa la instrucción imprimir.
La instrucción imprimir únicamente tiene como parámetro una cadena
'''
def __init__(self, cad, row, col):
self.cad = cad
self.row = row
self.col = col
def getNode(self):
node = Node("PRINT")
node.agregarHijoNodo(self.cad.getNode())
return node
class While(Instruccion):
'''
Esta clase representa la instrucción mientras.
La instrucción mientras recibe como parámetro una expresión lógica y la lista
de instrucciones a ejecutar si la expresión lógica es verdadera.
'''
def __init__(self, expLogica, instrucciones=[], row=0, col=0):
self.expLogica = expLogica
self.instrucciones = instrucciones
self.row = row
self.col = col
def getNode(self):
node = Node("WHILE")
node.agregarHijo("(")
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
for instr in self.instrucciones:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class Definicion(Instruccion):
'''
Esta clase representa la instrucción de definición de variables.
Recibe como parámetro el nombre del identificador a definir
'''
def __init__(self, id, row, col):
self.id = id
self.row = row
self.col = col
def getNode(self):
node = Node("DEFINITION")
node.agregarHijo("VAR")
node.agregarHijo(str(self.id))
return node
class Asignacion(Instruccion):
'''
Esta clase representa la instrucción de asignación de variables
Recibe como parámetro el identificador a asignar y el valor que será asignado.
'''
def __init__(self, id, expression, row, col):
self.id = id
self.expression = expression
self.row = row
self.col = col
def getNode(self):
node = Node("ASIGNATION")
node.agregarHijo(str(self.id))
node.agregarHijo("=")
node.agregarHijoNodo(self.expression.getNode())
return node
class Definicion_Asignacion(Instruccion):
def __init__(self, id, expression, row, col):
self.id = id
self.expression = expression
self.row = row
self.col = col
def getNode(self):
node = Node("DEF_ASIGN")
node.agregarHijo("VAR")
node.agregarHijoNodo(str(self.id))
node.agregarHijo("=")
node.agregarHijoNodo(self.expression.getNode())
return node
class Funcion_Main(Instruccion):
def __init__(self, instrucciones=[], row=0, col=0):
self.instrucciones = instrucciones
self.row = row
self.col = col
def getNode(self):
node = Node("MAIN")
node.agregarHijo("(")
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
for inst in self.instrucciones:
instrs.agregarHijoNodo(inst.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class If(Instruccion):
'''
Esta clase representa la instrucción if.
La instrucción if recibe como parámetro una expresión lógica y la lista
de instrucciones a ejecutar si la expresión lógica es verdadera.
'''
def __init__(self, expLogica, instrucciones=[], row=0, col=0):
self.expLogica = expLogica
self.instrucciones = instrucciones
self.row = row
self.col = col
def getNode(self):
node = Node("IF")
node.agregarHijo("(")
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
for instr in self.instrucciones:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class IfElse(Instruccion):
'''
Esta clase representa la instrucción if-else.
La instrucción if-else recibe como parámetro una expresión lógica y la lista
de instrucciones a ejecutar si la expresión lógica es verdadera y otro lista de instrucciones
a ejecutar si la expresión lógica es falsa.
'''
def __init__(self, expLogica, instrIfVerdadero=[], instrIfFalso=[], row=0, col=0):
self.expLogica = expLogica
self.instrIfVerdadero = instrIfVerdadero
self.instrIfFalso = instrIfFalso
self.row = row
self.col = col
def getNode(self):
node = Node("IF-ELSE")
node.agregarHijo("(")
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
if self.instrIfVerdadero is not None:
for instr in self.instrIfVerdadero:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
node.agregarHijo("ELSE")
node.agregarHijo("{")
if self.instrIfFalso is not None:
for instr in self.instrIfFalso:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class ElseIf(Instruccion):
def __init__(self, expLogica, instrIfVerdadero=[], instrElse=None, row=0, col=0):
self.expLogica = expLogica
self.instrIfVerdadero = instrIfVerdadero
self.instrElse = instrElse
self.row = row
self.col = col
def getNode(self):
node = Node("IF-ELSE")
node.agregarHijo("(")
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
if len(self.instrIfVerdadero) > 0:
for instr in self.instrIfVerdadero:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
elseNode = Node("ELSE")
node.agregarHijo("{")
elseNode.agregarHijoNodo(self.instrElse.getNode())
node.agregarHijoNodo(elseNode)
node.agregarHijo("}")
return node
class Break(Instruccion):
def __init__(self, row, col):
self.row = row
self.col = col
def getNode(self):
node = Node("BREAK")
return node
class Continue(Instruccion):
def __init__(self, row, col):
self.row = row
self.col = col
def getNode(self):
node = Node("CONTINUE")
return node
class Case(Instruccion):
def __init__(self, expression, instrucciones=[], break_instr=None, row=0, col=0):
self.expression = expression
self.instrucciones = instrucciones
self.break_instr = break_instr
self.row = row
self.col = col
def getNode(self):
node = Node("CASE")
instrs = Node("INTRUCTIONS")
for inst in self.instrucciones:
instrs.agregarHijoNodo(inst.getNode())
node.agregarHijoNodo(instrs)
return node
class Switch(Instruccion):
def __init__(self, expLogica, cases, default, row, col):
self.expLogica = expLogica
self.cases = cases
self.default = default
self.row = row
self.col = col
def getNode(self):
node = Node("SWITCH")
node.agregarHijo("(")
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijo(")")
cases = Node("CASES")
for case in self.cases:
cases.agregarHijoNodo(case.getNode())
node.agregarHijoNodo(cases)
return node
class For(Instruccion):
def __init__(self, exp1, expLogica, reAsign, instrucciones=[], row=0, col=0):
self.exp1 = exp1
self.expLogica = expLogica
self.reAsign = reAsign
self.instrucciones = instrucciones
self.row = row
self.col = col
def getNode(self):
node = Node("FOR")
node.agregarHijo("(")
node.agregarHijoNodo(self.exp1.getNode())
node.agregarHijoNodo(self.expLogica.getNode())
node.agregarHijoNodo(self.reAsign.getNode())
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INTRUCTIONS")
for instr in self.instrucciones:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class Cast:
def __init__(self, data, value, row, col):
self.data = data
self.value = value
self.col = col
self.row = row
def getNode(self):
node = Node("CAST")
node.agregarHijo("(")
node.agregarHijo(str(self.data))
node.agregarHijo(")")
node.agregarHijoNodo(self.value.getNode())
return node
class Function:
def __init__(self, name, params, instructions, row, col):
self.id = name
self.params = params
self.instructions = instructions
self.row = row
self.col = col
self.type = Type.NULL
def getNode(self):
node = Node("FUNCTION")
node.agregarHijo("func")
node.agregarHijo(str(self.id))
node.agregarHijo("(")
params = Node("PARAMS")
for param in self.params:
p = Node("PARAM")
p.agregarHijoNodo(param["type"])
p.agregarHijoNodo(param["id"])
params.agregarHijoNodo(p)
node.agregarHijoNodo(params)
node.agregarHijo(")")
node.agregarHijo("{")
instrs = Node("INSTRUCTIONS")
for instr in self.instructions:
instrs.agregarHijoNodo(instr.getNode())
node.agregarHijoNodo(instrs)
node.agregarHijo("}")
return node
class Call:
def __init__(self, name, params, row, col):
self.name = name
self.params = params
self.row = row
self.col = col
def getNode(self):
node = Node("CALL FUNCTION")
node.agregarHijo(str(self.name))
parameters = Node("PARAMS")
for p in self.params:
parameters.agregarHijoNodo(p.getNode())
node.agregarHijoNodo(parameters)
return node
class Return:
def __init__(self, exp, row, col):
self.exp = exp
self.row = row
self.col = col
def getNode(self):
node = Node("RETURN")
node.agregarHijoNodo(self.exp.getNode())
return node
class toNative:
def __init__(self, name, exp):
self.name = name
self.exp = exp
def getNode(self):
node = Node("TO NATIVE")
node.agregarHijo(str(self.name))
node.agregarHijoNodo(self.exp.getNode())
return node
class Read:
def __init__(self, row, col):
self.row = row
self.col = col
self.type = Type.CADENA
def getNode(self):
node = Node("READ")
return node
|
import math
def meters_to_feet(meters: float) -> float:
"""
This function takes a float representing a measurement in meters
and returns the corresponding value converted to feet.
The result is rounded to 2 decimal places.
:param meters: A float representing a measurement in meters.
:return: A float representing the input measurement converted to feet.
"""
feet = round(meters * 3.28084, 2)
return feet
def feet_to_meters(feet: float) -> float:
"""
This function takes a float representing a measurement in feet
and returns the corresponding value converted to meters.
The result is rounded to 2 decimal places.
:param feet: A float representing a measurement in feet.
:return: A float representing the input measurement converted to meters.
"""
met = float(round((feet * 0.3048), 2))
return met
def kilometer_to_miles(kilometers: float) -> float:
"""
This function takes a float representing a measurement in kilometers
and returns the corresponding value converted to miles.
The result is rounded to 2 decimal places.
:param kilometers: A float representing a measurement in kilometers.
:return: A float representing the input measurement converted to miles.
"""
miles = round(kilometers * 0.621371 , 2)
return miles
def miles_to_kilometers(miles: float) -> float:
"""
This function takes a float representing a measurement in miles
and returns the corresponding value converted to kilometers.
The result is rounded to 2 decimal places.
:param miles: A float representing a measurement in miles.
:return: A float representing the input measurement converted to kilometers.
"""
kilo = round(miles * 1.60934, 2)
return kilo
|
#-*- coding: UTF-8 -*-
from sys import argv #导入
script, filename = argv #解包
txt = open(filename) #打开指定文件
print "Here's you file %r:" % filename #打印引导句,引用一个变量
print txt.read() #读打开的文件并打印出来
print "Type the filename again:" # 打印引导句
file_again = raw_input(">") #输入文件名
txt_again = open(file_again) #打开输入的文件
print txt_again.read() #读打开的文件并打开
close(txt)
close(txt_again) |
import urllib
from bs4 import BeautifulSoup
page = urllib.urlopen("http://www.wunderground.com/history/airport/EPWR/2016/03/14/DailyHistory.html").read()
soup = BeautifulSoup(page, 'html.parser')
TemperatureTable = soup.findAll('table', attrs={"class": "responsive airport-history-summary-table", "id": "historyTable"})
def get_historyTable_temperature(historyTable):
"""
This method parses 'Mean Temperature', 'Max Temperature', 'Min Temperature' from wunderground.com airport-history-summary-table
:param historyTable: BeautifulSoup table object
:return: parsed decimal value
"""
temp_data = {}
for row in historyTable[0].findAll('tr'):
cells = row.findAll('td')
if len(cells) >0 :
cell_text = cells[0].get_text()
if cell_text == 'Mean Temperature':
temp_data['mean_temp'] = int(cells[1].findAll('span', attrs={"class": "wx-value"})[0].get_text())
elif cell_text == 'Max Temperature':
temp_data['max_temp'] = int(cells[1].findAll('span', attrs={"class": "wx-value"})[0].get_text())
elif cell_text == 'Min Temperature':
temp_data['min_temp'] = int(cells[1].findAll('span', attrs={"class": "wx-value"})[0].get_text())
return temp_data
print 'Max Temperature: ', get_historyTable_temperature(TemperatureTable)
|
'''
DCP #14
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
Approach: Monte Carlo Algorithm
'''
import random
def approximate_pi(iterations=10000):
total=0
inside=0
for i in range(iterations):
x=random.uniform(0,1)-0.5
y=random.uniform(0,1)-0.5
if((x**2)+(y**2))<=0.25:
#then inside the circle
inside+=1
total+=1
ratio=inside/total
#area of circle = ratio*area of square=>pi*0.5*0.5=1*1*ratio
return ratio*4
print("APPROXIMATED VALUE OF PI: {0:.3f}".format(approximate_pi()))
|
'''
DCP #9
This problem was asked by Airbnb.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?
'''
def maximumSum(arr):
incl0=arr[0]
excl0=0
n=len(arr)
for i in range(1,n):
incl1=excl0+arr[i] #if we include this element we need to exclude previous one
excl1=max(incl0,excl0) #if we exclude this element we consider the maximum till previous
incl0,excl0=incl1,excl1
return max(incl1,excl1)
assert maximumSum([2,4,6,2,5])==13
assert maximumSum([5,1,1,5])==10
assert maximumSum([3,1,1,5,1])==8
assert maximumSum([1,0,3,9,2])==10
|
def createGenerator():
mylist = range(5)
for i in mylist :
yield i*2
mygenerator = createGenerator()
for i in mygenerator:
print(i+3)
|
import sys
import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import Point, Polygon
def read_data(file):
# Read the data for voters and districts
# Step 1: Open the file
with open(file) as f:
contents = f.readlines()
contents = [x.strip() for x in contents]
# Step 2: Get the voters
n_voters = int(contents[0].split()[0])
voters = {}
for i in range(n_voters):
this_voter_str = contents[i+1].split()
this_voter = tuple([eval(x) for x in this_voter_str])
voters[i] = this_voter
# Step 3: Get the districts
n_dists = int(contents[n_voters+1])
dists = {}
for i in range(n_dists):
dists[i] = []
this_dist_str = contents[i+n_voters+2].split()
n_vertices = int(this_dist_str[0])
for j in range(n_vertices):
x, y = eval(this_dist_str[j*2+1]), eval(this_dist_str[j*2+2])
dists[i].append((x, y))
return (voters, dists)
def get_average_gap(voters, party):
# Get the mean difference between voter preference to a party and the average party preference
n_voters = len(voters) # number of voters
total_party = 0 # total preference to a party
total_mean = 0 # total average preference
for i in voters:
total_party += voters[i][party+1]
total_mean += (sum(voters[i][2:]) / len(voters[i][2:]))
avg_party = total_party / n_voters # mean preference to a party
avg_mean = total_mean / n_voters # mean average preference
gap = avg_party - avg_mean # preference gap
return gap
def get_dist_voters(voters, dists):
# Get the voters in each district (Warning: May be slow)
# Step 1: Initialization
dist_voters = {}
for d in dists:
dist_voters[d] = []
# Step 2: For each voter determine which district the voter belongs to
for v in voters:
this_voter = voters[v]
this_x, this_y = this_voter[0], this_voter[1] # location of the voter
for d in dists:
this_dist = dists[d]
if Polygon(this_dist).contains(Point(this_x, this_y)):
# The voter belongs to this district, add it
dist_voters[d].append(this_voter)
break
return dist_voters
def check_dist_sides(dists, max_sides = 9):
# Check if each district contains at most 9 sides
violations = [] # districts that violate this requirement
for i in dists:
if len(dists[i]) > max_sides:
violations.append((i, len(dists[i])))
return violations
def check_dist_sizes(dist_voters, n_voters = 333333, max_dev = 0.1):
# Check if number of voters in each district does not deviate from mean by more than 10%
violations = [] # districts that violate this requirement
n_dists = len(dist_voters)
min_voters = (n_voters / n_dists) * (1 - max_dev)
max_voters = (n_voters / n_dists) * (1 + max_dev)
for i in dist_voters:
if len(dist_voters[i]) < min_voters:
violations.append((i, len(dist_voters[i]), int(min_voters) + 1))
elif len(dist_voters[i]) > max_voters:
violations.append((i, len(dist_voters[i]), int(max_voters)))
return violations
def get_dist_results(dist_voters):
# Get the voting results in each district (number of votes each party gets)
# Step 1: Initialization
n_parties = len(dist_voters[0][0]) - 2 # number of parties
dist_results = {}
dist_results[-1] = [0 for i in range(n_parties)] # overall results
for d in dist_voters:
dist_results[d] = [0 for i in range(n_parties)] # results in each district
# Step 2: Calculate results district by district
for d in dist_voters:
for v in range(len(dist_voters[d])):
this_pref = dist_voters[d][v][2:] # party preferences for this voter
this_party = np.argmax(this_pref) # the party most preferred by this voter
dist_results[-1][this_party] += 1
dist_results[d][this_party] += 1
return dist_results
def get_one_dist_seats(dist_votes, n_rep):
# Get the number of seats for each party in one district
# Step 1: Get the percentages of votes for each party
n_parties = len(dist_votes) # number of parties
votes = [dist_votes[i] / sum(dist_votes) for i in range(n_parties)]
# Step 2: Calculate the number of seats each party should get
seats = [0 for i in range(n_parties)]
n_elected = 0
# Assume there are three representatives per district
# First round: Award one seat to each party with at least 25% of votes
for i in range(n_parties):
if n_elected < n_rep and votes[i] >= 1 / (n_rep + 1):
seats[i] += 1
n_elected += 1
votes[i] -= 1 / (n_rep + 1)
# Second round: To each party award one seat every 25% of votes
# At most one party may be awarded seats in this round (three-seat case)
for i in range(n_parties):
while n_elected < n_rep and votes[i] >= 1 / (n_rep + 1):
seats[i] += 1
n_elected += 1
votes[i] -= 1 / (n_rep + 1)
# Third round: Award remaining seats based on ranking of remaining votes
while n_elected < n_rep:
p = np.argmax(votes)
seats[p] += 1
n_elected += 1
votes[p] = 0
return seats
def get_all_dist_seats(dist_results, n_rep):
# Get the numbers of seats for each party in all districts
# Step 1: Initialization
dist_seats = {}
# Step 2: Calculate numbers of seats district by district
for d in dist_results:
dist_seats[d] = get_one_dist_seats(dist_results[d], n_rep)
return dist_seats
def get_total_seats(dist_seats):
# Get the total number of seats for each party
# Step 1: Initialization
n_parties = len(dist_seats[-1]) # number of parties
total_seats = [0 for i in range(n_parties)]
# Step 2: Calculate the total number of seats for each party
for d in dist_seats:
# d = -1 for the "overall" district, not needed here
if d != -1:
for i in range(n_parties):
total_seats[i] += dist_seats[d][i]
return total_seats
def get_wasted_votes(dist_results, dist_seats):
# Get the number of wasted votes in each district for each party
n_parties = len(dist_results[-1]) # number of parties
n_seats = sum(dist_seats[-1]) # number of seats per district
if n_parties > 2:
print("Error: Unable to handle cases with more than 2 parties.")
return
# Step 1: Calculate how many votes each party needs at least to get the current number of seats
needed = {}
for d in dist_results:
if d != -1:
needed[d] = [0 for i in range(n_parties)]
for i in range(n_parties):
if dist_seats[d][i] == 0:
# Party gets no seat, all seats are wasted
needed[d][i] = 0
else:
# Party gets some seats, needs at least the following number of votes
needed[d][i] = int(sum(dist_results[d]) * dist_seats[d][i] / (1 + n_seats)) + 1
# Step 2: Calculate how many votes are wasted for each party
wasted = {}
wasted[-1] = [0 for i in range(n_parties)] # total wasted votes
wasted[-2] = [0 for i in range(n_parties)] # total wasted votes (normalized by district sizes)
for d in needed:
wasted[d] = [dist_results[d][i] - needed[d][i] for i in range(n_parties)]
for d in needed:
for i in range(n_parties):
wasted[-1][i] += wasted[d][i]
wasted[-2][i] += wasted[d][i] / sum(dist_results[d])
return wasted
def get_efficiency_gap(dist_results, dist_seats):
# Get the efficiency gap
# Result is positive if Party 2 wasts more votes (Party 1 has advantage), negative otherwise
n_parties = len(dist_results[-1]) # number of parties
if n_parties > 2:
print("Error: Unable to handle cases with more than 2 parties.")
return
wasted = get_wasted_votes(dist_results, dist_seats)
gap = (wasted[-1][1] - wasted[-1][0]) / sum(dist_results[-1])
return gap
def print_result(d, file, with_total = False):
# Write a dictionary containing results to a file
f = open(file, "w")
if with_total:
f.write("Total ")
for j in range(len(d[-1])):
f.write(str(d[-1][j]) + " ")
f.write("\n")
for i in d:
if i >= 0:
f.write(str(i) + " ")
for j in range(len(d[i])):
f.write(str(d[i][j]) + " ")
f.write("\n")
f.close()
def print_seats(dist_seats, file):
# Write the election results to a file
total_seats = get_total_seats(dist_seats)
f = open(file, "w")
f.write("Total ")
for j in range(len(total_seats)):
f.write(str(total_seats[j]) + " ")
f.write("\n")
for i in dist_seats:
if i >= 0:
f.write(str(i) + " ")
for j in range(len(dist_seats[i])):
f.write(str(dist_seats[i][j]) + " ")
f.write("\n")
f.close()
def get_new_voters(dist_voters, delta, sd = 0.05, truncate = True):
# Get new party preferences for each voter following certain changes
# Step 1: Initialization
n_parties = len(delta) # number of parties
new_dist_voters = {}
for d in dist_voters:
new_dist_voters[d] = dist_voters[d][:]
# Step 2: Change party preferences
for d in new_dist_voters:
for v in range(len(new_dist_voters[d])):
this_new_voter = [dist_voters[d][v][0], dist_voters[d][v][1]] # location of the voter
this_new_preference = [0 for i in range(n_parties)]
for p in range(n_parties):
# Change the party preferences with delta and random noise
if truncate:
this_new_preference[p] = max(min(dist_voters[d][v][p+2] + np.random.normal(delta[p], sd), 1), 0)
else:
this_new_preference[p] = dist_voters[d][v][p+2] + np.random.normal(delta[p], sd)
new_dist_voters[d][v] = tuple(this_new_voter + this_new_preference)
return new_dist_voters
def get_partisanship_bias(dist_voters, gap, n_rep, truncate = True):
# Get partisanship bias
# Preliminary version: See what happens after modifying party preferences
n_parties = len(dist_voters[0][0]) - 2 # number of parties
gap = abs(gap) # average gap in voter preferences between each party and the mean
if n_parties > 2:
print("Error: Currently unable to handle cases with more than 2 parties.")
return
deltas = [-15 * gap, -10 * gap, -8 * gap, -6 * gap, -5 * gap, -4 * gap, -3 * gap]
deltas += [-2 * gap, -1.5 * gap, -1.2 * gap, -1.1 * gap, -1 * gap, -.9 * gap, -.8 * gap, -.5 * gap]
deltas += [0, .5 * gap, .8 * gap, .9 * gap, gap, 1.1 * gap, 1.2 * gap, 1.5 * gap, 2 * gap]
deltas += [3 * gap, 4 * gap, 5 * gap, 6 * gap, 8 * gap, 10 * gap, 15 * gap]
if abs(15 * gap) < 0.5:
deltas = [-0.5, -0.4, -0.3, -0.2, -0.1, -0.05] + deltas + [0.05, 0.1, 0.2, 0.3, 0.4, 0.5]
deltas.sort()
new_results = {}
for d in deltas:
# Get new voting results and number of seats for each delta
new_voters = get_new_voters(dist_voters, [d, -d], abs(d) / 2, truncate)
new_dist_results = get_dist_results(new_voters)
new_dist_seats = get_all_dist_seats(new_dist_results, n_rep)
new_total_seats = get_total_seats(new_dist_seats)
new_results[d] = {"results": new_dist_results[-1], "seats": new_total_seats}
return new_results
def get_partisanship_curve(new_results, file):
# Get partisanship curve
pvs = []
pss = []
for d in new_results:
pv = new_results[d]["results"][:][0] / sum(new_results[d]["results"])
ps = new_results[d]["seats"][:][0] / sum(new_results[d]["seats"])
pvs.append(pv)
pss.append(ps)
plt.plot(pvs, pss, "b-")
plt.title(file)
plt.xlabel("Percentage of votes")
plt.ylabel("Percentage of seats")
plt.hlines(0.5, 0, 1, "k", "dashed")
plt.vlines(0.5, 0, 1, "k", "dashed")
plt.savefig(file)
def analyze_map(input_file, output_loc, log_all = False):
# Put everything together, automatically analyze a map
# Step 1: Initialization
if output_loc[-1] != "/":
output_loc += "/"
log_file = output_loc + "log.txt"
f = open(log_file, "w")
f.write("Map Analysis\n")
f.write("\n")
# Step 2: Load a map containing voters and districts
voters, dists = read_data(input_file)
if len(dists) == 0:
f.write("This map contains no districts.")
f.close()
return
gap = get_average_gap(voters, 1)
# Step 3: Group voters by districts
dist_voters = get_dist_voters(voters, dists)
# Step 4: Check if the districts satisfy requirements
vio_sides = check_dist_sides(dists)
if len(vio_sides) > 0:
f.write(str(len(vio_sides)) + " district(s) have too many sides:\n")
for i in range(len(vio_sides)):
f.write("District " + str(vio_sides[i][0]) + " contains " + str(vio_sides[i][1]) + " sides\n")
f.write("\n")
vio_sizes = check_dist_sizes(dist_voters)
if len(vio_sizes) > 0:
f.write(str(len(vio_sizes)) + " district(s) contain too many or too few voters:\n")
for i in range(len(vio_sizes)):
f.write("District " + str(vio_sizes[i][0]) + " contains " + str(vio_sizes[i][1]) + " voters\n")
f.write("\n")
# Step 5: Get the election results in districts
dist_results = get_dist_results(dist_voters)
for i in range(len(dist_results[-1])):
f.write("Party " + str(i + 1) + " gets " + str(dist_results[-1][i]) + " votes\n")
f.write("\n")
if log_all:
print_result(dist_results, output_loc + "results_by_district.txt", True)
dist_seats = get_all_dist_seats(dist_results, 3)
total_seats = get_total_seats(dist_seats)
for i in range(len(total_seats)):
f.write("Party " + str(i + 1) + " gets " + str(total_seats[i]) + " representatives\n")
f.write("\n")
if log_all:
print_seats(dist_seats, output_loc + "seats_by_district.txt")
# Step 6: Analyze wasted votes (only for the 2-party case)
wasted = get_wasted_votes(dist_results, dist_seats)
if wasted is not None and log_all:
print_result(wasted, output_loc + "wasted_votes_by_district.txt", True)
# Step 7: Get partisanship gap curve
new_results = get_partisanship_bias(dist_voters, gap, 3)
if new_results is not None:
get_partisanship_curve(new_results, output_loc + "partisanship_gap_curve.png")
f.close()
if __name__ == "__main__":
if len(sys.argv) == 3:
input_file, output_loc, log_all = sys.argv[1], sys.argv[2], "False"
else:
input_file, output_loc, log_all = sys.argv[1], sys.argv[2], sys.argv[3]
log_all = eval(log_all)
analyze_map(input_file, output_loc, log_all)
|
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
GPIO.setup(GPIO_PIR, GPIO.IN) # Read output from PIR motion sensor
# GPIO.setup(3, GPIO.OUT) #LED output pin
print("Starting....")
try:
while True:
if GPIO.input(GPIO_PIR) == 1: # When output from motion sensor is LOW
print("MOTION DETECTED")
else:
print("NO MOTION")
time.sleep(0.1)
except KeyboardInterrupt:
print(" Quit")
# Reset GPIO settings
GPIO.cleanup()
|
# gabrielle french, [email protected]
# this code changes numeric, non-binary data into nominal data
infile = open('DisStudentGrade.csv','r')
outfile = open('FinalStudentPer.csv','w')
# change Medu from numeric to nominal
for line in infile:
if line[6] is 0:
line[6] = "none"
elif line[6] is 1:
line[6] = "elementary"
elif line[6] is 2:
line[6] = "junior high"
elif line[6] is 3:
line[6] = "high school"
else:
line[6] = "college"
# change Fedu
for line in infile:
if line[7] is 0:
line[7] = "none"
elif line[7] is 1:
line[7] = "elementary"
elif line[7] is 2:
line[7] = "junior high"
elif line[7] is 3:
line[7] = "high school"
else:
line[7] = "college"
# change traveltime
for line in infile:
if line[8] is 1:
line[8] = "<15 min"
elif line[8] is 2:
line[8] = "15 to 30 min"
elif line[8] is 3:
line[8] = "30 min to 1 hr"
else:
line[8] = ">1 hour"
# change studytime
for line in infile:
if line[9] is 1:
line[9] = "<2 hours"
elif line[9] is 2:
line[9] = "2 to 5 hours"
elif line[9] is 3:
line[9] = "5 to 10 hours"
else:
line[9] = "10 hours"
# change famrel
for line in infile:
if line[18] is 1:
line[18] = "very bad"
elif line[18] is 2:
line[18] = "bad"
elif line[18] is 3:
line[18] = "average"
elif line[18] is 4:
line[18] = "good"
else:
line[18] = "excellent"
# change freetime
for line in infile:
if line[19] is 1:
line[19] = "very low"
elif line[19] is 2:
line[19] = "low"
elif line[19] is 3:
line[19] = "average"
elif line[19] is 4:
line[19] = "high"
else:
line[19] = "very high"
# change goout
for line in infile:
if line[20] is 1:
line[20] = "very low"
elif line[20] is 2:
line[20] = "low"
elif line[20] is 3:
line[20] = "average"
elif line[20] is 4:
line[20] = "high"
else:
line[20] = "very high"
# change Dalc
for line in infile:
if line[21] is 1:
line[21] = "very low"
elif line[21] is 2:
line[21] = "low"
elif line[21] is 3:
line[21] = "average"
elif line[21] is 4:
line[21] = "high"
else:
line[21] = "very high"
# change Walc
for line in infile:
if line[22] is 1:
line[22] = "very low"
elif line[22] is 2:
line[22] = "low"
elif line[22] is 3:
line[22] = "average"
elif line[22] is 4:
line[22] = "high"
else:
line[22] = "very high"
# change health
for line in infile:
if line[23] is 1:
line[23] = "very bad"
elif line[23] is 2:
line[23] = "bad"
elif line[23] is 3:
line[23] = "average"
elif line[23] is 4:
line[23] = "good"
else:
line[23] = "very good"
print(line, file = outfile)
infile.close()
outfile.close()
|
# -*- coding: utf-8 -*-
import numpy as np
class Sigmoid(object):
def __init__(self):
pass
def forward(self, X):
self.activation = 1 / (np.exp(-X) + 1)
return self.activation
def backward(self, err_in):
return err_in * self.activation * (1 - self.activation)
|
import numpy as np
def zero_pad(X, pad):
"""
对数据集X的所有图像四周用0进行填充,填充只针对每个图像的高度和宽度,如图1所示。
参数:
X -- 为python numpy多维数组(m, n_H, n_W, n_C),用来表示一批图像,m:图像数量,n_H:图像高度,n_W:图像宽度,n_C:图像通道数量
pad -- 整数,表示在每个图像的四周垂直和水平维度填充增加的维度
返回:
X_pad -- 填充后的批量图像多维数组(m, n_H + 2*pad, n_W + 2*pad, n_C)
m:图像数量,n_H + 2*pad:填充后的图像高度,n_W + 2*pad:填充后的图像宽度,n_C:图像通道数量
"""
# ****** 在此开始编码 ****** #
X_pad = np.pad(X, ((0, 0),(pad, pad),(pad, pad),(0, 0)), 'constant', constant_values=0)
# ****** 在此开始编码 ****** #
return X_pad
# 测试函数
def test():
print("1. zero_pad()函数测试结果:")
print("**********************************")
np.random.seed(1)
# x = np.random.randn(4, 3, 3, 2)
x = np.random.randint(0, 256, size=(4, 3, 3, 2))
x_pad = zero_pad(x, 2)
print("x的维度 =", x.shape)
print("x_pad的维度 =", x_pad.shape)
print("\n")
print("x的第一个样本的第一个通道:")
print(x[0, :, :, 0])
print("\n")
print("x_pad的第一个样本的第一个通道:")
print(x_pad[0, :, :, 0])
print("**********************************")
# 绘制第一个样本的第一个通道原始数据和填充后的数据
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (6.0, 4.0) # 设置缺省图像尺寸:600x400像素
plt.rcParams['image.interpolation'] = 'nearest' # 图像绘制插值方法,nearest在小图像放大操作中性能良好,这里也可以用None、none
plt.rcParams['image.cmap'] = 'gray' # 设置图像绘制颜色为灰度
fig, axarr = plt.subplots(1, 2)
axarr[0].set_title('x')
axarr[0].imshow(x[0, :, :, 0])
axarr[1].set_title('x_pad')
axarr[1].imshow(x_pad[0, :, :, 0])
plt.show()
# 运行测试
if __name__ == "__main__":
test()
|
# Riddle Python / Загадки на питоне.
#
# Answers / right / wrong
right = 0
wrong = 0
# First riddle
flag1 = 0
answer1 = 'утюг'
riddle1 = print(('{0:*^30}'.format('ПЕРВАЯ ЗАГАДКА')), """\n
В Полотняной стране
По реке Простыне
Плывет пароход
То назад, то вперед,
А за ним такая гладь —
Ни морщинки не видать.
""")
while ( flag1 != 1 ):
choose = input('Ответ: ')
if (answer1 == str.lower(choose)):
print('\nПравильно! ', choose, '!\n')
right += 1
flag1 = 1
else:
print('\nНеправильно!\n')
wrong += 1
flag1 = 1
# Second riddle
flag2 = 0
answer2 = 'чайник'
riddle2 = print(('{0:*^30}'.format('ВТОРАЯ ЗАГАДКА')), """\n
В брюшке — баня,
В носу — решето,
Нос — хоботок,
На голове — пупок,
Всего одна рука
Без пальчиков,
И та — на спине
Калачиком.
""")
while ( flag2 != 1 ):
choose = input('Ответ: ')
if (answer2 == str.lower(choose)):
print('\nПравильно! ', choose, '!\n')
right += 1
flag2 = 1
else:
print('\nНеправильно!\n')
wrong += 1
flag2 = 1
# Third riddle
flag3 = 0
answer3 = 'год'
riddle3 = print(('{0:*^30}'.format('ТРЕТЬЯ ЗАГАДКА')), """\n
Стоит дуб,
В нем двенадцать гнезд,
В каждом гнезде
По четыре яйца,
В каждом яйце
По семи цыпленков.
""")
while ( flag3 != 1 ):
choose = input('Ответ: ')
if ( answer3 == str.lower(choose) ):
print('\nПравильно! ', choose, '!\n')
right += 1
flag3 = 1
else:
print('\nНеправильно!\n')
wrong += 1
flag3 = 1
# THE END
print('{0:*^30}'.format('КОНЕЦ'))
print('\nВсего дано ответов: ', wrong+right)
print('Правильных: ', right)
print('Неправильных:', wrong, '\n')
print('{0:*^30}'.format('')) |
numbers = [1,2,3,4,5,6]
numbers.sort()
for num in numbers:
if num % 2 == 0:
print(num) |
tall_list = input().split(',')
new_tall = eval(input())
new_list = []
# 以上勿改
new_list.extend(tall_list)
new_list = list(map(int, new_list))
new_list.append(new_tall)
new_list.sort()
# 以下勿改
for h in new_list:
print(h, end=' ') |
#!/usr/bin/env python3
# Author: [email protected]
# Script: loops.py
# Desc: for loop in python exercise
# Arguments: o
# Input:ipython3 loops.py
# Output: printed result in python terminal
# Date: Oct 2019
"""for loop in python exercise"""
# print number 1-5
for i in range(5):
print(i)
#print the elements in list
my_list = [0,2,"geronimo!", 3.0, True, False]
for k in my_list:
print(k)
#elements in summand were added to the provious one and printed
total = 0
summands = [0,1,11,111,1111]
for s in summands:
total =total +s
print(total)
# while loop
#print numbers less than 100
z=0
while z<100:
z=z+1
print(z)
## an infinite loop
b = True
while b:
print("GERONIMO! infinite loop! ctrl+c to stop!")
# ctrl + c to stop! |
#!/usr/bin/env python3
# Author: Y_Sun [email protected]
# Script: lc1.py
# Desc: practical
# Arguments: 0
# Input:ipython3 lc1.py
# Output: output list printed in python terminal
# Date: Oct 2019
"""python practical"""
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7),
('Delichon urbica','House martin',19),
('Junco phaeonotus','Yellow-eyed junco',19.5),
('Junco hyemalis','Dark-eyed junco',19.6),
('Tachycineata bicolor','Tree swallow',20.2),
)
#(1) Write three separate list comprehensions that create three different
# lists containing the latin names, common names and mean body masses for
# each species in birds, respectively.
latin=[x[0] for x in birds]
print (latin)
common=[x[1] for x in birds]
print (common)
masses=[x[2] for x in birds]
print (masses)
# (2) Now do the same using conventional loops (you can choose to do this
# before 1 !).
for i in range(3):
lists=[x[i] for x in birds]
print(lists)
|
def generate_vector_c(c,n):
vector = []
for k in range(2*n+1):
kth_value = min(k, 2*n-k, c)
result = format(kth_value, "02d")
print(result, end = " ")
vector.append(kth_value)
return vector
def generate_matrix_n(n):
matrix = []
for i in range(n+1):
vector = generate_vector_c(i, n)
print("\n")
matrix.append(vector)
return matrix
def main():
value = int(input("Insert an integer value between 0 and 99: "))
if value < 0 or value > 99:
print("The input number is invalid")
return 0
generate_matrix_n(value)
main()
|
#!/usr/bin/python3
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.split(splitter)
return (mins + '.' + secs)
def open_and_split(file):
try:
with open(file) as my_file:
data = my_file.readline()
return (data.strip().split(','))
except IOError as ioerr:
print('File error: ' + str(ioerr))
return(None)
james = open_and_split('james.txt')
julie = open_and_split('julie.txt')
mikey = open_and_split('julie.txt')
sarah = open_and_split('sarah.txt')
print(sorted(set([sanitize(t) for t in james]))[0:3])
print(sorted(set([sanitize(t) for t in julie]))[0:3])
print(sorted(set([sanitize(t) for t in mikey]))[0:3])
print(sorted(set([sanitize(t) for t in sarah]))[0:3])
|
import random
def choose_noccer(list):
noccer_index=random.randint(0,len(list)-1)
noccer=list[noccer_index]
list.remove(noccer)
return noccer,list
#all_hours=['15:45', '15:00','14:00','13:00','12:00','11:00','10:00']
all_hours=['10:00', '11:00','12:00','13:00','14:00','15:00','15:45']
all_noccers=['Ramon', 'Brendan', 'Walter', 'Jeff', 'Frank', 'Brian', 'Tim', 'Lan', 'Donald', 'Jon','Jay']
shutdown_noccers=raw_input("Who is on shutdown? (eparated by spaces)").split(' ')
for shutdown_noccer in shutdown_noccers:
all_noccers.remove(shutdown_noccer)
chosen_noccers=[]
for hour in all_hours:
if hour=="15:00" or hour=="15:45":
choice,shutdown_noccers=choose_noccer(shutdown_noccers)
print hour,choice
elif hour=="12:00":
choice,startup_noccers=choose_noccer(all_noccers)
print hour,choice," - Don't forget to shutdown FREJ :)"
else:
choice,startup_noccers=choose_noccer(all_noccers)
print hour,choice
|
import pandas as pd
import numpy as np
# instead of 'how' for dataframe,we use 'join' for series, inner -> intesection, outer -> union
# concatenating along an axis
arr = np.arange(12).reshape((3,4))
#print(arr)
#print(np.concatenate([arr,arr],axis=1)) #axis=1 is along column, concatenated along the columns
s1 = pd.Series([0, 1], index=['a', 'b'])
s2 = pd.Series([2, 3, 4], index=['c', 'd', 'e'])
s3 = pd.Series([5, 6], index=['f', 'g'])
print(pd.concat([s1, s2, s3]))
print(pd.concat([s1, s2, s3], axis=1))#<Default axis 0>
s4 = pd.concat([s1 * 5, s3])
print(s4)
print(pd.concat([s1, s4], axis=1)) #<Default of join ->outer>
print(pd.concat([s1, s4], axis=1, join='inner'))
print(pd.concat([s1, s4], axis=1, join_axes=[['a', 'c', 'b', 'e']])) |
# Dealing with files in python
import os
import sys
def file_wr(filename):
if os.path.exists(filename):
sys.stderr.write("File exists\n")
sys.exit(2)
f = open(filename,'w')
f.write('aaaaaaaaaaaaaa\n')
f.write('bbbbbbbbbbbbbb\n')
f.write('cccccccccccccc\n')
f.close()
def file_rd(filename):
if not os.path.exists(filename):
sys.stderr.write("No such file")
sys.exit(3)
f = open(filename)
#print(f.read())
print(f.readline())
print(f.seek.__doc__)
f.seek(9,0) # the second zero in the seek() is 0 to seek beginning, is 1 to seek middle, 2 to seek end
print(f.readlines())
f.close()
def list_wr(fname, lst):
f = open(fname,'w')
lst = list(map(lambda x: str(x)+'\n', lst))
f.writelines(lst)
f.close()
def list_rd(fname):
f = open(fname)
f_list = f.readlines()
#print(f_list)
o = list(map(lambda x: int(x.strip('\n')), f_list))
print(o)
f.close()
'''def dict_wr(fname,dct):
f = open(fname,'w')
dct = list(map(lambda x: (str(x.items()[0])+','+ str(x.items()[1])+'\n'),dct))
f.writelines(dct)
f.close()'''
def dict_wr1(filename,d1):
f = open(filename,'w')
for (k,v) in d1.items():
f.write(str(k)+','+str(v)+'\n')
f.close()
def dict_rd(filename):
f = open(filename)
rlis = list(map(lambda x:x.strip(),f.readlines()))
rlis = list(map(lambda x:x.strip(),f.readlines()))
rlis = list(map(lambda x:x.split(','),rlis))
content = dict(map(lambda x:(x[0],int(x[1])),rlis))
f.close()
lst1 = [12,19,17,5]
dct = {'u':1,'v':3,'w':6}
d1 = {'u':1,'v':3,'w':6}
if __name__ == '__main__':
#file_wr('output.txt')
#file_rd('output.txt')
#list_wr('listout.txt',lst1)
#list_rd('listout.txt')
#dict_wr('dictout.txt',dct)
dict_wr1('outdict.csv',d1)
dict_rd('outdict.csv')
|
import pandas as pd
import numpy as np
# df1 = pd.DataFrame({'lkey':['a','d','b'],
# 'data1':range(3)})
# df2 = pd.DataFrame({'rkey':['a','c','a','b','c','c','b'],
# 'data2':range(7)})
#
# print(pd.merge(df1,df2,left_on='lkey',right_on='rkey')) # how='inner' by default, gives intersection
#
# print("using how=outer\n",pd.merge(df1,df2,left_on='lkey',right_on='rkey',how='outer')) # union
# print("using how=left\n",pd.merge(df1,df2,left_on='lkey',right_on='rkey',how='left'))
# print("using how=right\n",pd.merge(df1,df2,left_on='lkey',right_on='rkey',how='right'))
# on is used for fixing/making a key constant, how is used to specify the method of wrangling like intersection,
# or union, or left oriented or right oriented
left = pd.DataFrame({'st': ['KA', 'KA', 'KL'],
'fg': ['pd', 'wh', 'pd'],
'lqty': [12, 11, 14]})
right = pd.DataFrame({'st': ['KA', 'KA', 'KL','KL'],
'fg': ['pd', 'pd', 'pd','cn'],
'rqty': [5,7,6,4]})
# #pd.merge(left, right, on=['key1', 'key2'], how='outer')
# #pd.merge(left, right, on='key1')
# #pd.merge(left, right, on='key1', suffixes=('_left', '_right'))
#print(pd.merge(left,right,on='st'))
#print(pd.merge(left,right,on='fg'))
#print(pd.merge(left,right,on=('st','fg')))
#print(pd.merge(left,right,on='st',how="outer"))
#print(pd.merge(left,right,on='fg',how="outer"))
#print(pd.merge(left,right,on=('st','fg'),how="outer"))
#print(pd.merge(left,right,on='st',how="left"))
# print(pd.merge(left,right,on='fg',how="left"))
# print(pd.merge(left,right,on=('st','fg'),how="left"))
#
# print(pd.merge(left,right,on='st',how="right"))
# print(pd.merge(left,right,on='fg',how="right"))
# print(pd.merge(left,right,on=('st','fg'),how="right"))
|
#
def check_fn():
user_in = input("Enter yes/no ").strip()
while user_in != 'YES':
if user_in == 'YES':
print('Accepted')
continue
elif user_in == 'yes':
print(user_in.upper())
break
else:
print("invalid input.. pls enter again")
check_fn()
check_fn() |
# Transpose a list of lists
l = [int(x) for x in input().split(',')]
ll = [l.append(list(x)) for x in input()]
print(ll)
|
# set trace acts like a breakpoint. When the program hits the point,
# where set_trace is called, it enters the debugger
# for example
import pdb
def dict_wr1(filename,d1):
f = open(filename,'w')
pdb.set_trace()
for (k,v) in d1.items():
f.write(str(k)+','+str(v)+'\n')
f.close()
dict_wr1() |
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(12).reshape(3,4),
columns=list('abcd'),
index=['tn','ka','kl'])
print(df1)
s1 =df1.loc['ka']
print(s1)
print(df1-s1) # subtracting s1 to all rows
print(df1+s1) # adding s1 to all rows
f = lambda x:x.max() - x.min()
print(df1.apply(f))# by default axis=0 ie for rows
print(df1.apply(f,axis=1))
|
import pdb
def f1(some_arg):
some_other = some_arg + 1
print(some_other)
myadd(some_arg, some_other)
return f2(some_other)
def f2(some_arg):
some_other = some_arg + 1
some_other = 2 * some_other - 17
some_arg = 3 * (some_other + 12)
myadd(some_arg, some_other)
some_other = some_other + some_arg
print(some_other)
return f3(some_other)
def f3(some_arg):
some_other = some_arg + 1
print(some_other)
return f4(some_other)
def f4(some_arg):
some_other = some_arg + 1
some_other = 2 * some_other - 17
some_arg = 3 * (some_other + 12)
some_other = myarith(some_other, some_arg)
print(some_other)
return some_other
def myadd(x,y):
print("x is", x)
print(x+y)
def myarith(x,y):
x = 9/x + 1.8*y
y = 7.8*(x/9 + 2.3*y)
return x + y
pdb.run("f1(1)")
# These are debugging functions
# s for single stepping <- debugger commands ( will step into a function if function call is there)
# p for print
# n is another cmd for single stepping ( will not step into a function)
# b for breakpoint( at function or a line)
# values of variables can be updated using !<variable_name> = <new_value>
# disable <breakpt_no> ( disables the break point) or to enable <breakpt_no>
# clear <breakpt_no> to delete the breakpt
# j ( used to jump to any line only within a specific function) |
# dict to implement set functions
# intersection, union, subtraction, symm-diff, issubset
a = {'a':5, 't':3, 'c':4, 'e':7}
b = {'a':3, 'l':9,'e':1, 'd':6}
# print(set(a))
# print(set(b))
c,d = [],[]
# ad = set(a.items())
# bd = set(b.items())
# print(ad)
# print(bd)
for (k,v) in a.items():
c.append((k,v))
#print(c)
for (k,v) in b.items():
d.append((k,v))
#print(d)
s1 = set(c)
s2 = set(d)
print("The set 1 is",s1)
print("The set 2 is",s2)
s3 = s1.intersection(s2)
print(s3)
ds3 = dict(s3)
print("The intersection is",ds3)
s4 = s1.union(s2)
ls = list(s4)
# tem_d = {}
# for i in range(len(ls)):
# tem_d[(i[0])] = i[1]
# print(tem_d)
ds4 = dict(s4)
print("The union is",ds4)
s5 = s1.symmetric_difference(s2)
print(s5)
s6 = s1.issubset(s2)
print(s6)
|
# Keywords cannot be overwritten.
# But builtins can be overwritten
# __builtins__ is a namespace which has methods like map
map = 8
#m = list(map(lambda x:x*2, [2,1,4]))
n = list(__builtins__.map(lambda x:x*2, [2,1,4]))
print(n)
print(map)
map = __builtins__.map
m = list(map(lambda x:x*2, [2,1,4]))
print(m)
|
# What if we want some attributes to be created before the creation of an instance?
# this can be done in the constructor
#? __init__() -> private, used before the creator of the object - not called by the user
#? Called Magic Method because its called automatically
class MagicMethods(object):
def __init__(self, value):
print('Calling __init__')
# we want to validate data that goes into our data - validate before initialization
#? Examples
# Server - Validate we can connect to the server
# Networking - Validate Connection
try:
value = int(value)
except ValueError:
value = 0
self.value = value
def inrimental(self):
self.value += 1
mm = MagicMethods(25)
mm.inrimental()
mm.inrimental()
print(mm.value) |
#!/usr/bin/python3
def numeroPerfecto(num):
'''Funcion que recibe como entrada n numeros enteros positivos, y por cada
uno de ellos imprime sus divisores e indica si es perfecto o no.
'''
suma = 0
for i in range(1, num):
if num % i == 0:
suma += i
print("divisor=", i)
if num == suma:
print(f"suma de divisores = {suma}")
return True
else:
print(f"suma de divisores = {suma}")
return False
if __name__ == "__main__":
numInputs = int(input("Introduzca la cantidad de numeros a validar: "))
i = 1
while i <= numInputs:
num = int(input("introduzca un numero: "))
# llamada al metodo numeroPerfecto
if numeroPerfecto(num):
print(f"{num} es un numero perfecto")
else:
print(f"{num} no es un numero perfecto")
# incremento contador del bucle
i += 1
|
#!/usr/bin/python3
'''Programa que puede simular el funcionamiento de un display de siete
segmentos.
'''
numbers = {
1: [[" ", " ", "#"], [" ", " ", "#"], [" ", " ", "#"],
[" ", " ", "#"], [" ", " ", "#"]],
2: [["#", "#", "#"], [" ", " ", "#"], ["#", "#", "#"],
["#", " ", " "], ["#", "#", "#"]],
3: [["#", "#", "#"], [" ", " ", "#"], ["#", "#", "#"],
[" ", " ", "#"], ["#", "#", "#"]],
4: [["#", " ", "#"], ["#", " ", "#"], ["#", "#", "#"],
[" ", " ", "#"], [" ", " ", "#"]],
5: [["#", "#", "#"], ["#", " ", " "], ["#", "#", "#"],
[" ", " ", "#"], ["#", "#", "#"]],
6: [["#", "#", "#"], ["#", " ", " "], ["#", "#", "#"],
["#", " ", "#"], ["#", "#", "#"]],
7: [["#", "#", "#"], [" ", " ", "#"], [" ", "#", "#"],
[" ", " ", "#"], [" ", " ", "#"]],
8: [["#", "#", "#"], ["#", " ", "#"], ["#", "#", "#"],
["#", " ", "#"], ["#", "#", "#"]],
9: [["#", "#", "#"], ["#", " ", "#"], ["#", "#", "#"],
[" ", " ", "#"], [" ", " ", "#"]],
0: [["#", "#", "#"], ["#", " ", "#"], ["#", " ", "#"],
["#", " ", "#"], ["#", "#", "#"]]
}
def display():
try:
num = input("Ingrese un numero: ")
print()
if not num : #cadena vacia
raise TypeError
elif not num.isdigit():
raise ValueError
num = [int(x) for x in num]
printDisplay = [[] for row in range(5)]
for row in range(5):
key = 0
while key < len(num):
col = 0
while col < 3:
printDisplay[row].append(numbers[num[key]][row][col])
col += 1
printDisplay[row].append(" ")
key += 1
for row in printDisplay:
for col in row:
print(col, end="")
print()
except ValueError:
print("Error\nIngrese unicamente numeros")
respuesta = input("Desea volver a intentarlo ? y / n :")
if respuesta.lower() == 'y':
display()
else:
print("FIN...")
except TypeError:
print("Error\ningreso vacio")
respuesta = input("Desea volver a intentarlo ? y / n :")
if respuesta.lower() == 'y':
display()
else:
print("FIN...")
if __name__ == "__main__":
display()
|
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# So the thing is if we read left to right as "asasa" AND right to left "asasa" = then we got the point.
# To reach that we need take 100*100 in cycle from 100 to 999, take result like string and check spelling
result_of_product = 0
line_to_search_from_result = str
is_palindrome = str
mass_item_number = 0
mass_of_first=[]
mass_of_second=[]
mass_of_palindromes=[]
for first_number in range(100,999):
for second_number in range(100,999):
result_of_product = first_number * second_number
line_to_search_from_result = str(result_of_product)
is_palindrome = line_to_search_from_result[::-1]
if is_palindrome == line_to_search_from_result:
mass_item_number += 1
mass_of_first.append(first_number)
mass_of_second.append(second_number)
mass_of_palindromes.append(result_of_product)
for search in range(1, mass_item_number):
max_pallindrom = max(mass_of_palindromes)
index_of_founded = mass_of_palindromes.index(max(mass_of_palindromes))
max_number_in_mass_of_first = mass_of_first[index_of_founded]
max_number_in_mass_of_second = mass_of_second[index_of_founded]
print('We found', + mass_item_number, 'palindromes')
print("Biggest palindrome", +max_pallindrom, 'with numbers', +max_number_in_mass_of_first, '*', +max_number_in_mass_of_second) |
#Problema 01 - Corrida de Fórmula 01
#Versão Original elaborada pelo professor Givanaldo Rocha
#Desenvolver uma aplicação para simular a dinâmica de uma corrida de Fórmula 1. Serão
#duas threads em que uma representa o carro de Felipe Massa e a outra representa o carro
#de Lewis Hamilton. As threads possuem as seguintes características:
#● Cada thread possui um loop com 65 interações (as voltas da pista).
#● A cada volta, a thread dorme durante um tempo aleatório entre 0 e 1 segundo,
#representando o tempo gasto para percorrer a volta.
#O programa deve aguardar as duas threads terminarem, representando a linha de chegada,
#e então informar quem venceu a corrida (dica: pesquisar o método join()).
import threading
import time
vencedor=['1º Lugar: ','','2º Lugar: ','']
def massa(deley):
for i in range(66):
if i==65:
if vencedor[1]=='':
vencedor[1]="Felipe Massa"
elif vencedor[1]!='':
vencedor[3]="Felipe Massa"
else:
print("Felipe Massa está na volta: ",i)
time.sleep(deley)
def hamilton(deley):
for i in range(66):
if i==65:
if vencedor[1]=='':
vencedor[1]="Lewis Hamilton"
elif vencedor[1]!='':
vencedor[3]="Lewis Hamilton"
else:
print("Lewis Hamilton está na volta: ",i)
time.sleep(deley)
print ('******************************************************************************************************************************')
print ('**************************** CORRIDA DE FÓRMULA 01- Felipe Massa e Lewis Hamilton*********************************************')
print ('******************************************************************************************************************************')
print("Iniciou a corrida!!!")
#for i in range(10):
t1=threading.Thread(target=massa,args=(1,))
t2=threading.Thread(target=hamilton,args=(1,))
t1.start()
t2.start()
t1.join()
t2.join()
print(f'{vencedor[0]}{vencedor[1]}')
print(f'{vencedor[2]}{vencedor[3]}')
print("Fim da corrida.")
print ('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')
print ('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-JOSÉ RICARDO QUINTINO VIDAL - TSI-2019.1 - IFRN - PARNAMIRIM-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-') |
Celsius = float(input())
print("This equal", ((Celsius * 9 / 5) + 32), "Fahrenheit degrees")
print("This equal", (Celsius + 273.15), "Kelvin degrees")
|
import math
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(b/a)
print(a/b)
print(a*b)
math.log10(a)
print(a*b)
|
print("Mass in grams:")
mass = int(input())
print("Temperature in Celsius:")
dtemp = int(input())
q = 4.186 * mass * dtemp
print("The total energy in Joules: %f" %q) |
loaves = int(input("Amount of loaves: "))
price = loaves*3.49
discount = price*0.6
total_price = price - discount
print("Price of the bread", price)
print("Value of discount:", discount)
print("Total price:", total_price) |
from math import pi
s = float(input ())
print (str(s) + str(pi * s**2))
|
from math import radians, cos, sin, asin, sqrt
print("Enter the latitude and longitude of two points on the Earth in degrees:")
lt1 = float(input(" Latitude 1: "))
lt2 = float(input(" Latitude 2: "))
ln1 = float(input(" Longitude 1: "))
ln2 = float(input(" Longitude 2: "))
dln = ln2 - ln1
dlt = lt2 - lt1
a = sin(dlt/2)*2 + cos(lt1) * cos(lt2) * sin(dln/2)*2
c = 2 * asin(sqrt(a))
r = 6371
print("Distance is: ",c*r,"Kilometers")
|
for s in range(int(input())):
s = input()
a = s.count("A")
b = s.count("D")
if a > b:
print("Anton")
else:
print("Danik") |
# Language: Python 3
# Run: python3 elgamal_ecc_6.py 9 201
# Parameter 1: <positive_integer_number> - Number of bits to generate the key
# Parameter 2: <integer_number_to_encrypt> - Integer number to encrypt
# importing libraries
import sys, random
# Inverse function - Returning 0 instead of raise an error. Removed gcde
def invm(m, a):
if a<0:
a = a + m
for i in range(1, m):
if (a * i) % m == 1:
return i
else:
return 0
#Modular exponentiation
def expm(m, a, k):
if k == 0:
return 1
if k == 1:
return a % m
if ((k % 2) == 0):
return expm(m, (a*a)%m, k//2) % m
return a*expm(m, (a*a)%m, (k-1)//2) % m
#Check if n is prime with t fermat rounds
def is_prime_fermat(n,t):
for _ in range(1,t+1):
a = random.randint(1,n-1)
r = expm(n,a,n-1)
if r != 1:
return False
return True
#Generate a prime number with n-bits, test with fermat rounds, also checks message bts number
def generate_prime_number(n, rounds, message):
nbit_number = 0
f = False
while nbit_number == 2 or nbit_number % 2 == 0 or int.bit_length(nbit_number) != n or nbit_number <= message:
nbit_number = random.getrandbits(n)
while not f:
f = is_prime_fermat(nbit_number, rounds)
if not f:
nbit_number += 2
return (nbit_number)
#ECC addition function
def ecc_add(x1, y1, x2, y2, a, p):
if (x1 == x2) and (y1 == y2):
r = (((3 * (x1 * x1)) + a) * invm(p, (y1 * 2))) % p
else:
r = ((y2 - y1) * invm(p, (x2 - x1))) % p
x3 = ((r*r) - x2 - x1) % p
y3 = ((r*(x1 - x3)) - y1) % p
return x3, y3
#Find curve points
def ecc_points(rand1,rand2,p):
curve_points = []
for i in range(0, p-1):
[curve_points.append([i,j]) for j in range(0, p-1) if (j*j) % p == (i**3 + (rand1 * i) + rand2) % p]
#Uncomment the line below to print all curve points
#print("Curve points:",curve_points)
return curve_points
#Find curve base points
def ecc_base(curve_points,a,p):
t = 0
c = []
l = len(curve_points)
while ( t != l ):
c.append(curve_points[t][0])
[c.append(ecc_add(curve_points[t][0], curve_points[t][1], curve_points[t][0], curve_points[t][1], a, p)[0]) for _ in range(1, l)]
if set(curve_points[0]).intersection(set(c)) != 0:
gx, gy = curve_points[t][0], curve_points[t][1]
break
t += 1
c = []
return gx, gy
#Creates key - ElGamal ECC
def create_key(gx,gy,a,p):
# Private Key
priv = random.randint(2, p - 1)
print("\nPrivate Key:", priv)
# Public Key
x1, y1 = gx, gy
for _ in range(0, priv):
x1, y1 = ecc_add(x1, y1, gx, gy, a, p)
pkx, pky = x1, y1
# k value
k = random.randrange(2, p - 1)
print("\nRandom k:", k)
c1x, c1y, c2x, c2y = gx, gy, pkx, pky
for _ in range(0, k):
c1x, c1y = ecc_add(c1x, c1y, gx, gy, a, p)
c2x, c2y = ecc_add(c2x, c2y, pkx, pky, a, p)
print("\nKey C1: (%s,%s)" %(c1x,c1y))
print("\nKey C2: (%s,%s)" %(c2x,c2y))
return c1x,c1y,c2x,c2y,priv
#Encrypt function - ElGamal ECC
def ecc_encrypt(m,x1,y1,a,p):
return ecc_add(m, m, x1, y1, a, p)
#Decrypt function - ElGamal ECC
def ecc_decrypt(c1x,c1y,c2x,c2y,priv,a,p):
t1, t2 = c1x, c1y
for _ in range(0,priv):
t1,t2 = ecc_add(t1, t2, c1x, c1y, a, p)
return ecc_add(t1, (t2*(-1) + p), c2x, c2y, a, p)
#Execution
if len(sys.argv) != 3 or int(sys.argv[1]) < 3:
print("\nSyntax: {} <positive_integer_number> <integer_number_to_encrypt>\n".format(sys.argv[0]))
sys.exit(0)
number_of_bits = int(sys.argv[1])
fermat_rounds = 3
m = int(sys.argv[2])
if (m.bit_length() > number_of_bits-1):
print("\nThe number {} is a {}-bits number. The key lenght (first parameter) should be {} or more \n".format(m, m.bit_length(), m.bit_length()+1))
sys.exit(0)
p = int(generate_prime_number(number_of_bits, fermat_rounds, m))
print("\nPrime:", p)
a = random.randrange(p, p*2)
b = random.randrange(p, p*2)
print("\n*** Calculating curve points ***")
curve_points = ecc_points(a,b,p)
gx, gy = ecc_base(curve_points,a,p)
print("\nBase point: (%s,%s)" %(gx, gy))
c1x,c1y,c2x,c2y,priv = create_key(gx,gy,a,p)
cipher_x, cipher_y = ecc_encrypt(m,c2x,c2y,a,p)
print("\nCipherText: (%s,%s)" %(cipher_x,cipher_y))
decrypted,_ = ecc_decrypt(c1x,c1y,cipher_x, cipher_y,priv,a,p)
print("\nDecrypted Message: %s" %(decrypted))
|
# utils.py
# Math library
# Author: Sébastien Combéfis
# Version: February 8, 2018
import math
def fact(n):
"""Computes the factorial of a natural number.
Pre: -
Post: Returns the factorial of 'n'.
Throws: ValueError if n < 0
"""
if n < 0:
raise ValueError
result = 1
while n > 0 :
result *= n
n -= 1
return result
def roots(a, b, c):
"""Computes the roots of the ax^2 + bx + c = 0 polynomial.
Pre: -
Post: Returns a tuple with zero, one or two elements corresponding
to the roots of the ax^2 + bx + c polynomial.
"""
delta=(b**2)-(4*a*c)
if delta < 0:
return None
if delta == 0:
return (-b/(2*a),)
else:
return ((-b+math.sqrt(delta))/(2*a), (-b-math.sqrt(delta))/(2*a))
def f(x):
"""
Used only for the 'integrate' function, as an argument"
"""
return x
def integrate(function, lower, upper):
"""Approximates the integral of a fonction between two bounds
Pre: 'function' is a valid Python expression with x as a variable,
'lower' <= 'upper',
'function' continuous and integrable between 'lower‘ and 'upper'.
Post: Returns an approximation of the integral from 'lower' to 'upper'
of the specified 'function'.
"""
return (function (lower)+function (upper))* (upper - lower) / 2 #first degree approximation
if __name__ == '__main__':
print(fact(5))
print(roots(2, 1, -1))
print(integrate(f, 0, 1))
|
#!/usr/bin/env python3
import sys
import copy
import numpy
from math import gcd
if len(sys.argv) != 2:
print("usage: solve.py input.txt")
exit(1)
p1 = 0
p2 = 0
def compute_lcm(a):
lcm = a[0]
for i in a[1:]:
lcm = lcm * i // gcd(lcm, i)
return lcm
def busadd(bus,earliest):
arrival = 0
while arrival < earliest:
arrival += bus
if arrival > earliest:
return arrival
def tcheck(buses,t):
tgood = False
for key,value in buses.items():
if (t + value) % key == 0:
tgood = True
#print("Tgood! - ",t," % ",key," == ",value)
else:
tgood = False
break
if tgood == True:
return "Passed"
with open(sys.argv[1]) as f:
inputlist = f.read().splitlines()
earliest = int(inputlist[0])
buses = inputlist[1].split(",")
buses2 = copy.deepcopy(buses)
buses = list(filter(("x").__ne__, buses))
buses = list(map(int, buses))
print(earliest)
print(buses)
arrivals = []
for b in buses:
#print("BUS ID ",b)
arrivals.append(busadd(b,earliest))
waittime = min(arrivals) - earliest
#busID with shortest time * wait time
p1 = buses[arrivals.index(min(arrivals))] * waittime
busdict = {}
for b in buses2:
if b != 'x':
print("Bus ID :",int(b)," T+",buses2.index(b))
busdict[int(b)] = buses2.index(b)
#busdict{busid:T+ departure time}
#print(busdict)
busdepartures = []
for key, value in busdict.items():
busdepartures.append(value)
#print(busdepartures)
#had working solution that was extremely inefficient and would never have actually solved part2. learned solution from @whiplashoo (https://github.com/whiplashoo/advent_of_code_2020/blob/main/day13.py)
timestamp = 0
matched_buses = [buses[0]]
while True:
#reduce number of timestamps to try by incrementing by lcm of bus ID's who's departure time + timestamp leaves no remainder.
timestamp += compute_lcm(matched_buses)
#print("adding ",compute_lcm(matched_buses)," to timestamp")
#print("checking ",timestamp)
for i, b in enumerate(buses):
#check timestamp + bus ID departure time offset remainder
if (timestamp + busdepartures[i]) % b == 0:
if b not in matched_buses:
#print(" no remainder: ",timestamp)
#print("adding ",b," to matched-buses because ",timestamp," + bus #",b,"'s offset (+T ",busdepartures[i],") / ",b," = 0")
matched_buses.append(b)
#print(matched_buses)
if len(matched_buses) == len(buses):
break
#print(timestamp)
p2 = timestamp
print("Part 1:",p1)
print("Part 2:",p2) |
print("Welcome to the tip calculator")
total=float(input("What was the total bill? "))
groupCount=int(input("How many people are in your group? "))
tipAmount=float(input("What percentage would you like to tip?"))
final=(total+(total*(tipAmount*0.01)))/groupCount
print(f"Each person should pay {final}")
|
import numpy as np
import matplotlib.pyplot as plt
def bland_altman_plot(
m1,
m2,
sd_limit=1.96,
ax=None,
fig=None,
ages=None,
point_labels=None,
display_labels=None,
highlight_points=None,
hide_points=None,
y_lim=100,
title="",
x_axis="",
scatter_kwds=None,
mean_line_kwds=None,
limit_lines_kwds=None,
):
"""
Bland-Altman Plot.
A Bland-Altman plot is a graphical method to analyze the differences
between two methods of measurement. The mean of the measures is plotted
against their difference.
Parameters
----------
m1, m2: pandas Series or array-like
sd_limit : float, default 1.96
The limit of agreements expressed in terms of the standard deviation of
the differences. If `md` is the mean of the differences, and `sd` is
the standard deviation of those differences, then the limits of
agreement that will be plotted will be
md - sd_limit * sd, md + sd_limit * sd
The default of 1.96 will produce 95% confidence intervals for the means
of the differences.
If sd_limit = 0, no limits will be plotted, and the ylimit of the plot
defaults to 3 standard deviatons on either side of the mean.
ax: matplotlib.axis, optional
matplotlib axis object to plot on.
scatter_kwargs: keywords
Options to to style the scatter plot. Accepts any keywords for the
matplotlib Axes.scatter plotting method
mean_line_kwds: keywords
Options to to style the scatter plot. Accepts any keywords for the
matplotlib Axes.axhline plotting method
limit_lines_kwds: keywords
Options to to style the scatter plot. Accepts any keywords for the
matplotlib Axes.axhline plotting method
Returns
-------
ax: matplotlib Axis object
:param display_labels:
"""
if display_labels and not point_labels:
print("Warning: Display labels was requested but no labels have been provided")
# if highlight_points and not point_labels:
# print ("Warning: Highlight points was requested but no labels have been provided")
# if hide_points and not point_labels:
# print ("Warning: Hide points was requested but no labels have been provided")
if len(m1) != len(m2):
raise ValueError("m1 does not have the same length as m2.")
if sd_limit < 0:
raise ValueError("sd_limit ({}) is less than 0.".format(sd_limit))
if ages:
agesLabel = True
else:
agesLabel = False
if point_labels:
pointLabel = True
else:
pointLabel = False
means = np.mean([m1, m2], axis=0)
diffs = m1 - m2
mean_diff = np.mean(diffs)
std_diff = np.std(diffs, axis=0)
if hide_points:
del_idx = []
idx = 0
for label in point_labels:
if label in hide_points:
del_idx.append(idx)
idx += 1
m1 = np.delete(m1, del_idx)
m2 = np.delete(m2, del_idx)
ages = np.delete(ages, del_idx)
point_labels = np.delete(point_labels, del_idx)
# if ax is None:
# ax = plt.gca()
scatter_kwds = scatter_kwds or {}
if "s" not in scatter_kwds:
scatter_kwds["s"] = 20
mean_line_kwds = mean_line_kwds or {}
limit_lines_kwds = limit_lines_kwds or {}
for kwds in [mean_line_kwds, limit_lines_kwds]:
if "color" not in kwds:
kwds["color"] = "gray"
if "linewidth" not in kwds:
kwds["linewidth"] = 1
if "linestyle" not in mean_line_kwds:
kwds["linestyle"] = "--"
if "linestyle" not in limit_lines_kwds:
kwds["linestyle"] = ":"
if agesLabel:
x = ages
y = diffs
else:
x = means
y = diffs
fig, ax = plt.subplots(figsize=(8, 5))
sc = ax
if highlight_points and pointLabel:
cmap = []
for point in point_labels:
if not hide_points or point not in hide_points:
colour = "Red" if point in highlight_points else "Blue"
cmap.append(colour)
else:
cmap = ["Blue"] * len(m1)
# z = np.polyfit(x, y, 2)
# p = np.poly1d(z)
# ax.plot(x,p(x))
sc = ax.scatter(x, y, c=cmap, **scatter_kwds)
ax.axhline(mean_diff, **mean_line_kwds) # draw mean line.
# Annotate mean line with mean difference.
ax.annotate(
"mean diff:\n{}".format(np.round(mean_diff, 2)),
xy=(0.99, 0.5),
horizontalalignment="right",
verticalalignment="center",
fontsize=14,
xycoords="axes fraction",
)
if display_labels and pointLabel:
for label, x_val, y_val in zip(point_labels, x, y):
if label in display_labels:
plt.annotate(
label,
xy=(x_val, y_val),
xytext=(-20, 20),
textcoords="offset points",
ha="right",
va="bottom",
bbox=dict(boxstyle="round,pad=0.5", fc="yellow", alpha=0.5),
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
)
if pointLabel:
for label, x_val, y_val in zip(point_labels, x, y):
annot = plt.annotate(
label,
xy=(x_val, y_val),
xytext=(-20, 20),
textcoords="offset points",
ha="right",
va="bottom",
bbox=dict(boxstyle="round,pad=0.5", fc="yellow", alpha=0.5),
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
)
annot.set_visible(False)
if sd_limit > 0:
half_ylim = (1.5 * sd_limit) * std_diff
ax.set_ylim(mean_diff - half_ylim, mean_diff + half_ylim)
limit_of_agreement = sd_limit * std_diff
lower = mean_diff - limit_of_agreement
upper = mean_diff + limit_of_agreement
for j, lim in enumerate([lower, upper]):
ax.axhline(lim, **limit_lines_kwds)
ax.annotate(
"-SD{}: {}".format(sd_limit, np.round(lower, 2)),
xy=(0.99, 0.07),
horizontalalignment="right",
verticalalignment="bottom",
fontsize=14,
xycoords="axes fraction",
)
ax.annotate(
"+SD{}: {}".format(sd_limit, np.round(upper, 2)),
xy=(0.99, 0.92),
horizontalalignment="right",
fontsize=14,
xycoords="axes fraction",
)
elif sd_limit == 0:
half_ylim = 3 * std_diff
ax.set_ylim(mean_diff - half_ylim, mean_diff + half_ylim)
ax.set_title(title)
ax.set_ylim(-1 * y_lim, y_lim)
ax.set_ylabel("Difference", fontsize=24)
if agesLabel:
ax.set_xlabel(x_axis, fontsize=24)
else:
ax.set_xlabel("Means", fontsize=24)
ax.tick_params(labelsize=13)
plt.tight_layout()
def update_annot(ind):
pos = sc.get_offsets()[ind["ind"][0]]
annot.xy = pos
# text = "N{}".format(" N".join(list(map(str,ind["ind"]))))
text = "{}".format(" ").join(list(map(get_label, (ind["ind"]))))
annot.set_text(text)
# annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
# annot.get_bbox_patch().set_alpha(0.4)
def get_label(pos):
if len(point_labels[int(pos)]) > 0:
return point_labels[int(pos)]
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = sc.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event", hover)
return ax
|
import csv
from feature_extraction import calculate_features
"""
TASK: Prepare data-set from raw text
DATA-SET-FORMAT: CSV
INPUT: Raw lines from dataset
OUTPUT: CSV containing features extracted from dataset
"""
def dataset_preparation(dump_filename, dataset_filename):
# first read the text
# for each paragraph, calculate sentence length, sentence count, word length, word count
# avg syllable per word, total syllable, time to read
# @TODO: Add number of punctuation, text classification, positive words count
# write each line in a csv format
data = [[part.strip() for part in line.split('___', 4)] for line in open(dataset_filename).readlines()]
with open(dump_filename, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(["id", "text", "avg word length", "word count", "syllable per word", "total syllables", "avg sentence length", "sentence count", "reading time"])
for line in data:
arr = calculate_features(line[3].strip())
writer.writerow([int(line[0]), line[3].strip()] + arr + [float(line[1])])
print [int(line[0]), line[3].strip()] + arr + [float(line[1])]
if __name__ == '__main__':
dataset_preparation('../dataset/dataset.csv', '../dataset/reading-dataset.txt')
|
""" Blinkt-Clocky -- 8 light led clock for the Pimoroni Blinkt!
"""
from datetime import datetime as dt
from time import sleep
from blinkt import clear, show, set_pixel, NUM_PIXELS
def main():
"""The Clocky light displays the hour range, the minute range, the
second range, and a clock tick.
To read the clock:
The hours are represented by a blue bar with a bright end. The
longer the bar, the later it is in the day. Each segment in the
bar represents 3 hours.
The minutes are represented by the 2nd light on the bar. A blue
light is displayed when the minutes are between 0 and 15. A green
light is displayed for minutes 16-30. A white light represents
minutes 31-45 and a red light for minutes 46-59.
The seconds are represented by the 1st light on the bar. A blue
light is displayed when the seconds are between 0 and 15. A green
light is displayed for seconds 16-30. A white light represents
seconds 31-45 and a red light for seconds 46-59.
If the last light on the bar is not already lit for another
purpose, then it is used to display a pendulum of the clock,
displaying a white light for the odd seconds within each minute.
"""
while True:
pixels = [None for i in range(NUM_PIXELS)]
hour_now = dt.now().hour
pixhr_now = int(hour_now/3)
for p in range(pixhr_now):
pixels[p] = 'H'
pixels[pixhr_now-1] = '!'
if hour_now > 2:
second_pix, minute_pix = 0, 1
else:
second_pix = NUM_PIXELS - 1
minute_pix = second_pix - 1
pixels[minute_pix] = 'M'
pixels[second_pix] = 'S'
for i in range(len(pixels)):
if pixels[i] == 'M':
pixels[i] = "BGWR"[int(dt.now().minute / 15)]
elif pixels[i] == 'S':
pixels[i] = "BGWR"[int(dt.now().second / 15)]
elif pixels[i] == '!':
pixels[i] = 1
elif pixels[i] == 'H':
pixels[i] = "B"
clear()
for i in filter(lambda _: bool(pixels[_]), range(len(pixels))):
if type(pixels[i]) is int and pixels[i] == 1:
set_pixel(i, 100, 0, 100, 0.1)
elif pixels[i] == 'R':
set_pixel(i, 200, 0, 0, 0.033)
elif pixels[i] == 'G':
set_pixel(i, 0, 200, 0, 0.033)
elif pixels[i] == 'B':
set_pixel(i, 0, 0, 200, 0.033)
elif pixels[i] == 'W':
set_pixel(i, 200, 200, 200, 0.033)
# set second flash if that last pixel is free and it's normal mode
if second_pix == 0 and pixels[-1] is None:
if bool(dt.now().second % 2):
set_pixel(len(pixels)-1, 20, 20, 20, 0.033)
show()
sleep(0.5)
if __name__ == "__main__":
main()
|
class binaryTree:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def pr(root):
if root==None:
return
print(root.data)
pr(root.left)
pr(root.right)
import queue
def inp():
q=queue.Queue()
print("enter root")
rootD=int(input())
if rootD!=-1:
root=binaryTree(rootD)
q.put(root)
while(not(q.empty())):
curr=q.get()
print("enter left child of",curr.data)
leftData=int(input())
if leftData!=-1:
leftN=binaryTree(leftData)
curr.left=leftN
q.put(leftN)
print("enter right child of",curr.data)
rightData=int(input())
if rightData!=-1:
rightN=binaryTree(rightData)
curr.right=rightN
q.put(rightN)
return root
def pr2(root):
q=queue.Queue()
q.put(root)
while(not(q.empty())):
curr=q.get()
print(curr.data)
if curr.left is not None:
print(curr.left.data)
q.put(curr.left)
if curr.right is not None:
print(curr.right.data)
q.put(curr.right)
print()
root=inp()
pr2(root) |
def can_win(board, pos):
if pos < 0 or pos > len(board) - 1:
return False
current_pos_value = board[pos]
if is_winning_slot(board, pos - current_pos_value) or is_winning_slot(board, pos + current_pos_value):
return True
return False
def is_winning_slot(board, new_position):
if new_position < 0 or new_position > len(board) - 1:
return False # stepped too far!
if board[new_position] == 0:
return True
return False
# Test!
board = [0, 0, 0, 0, 0, 0, 0]
print(can_win(board, 3))
board = [1, 3, 2, 0, 5, 2, 8, 4, 1]
print(can_win(board, 76)) # never trust the user!
|
import sqlite3
import sys
import random
from random import randrange
from datetime import datetime, timedelta, date, time
'''Resources for SQLite in python and implementing user logins
https://eclass.srv.ualberta.ca/pluginfile.php/5149362/mod_label/intro/SQLite-in-Python-1.pdf -- BEST
https://eclass.srv.ualberta.ca/mod/page/view.php?id=3659763 -- Assignment Spec
https://github.com/imilas/291PyLab -- BEST
https://eclass.srv.ualberta.ca/pluginfile.php/5149359/mod_label/intro/QL-eSQL.pdf?time=1567207038507 -- SQL inside applications slides
https://stackoverflow.com/questions/973541/how-to-set-sqlite3-to-be-case-insensitive-when-string-comparing -- Case sensitive for SQL'''
db = sys.argv[1]
conn = sqlite3.connect(db)
cursor = conn.cursor()
cursor.execute('PRAGMA foreign_keys=ON;')
conn.commit()
def main():
print("***WELCOME****")
user = login()
if user[0][0] == 'a':
agent_prompt(str(user[0][1]))
elif user[0][0] == 'o':
officer_prompt()
else:
print(user[0][0])
print("error")
def login():
isUser = False
while isUser == False:
user = getUser()
if len(user) != 0:
isUser = True
else:
print("Invalid user id or password, please try again")
return user
def logout():
print("LOGGING OUT...")
main()
def getUser():
username = input("User ID: ")
pwd = input("Password: ")
cursor.execute("SELECT utype, city FROM users WHERE uid LIKE ? AND pwd = ?", (username, pwd))
user = cursor.fetchall()
return user
def generateUniqueID():
existing_IDs = []
numbers = list(range(10000))
random_number = random.choice(numbers)
while random_number in existing_IDs:
generateUniqueID()
existing_IDs.append(random_number)
return random_number
def officer_prompt():
display_officer_options()
while True:
input_option = str(input("Select option: "))
option = input_option
if option == '0':
issue_ticket()
display_officer_options()
elif option == '1':
find_car_owner()
display_officer_options()
elif option == '2':
logout()
else:
print("****ERROR***** invalid option please try again")
display_officer_options()
def agent_prompt(user):
display_agent_options()
while True:
input_option = str(input("Selection option: "))
option = input_option
if option == '0':
register_birth(user)
display_agent_options()
elif option == '1':
register_marriage(user)
display_agent_options()
elif option == '2':
renew_vehicle_Reg()
display_agent_options()
elif option == '3':
process_bill_of_sale()
display_agent_options()
elif option == '4':
process_payment()
display_agent_options()
elif option == '5':
get_driver_abstract()
display_agent_options()
elif option == '6':
logout()
else:
print("****ERROR***** invalid option please try again")
display_agent_options()
def display_agent_options():
print("****Options****")
print("Register birth (press 0)")
print("Register Marriage (press 1)")
print("Renew Vehicle Registration (press 2)")
print("Process Bill of Sale (press 3)")
print("Process Payment (press 4)")
print("Get Driver Abstract (press 5)")
print("Logout (press 6)")
def display_officer_options():
print("****Options****")
print("Issue a Ticket (press 0)")
print("Find Car Owner (press 1)")
print("Logout (press 2)")
def register_birth(user): #needs nbregplace and new unique id generator
'''The agent should be able to register a birth by providing the first name, the last name, the gender, the birth date, the birth place of the newborn,
as well as the first and last names of the parents. The registration date is set to the day of registration (today's date) and the registration place is set to the city of the user.
The system should automatically assign a unique registration number to the birth record. The address and the phone of the newborn are set to those of the mother. If any of the parents is not in the database,
the system should get information about the parent including first name, last name, birth date, birth place, address and phone. For each parent, any column other than the first name and last name can be null if it is not provided.'''
birthregno = randrange(1000000000)
while True:
cursor.execute("SELECT EXISTS(SELECT 1 FROM births WHERE regno=?)", (birthregno,))
temp = cursor.fetchall()
if int(temp[0][0]) == 1:
birthregno = randrange(1000000000)
else:
conn.commit()
break
nbfname = input("Newborn's First Name: ")
nblname = input("Newborn's Last Name: ")
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (nbfname, nblname))
nbperson = cursor.fetchall()
if nbperson != []:
print("This newborn is already registered as a person in the database. Returning to agent options.")
return
nbregdate = date.today()
nbregplace = str(user)
nbgender = input("Newborn's Gender (M/F): ")
nbf_fname = input("Newborn's Father's First Name: ")
nbf_lname = input("Newborn's Father's Last Name: ")
nbm_fname = input("Newborn's Mother's First Name: ")
nbm_lname = input("Newborn's Mother's Last Name: ")
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (nbm_fname, nbm_lname))
nbmother = cursor.fetchall()
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (nbf_fname, nbf_lname))
nbfather = cursor.fetchall()
while nbmother == []:
nbm_fname = input("Confirm Mother's first name: ") # Need to make sure this isn't null
nbm_lname = input("Confirm Mother's last name: ") # Need to make sure this isn't null
motherbdate = input("What is the Mother's birth date? (YYYY-MM-DD): ")
motherbplace = input("What is the Mother's birth place? (format): ")
motheraddress = input("What is the Mother's address? (format): ")
motherphone = input("What is the Mother's phone number?: (###-###-####)")
mother_data = (nbm_fname,nbm_lname,motherbdate,motherbplace,motheraddress,motherphone)
cursor.execute("INSERT INTO persons(fname, lname, bdate, bplace, address, phone) VALUES (?,?,?,?,?,?)", mother_data)
conn.commit()
break
while nbfather == []:
nbf_fname = input("Confirm Father's first name: ") # Need to make sure this isn't null
nbf_lname = input("Confirm Father's last name: ") # Need to make sure this isn't null
fatherbdate = input("What is the Father's birth date? (YYYY-MM-DD): ")
fatherbplace = input("What is the Father's birth place?: ")
fatheraddress = input("What is the Father's address?: ")
fatherphone = input("What is the Father's phone number? (###-###-####): ")
father_data = (nbf_fname,nbf_lname,fatherbdate,fatherbplace,fatheraddress,fatherphone)
cursor.execute("INSERT INTO persons(fname, lname, bdate, bplace, address, phone) VALUES (?,?,?,?,?,?)", father_data)
conn.commit()
break
cursor.execute("SELECT address FROM persons WHERE ? LIKE fname AND ? LIKE lname", (nbm_fname, nbm_lname)) #Finds mother's address
nbaddress = cursor.fetchall()
cursor.execute("SELECT phone FROM persons WHERE ? LIKE fname AND ? LIKE lname", (nbm_fname, nbm_lname)) #Finds mother's phone number
nbphone = cursor.fetchall()
baby_data = (birthregno,nbfname,nblname,nbregdate,nbregplace,nbgender,nbf_fname,nbf_lname,nbm_fname,nbm_lname)
person_data = (nbfname, nblname, nbregdate, nbregplace, str(nbaddress), str(nbphone))
cursor.execute("INSERT INTO persons(fname, lname, bdate, bplace, address, phone) VALUES (?,?,?,?,?,?)", person_data) #First we register the baby as a person
conn.commit()
cursor.execute("INSERT INTO births(regno, fname, lname, regdate, regplace, gender, f_fname, f_lname, m_fname, m_lname) VALUES (?,?,?,?,?,?,?,?,?,?)", baby_data) #We then register it as a birth
conn.commit()
print("Registration Complete! Returning to Agent Options")
def register_marriage(user):
'''The user should be able to provide the names of the partners and the system should assign the registration date and place and a unique registration number as discussed in registering a birth.
If any of the partners is not found in the database, the system should get information about the partner including first name, last name, birth date, birth place, address and phone.
For each partner, any column other than the first name and last name can be null if it is not provided.'''
marriageno = randrange(1000000000)
while True:
cursor.execute("SELECT EXISTS(SELECT 1 FROM marriages WHERE regno=?)", (marriageno,))
temp = cursor.fetchall()
if int(temp[0][0]) == 1:
marriageno = randrange(1000000000)
else:
conn.commit()
break
marriagedate = date.today()
marriageplace = str(user)
p1fname = input("What is partner 1's first name?: ")
p1lname = input("What is partner 1's last name?: ")
p2fname = input("What is partner 2's first name?: ")
p2lname = input("What is partner 2's last name?: ")
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (p1fname, p1lname))
partner1 = cursor.fetchall()
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (p2fname, p2lname))
partner2 = cursor.fetchall()
while partner1 == []:
p1fname = input("Confirm Partner 1's first name: ") # Need to make sure this isn't null
p1lname = input("Confirm Partner 1's last name: ") # Need to make sure this isn't null
partner1bdate = input("What is Partner 1's birth date? (YYYY-MM-DD): ")
partner1bplace = input("What is the Partner 1's birth place? (format): ")
partner1address = input("What is the Partner 1's address? (format): ")
partner1phone = input("What is the Partner 1's phone number?: (###-###-####)")
partner1_data = (p1fname,p1lname,partner1bdate,partner1bplace,partner1address,partner1phone)
cursor.execute("INSERT INTO persons(fname, lname, bdate, bplace, address, phone) VALUES (?,?,?,?,?,?)", partner1_data)
conn.commit()
break
while partner2 == []:
p2fname = input("Confirm Partner 2's first name: ") # Need to make sure this isn't null
p2lname = input("Confirm Partner 2's last name: ") # Need to make sure this isn't null
partner2bdate = input("What is the Partner 2's birth date? (YYYY-MM-DD): ")
partner2bplace = input("What is the Partner 2's birth place?: ")
partner2address = input("What is the Partner 2's address?: ")
partner2phone = input("What is the Partner 2's phone number? (###-###-####): ")
partner2_data = (p2fname,p2lname,partner2bdate,partner2bplace,partner2address,partner2phone)
cursor.execute("INSERT INTO persons(fname, lname, bdate, bplace, address, phone) VALUES (?,?,?,?,?,?)", partner2_data)
conn.commit()
break
marriage_data = (marriageno,marriagedate,marriageplace,p1fname,p1lname,p2fname,p2lname)
cursor.execute("INSERT INTO marriages(regno,regdate,regplace,p1_fname,p1_lname,p2_fname,p2_lname) VALUES (?,?,?,?,?,?,?)", marriage_data)
conn.commit()
print("Registration Complete! Returning to Agent Options")
def renew_vehicle_Reg():
'''The user should be able to provide an existing registration number and renew the registration.
The system should set the new expiry date to one year from today's date if the current registration either has expired or expires today.
Otherwise, the system should set the new expiry to one year after the current expiry date.'''
vehicleregno = input("Enter the vehicle's registration number: ")
cursor.execute("SELECT expiry FROM registrations WHERE ? = regno", (vehicleregno,))
rawexpiry = cursor.fetchall()
if rawexpiry == []:
print("That registration number is invalid! Returning to agent options.")
return
rawexpirystring = str(rawexpiry)
#rawexpirystring = rawexpirystring.translate(None, '[(,)]') #This DOESNT work in python 3, but DOES in python 2
rawexpirystring = rawexpirystring.translate({ord(i):None for i in '[(,)]'}) #This DOESNT work in python 2, but DOES in python 3
currentexpiry = datetime.strptime(rawexpirystring, "'%Y-%m-%d'").date()
todays_date = date.today()
if currentexpiry <= todays_date:
newexpiry = todays_date.replace(todays_date.year + 1)
else:
newexpiry = currentexpiry.replace(currentexpiry.year + 1)
cursor.execute("UPDATE registrations SET expiry = ? WHERE regno = ?", (newexpiry, vehicleregno))
conn.commit()
print("Vehicle registration renewed! Returning.")
def process_bill_of_sale():
'''The user should be able to record a bill of sale by providing the vin of a car, the name of the current owner, the name of the new owner, and a plate number for the new registration.
If the name of the current owner (that is provided) does not match the name of the most recent owner of the car in the system, the transfer cannot be made.
When the transfer can be made, the expiry date of the current registration is set to today's date and a
new registration under the new owner's name is recorded with the registration date and the expiry date set by the system to today's date and a year after today's date respectively.
Also a unique registration number should be assigned by the system to the new registration. The vin will be copied from the current registration to the new one.'''
entered_vin = input("What is the VIN of the vehicle that is to be sold?: ")
current_owner_fname = input("What is the first name of the vehicle's current owner?: ")
current_owner_lname = input("What is the last name of the vehicle's current owner?: ")
cursor.execute("SELECT r.fname FROM registrations r WHERE ? = r.vin AND ? LIKE r.fname AND ? LIKE r.lname AND regdate = (SELECT max(r2.regdate) FROM registrations r2 WHERE r.fname = r2.fname AND r.lname = r2.lname AND r.vin = r2.vin)", (entered_vin, current_owner_fname, current_owner_lname))
latest_owner_fname = cursor.fetchall() #Need to heavily test this query, mostly for case sensitivity
conn.commit()
cursor.execute("SELECT r.lname FROM registrations r WHERE ? = r.vin AND ? LIKE r.fname AND ? LIKE r.lname AND regdate = (SELECT max(r2.regdate) FROM registrations r2 WHERE r.fname = r2.fname AND r.lname = r2.lname AND r.vin = r2.vin)", (entered_vin, current_owner_fname, current_owner_lname))
latest_owner_lname = cursor.fetchall() #Need to heavily test this query, mostly for case sensitivity
conn.commit()
str_latest_owner_fname = str(latest_owner_fname)
#str_latest_owner_fname = str_latest_owner_fname.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
str_latest_owner_fname = str_latest_owner_fname.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
str_latest_owner_lname = str(latest_owner_lname)
#str_latest_owner_fname = str_latest_owner_fname.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
str_latest_owner_lname = str_latest_owner_lname.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
str_latest_owner_fname = str_latest_owner_fname.strip("''")
str_latest_owner_lname = str_latest_owner_lname.strip("''")
str_latest_owner_fname_lower = str_latest_owner_fname.lower()
str_latest_owner_lname_lower = str_latest_owner_lname.lower()
if (latest_owner_fname == []) or (latest_owner_lname ==[]):
print("This person and/or vehicle does not exist in the database. Exiting.")
return
elif (str_latest_owner_fname_lower != current_owner_fname.lower()) or (str_latest_owner_lname_lower != current_owner_lname.lower()):
print("The name you have entered is not the latest owner of this vehicle. Exiting.")
return
else:
new_owner_fname = input("What is the first name of the new owner?: ")
new_owner_lname = input("What is the last name of the new owner?: ")
cursor.execute("SELECT fname, lname FROM persons WHERE ? LIKE fname AND ? LIKE lname", (new_owner_fname, new_owner_lname))
new_owner = cursor.fetchall()
if new_owner == []:
print("The new owner of this vehicle does not exist in the database. Transaction incomplete. Returning.")
return
entered_plate = input("What is the requested new license plate number?: ")
current_expiry = date.today()
cursor.execute("UPDATE registrations SET expiry = ? WHERE vin = ?", (current_expiry, entered_vin))
conn.commit()
new_registration_date = date.today()
new_expiry_date = current_expiry.replace(current_expiry.year + 1)
unique_registration_number = randrange(1000000000)
while True:
cursor.execute("SELECT EXISTS(SELECT 1 FROM registrations WHERE regno=?)", (unique_registration_number,))
temp = cursor.fetchall()
if int(temp[0][0]) == 1:
unique_registration_number = randrange(1000000000)
else:
conn.commit()
break
new_owner_data = (unique_registration_number, new_registration_date, new_expiry_date, entered_plate, entered_vin, new_owner_fname, new_owner_lname)
cursor.execute("INSERT INTO registrations(regno, regdate, expiry, plate, vin, fname, lname) VALUES (?,?,?,?,?,?,?)", new_owner_data)
conn.commit()
def process_payment():
'''The user should be able to record a payment by entering a valid ticket number and an amount.
The payment date is automatically set to the day of the payment (today's date).
A ticket can be paid in multiple payments but the sum of those payments cannot exceed the fine amount of the ticket.'''
ticketnumber = input("Enter the ticket number: ")
paymentamount = input("Enter the payment amount: ")
paymentdate = date.today()
cursor.execute("SELECT fine FROM tickets WHERE ? = tno", (ticketnumber,))
fine_amount = cursor.fetchall()
if fine_amount == []:
print("This ticket doesn't exist. Returning to agent operations.")
return
fine_amount = str(fine_amount)
#fine_amount = fine_amount.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
fine_amount = fine_amount.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
fine_amount = float(fine_amount)
paymentamount = float(paymentamount)
cursor.execute("SELECT pdate FROM payments WHERE ? = tno", (ticketnumber,))
fine_date = cursor.fetchall()
if fine_date != []:
fine_date_string = str(fine_date)
#fine_date_string = fine_date_string.translate(None, '[(,)]') #This DOESNT work in python 3, but DOES in python 2
fine_date_string = fine_date_string.translate({ord(i):None for i in '[(,)]'}) #This DOESNT work in python 2, but DOES in python 3
fine_date_object = datetime.strptime(fine_date_string, "'%Y-%m-%d'").date()
if fine_date_object == date.today():
print("This ticket has already been paid today. Try again tomorrow!")
return
if paymentamount > fine_amount:
paymentamount = fine_amount
print("You have overpaid this ticket. The true amount paid was $" + str(paymentamount))
fine_amount = fine_amount - paymentamount
cursor.execute("UPDATE tickets SET fine = ? WHERE tno = ?", (fine_amount, ticketnumber))
conn.commit()
else:
fine_amount = fine_amount - paymentamount
print("Ticket paid for $" + str(paymentamount))
cursor.execute("UPDATE tickets SET fine = ? WHERE tno = ?", (fine_amount, ticketnumber))
conn.commit()
payment_data = (ticketnumber, paymentdate, paymentamount)
cursor.execute("INSERT INTO payments(tno, pdate, amount) VALUES (?,?,?)", payment_data)
conn.commit()
def get_driver_abstract():
#The user should be able to enter a first name and a last name and get a driver abstract, which includes number of tickets, the number of demerit notices, the total number of demerit points received both within the past two years and within the lifetime.
#The user should be given the option to see the tickets ordered from the latest to the oldest. For each ticket, you will report the ticket number,
#the violation date, the violation description, the fine, the registration number and the make and model of the car for which the ticket is issued.
#If there are more than 5 tickets, at most 5 tickets will be shown at a time, and the user can select to see more.
abstract_fname = input("What is the driver's first name?: ")
abstract_lname = input("What is the driver's last name?: ")
cursor.execute("SELECT regno FROM registrations WHERE ? LIKE fname AND ? LIKE lname", (abstract_fname, abstract_lname))
abstract_regno = cursor.fetchall()
if len(abstract_regno) > 1:
abstract_regno_string = str(abstract_regno)
#abstract_regno_string = abstract_regno_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
abstract_regno_string = abstract_regno_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
abstract_regno_list = abstract_regno_string.split()
print("Driver Abstract: ")
length_of_list = range(len(abstract_regno_list))
number_of_tickets_counter = 0
for i in length_of_list:
cursor.execute("SELECT COUNT(*) FROM tickets WHERE ? = regno", (abstract_regno_list[i],))
number_of_tickets = cursor.fetchall()
number_of_tickets_string = str(number_of_tickets)
#number_of_tickets_string = number_of_tickets_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
number_of_tickets_string = number_of_tickets_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
number_of_tickets_int = int(number_of_tickets_string)
number_of_tickets_counter += number_of_tickets_int
number_of_tickets_string = str(number_of_tickets_counter)
print("Number of tickets received: " + number_of_tickets_string)
cursor.execute("SELECT COUNT(*) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname", (abstract_fname, abstract_lname))
number_of_demeritNotices = cursor.fetchall()
number_of_demeritNotices_string = str(number_of_demeritNotices)
#number_of_demeritNotices_string = number_of_demeritNotices_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
number_of_demeritNotices_string = number_of_demeritNotices_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of demerit notices received: " + number_of_demeritNotices_string)
cursor.execute("SELECT SUM(points) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname AND ddate >= date('now', '-2 years')", (abstract_fname, abstract_lname))
recent_number_demerits = cursor.fetchall()
recent_number_demerits_string = str(recent_number_demerits)
#recent_number_demerits_string = recent_number_demerits_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
recent_number_demerits_string = recent_number_demerits_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of demerits within the last two years received: " + recent_number_demerits_string)
cursor.execute("SELECT SUM(points) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname", (abstract_fname, abstract_lname))
total_number_demerits = cursor.fetchall()
total_number_demerits_string = str(total_number_demerits)
#total_number_demerits_string = total_number_demerits_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
total_number_demerits_string = total_number_demerits_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of lifetime demerits received: " + total_number_demerits_string)
optional_order = input("Would you like to see the tickets in order of latest to oldest? (Y/N): ")
optional_order = optional_order.lower()
while (optional_order != "y") and (optional_order != "n"):
optional_order = input("Incorrect response. Would you like to see the tickets in order of latest to oldest? (Y/N): ")
break
ticket_counter = 0
for i in length_of_list:
if optional_order == "y":
cursor.execute("SELECT t.tno, t.vdate, t.violation, t.fine, t.regno, v.make, v.model FROM tickets t LEFT OUTER JOIN registrations r ON r.regno = t.regno LEFT OUTER JOIN vehicles v on v.vin = r.vin WHERE ? = t.regno ORDER BY t.vdate DESC", (abstract_regno_list[i],))
abstract_info = cursor.fetchall() #might need to move this out of the for loop
for row in abstract_info:
print(row)
ticket_counter += 1
if ticket_counter == 5 and number_of_tickets_counter > 5:
choice_of_five = input("Five tickets have been displayed, would you like to see more? (Y/N): ")
if choice_of_five.lower() == "y":
continue
else:
return
elif optional_order == "n":
cursor.execute("SELECT t.tno, t.vdate, t.violation, t.fine, t.regno, v.make, v.model FROM tickets t LEFT OUTER JOIN registrations r ON r.regno = t.regno LEFT OUTER JOIN vehicles v on v.vin = r.vin WHERE ? = t.regno", (abstract_regno_list[i],))
abstract_info = cursor.fetchall() #might need to move this out of the for loop
for row in abstract_info:
print(row)
ticket_counter += 1
if ticket_counter == 5 and number_of_tickets_counter > 5:
choice_of_five = input("Five tickets have been displayed, would you like to see more? (Y/N): ")
if choice_of_five.lower() == "y":
continue
else:
return
if len(abstract_regno) == 1:
abstract_regno_string = str(abstract_regno)
#abstract_regno_string = abstract_regno_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
abstract_regno_string = abstract_regno_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print(abstract_regno_string)
print("Driver Abstract: ")
cursor.execute("SELECT COUNT(*) FROM tickets WHERE ? = regno", (abstract_regno_string,))
number_of_tickets = cursor.fetchall()
number_of_tickets_string = str(number_of_tickets)
#number_of_tickets_string = number_of_tickets_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
number_of_tickets_string = number_of_tickets_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of tickets received: " + number_of_tickets_string)
cursor.execute("SELECT COUNT(*) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname", (abstract_fname, abstract_lname))
number_of_demeritNotices = cursor.fetchall()
number_of_demeritNotices_string = str(number_of_demeritNotices)
#number_of_demeritNotices_string = number_of_demeritNotices_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
number_of_demeritNotices_string = number_of_demeritNotices_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of demerit notices received: " + number_of_demeritNotices_string)
cursor.execute("SELECT SUM(points) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname AND ddate >= date('now', '-2 years')", (abstract_fname, abstract_lname))
recent_number_demerits = cursor.fetchall()
recent_number_demerits_string = str(recent_number_demerits)
#recent_number_demerits_string = recent_number_demerits_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
recent_number_demerits_string = recent_number_demerits_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of demerits within the last two years received: " + recent_number_demerits_string)
cursor.execute("SELECT SUM(points) FROM demeritNotices WHERE ? LIKE fname AND ? LIKE lname", (abstract_fname, abstract_lname))
total_number_demerits = cursor.fetchall()
total_number_demerits_string = str(total_number_demerits)
#total_number_demerits_string = total_number_demerits_string.translate(None, '[("",)]') #This DOESNT work in python 3, but DOES in python 2
total_number_demerits_string = total_number_demerits_string.translate({ord(i):None for i in '[("",)]'}) #This DOESNT work in python 2, but DOES in python 3
print("Number of lifetime demerits received: " + total_number_demerits_string)
optional_order = input("Would you like to see the tickets in order of latest to oldest? (Y/N): ")
optional_order = optional_order.lower()
while (optional_order != "y") and (optional_order != "n"):
optional_order = input("Incorrect response. Would you like to see the tickets in order of latest to oldest? (Y/N): ")
break
if optional_order == "y":
cursor.execute("SELECT t.tno, t.vdate, t.violation, t.fine, t.regno, v.make, v.model FROM tickets t LEFT OUTER JOIN registrations r ON r.regno = t.regno LEFT OUTER JOIN vehicles v on v.vin = r.vin WHERE ? = t.regno ORDER BY t.vdate DESC", (abstract_regno_string,))
abstract_info = cursor.fetchall()
for row in abstract_info:
print(row)
elif optional_order == "n":
cursor.execute("SELECT t.tno, t.vdate, t.violation, t.fine, t.regno, v.make, v.model FROM tickets t LEFT OUTER JOIN registrations r ON r.regno = t.regno LEFT OUTER JOIN vehicles v on v.vin = r.vin WHERE ? = t.regno", (abstract_regno_string,))
abstract_info = cursor.fetchall()
for row in abstract_info:
print(row)
elif len(abstract_regno) == 0:
print("This person has no tickets on file! Returning.")
return
def logout():
print("Logging out....")
main()
def issue_ticket():
'''The user should be able to provide a registration number and see the person name that is listed in the registration and the make, model, year and color of the car registered.
Then the user should be able to proceed and ticket the registration by providing a violation date, a violation text and a fine amount. A unique ticket number should be assigned automatically and the ticket should be recorded.
The violation date should be set to today's date if it is not provided.'''
while True:
regno = int(input("Enter a registration number: "))
cursor.execute("SELECT regno, vin, fname, lname FROM registrations WHERE regno = ?;", (regno,))
regInfo = cursor.fetchall()
conn.commit()
if regInfo == []:
option = input('Registration number not found would you like to try again? (y/n): ')
if option == 'n':
return
elif regInfo[0][0] == regno:
break
vin = regInfo[0][1]
fname = regInfo[0][2]
lname = regInfo[0][3]
cursor.execute("SELECT make, model, year, color FROM vehicles WHERE vin = ?;",(vin,))
vehicleInfo = cursor.fetchall()
conn.commit()
make = vehicleInfo[0][0]
model = vehicleInfo[0][1]
year = vehicleInfo[0][2]
color = vehicleInfo[0][3]
print("\n***Vehicle Info***")
print("Make: " + str(make))
print("Model: " + str(model))
print("Year: " + str(year))
print("Color: " + str(color))
while True:
vDate = input('Enter violation date (YYYY-MM-DD)')
vText = input('Enter violation text: ')
fineAmount = input(('Enter fine amount: '))
if fineAmount.isdigit() == False:
print('ERROR, Invalid fine value entered please try again')
if vDate == '':
vDate = datetime.datetime.now().strftime("%Y-%m-%d")
if vText == '':
vText = None
else:
break
tno = randrange(1000000000)
while True:
cursor.execute("SELECT EXISTS(SELECT 1 FROM tickets WHERE tno=?)", (tno,))
temp = cursor.fetchall()
if int(temp[0][0]) == 1:
tno = randrange(1000000000)
else:
conn.commit()
break
cursor.execute("insert into tickets values(?,?,?,?,?)", (tno,regno,fineAmount,vText,vDate))
conn.commit()
def find_car_owner():
'''The user should be able to look for the owner of a car by providing one or more of make, model, year, color, and plate.
The system should find and return all matches. If there are more than 4 matches, you will show only the make, model, year, color,
and the plate of the matching cars and let the user select one. When there are less than 4 matches or when a car is selected from a list shown earlier,
for each match, the make, model, year, color, and the plate of the matching car will be shown as well as the latest registration date, the expiry date, and the name of the person listed in the latest registration record.'''
selectQuery = "SELECT v.make, v.model, v.year, v.color, r.plate, regdate, expiry, fname, lname FROM vehicles v LEFT JOIN registrations r ON r.vin = v.vin WHERE "
carDetails = ['make', 'model', 'year', 'color', 'plate']
userSelections = []
userValues = []
for i in range(0, len(carDetails)): #Store inputs of the different car details
temp = input("Enter "+carDetails[i] + ": ")
if temp != '':
userValues.append(temp)
userSelections.append(carDetails[i])
if len(userValues) == 0:
print("ERROR, you must enter at least one of the fields")
return
for i in range(0, len(userSelections)):
if i == len(userSelections) - 1:
if userSelections[i] == 'year':
selectQuery += 'v.'+ userSelections[i] + '=' + userValues[i]
elif userSelections[i] == 'plate':
selectQuery += 'r.'+userSelections[i] + '=' + single_quote(userValues[i])
else:
selectQuery += 'v.' + userSelections[i] + ' LIKE ' + single_quote(userValues[i])
else:
if userSelections[i] == 'year':
selectQuery += 'v.'+ userSelections[i] + '=' + userValues[i] + ' AND '
elif userSelections[i] == 'plate':
selectQuery += 'r.'+userSelections[i] + '=' + single_quote(userValues[i]) + ' AND '
else:
selectQuery += 'v.' + userSelections[i] + ' LIKE ' + single_quote(userValues[i]) + ' AND '
selectQuery += " GROUP BY v.vin"
cursor.execute(selectQuery)
fetched = cursor.fetchall()
if len(fetched) == 0:
print('No results found')
elif len(fetched) >= 4:
formated_row = '{:<10} {:>6} {:>6} {:>6} {:^10}'
i = 1
for row in fetched:
if i == 1:
print(" "+formated_row.format("Make", "Model", "Year", "Color", "Plate"))
print(str(i)+ " " + formated_row.format(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4])))
i = i + 1
selectionRow = int(input("Select row from vehicles for more information: "))
while (selectionRow < 1) or (selectionRow > len(fetched)):
print("ERROR, invalid selection please try again")
selectionRow = int(input("Select row from vehicles for more information: "))
selection = fetched[selectionRow-1]
make = str(selection[0])
model = str(selection[1])
year = str(selection[2])
color = str(selection[3])
plate = str(selection[4])
formated_row = '{:<10} {:^10} {:^10} {:^10} {:^10} {:^15} {:^15} {:^15} {:^15}'
if plate == "None":
print(formated_row.format("Make", "Model", "Year", "Color", "Plate","Regdate","Expiry Date","First name", "Last name"))
print(formated_row.format(make, model, year, color, plate, "None", "None", "None", "None"))
else:
selectQuery = """SELECT v.make, v.model, v.year, v.color, r.plate, r.regdate, r.expiry, r.fname, r.lname FROM vehicles v
LEFT JOIN registrations r ON v.vin = r.vin WHERE v.make like ? AND v.model like ? AND v.year = ? AND v.color LIKE ? AND r.plate = ?
ORDER BY r.regdate DESC LIMIT 1"""
cursor.execute(selectQuery, (make, model, year, color, plate))
fetched = cursor.fetchall()
print(formated_row.format("Make", "Model", "Year", "Color", "Plate","Regdate","Expiry Date","First name", "Last name"))
for row in fetched:
print(formated_row.format(*row))
else:
formated_row = '{:<10} {:^10} {:^10} {:^10} {:^10} {:^15} {:^15} {:^15} {:^15}'
selectQuery += "AND r.regdate = (SELECT MAX(regdate) FROM registrations WHERE vin = v.vin)"
print(selectQuery)
print(formated_row.format("Make", "Model", "Year", "Color", "Plate","Regdate","Expiry Date","First name", "Last name"))
for row in fetched:
print(formated_row.format(*row))
conn.commit()
def single_quote(word):
return "'%s'" % word
main()
conn.close()
|
# Find the smallest number
def find_smallest_number(list_of_number):
smallest = list_of_number[0]
for num in list_of_number:
print("current number: " + str(num))
print("smallest is: " + str(smallest))
if num < smallest:
print("current is smaller than smallest!!")
smallest = num
return smallest
print("The smallest number is: " + str(find_smallest_number([1,2,3,4,5,6,7,8,9,10])))
# ================================================================================================================================
# Find the largest number
def find_largest_number(list_of_number):
largest = list_of_number[0]
for num in list_of_number:
print("current number: " + str(num))
print("largest is: " + str(largest))
if num > largest:
print("current is the largest out of the list!!")
largest = num
return largest
print("The largest number is: " + str(find_largest_number([1,2,3,4,5,6,7,8,9,10])))
# ================================================================================================================================
# # Find the shortest string
def shortest_string(list_of_strings):
shortest = str(1e99)
for string in list_of_strings:
if len(string) < len(shortest):
shortest = string
print(shortest)
shortest_string(["apple", "banana", "carrot cake"])
# ================================================================================================================================
# # Find the longest string
def longest_string(list_of_strings):
longest = str(num)
for string in list_of_strings:
if len(string) > len(longest):
longest = string
print(longest)
shortest_string(["apple", "banana", "carrot cake"])
# ================================================================================================================================ |
import re
import itertools
input = open('day13input2.txt','r')
regex = re.compile(r"(.*)\swould\s([a-z]{4}\s\d+)\shappiness\sunits\sby\ssitting\snext\sto\s(.*)\.")
gainregex = re.compile("gain")
data = []
people = []
maximumHappiness = 0
def happinessValue(person,neighbor):
# Iterate through data and find the correct record
for entry in data:
if person == entry[0] and neighbor == entry[1]:
return entry[2]
# Extract the data from the text file, build an array with all of the values
for line in input:
entry = []
m = re.search(regex,line)
entry.append(m.group(1))
if m.group(1) not in people:
people.append(m.group(1))
entry.append(m.group(3))
value = m.group(2)
valuearray = value.split(' ')
if valuearray[0] == 'gain':
entry.append(int(valuearray[1]))
elif valuearray[0] == 'lose':
entry.append(int(valuearray[1])*-1)
else:
print("Invalid amount")
data.append(entry)
# Iterate through every possible seating arrangement
for arrangement in itertools.permutations(people):
# Calculate happiness points for each arrangement, keep the highest value
happiness = 0
lastIndex = len(arrangement)-1
for position in range(len(arrangement)):
# Special case for beginning of list
if position == 0:
# Person to the left (wrap around to end of list)
happiness += happinessValue(arrangement[position], arrangement[lastIndex])
# Person to the right
happiness += happinessValue(arrangement[position], arrangement[position+1])
# Special case for end of list
elif position == lastIndex:
# Person to the left
happiness += happinessValue(arrangement[position], arrangement[position-1])
# Person to the right (wrap around to beginning of list)
happiness += happinessValue(arrangement[position], arrangement[0])
else:
# Person to the left
happiness += happinessValue(arrangement[position], arrangement[position-1])
# Person to the right
happiness += happinessValue(arrangement[position], arrangement[position+1])
# Save maximum happiness value
if happiness > maximumHappiness:
maximumHappiness = happiness
print(str(maximumHappiness)) |
"""
Loading the boston dataset and examining its target (label) distribution.
"""
# Load libraries
import numpy as np
import pylab as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
from sklearn.cross_validation import train_test_split
from sklearn.metrics import make_scorer
from sklearn import grid_search
from sklearn.neighbors import NearestNeighbors
################################
### ADD EXTRA LIBRARIES HERE ###
################################
def load_data():
'''Load the Boston dataset.'''
boston = datasets.load_boston()
return boston
def explore_city_data(city_data):
'''Calculate the Boston housing statistics.'''
# Get the labels and features from the housing data
housing_prices = city_data.target
housing_features = city_data.data
###################################
### Step 1. YOUR CODE GOES HERE ###
###################################
print '\n'
# Please calculate the following values using the Numpy library
# Size of data?
size_housing_prices = housing_prices.size
print "Size housing prices: " + str(size_housing_prices)
# Number of features?
size_housing_features = housing_features.size
print "Size housing features: " + str(size_housing_features)
# Minimum value?
min_housing_prices = np.min(housing_prices)
print "Min housing prices: " + str(min_housing_prices)
# Maximum Value?
max_housing_prices = np.max(housing_prices)
print "Max housing prices: " + str(max_housing_prices)
# Calculate mean?
mean_housing_prices = np.mean(housing_prices)
print "Mean housing prices: " + format(mean_housing_prices, '.2f')
# Calculate median?
median_housing_prices = np.median(housing_prices)
print "Median housing prices: " + format(median_housing_prices, '.2f')
# Calculate standard deviation?
std_housing_prices = np.std(housing_prices)
print "Std housing prices: " + format(std_housing_prices, '.2f') + '\n'
def performance_metric(label, prediction):
'''Calculate and return the appropriate performance metric.'''
#1.10.7.2. Regression criteria
#If the target is a continuous value, then for node m, representing a region R_m with N_m observations, a common criterion to minimise is the Mean Squared Error
#source: http://scikit-learn.org/stable/modules/tree.html#regression-criteria
###################################
### Step 2. YOUR CODE GOES HERE ###
###################################
error = mean_squared_error(label, prediction)
#print mean_squared_error
#http://scikit-learn.org/stable/modules/model_evaluation.html#model-evaluation: 3.3.4.3. Mean squared error
#http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics
return error
def split_data(city_data):
'''Randomly shuffle the sample set. Divide it into training and testing set.'''
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
###################################
### Step 3. YOUR CODE GOES HERE ###
###################################
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return X_train, y_train, X_test, y_test
#http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html
def learning_curve(depth, X_train, y_train, X_test, y_test):
'''Calculate the performance of the model after a set of training data.'''
# We will vary the training set size so that we have 50 different sizes
sizes = np.linspace(1, len(X_train), 50)
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))
print "Decision Tree with Max Depth: "
print depth
for i, s in enumerate(sizes):
# Create and fit the decision tree regressor model
regressor = DecisionTreeRegressor(max_depth=depth)
regressor.fit(X_train[:s], y_train[:s])
# Find the performance on the training and testing set
train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot learning curve graph
learning_curve_graph(sizes, train_err, test_err)
def learning_curve_graph(sizes, train_err, test_err):
'''Plot training and test error as a function of the training size.'''
pl.figure()
pl.title('Decision Trees: Performance vs Training Size')
pl.plot(sizes, test_err, lw=2, label = 'test error')
pl.plot(sizes, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Training Size')
pl.ylabel('Error')
pl.show()
def model_complexity(X_train, y_train, X_test, y_test):
'''Calculate the performance of the model as model complexity increases.'''
print "Model Complexity: "
# We will vary the depth of decision trees from 2 to 25
max_depth = np.arange(1, 25)
train_err = np.zeros(len(max_depth))
test_err = np.zeros(len(max_depth))
for i, d in enumerate(max_depth):
# Setup a Decision Tree Regressor so that it learns a tree with depth d
regressor = DecisionTreeRegressor(max_depth=d)
# Fit the learner to the training data
regressor.fit(X_train, y_train)
# Find the performance on the training set
train_err[i] = performance_metric(y_train, regressor.predict(X_train))
# Find the performance on the testing set
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot the model complexity graph
model_complexity_graph(max_depth, train_err, test_err)
def model_complexity_graph(max_depth, train_err, test_err):
'''Plot training and test error as a function of the depth of the decision tree learn.'''
pl.figure()
pl.title('Decision Trees: Performance vs Max Depth')
pl.plot(max_depth, test_err, lw=2, label = 'test error')
pl.plot(max_depth, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Max Depth')
pl.ylabel('Error')
pl.show()
def fit_predict_model(city_data):
'''Find and tune the optimal model. Make a prediction on housing data.'''
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
# Setup a Decision Tree Regressor
regressor = DecisionTreeRegressor()
parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}
###################################
### Step 4. YOUR CODE GOES HERE ###
###################################
# 1. Find the best performance metric
# should be the same as your performance_metric procedure
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html
#sklearn.metrics.make_scorer(score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs)
scorer = make_scorer(mean_squared_error, greater_is_better=False)
# 2. Use gridearch to fine tune the Decision Tree Regressor and find the best model
# http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html
#sklearn.grid_search.GridSearchCV
#class sklearn.grid_search.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise')
reg = grid_search.GridSearchCV(regressor, parameters, scoring=scorer)
# Alternative implementation with Randomized search
#reg = grid_search.RandomizedSearchCV(regressor, parameters, n_iter=10, scoring=scorer)
# Fit the learner to the training data
print "Final Model: "
print reg.fit(X, y)
print '\n' "Best parameter from grid search: " + str(reg.best_params_) +'\n'
# Use the model to predict the output of a particular sample
x = [11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385, 24, 680.0, 20.20, 332.09, 12.13]
y = reg.predict(x)
# Alternative implementation with best_estimator
# Retrieve the best estimator found by GridSearchCV.
#est = reg.best_estimator_
# Use the object 'est' to make a prediction
#y = est.predict(x)
print "House: " + str(x)
print "Prediction: " + str(y)
# Implementation with nearest neighbor
#nbrs = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(X)
#dist, ind = nbrs.kneighbors(x)
#print "Nearest Neighbor: " +str(dist)
def main():
'''Analyze the Boston housing data. Evaluate and validate the
performanance of a Decision Tree regressor on the Boston data.
Fine tune the model to make prediction on unseen data.'''
# Load data
city_data = load_data()
# Explore the data
explore_city_data(city_data)
# Training/Test dataset split
X_train, y_train, X_test, y_test = split_data(city_data)
# Learning Curve Graphs
max_depths = [1,2,3,4,5,6,7,8,9,10]
for max_depth in max_depths:
learning_curve(max_depth, X_train, y_train, X_test, y_test)
# Model Complexity Graph
model_complexity(X_train, y_train, X_test, y_test)
# Tune and predict Model
fit_predict_model(city_data)
main()
|
import os
# open a file/create if exists.
# display all the dando #1-whatever.
# loop until quit.
file = open('dando.txt', 'a+')
x = True
while x == True:
os.system('clear')
command = input('DANDO | Go - > ')
if command[:1] == 'a':
print('a')
file.write(command[1:] + '/n')
elif command == 'd':
print('delete')
elif command == 'q':
print(exiting...)
x = False
else:
print('nothing..') |
#!/usr/bin/env python
# coding: utf-8
'''microondas2.py: demonstração de clousure (este exemplo não funciona)
Este exemplo mostra o problema: a variável `tempo` definida no corpo de
`montar_painel` não pode ser alterada dentro de `ajustar`. O erro é:
UnboundLocalError: local variable 'tempo' referenced before assignment
As variações deste arquivo demonstram formas diferentes de resolver o
problema.
Os exemplos também mostram formas diferentes de passagem do valor do
incremento `incr` para função `ajustar`.
'''
from Tkinter import *
def montar_painel(janela):
tempo = 0
visor = Label(janela)
visor['text'] = tempo
visor.pack()
for segundos in [60, 30, 10]:
def ajustar(incr=segundos):
print incr
tempo = tempo + incr # UnboundLocalError!!!
visor['text'] = tempo
botao = Button(janela, text=segundos, command=ajustar)
botao.pack()
janela = Tk()
montar_painel(janela)
sair = Button(janela, text="Sair", fg="red", command=janela.quit)
sair.pack()
janela.mainloop()
|
# Installing Word2 number library
!pip install word2number
from word2number import w2n
import re
#Converts words to numbers
def word_to_num(string):
''' Converts english words to numbers such as hundred to 100 '''
words = string.split()
numbers=[]
for word in words:
try:
numbers.append( (word,w2n.word_to_num(word) ))
except:
numbers.append((word,'none'))
temp = 0
new_numbers=[]
old_num_index = []
for i in range(len(numbers)):
if type(numbers[i][1])==int:
temp=temp+1
else:
if temp >=2:
new_number_string = ''
for j in range(temp,0,-1):
new_number_string = new_number_string+" " + numbers[i-j][0]
old_num_index.append(i-j)
new_numbers.append((new_number_string.strip(),w2n.word_to_num(new_number_string)))
temp = 0
temp = 0
for i in old_num_index:
del numbers[i-temp]
temp+=1
numbers.extend(new_numbers)
for i in range(len(numbers)-1,-1,-1):
if type(numbers[i][1])==int:
string = string.replace(numbers[i][0],str(numbers[i][1]))
return string
#Dollar Rule
def dollar_rule(string):
''' Converts dollar or dollars to dollar sign i.e $ '''
regx_dollar = r'\d+\s+dollars|\d+\s+dollar'
list_of_matches = re.findall(regx_dollar,string)
for match in list_of_matches:
converted_string = '$'+str(match.split()[0])
string = string.replace(match,converted_string)
return string
#abbreviations rule
def abbreviations_rule(string):
''' Converts some abbreviations to their original form such as: double a to aa'''
custom_w2n = {"single":1,
"double":2,
"triple":3,
"quadruple":4,
"quintuple":5,
"sextuple":6,
"septuple":7,
"octuple":8,
"nonuple":9,
"decuple":10
}
for word in custom_w2n:
list_of_matches = re.findall(word + '\s+\w',string)
for match in list_of_matches:
n_times = custom_w2n[word]
converted_string = n_times*str(match.split()[1])
string = string.replace(match,converted_string)
list_of_matches = re.findall(r'\s[a-zA-Z]\s[a-zA-Z]\s',string)
for match in list_of_matches:
converted_string = ' '+match.split()[0]+match.split()[1]+' '
string = string.replace(match,converted_string)
return string
#Spoken English To Written English Conversion class.
class SpokenToWritten:
def __init__(self):
self.dollar_rule=dollar_rule
self.word_to_num = word_to_num
self.abbreviations_rule = abbreviations_rule
def Convert(self,input_string):
temp_string = self.word_to_num(input_string)
temp_string = self.dollar_rule(temp_string)
output_string = self.abbreviations_rule(temp_string)
return output_string
input_string = input("Enter Spoken English Text: ")
output_string = SpokenToWritten().Convert(input_string)
print("Written English Text Output : ",output_string)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.