text
stringlengths 37
1.41M
|
---|
# ************************************************************
# Bike assinment is in this file
# # class User:
# # pass
# # michael = User()
# # anna = User()
# # print(michael,anna)
# class User:
# def __init__(self,name,email,num):
# self.name = name
# self.email = email
# self.logged = False
# self.level = num
# def login(self):
# if self.logged == True:
# print(self.name + "has just logged in." + "Welcome " + self.name + "!!!")
# return self
# def leveled(self):
# if self.level > "3":
# print(self.name + " your level is " + self.level)
# return self
# new_user1 = User("Ash", "[email protected]", "5")
# new_user2 = User("Folami", "[email protected]", "9")
# # print(new_user.name, new_user.email, new_user.level)
# new_user1.login().leveled()
# new_user2.login().leveled()
# # class User:
# # name="Anna"
# # anna = User()
# # print("anna's name:", anna.name)
# # User.name = "Bob"
# # print("anna's name after change:", anna.name)
# # bob = User()
# # print("bob's name:", bob.name)
# ********************************************************************
# ********************************************************************
# ********************************************************************
# ********************************************************************
# ********************************************************************
# bike assignment below
# ********************************************************************
# ********************************************************************
# ********************************************************************
# ********************************************************************
# ********************************************************************
# ********************************************************************
class Bike:
def __init__(self, name, price, speed, miles):
self.name = name
self.price = price
self.speed = speed
self.miles = miles
def displayinfo(self):
print(f"My Bike is {self.name} price tag of {self.price} has speed {self.speed} and it's mileage is {self.miles} ")
return self
def riding(self):
self.miles = self.miles + 100
print(f"riding and my new mileage is {self.miles}")
return self
def reversing(self):
self.miles = self.miles - 200
if self.miles < 0:
self.miles = 0
print(f"reversing and my new mileage is {self.miles}")
return self
bike1 = Bike("Raptor", "$6500", "220mph", 300)
bike2 = Bike("Night-Hawk", "$7500", "230mph", 780)
bike3 = Bike("Ninja", "$5500", "180mph", 220)
bike1.riding().riding().riding().reversing().displayinfo()
bike2.riding().riding().reversing().reversing().displayinfo()
bike3.reversing().reversing().reversing().displayinfo()
bike3.reversing().reversing()
|
__author__ = 'student'
import turtle
def draw(l,n):
if n == 0:
turtle.forward(l)
return
draw(l/4,n-1)
turtle.left(90)
draw(l/4,n-1)
turtle.right(90)
draw(l/4,n-1)
turtle.right(90)
draw(l/4,n-1)
draw(l/4,n-1)
turtle.left(90)
draw(l/4,n-1)
turtle.left(90)
draw(l/4,n-1)
turtle.right(90)
draw(l/4,n-1)
turtle.speed(10)
draw(100,2) |
import time
respuesta = 0
sino = "si"
lista =[]
while sino == "si":
print("Dime una palabra")
respuesta = input()
lista.append(respuesta)
sino = input("Quieres añadir otra palabra mas? si/no\n")
for i in lista:
print(i)
time.sleep (0.65) |
"""
- Create a script called `[seed.py](http://seed.py)` that populates a SQLite database. By default it should search for the first 150 users from GitHub but the script should accept a param called `total` to customize the number of users.
- The fields required for this users are:
- username
- id
- image url
- type
- link to his GitHub profile
"""
import requests
import sqlite3
def insert_database_row(username, id, image, type, link):
database_connection = ''
try:
database_connection = sqlite3.connect('./database/git_users.db')
cursor = database_connection.cursor()
print("Connected to SQLite")
sqlite_insert_with_param = """INSERT INTO github_users
(username, id, image, type, link)
VALUES (?, ?, ?, ?, ?);"""
fields = (username, id, image, type, link)
cursor.execute(sqlite_insert_with_param, fields)
database_connection.commit()
print("Python Variables inserted successfully into github_users table")
cursor.close()
except sqlite3.Error as error:
print("Failed to insert Python variable into sqlite table", error)
finally:
if database_connection:
database_connection.close()
print("The SQLite connection is closed")
def get_git_users(pagination,last_user_id = 0):
if last_user_id == 0:
URL = f"https://api.github.com/users?per_page={pagination}"
else:
URL = f"https://api.github.com/users?per_page={pagination}&since={last_user_id}"
USER = "EmmanuelLinares1974"
TOKEN = "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"
HEADERS = {'Authorization':'token %s' % TOKEN, 'Accept': 'application/vnd.github.v3+json'}
return requests.get(URL, HEADERS)
def get_git_data(total):
tup = tuple(get_iterations(total))
print(tup)
if tup[0] != 0:
counter = 0
last_id = 0
tot_aux = total
while counter < tup[0]:
response = get_git_users(100,last_id)
users_aux_page = response.json()
if counter == 0:
users_first_page = users_aux_page
else:
users_first_page = users_first_page + users_aux_page
for user in users_first_page:
last_id = user['id']
counter += 1
tot_aux -= 100
if tot_aux != 0:
response = get_git_users(tot_aux, last_id)
users_aux_page = response.json()
return users_first_page + users_aux_page
else:
#Given number is lower than 100
response = get_git_users(total)
users_first_page = response.json()
return users_first_page
def get_iterations(total):
return divmod(total,100)
def get_git_users_data(total):
clean_users = []
del_tab()
for user in get_git_data(total):
clean_user = {}
clean_user["id"]= user["id"]
clean_user["username"]= user["login"]
clean_user["image"]= user["avatar_url"]
clean_user["type"]= user["type"]
clean_user["link"]= user["url"]
clean_users.append(clean_user)
insert_database_row(clean_user["username"], clean_user["id"], clean_user["image"], clean_user["type"], clean_user["link"])
def get_users(total):
get_git_users_data(total)
database_connection = sqlite3.connect('./database/git_users.db')
cursor = database_connection.cursor()
cursor.execute("SELECT * FROM github_users")
usuarios = cursor.fetchall()
database_connection.commit()
database_connection.close()
return usuarios
def del_tab():
database_connection = sqlite3.connect('./database/git_users.db')
cursor = database_connection.cursor()
cursor.execute("DELETE FROM github_users")
database_connection.commit()
database_connection.close() |
import unittest
import game, player, board
class TestGameCheckMove(unittest.TestCase):
def test_check_move_valid(self):
test_game = game.Game("Player1", "Player2")
valid = test_game.check_move((0, 0), test_game.players[0])
self.assertTrue(valid)
def test_check_move_invalid(self):
test_game = game.Game("Player1", "Player2")
valid = test_game.check_move((0, 5), test_game.players[0])
self.assertFalse(valid)
class TestGameEndGame(unittest.TestCase):
def test_end_game_no_winner(self):
test_game = game.Game("Player1", "Player2")
winner = 'boardfull'
win = test_game.end_game(winner)
self.assertFalse(win)
def test_end_game_winner(self):
test_game = game.Game("Player1", "Player2")
winner = test_game.players[0]
win = test_game.end_game(winner)
print(win)
self.assertTrue(win)
class TestGameIsValidPlayer(unittest.TestCase):
def test_player_is_valid(self):
test_game = game.Game("Player1", "Player2")
test_player = test_game.players[0]
valid = test_game.is_valid_player(test_player)
self.assertTrue(valid)
def test_player_not_valid(self):
test_game = game.Game("Player1", "Player2")
test_player = player.Player("Player3", "Y")
valid = test_game.is_valid_player(test_player)
self.assertFalse(valid)
if __name__ == "__main__":
unittest.main() |
var1 = 'hello'
var2 = 32
var3 = 36.7
print(type(var1))
print(type(var2))
print(type(var3))
#typecasting
var1 = "52"
var2 = "34"
print((var1)+var2)
#typecasting
print(int(var1)+int(var2))
var1 = "54"
var2 = "32"
print(10*int(var1) + int(var2))
#wanna print any thing multiple tyms then we do
print(10 * "hello\n")
#now we wanna add strings and print it 10 times
var1 = '54'
var2 = '32'
print(10 * str (int(var1) + int(var2))) |
# Python Basic
print("enter no a")
a= int(input())
print("enter no b")
b= int(input())
addition = a + b
print("addition is:", addition)
print("type",type(addition)) |
# Python program for Addition of two integers
print("Enter first number ")
a= input()
print("Enter second number")
b= input()
addition = a+b
print("Addition is:", addition) |
# open the text of much ado about nothing and read it in line by line
# count the number of lines by Beatrice
# for this one, let's just annotate the lines with what is happening
file_path = "ado.txt
with open (file_path, 'w') as file_input:
text = file_input.readline()
benedickt_lines = {}
counters = 0
for line in texts:
if line.startswith('BENEDICK'):
line_counter = 1
while text[counter + line_counter] != '\n':
benedick_lines.append(text[counter + line_counter])
line_counter = line_counter + 1
counter = counter + 1
print(benedick_lines) |
import nltk
# given a text file, print the first 100 text characters of it
def read_file(path_to_text):
# take a file path and return the raw text from it
with open(path_to_text, 'r') as fin:
raw_text = fin.read()
return raw_text
def split_text(raw_text):
# takes a text and splits it into a series of tokens (words in text
# analysis lingo)
tokens = raw_text.split(' ')
return tokens
def does_something_interesting(tokens):
# takes a list of tokens and creates a frequency dispersion plot
words_to_chart = ['he', 'she', 'the', 'said', 'boat']
nltk.Text(tokens).dispersion_plot(words_to_chart)
text_path = 'woolf.txt'
print(text_path)
raw_text = read_file(text_path)
print(raw_text[0:15])
tokens = split_text(raw_text)
print(tokens[0:15])
does_something_interesting(tokens) |
# given a file path, store and print it
text_path = 'woolf.txte'
# hint - it might have worked, but is the output correct? Not all errors are errors Python can detect!
print(text_pathed)
|
# Module dedicated to data wrangling functions
import pandas as pd
# Función hacer_df() de mining_tb que recibe como parámetro un archivo de excel, hace un dataframe con sólo la primera hoja y sólo las 2 primeras columnas poniendo como índice la primera y, luego, mediante un for va recorriendo el resto de las hojas concatenando la segunda columna de cada una al primer dataframe. La función devuelve un dataframe con las fechas como índice y los precios de cada ámbito geográfico como columnas.
def hacer_df(archivo):
nombre_df=pd.read_excel(archivo,sheet_name=0,index_col=0,usecols=[0,1])
for sheet in range(1,26):
nombre_df=pd.concat((nombre_df,pd.read_excel(archivo,sheet_name=sheet,index_col=0,usecols=[0,1])),axis=1)
return nombre_df
# Función hacer_float() de mining_tb que toma como parámetro un dataframe, hace una copia, elimina los caracteres no numéricos, el 2 de m² y si hay alguna coma (para decimales) la cambia por un punto. para después convertir las cadenas numéricas a float. La función devuelve un dataframe con valores tipo float.
def hacer_float(dataframe):
nombre=dataframe.copy()
nombre.replace(regex=True, inplace=True, to_replace=r"\.|\D{2}|2$", value=r"")
nombre.replace(regex=True, inplace=True, to_replace=r"\,", value=r".")
for c in nombre.columns:
nombre[c]=pd.to_numeric(nombre[c],downcast="float")
return nombre
# Función seleccion_columnas() de mining_tb para seleccionar el ámbito (columnas) a analizar. La función toma como parámetros un dataframe y la posicion de dos columnas para seleccionar un rango. La función devuelve la lista de esas columnas selecionadas.
def seleccion_columnas(dataframe,col1,col2):
columnas=dataframe.columns[col1:col2]
return columnas
|
###########################################################################################################
# What this is: Webpage scraper for the Forbes 2000 List
# Purpose: Take a list of URLs from CSV, scrape the associated webpages for
# the company details, and save as CSV. Sales Operations will upload
# to Salesforce.
# How to use this: 1 - Create a CSV of Forbes 2000 URLs (example below)
# 2 - In "ProcessURLs" the constructor __init__(self, TEST_ON) enter the path of
# CSV files for input and output
# 3 - Pass 0 or 1 to the constructor to turn test on or off
# 4 - Run this script
# Example URL: http://www.forbes.com/companies/actavis
###########################################################################################################
########## Some Text Functions ##########
import re #for regex on URL
import time # check run time
import math
# Return proper case string
def properCase(inStr):
return ( inStr[0].upper() + inStr[1:])
# Return the company name in upper case
def getForbesCompany(inStr):
return [i for i in re.split(r'(\W+)',inStr)][10]
###########################################################################################################
# CLASS
# Name: forbes_killer
# Purpose: Take a URL to the Forbes website and strip the info
# Example URL: http://www.forbes.com/companies/actavis
###########################################################################################################
import urllib.request as urlr # For URLOpen
import urllib.error
class forbes_killer:
# Values hold everything scraped that we want
values = {'ForebsURL':'',
'MarketCap': 0,
'Industry': '',
'Founded': 0,
'Country': '',
'CEO': '',
'Employees': 0,
'Sales': '',
'Headquarters': '',
'Website': '',
'EmailDomain': ''
}
start = 0
ourStuff = ''
companyName = ''
lastEnd = 0 # lastEnd from the last DT tag
VALID_WEBSITE = 1 # If invalid website set to 0, set in getStringFromURL
# Default constructor
def __init__(self):
# Base Forbes URL
self.values['Website'] = 'http://www.forbes.com/companies/'
# Constructor taking a URL
def __init__(self,url):
self.values['Website'] = url.replace(",","")
self.getStringFromURL()
if( self.VALID_WEBSITE != 0):
self.values['ForebsURL'] = self.values['Website']
self.run()
else:
print("Error with website '" + self.values['Website'] + "'----------- Moving on.")
# Open URL and save it for later
def getStringFromURL(self):
try:
with urlr.urlopen( self.values['Website'] ) as f:
self.ourStuff = str( f.read(1000000).decode('utf-8') )
f.close()
except ValueError:
print("ValueError: Couldn't open '" + self.values['Website'] + "'\nYou should delete this row from the file.")
self.VALID_WEBSITE = 0
except urllib.error.URLError:
print("urllib.error.URLError: Couldn't open '" + self.values['Website'] + "'\nYou should delete this row from the file.")
self.VALID_WEBSITE = 0
except socket.gaierror:
print("socket.gaierror: Couldn't open '" + self.values['Website'] + "'\nYou should delete this row from the file.")
self.VALID_WEBSITE = 0
# Shrinks the String in mem
def shrinkOurStuff(self):
start = self.ourStuff.find( "<h1 class=\"large\">")
end = self.ourStuff.find( "<!-- End Data -->" )
self.ourStuff = self.ourStuff[start:end]
# Test String method
def printSome(self):
for k,v in self.values.items():
print(k, v)
# Add tag to self
def addToValues(self, tagName, tagValue):
self.values[ tagName ] = tagValue
# Get Market Cap
def getMarketCap(self):
start = self.ourStuff.find( "<li class=\"amount\">" ) + len ("<li class=\"amount\">")
end = self.ourStuff.find( "</li>", start)
ret = self.ourStuff[start:end].replace("<span>","")
ret = ret.replace("</span>","")
return ret
def getEmailDomain( self):
start = self.values['Website'].find("www.") + len("www.")
return self.values['Website'][start:]
# get website from DD tag
# Ex: <a href="http://www.actavis.com" target="_blank">http://www.actavis.com</a>
def getWebsite(self, instr):
start = instr.find("http")
end = instr.find("\" target=")
return instr[start:end]
def formatStringCurr(self, instr):
multiplier = 1
instr = instr.replace("$","")
instr = instr.replace(" ","")
if( instr.find("Billion")):
multiplier = 1000000000
instr = instr.replace("Billion","")
if ( instr.find("B" ) ):
multiplier = 1000000000
instr = instr.replace('B',"")
if( instr.find("Million")):
multiplier = 1000000
instr = instr.replace("Million","")
if ( instr.find("M" ) ):
multiplier = 1000000
instr = instr.replace("M","")
try:
retVal = float(instr)*multiplier
except ValueError:
print("Failed on " + instr)
instr = 0
return float(instr)*multiplier
# Checks if the DT tag is a valid key
def validDT(self, dt):
if( dt in self.values):
return 1
else:
return 0
# Finds the next DT tag
def getDtTag(self, instr, start):
start = instr.find("<dt>", start) + len("<dt>")
end = instr.find("</dt>", start)
tag = instr[start:end]
self.ourStuff = self.ourStuff[end:]
self.lastEnd = end + 1
return tag
# Finds the next DD tag
# called after getDtTag
def getDdTag(self, instr, start):
start = instr.find("<dd>", start) + len("<dd>")
end = instr.find("</dd>", start)
tag = instr[start:end]
self.ourStuff = self.ourStuff[end:]
self.lastEnd = end + 1
return tag
# Run the program
# Method
# 1 - Get the company name for fun
# 2 - Reduce the size of the string in memory
# 3 - Get the market cap
# 4 - Add the other tags to this class
# 5 - Print the dict as text
def run(self):
self.companyName = properCase( getForbesCompany( self.values['Website'] ) )
self.shrinkOurStuff()
# print("MarketCap: " + self.getMarketCap() )
self.addToValues('MarketCap', self.formatStringCurr( self.getMarketCap() ) )
instr = self.ourStuff
count = instr.count("<dt>")
while count != 0:
dt = self.getDtTag( instr, self.lastEnd )
if( dt == 'Chief Executive Officer'):
dt = 'CEO'
# end
if( self.validDT(dt) == 1 ):
if( dt == 'Website'):
dd = self.getWebsite( self.getDdTag( instr, self.lastEnd) )
else:
dd = self.getDdTag( instr, self.lastEnd )
# end if( dt == 'Website')
if( dt == 'Sales'):
dd = self.formatStringCurr ( dd )
# end if( dt == 'Sales')
self.addToValues(dt,dd)
count = count - 1
self.addToValues('EmailDomain',self.getEmailDomain())
# end if( validDT == 1 )
self.printSome()
# end while count != 0
# end def run(self)
###########################################################################################################
# CLASS
# Name: ProcessURLs
# Purpose: read a CSV in and get the associated URL. Close it. Write each URL and associated
# fields to a file.
# Example URL: http://www.forbes.com/companies/actavis
###########################################################################################################
import csv
class ProcessURLs:
inFileName = '__'
outFileName = '__'
URLs = []
killers = [] # Dictionaries
keys = [] # Dictionary key values
# default constructor looks at the CSV in the directory
def __init__(self):
print("In default constructor")
self.run()
# Constructor takes filename
def __init__(self, TEST_ON):
if ( TEST_ON == 0):
self.inFileName = 'C:/Users/andreas.slovacek.MS/AppData/Local/Programs/Python/Python35/Scripts/Test_URLs.csv'
self.outFileName = 'test_output.csv'
else:
self.inFileName = 'C:/Users/andreas.slovacek.MS/AppData/Local/Programs/Python/Python35/Scripts/full_list_urls.csv'
self.outFileName = 'full_output.csv'
self.run()
# Runs the program
# 1 - Open the file
# 2 - Read the lines into a list
# 3 - Create a list of the keys
# 4 - open CSV writer
# 5 - write keys to header
# 6 - create the processed object
# 7 - print the object to the screen
# 8 - create the string to write
def run(self):
# 1
with open( self.inFileName, newline='') as csvfile:
csvReader = csv.reader(csvfile, delimiter=' ', quotechar='|')
count = 0
# 2
for row in csvReader:
if( count != 0):
row = str(row).replace("['","")
row = row.replace("']","")
self.URLs.append( row )
count = count + 1
# 3
print("\n\n\n" + "-"*40)
self.keys = forbes_killer("www").values.keys()
# 4
with open(self.outFileName, 'w', newline='') as csvfile:
#with open('full.csv', 'w', newline='') as csvfile:
# 5
writer = csv.DictWriter(csvfile, fieldnames=self.keys)
writer.writeheader()
for u in self.URLs:
# 6
x = forbes_killer(u)
writer.writerow( x.values )
self.killers.append( x )
# 7
# x.printSome()
# 8
#writer.writerow( x.values )
#print( self.returnValueString( x.values ) )
def returnValueString(self, inDict):
outStr = ''
for k in self.keys:
outStr = str(inDict[k]) + ";"
return outStr
#x = forbes_killer('http://www.forbes.com/companies/actavis')
# y = ProcessURLs(1) # Test run
z = ProcessURLs(0) # live run
|
score = 0
First_name = input("What is your First name?")
Last_name = input("What is your Last name?")
age = input("What is your age?")
print("Hello " + First_name + " " + Last_name)
print("Welcome to a Nation Wide PANDEMIC")
print("Let's see how much you know about Covid-19")
# Question 1
answer1 = input("How many confirmed Covid-19 cases are there in Massachusetts? \na.10,000 \nb.30,000 \nc.over 60,000 \nEnter answer:")
if answer1 == "c" or answer1 == "over 60,000":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Wrong answer! The correct answer is c.over 60,000")
print("score: ", score)
# Question 2
answer2 = input("Since the Pandemic how many related deaths have been reported in Massachusetts? \na.Less than 500 \nb.1,000 \nc.over 4,000 \nEnter answer:")
if answer2 == "c" or answer2 == "over 4,000":
score += 1
print("Hooray that is correct")
print("score: ", score)
else:
print("That is not correct the answer. The correct answer is c.over 4,000")
print("score: ", score)
# Question 3
answer3 = input("What county has the most reported Covid-19 cases? \na.Middlesex County \nb.Essex County \nc.Suffolk County \nd.Norfolk County \nEnter answer:")
if answer3 == "a" or answer3 == "Middlesex County":
score += 1
print("Way to go that is correct")
print("score: ", score)
else:
print("Incorrect! The correct answer is a.Middlesex County")
print("score: ", score)
# Question 4
answer4 = input("What are some ways to protect yourself during this Pandemic? \na.Wear a mask \nb.Social distance \nc.Wash your hands for at least 20 seconds with soap \nd.All of the above \nEnter answer:")
if answer4 == "d" or answer4 == "All the Above":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Sorry wrong answer. The correct answer is d.All of the above")
print("score: ", score)
# Question 5
answer5 = input("How much is the fine in Lawrence,MA if you don't wear a mask? \na.$50 \nb.$150 \nc.$300 \nd.$500 \nEnter answer:")
if answer5 == "c" or answer5 == "$300":
score += 1
print("That is correct!")
print("score: ", score)
else:
print("Wrong answer! The correct answer is c.$300")
print("score: ", score)
# Question 6
answer6 = input("The city of Lawrence will fine anyone ages ___ and up for not wearing a mask in Lawrence,MA \na.6 \nb.5 \nc.2 \nd.4 \nEnter answer:")
if answer6 == "a" or answer6 == "6":
score += 1
print("Correct answer")
print("score: ", score)
else:
print("That is not right! The correct answer is a.6")
print("score: ", score)
# Question 7
answer7 = input("What are the symptoms for Covid-19 \na.Cough \nb.Muscle pain \nc.Shortness of breathe \nd.All of the above \nEnter answer:")
if answer7 == "d" or answer7 == "All of the above":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Wrong answer! The correct answer is d.All of the above")
print("score: ", score)
# Question 8
answer8 = input("Who does Covid-19 impact the most? \na.People over the age of 65 \nb.People of all ages \nc.People with underlining conditions \nd.People under 50 \nEnter answer:")
if answer8 == "b" or answer8 == "People of all ages":
score += 1
print("That is correct")
print("You are on a roll")
print("score: ", score)
else:
print("That is not correct! The correct answer is b.People of all ages")
print("score: ", score)
# Question 9
answer9 = input("Is sex recommended during Covid-19? \na.Yes it is ok as long as your wearing a mask. \nb.No sex isn't recommended and you should keep your social distance \nEnter answer:")
if answer9 == "b" or answer9 == "Sex isn't recommended and you should keep your social distance":
score += 1
print("That is correct")
print("score: ", score)
else:
print("That isn't correct! The correct answer is b.Sex isn't recommend and you should keep your social distance")
print("score: ", score)
# Question 10
answer10 = input("What businesses are considered essential during this Pandemic? \na.Grocery Stores \nb.Pharmacies \nc.Hospitals \nd.All of the above \nEnter answer:")
if answer10 == "d" or answer10 == "All of the above":
score += 1
print("That is the correct answer")
print("score: ", score)
else:
print("Wrong answer! The correct answer is d.All of the above")
print("score: ", score)
if score <=4:
print("Your total score is:", score, "-Better luck Next Time-")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy")
elif score == 5:
print("Your total score is:", score, "-Not bad-")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy")
else:
print("Your total score is:", score, "-Great Job! I see you know a lot about the Covid-19 Pandemic")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy") |
'''
@file: Question5-lab1.py
@author: James Rolfe
@updated: 20170130
'''
import random
import numpy as np
import matplotlib.pyplot as plt
# constant declaration
LOW_BOUND = 0
HIGH_BOUND = 1
# number of samples taken
NUM_OF_SAMPLES = [25, 10, 50, 100, 500, 1000]
# number of data points per sample
NUM_OF_DATA = [25, 10, 50, 100, 500, 1000]
# scale for exponential
EXP_SCALE = 1
np.random.seed(124) # set the seed
#use the following function to test CLT.
#The following code generates samples using 'uniform',
#or samples from a uniform distribution.
'''
@args: a: int, b: int, num_of_data: int, num_of_samples: int
@post: prints to stdout and displays graph using matplotlib.pyplot
@returns: null
'''
def clt_uniform(a, b, num_of_data, num_of_samples):
means = []
#Here is a for loop to generate samples with low=a, high=b based on the given
#numberOfSample and numberOfData, e.g. sample = numpy.random.uniform(...)
for i in range(num_of_samples):
sample = np.random.uniform(a, b, num_of_data)
sample_mean = np.mean(sample)
# append mean of sample
means.append(sample_mean)
# mean of samples' means is stored in the following line
ans = np.mean(means)
print('population mean for ' + str(num_of_data) + ' data points and '
+ str(num_of_samples) + ' samples is: ' + str(ans))
plt.hist(means)
plt.title('Hist given '+ str(num_of_data)+ ' data points and '
+ str(num_of_samples) + ' samples (UNIFORM)')
plt.show()
'''
@args: a: int, num_of_data: int, num_of_samples: int
@post: prints to stdout and displays graph using matplotlib.pyplot
@returns: null
'''
def clt_exponential(a, num_of_data, num_of_samples):
means = []
for i in range(num_of_samples):
sample = np.random.exponential(a, num_of_data)
sample_mean = np.mean(sample)
# append mean of sample
means.append(sample_mean)
# mean of samples' means is stored in the following line
ans = np.mean(means)
print('population mean for ' + str(num_of_data) + ' data points and '
+ str(num_of_samples) + ' samples is: ' + str(ans))
plt.hist(means)
plt.title('Hist given '+ str(num_of_data)+ ' data points and '
+ str(num_of_samples) + ' samples (EXPONENTIAL)')
plt.show()
print('========== UNIFORM RESULTS ==========')
for x in NUM_OF_DATA:
clt_uniform(LOW_BOUND, HIGH_BOUND, x, NUM_OF_SAMPLES[0])
for x in NUM_OF_SAMPLES:
clt_uniform(LOW_BOUND, HIGH_BOUND, NUM_OF_DATA[0], x)
print('=== Test how many data points required for accurate'
+ ' mean estimate ===')
for i in range(4):
clt_uniform(LOW_BOUND, HIGH_BOUND, i+1, 1000)
print('\n========== EXPONENTIAL RESULTS ==========')
for x in NUM_OF_DATA:
clt_exponential(EXP_SCALE, x, NUM_OF_SAMPLES[1])
for x in NUM_OF_SAMPLES:
clt_exponential(EXP_SCALE, NUM_OF_DATA[1], x)
|
"""
@filename: lms.py
@author: James Rolfe
@date: 20170327
@reqs: LMSalgtrain.csv, LMSalgtest.csv
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
TRAIN_CSV = 'LMSalgtrain.csv'
TEST_CSV = 'LMSalgtest.csv'
def read_data(filename):
# use pandas dataframe to read values from csv
df = pd.read_csv(filename)
# separate inputs and outputs
X = df.drop(['z', 'estimate'], axis=1)
# add bias term to inputs
X.insert(len(X.columns), 'bias', np.ones((X.shape[0], 1)),
allow_duplicates=True)
Y = df['estimate']
Z = df['z']
return X, Y, Z
'''
@params: z: np.matrix(int|float)
@post: call to np.exp()
@returns: np.matrix(int|float)
'''
def sigmoid(z):
# use the definition of the sigmoid function
return 1.0 / (1.0 + np.exp(-1.0 * z))
def ols(X_train, Y_train, X_test):
# create linear regression object
regr = linear_model.LinearRegression()
# train the model without the index column
regr.fit(X_train, Y_train)
# get predictions from trained model
predictions = regr.predict(X_test)
return predictions, regr.coef_
def mse(Y_test, preds):
mse = mean_squared_error(Y_test, preds)
return mse
def update_weights(X, ts, W, eta):
for idx in range(X.shape[0]):
y = W.transpose().dot(X[idx][:].transpose())
err = ts[idx] - y
delta_W = np.matrix(eta * err * X[idx][:]).transpose()
W += delta_W
return W
def delta(X, ts, eta, iters):
W = np.zeros((X.shape[1], 1))
while(True):
W = update_weights(X, ts, W, eta)
ys = W.transpose().dot(X.transpose())
MSE = mse(list(ts), ys.tolist()[0])
iters -= 1
if iters < 1:
return MSE, W
'''
This function takes a prediction array full of class values and a ground truth
data frame full of class values and returns a confusion matrix data frame.
@params: prediction:array, ground_truth:pandas.DataFrame
@post: prints the conf matrix to stdout
@returns: confMatrix:pandas.DataFrame
'''
def confusionMatrix(df_Y, prediction, ground_truth):
# get the column names for the conf matrix
names = list(df_Y['z'].unique())
# names.reverse() # make the list so the conf matrix comes out as requested
# initialize the data that will make up the conf matrix data frame
conf_data = [[0 for i in range(len(names))] for j in range(len(names))]
confMatrix = pd.DataFrame(conf_data, index=names, columns=names)
# names the columns and indices of the conf matrix
confMatrix.index.names = ['actual']
confMatrix.columns.names = ['predicted']
# load the data
for i in range(len(prediction)):
confMatrix.loc[ground_truth[i], prediction[i]] += 1
print('\nconfusion matrix')
print(confMatrix)
return confMatrix
'''
This function calculates the trace of a pandas data frame. The dataframe is
assumed to be square.
@params: df:pandas.DataFrame
@post: none
@returns: float
'''
def df_trace(df):
# sum the left-to-right diagnal of the data frame
return sum(df.loc[i,i] for i in range(len(df)))
'''
conf = confusionMatrix(prediction, groundtruth)
# calculate the accuracy as the number of true positives plus true negatives
# over the total classifications. multiplied by 100 for percentage
accuracy = (float(df_trace(conf))/conf.sum().sum())*100
print('\naccuracy = ' + str(accuracy) + '%')
'''
# get data frames of data from csvs
X_train, Y_train, Z_train = read_data(TRAIN_CSV)
X_test, Y_test, Z_test = read_data(TEST_CSV)
# get the OLS solution
ols_preds, ols_coefs = ols(X_train, Y_train, X_test)
# get lms solution
lms_train_mse, lms_coefs = delta(X_train.values, Y_train.values, 0.0001, 1000)
print('weights for LMS:')
print(lms_coefs)
print('training mse for LMS (full batch)[eta=0.0001; iters=1000]: %.3f'% lms_train_mse)
lms_preds = X_test.values.dot(lms_coefs)
print('testing mse for LMS (full batch)[eta=0.0001; iters=1000]: %.3f'% mse(Y_test, lms_preds))
print('weights for OLS:')
print(ols_coefs)
print('training mse for OLS: %.3f'% mse(Y_train, ols(X_train, Y_train, X_train)[0]))
print('testing mse for OLS: %.3f'% mse(Y_test, ols_preds))
|
import sys
import collections
RetVal = collections.namedtuple('RetVal', ['count', 'array'])
def merge_and_count(left_arr, right_arr):
arr = []
count = 0
j = 0
k = 0
for i in range(len(left_arr) + len(right_arr)):
if j == len(left_arr):
arr.append(right_arr[k])
k = k+1
elif k == len(right_arr) or left_arr[j] < right_arr[k]:
arr.append(left_arr[j])
j = j+1
else :
arr.append(right_arr[k])
k = k+1
count = count + len(left_arr) - j
return RetVal(count, arr)
def sort_and_count(arr):
if int(len(arr)) < 2:
return RetVal(0, arr)
elif int(len(arr)) == 2:
if arr[0] > arr[1]:
return RetVal(1, [arr[1], arr[0]])
return RetVal(0, arr)
else:
left = sort_and_count(arr[0:int(len(arr)/2)])
right = sort_and_count(arr[int(len(arr)/2):])
split = merge_and_count(left.array, right.array)
return RetVal(left.count + right.count + split.count, split.array)
a = []
for line in sys.stdin:
a.append(int(line))
ret = sort_and_count(a)
print(ret.count)
|
#1
name = str("Angelina")
print(name)
#2
age = int(24)
print(age)
#3
a = float(4.5)
print(a)
#4
n = bytes(8)
print(n)
#5
new_list = list()
name_1 = "Angelina"
name_2 = "Vadim"
name_3 = "Vladislaw"
new_list =[name_1, name_2, name_3]
for i in new_list:
print('name =' , i)
#6
k = tuple('hello, world!')
print(k)
#7
s = set('Partly',)
print(s)
#8
box = frozenset('red',)
print(box)
#9
d = dict(short='dict', long='dictionary')
print(d)
#10.1
print('name=', name, type(name))
#10.2
print('age =', age, type(age))
#10.3
print('a = ', a, type(a))
#10.4
print('n=', n, type(n))
#10.5
print(new_list, type(new_list))
#10.6
print(k,type(k))
#10.7
print(s, type(s))
#10.8
print(box, type(box))
#10.9
print(d, type(d))
#11
names=str('Angelina')
lastname = str('Oksak')
summa = (names + lastname)
print(summa)
#12
a1 = int(7)
b2 = int(2)
summa_1= (a1 + b2)
print(summa_1)
#13
division = (a1 / b2)
print(division)
#14
multiplication = (a1 * b2)
print(multiplication)
#15
at = (a1 // b2)
print(at)
#16
at1 =(a1 % b2)
print(at1)
|
# Given a non-empty array of decimal digits representing a non-negative integer,
# increment one to the integer.The digits are stored such that
# the most significant digit is at the head of the list, and each element
# in the array contains a single digit.
# You may assume the integer does not contain any leading zero,
# except the number 0 itself.
def plusOne(digits: list) -> list:
temp = digits[::-1]
count = 0
for i in temp:
if i == 9:
count += 1
else:
break
if count != len(temp):
temp[0] += 1
for i in range(len(temp)):
if temp[i] > 9:
temp[i] = 0
temp[i + 1] += 1
else:
for i in range(len(temp)):
temp[i] = 0
temp.append(1)
return temp[::-1]
#new version
def plus_one(digits: list) -> list:
carry = False
for i in reversed(range(len(digits))):
digits[i] += 1
if digits[i] > 9:
digits[i] = 0
carry = True
else:
carry = False
break
if carry:
digits.insert(0, 1)
return digits
print(plus_one([1,1,5,9]))
print(plus_one([1,1,1,9]))
print(plus_one([1,9,9,9]))
print(plus_one([9,9,9,9]))
|
# Given a sorted array of distinct integers and a target value,
# return the index if the target is found.
# If not, return the index where it would be if it were inserted in order.
def searchInsert(nums: list, target: int) -> int:
pos = 0
if target in nums:
return nums.index(target)
else:
for i in nums:
if target < i:
pos = nums.index(i)
break
else:
pos += 1
return pos
print(searchInsert([1, 3, 5, 6], 5))
|
#Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа,
#третий - операция, которая должна быть произведена над ними.
# Если третий аргумент +, сложить их; если —, то вычесть; * — умножить;
# / — разделить (первое на второе). В остальных случаях вернуть
# строку "Неизвестная операция".
def arithmetic(a,b,c) -> int:
if c == "+":
return a+b
elif c == "-":
return a-b
elif c == "*":
return a*b
elif c == "/":
return a/b
else:
return "Неизвестная операция"
print(arithmetic(2,3, "+")) |
from prac_08.car import Car
import random
class UnreliableCar(Car):
"""Special version of car that includes unreliability"""
def __init__(self, name, fuel, reliability):
super().__init__(name, fuel)
self.reliability = reliability
def drive(self, distance):
"""Drive the car a given distance. Given its reliability is greater than a random number.
Drive given distance if car has enough fuel
or drive until fuel runs out return the distance actually driven.
"""
if self.reliability > random.randrange(0, 100):
if distance > self.fuel:
distance = self.fuel
self.fuel = 0
else:
self.fuel -= distance
self.odometer += distance
else:
distance = 0
return distance
|
""""Matthew Rooke"""
MIN_LENGTH = 5
def main():
password = get_password()
print_hidden_length(password)
def print_hidden_length(password):
for character in range(len(password)):
print("*", end="")
def get_password():
password = input("Enter your password:")
while len(password) < MIN_LENGTH:
password = input("Enter a password {} characters long:".format(MIN_LENGTH))
return password
main() |
import random
from heapq import *
# Quicksort routine for given collection of elements.
# Simple version defined in wikipedia (uses O(n) memory)
def quicksort(elements):
# If one or zero elements, then just return (technically already sorted)
if (len(elements) <= 1):
return elements
else:
# Choose pivot and then create lists containing elements that are
# less than and greater than the pivot element.
pivot = elements[len(elements) / 2]
left = []
right = []
for i in range(len(elements)):
if (i != len(elements)/2):
if (elements[i] <= pivot):
left.append(elements[i])
else:
right.append(elements[i])
# Now just recursively call quicksort on the left & right lists and combine
# at the end with the pivot element.
return quicksort(left) + [pivot] + quicksort(right)
############################################################
# Mergesort
def mergesort(n):
if len(n) > 1:
mid = len(n) // 2
a = n[mid:]
b = n[:mid]
if len(a) > 1:
a = mergesort(a)
if len(b) > 1:
b = mergesort(b)
return merge(a, b)
else:
return n
def merge(a, b):
result = []
while a and b:
if (a[0] < b[0]):
result.append(a[0])
a = a[1:]
else:
result.append(b[0])
b = b[1:]
if a:
result.extend(a)
else:
result.extend(b)
return result
############################################################
# (Modified code taken from http://codehost.wordpress.com/2011/07/22/radix-sort/)
# Radix sort for variable length strings
def radixsort(array):
if (len(array) <= 1):
return array
maxLen = -1
for string in array: # Find longest string
strLen = len(string)
if strLen > maxLen:
maxLen = strLen
oa = ord('0') - 1; # First character code
oz = ord('z') - 1; # Last character code
n = oz - oa + 2; # Number of buckets (+empty character)
buckets = [[] for i in range(0, n)] # The buckets
for position in reversed(range(0, maxLen)):
for string in array:
index = 0 # Assume "empty" character
if position < len(string): # Might be within length
index = ord(string[position]) - oa
buckets[index].append(string) # Add to bucket
del array[:]
for bucket in buckets: # Reassemble array in new order
array.extend(bucket)
del bucket[:]
return array
############################################################
# Selection sort algorithm
def selectionsort(arr):
for i in range(0, len(arr)-1):
minIndex = i
for j in range(i+1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
arr[i], arr[minIndex] = arr[minIndex], arr[i]
return arr
"""
Comparison functions
Arguments:
a - first element to compare
b - second element to compare
Returns:
negative integer if the first precedes the second
0 if both arguments have equal ordering
positive integer if the first succeeds the second
"""
# default to sort by length
def default_cmp(a, b):
return len(a) - len(b)
"""
Sorting functions
Arguments:
list - list of elements (url strings)
cmp - comparison function
Returns:
sorted list of elements
"""
def quicksort2(list, cmp=default_cmp):
return qsort2(list[:], cmp)
def qsort2(list, cmp):
if list == []:
return list
else:
pivot_ndx = random.choice(range(len(list)))
pivot = list.pop(pivot_ndx)
left = [x for x in list if cmp(x, pivot) < 0]
right = [x for x in list if cmp(x, pivot) >= 0]
return qsort2(left, cmp) + [pivot] + qsort2(right, cmp)
def insertionsort(list, cmp=default_cmp):
for i in range(1, len(list)):
save = list[i]
j = i
while j > 0 and cmp(list[j - 1], save) > 0:
list[j] = list[j - 1]
j -= 1
list[j] = save
return list
def mergesort2(list, cmp=default_cmp):
size = len(list)
if (size <= 1):
return list
left = mergesort2(list[0 : size/2], cmp)
right = mergesort2(list[size/2 : size], cmp)
return merge2(left, right, cmp)
def merge2(left, right, cmp):
result = []
while (len(left) > 0 or len(right) > 0):
# both non empty
if (len(left) > 0 and len(right) > 0):
c = cmp(left[0], right[0])
if (c <= 0):
result.append(left.pop(0))
else:
result.append(right.pop(0))
# right is empty
elif (len(left) > 0):
result.append(left.pop(0))
# left is empty
else:
result.append(right.pop(0))
return result
def msvalue(n):
'''
Returns the most significant value of n, i.e. n rounded
down to the nearest significant digit.
So msvalue(1) -> 1
msvalue(25) -> 10
msvalue(987) -> 100
'''
if n < 10:
return 1
else:
return 10 * msvalue(n / 10)
def bucketsort(list, cmp=default_cmp):
'''
Recursively performs bucket sort on the list
of strings, using their lengths to index
them.
'''
# Pre-parse the length of each string in the list
# so that we can find the min and max with which to set
# up the buckets.
len_list = []
max_val = 0
min_val = sys.maxint
for i in range(len(list)):
length = len(list[i])
len_list.append((length, list[i])) # store list item as tuple (length, item)
if length > max_val:
max_val = length
if length < min_val:
min_val = length
# Range of values that each bucket holds.
bucket_size = msvalue(max_val - min_val)
# Set up the empty buckets.
num_buckets = (max_val / bucket_size) - (min_val / bucket_size)
bucket_list = []
for i in range(num_buckets + 1):
bucket_list.append([])
# Index the list elements into their respective buckets.
n = len(list)
for i in range(n):
# Items are indexed by rounding down to the nearest bucket.
index = (len_list[i][0] / bucket_size) - (min_val / bucket_size)
bucket_list[index].append(len_list[i][1])
# Sort the buckets. If all elements indexed
# to the same bucket, use another sorting
# algorithm to perform the final sort on
# that bucket.
for i in range(len(bucket_list)):
if len(bucket_list[i]) > 0:
if len(bucket_list[i]) == len(list):
bucket_list[i] = insertionsort(bucket_list[i], cmp)
else:
bucket_list[i] = bucketsort(bucket_list[i])
# Concatenate all of the sorted buckets
ret_val = []
for i in range(len(bucket_list)):
ret_val += bucket_list[i]
return ret_val
|
def mean(vals):
"""Calculate the arithmetic mean of a list of numbers in vals"""
assert type(vals) is list, 'input must be list'
ivals = []
for n in vals:
ivals.append(float(n))
if ivals == []:
return 0
else:
total = sum(ivals)
length = len(ivals)
return total/length
print(ivals)
#print(mean("hello")) |
"""
unosi se cetvorocifreni broj
odrediti broj koji se dobija zamjenom trece i druge cifre
"""
broj = (input("Unesite cetvorocifreni broj "))
cifra1 = int(broj[0])
cifra2 = int(broj[1])
cifra3 = int(broj[2])
cifra4 = int(broj[3])
broj2 = cifra1*1000+cifra3*100+cifra2*10+cifra4
print(broj2) |
import json
EUR_FILE = 'eur-gbp-2001.json'
GBP_FILE = 'gbp-eur-2001.json'
def get_forex_data(file_name):
with open(file_name, 'r') as file:
eur_data = json.load(file)["Time Series FX (Daily)"]
euro_daily = []
for day in sorted(eur_data):
euro_daily.append((day, eur_data[day]["4. close"]))
return euro_daily
class SMA_val:
def __init__(self, name):
self.name = name
self.daily_values = []
def get_current_price(self):
return float(self.daily_values[-1][1])
def add_daily_quote(self, today_val):
self.daily_values.append(today_val)
def sma_50(self):
if len(self.daily_values) == 0:
print("no values to calculate sma")
return 0
elif len(self.daily_values) < 50:
print("no enough values to calculate sma")
return 0
return reduce((lambda x, y: x + y), map((lambda x: float(x[1])),self.daily_values[-50:])) / 50
def sma_20(self):
if len(self.daily_values) == 0:
print("no values to calculate sma")
return 0
elif len(self.daily_values) < 20:
print("no enough values to calculate sma")
return 0
return reduce((lambda x, y: x + y), map((lambda x: float(x[1])),self.daily_values[-20:])) / 20
def is_moving_average_below(currency):
return currency.sma_20() < currency.sma_50()
def sell(position, money, eur, gbp):
if position == eur.name:
return money * gbp.get_current_price()
elif position == gbp.name:
return money * eur.get_current_price()
if __name__ == "__main__":
eur_vals = get_forex_data(EUR_FILE)
gbp_vals = get_forex_data(GBP_FILE)
MONEY = 1000
DAY = 0
eur = SMA_val("eur")
gbp = SMA_val("gbp")
position = "gbp"
while True:
eur.add_daily_quote(eur_vals[DAY])
gbp.add_daily_quote(gbp_vals[DAY])
DAY += 1
if DAY < 50:
continue
if position == "gbp":
if is_moving_average_below(gbp):
MONEY = sell(position, MONEY, eur, gbp)
position = "eur"
# else:
# nothing for now
elif position == "eur":
if is_moving_average_below(eur):
MONEY = sell(position, MONEY, eur, gbp)
position = "gbp"
# else:
# nothing for now
if DAY > 3000 and position == "gbp":
print(MONEY)
print(DAY)
break
|
import click
def manual_fitness(dnr: list) -> int:
print(dnr)
score = input("Enter score> ")
return int(score)
def random_dnr(size: int, seq: list) -> list:
from random import choice
return [choice(seq) for _ in range(0, size)]
def evaluate(population: list, fitness_fn: callable) -> list:
for pop in population:
yield fitness_fn(pop), pop
def mix(dnr1: list, dnr2: list, size: int) -> list:
from random import randint
r = randint(1, size)
return dnr1[:r] + dnr2[r:]
def mutate(dnr: list, seq: list):
from random import randint, choice
if randint(0, 1000) == 0:
print("Mutating")
r = randint(0, len(dnr) - 1)
dnr[r] = choice(seq)
def evolution(population, fitness_fn, size, seq, limit):
top = sorted(evaluate(population, fitness_fn), key=lambda x: x[0], reverse=True)[:limit]
print(top)
population.clear()
for i in range(0, len(top)):
for j in range(i, len(top)):
population.append(mix(top[i][1], top[j][1], size))
population += top
for pop in population:
mutate(pop, seq)
@click.command()
@click.option("--size", help="Sequance length", type=int)
@click.option("--population_size", help="Population size", type=int, default=6)
@click.option("--fitness_fn", help="Fitness function", type=str, default="__main__.manual_fitness")
@click.argument("seq", nargs=-1)
def main(size, population_size, fitness_fn, seq):
population = [random_dnr(size, seq)
for i in range(0, population_size)]
def get_function():
buff = fitness_fn.split(".")
mod = ".".join(buff[:-1])
fn = buff[-1]
m = __import__(mod)
return getattr(m, fn)
fitness = get_function()
iteration = 1
while True:
print("iteration: {0}".format(iteration))
evolution(population, fitness, size, seq, int(population_size / 2))
iteration += 1
if __name__ == "__main__":
main()
|
print("Enter a string")
strn = input()
print("The String is")
print(strn)
print(strn[1:])
print(strn[2:])
print(strn[:1:-1])
|
a = 21
b = 10
c = 0
c = a + b
print("Value of addition is ", c)
c = a - b
print(" Value subraction is ", c )
c = a * b
print(" Value of multiplicationis ", c )
c = a / b
print ("Value of division is ", c )
c = a % b
print (" Value of remainder is ", c)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if not head or not head.next:
return head
head_lt, head_ge = None, None
p_lt, p_ge = None, None
p = head
while p:
if p.val < x:
if not p_lt:
head_lt = ListNode(val=p.val)
p_lt = head_lt
else:
p_lt.next = ListNode(val=p.val)
p_lt = p_lt.next
else:
if not p_ge:
head_ge = ListNode(val=p.val)
p_ge = head_ge
else:
p_ge.next = ListNode(val=p.val)
p_ge = p_ge.next
p = p.next
if p_lt:
p_lt.next = head_ge
return head_lt
return head_ge
|
def pow(n):
def inner(x):
return x ** n
return inner
if __name__ == '__main__':
cube = pow(3)
print(cube(10))
|
class Solution:
def minimumPathCost(self, triangle):
'''
:type triangle: list of list of int
:rtype: int
'''
height = len(triangle)
row = height - 2
while row >= 0:
for i in range(row + 1): # the number elements in equal the # of the row
triangle[row][i] += min(triangle[row + 1][i], triangle[row + 1][i + 1])
row -= 1
print(triangle)
return triangle[0][0]
|
from numpy import exp, array, random, dot
class NeuralNetwork():
def __init__(self):
# Seed the random number generator, so it generates the same numbers
# every time the program runs.
random.seed(1)
# initialize weights randomly with mean 0
self.synaptic_weights_1 = 2 * random.random((3, 3)) - 1
self.synaptic_weights_2 = 2 * random.random((3, 3)) - 1
self.synaptic_weights_3 = 2 * random.random((3, 1)) - 1
# The Sigmoid function, which describes an S shaped curve.
# We pass the weighted sum of the inputs through this function to
# normalise them between 0 and 1.
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
# The derivative of the Sigmoid function.
# This is the gradient of the Sigmoid curve.
# It indicates how confident we are about the existing weight.
def __sigmoid_derivative(self, x):
return x * (1 - x)
# We train the neural network through a process of trial and error.
# Adjusting the synaptic weights each time.
def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations):
for iteration in range(number_of_training_iterations):
output_1 = self.think(training_set_inputs, self.synaptic_weights_1)
output_2 = self.think(output_1, self.synaptic_weights_2)
output_3 = self.think(output_2, self.synaptic_weights_3)
error_3 = training_set_outputs - output_3
error_2 = dot(self.synaptic_weights_3, error_3.T) * (self.__sigmoid_derivative(output_2).T)
error_1 = dot(self.synaptic_weights_2, error_2) * (self.__sigmoid_derivative(output_1).T)
adjustment_3 = dot(output_2.T, error_3)
adjustment_2 = dot(output_1.T, error_2.T)
adjustment_1 = dot(training_set_inputs.T, error_1.T)
self.synaptic_weights_1 += adjustment_1
self.synaptic_weights_2 += adjustment_2
self.synaptic_weights_3 += adjustment_3
# The neural network thinks.
def think(self, inputs, weights):
# Pass inputs through our neural network (our single neuron).
return self.__sigmoid(dot(inputs, weights))
def predict(self, inputs):
l1 = self.__sigmoid(dot(inputs, self.synaptic_weights_1))
l2 = self.__sigmoid(dot(l1, self.synaptic_weights_2))
l3 = self.__sigmoid(dot(l2, self.synaptic_weights_3))
return l3
if __name__ == "__main__":
#Intialise a single neuron neural network.
neural_network = NeuralNetwork()
print("Random starting synaptic weights: ")
print(neural_network.synaptic_weights_1)
print(neural_network.synaptic_weights_2)
print(neural_network.synaptic_weights_3)
# The training set. We have 4 examples, each consisting of 3 input values
# and 1 output value.
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
# Train the neural network using a training set.
# Do it 10,000 times and make small adjustments each time.
neural_network.train(training_set_inputs, training_set_outputs, 10000)
print("New synaptic weights after traning")
print(neural_network.synaptic_weights_1, neural_network.synaptic_weights_2, neural_network.synaptic_weights_3)
# Test the neural network with a new situation.
print("Considering new situation [1, 0, 0] -> ?: ")
print(neural_network.predict(array([1, 0, 0]))) |
import Materials
class Cage:
"""This class describe one cell"""
temperature = None
material = None
mass = None
upd_q = None # q that cell get from other cells
fraction = 0 # parameter that is used for change effective_mass
checker_transformation = True # exit criteria
# const
dx = 10 ** (-3)
S = dx ** 2
t_0 = 10 ** (-3)
V = S * dx
def interaction(self, *cell_list):
for i in range(len(cell_list)):
self.upd_q += 0.5 * (self.material.conductivity + cell_list[i].material.conductivity) * (
-self.temperature + cell_list[i].temperature) / Cage.dx * Cage.t_0 * Cage.S * (
1 - self.fraction) ** (1 / 3) # q that taken from cell
if (self.material.name is 'Water') and self.fraction >= 0.99: # check if saved_q >= lambda * effective_mass
self.checker_transformation = False # exit if False
self.fraction = 0 # change to initial
self.material = Materials.ice # change material
self.V = self.mass / self.material.density
if (self.material.name is 'Ice') and self.fraction >= 0.99: # check if saved_q >= lambda * effective_mass
self.checker_transformation = False # exit if False
self.fraction = 0 # change to initial
self.material = Materials.water # change material
self.V = self.mass / self.material.density # Mass conservation law
if round(self.temperature, 2) == self.material.trans_temperature and self.checker_transformation:
self.fraction += self.upd_q / (self.material.fusion * self.mass) * 100
self.upd_q = 0
# if round(self.temperature, 1) > self.material.trans_temperature:
# self.checker_transformation = True # IF WE WANT TO DO 2 PHASE TRANSFORMATION
# DONT KNOW WORK OR NOT
def change_temp(self):
self.temperature += self.upd_q / (self.material.capacity * self.mass)
self.upd_q = 0
def __init__(self, temperature=None, material=None):
self.temperature = temperature
self.material = material
self.mass = material.density * Cage.S * Cage.dx
self.upd_q = 0
|
## Basic Controls
elevatorFloor01 = 1
elevatorFloor02 = 1
elevatorFloor03 = 1
elevatorFloor04 = 1
elUser = 1
system = "on"
while system == "on":
elevatorFloor01int = str(elevatorFloor01)
elevatorFloor02int = str(elevatorFloor02)
elevatorFloor03int = str(elevatorFloor03)
elevatorFloor04int = str(elevatorFloor04)
userInput = input("user: ")
if userInput == "systemOff":
print()
print("shutting off")
print()
system = "off"
elif userInput == "report":
print()
print("Elevator 1 = " + elevatorFloor01int)
print("Elevator 2 = " + elevatorFloor02int)
print("Elevator 3 = " + elevatorFloor03int)
print("Elevator 4 = " + elevatorFloor04int)
print()
elif userInput == "send":
sendToElChoice = int(input("select elevator: "))
sendToFlChoice = int(input("select floor: "))
print()
print("Elevator has been sent")
print()
if sendToElChoice == 1:
elevatorFloor01 = sendToFlChoice
elif sendToElChoice == 2:
elevatorFloor02 = sendToFlChoice
elif sendToElChoice == 3:
elevatorFloor03 = sendToFlChoice
elif sendToElChoice == 4:
elevatorFloor04 = sendToFlChoice
## basic algorithm for user
elif userInput == "call":
userGoingTo = int(input("Which floor: "))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 16:17:49 2021
@author: carmine
"""
# 7. Реализовать генератор с помощью функции с ключевым словом yield,
# создающим очередное значение. При вызове функции должен создаваться
# объект-генератор. Функция должна вызываться следующим образом:
# for el in fact(n). Функция отвечает за получение факториала числа,
# а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
n = int(input("Enter n: "))
def fact(n):
f = 1
for i in range(1, n+1):
f = f * i
yield f
g = fact(n)
print(g)
for el in g:
print(el)
|
# -*- coding: utf-8 -*-
"""
1. Реализовать класс «Дата», функция-конструктор которого должна принимать
дату в виде строки формата «день-месяц-год».
В рамках класса реализовать два метода.
Первый, с декоратором @classmethod, должен извлекать число, месяц, год
и преобразовывать их тип к типу «Число».
Второй, с декоратором @staticmethod, должен проводить валидацию числа,
месяца и года (например, месяц — от 1 до 12).
Проверить работу полученной структуры на реальных данных.
"""
class Date:
def __init__(self, str_date: str):
self.str_date = str_date
@classmethod
def cast_date(cls, str_date):
date = str_date.split('-')
try:
day = int(date[0])
month = int(date[1])
year = int(date[2])
except ValueError:
print("Incorrect input. Can't cast into int.")
else:
return day, month, year
@staticmethod
def valid_date(date):
day = date[0]
month = date[1]
year = date[2]
try:
if (year <= 0):
raise ValueError
except:
print("year < 0")
try:
if (month <= 0 or month > 12):
raise ValueError
except:
print("month <= 0 or month > 12")
try:
if (day <= 0 or day > 31):
raise ValueError("day <= 0 or day > 31")
except ValueError:
print("day <= 0 or day > 31")
else:
return f"Date is ok"
x = Date("12-12-1234d")
d, m, y = Date.cast_date("12-12-1234")
print(d, m, y)
print(Date.valid_date(Date.cast_date("12-12-1234")))
print(Date.cast_date("12-12-1234d"))
print(Date.valid_date(Date.cast_date("12-13-1234")))
|
from disjointsets import Node,DisjointSets
ds = DisjointSets()
nodes = []
mst=[]
def krus(vert, weight):
for i in vert:
node = ds.makeset(i)
nodes.append(node)
print(vert)
print(weight)
for i in weight:
if(ds.union(nodes[i[0]],nodes[i[1]])):
mst.append((i[0],i[1]))
print(mst)
def main():
weight={}
vert=[]
file = open("input.txt",'r')
for line in file:
line = line.strip()
line = line.split()
n = int(line[0])
vert.append(n)
for i in range(1,len(line)):
v,w = line[i].split(',')
if(not (int(v),n) in weight.keys()):
weight[(n,int(v))] = int(w)
file.close()
weight={k: v for k, v in sorted(weight.items(), key=lambda item: item[1])}
krus(vert,weight)
if __name__ == "__main__":
main() |
def fib_iter(n):
f1 = 0
f2 = 1
n-=2
print(f1)
print(f2)
while(n):
f3 = f1 + f2
n-=1
print(f3)
f1 = f2
f2 = f3
def fib_rec(n):
if(n<=1):
return n
else:
return fib_rec(n-1) + fib_rec(n-2)
def main():
n = int(input())
print("Iterative: ")
fib_iter(n)
print("Recursive: ")
for i in range(n):
print(fib_rec(i))
main()
|
def fact_iter(n):
fact = 1
for i in range(1,n+1):
fact*=i
return fact
def fact_rec(n):
while(n>0):
if (n <= 1):
return 1
return n*fact_rec(n-1)
def main():
n = int(input())
print("Iterative: " + str(fact_iter(n)))
print("Recursive: " + str(fact_rec(n)))
main()
|
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 26 22:58:47 2021
@author: Immanuel
"""
import datetime
import random
print("WELCOME TO BANK OF OJI!!!")
print("Insert Your Card Here")
atmpin = 3005
#we will store the atm pin here#
transaction = ["Check Balance","Deposit Money","Withdrawal",
"Transfer","Change Your Pin", "Quit" ]
#we are storing all the tramsactions here#
activebal = 500000
#we are storing a fix amount as the money the person has
pin = int(input("Enter in your pin: "))
print()
def login():
if pin == 3005:
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
login()
print('Choose your transaction: ')
print('1. Withdrawal')
print('2. Deposit')
print('3. Complaint')
print('4. Register')
print('5. Recharge')
trans = input("transaction: ")
def generateAccountNumber():
print('Generating Account Number')
generated_num = random.randrange(1111111111,9999999999)
print(f'{generated_num}')
def withdraw():
withdraw = input('How much would you like to withdraw: ')
print (f'You withdrew {withdraw} succesfully')
def deposit():
depo = int(input('How much would you like to deposit?: '))
currentbal = (activebal) + (depo)
print (f'Current balance is {currentbal}')
def complaint():
comp = input('What issue will you like to report?: ')
print(f'your complaint {comp} has been taken')
print ('Thank you for contacting us')
def register():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
password = input('Enter your password: ')
print(f'{first_name} {last_name} with the password {password} has been added')
generateAccountNumber()
def recharge():
print('Choose a network')
print('1. MTN')
print('2. GLO')
print('3. AIRTEL')
print('4. 9MOBILE')
net_work = input('Enter the Network: ')
print(f'{net_work}')
def MTN():
amount = int(input("Enter amount you want to buy: "))
print(f'{amount} recharged')
def GLO():
amount = int(input("Enter amount you want to buy: "))
print(f'{amount} recharged')
def AIRTEL():
amount = int(input("Enter amount you want to buy: "))
print(f'{amount} recharged')
def MOBILE():
amount = int(input("Enter amount you want to buy: "))
print(f'{amount} recharged')
if trans == ('1'):
withdraw()
if trans == ('2'):
deposit()
if trans == ('3'):
complaint()
if trans == ('4'):
register()
if trans == ('5'):
recharge()
if net_work == ('1'):
MTN()
if net_work == ('2'):
GLO()
if net_work == ('3'):
AIRTEL()
if net_work == ('4'):
MOBILE()
|
import numpy as np
from main import *
"""
Ant class
"""
class Ant:
def __init__(self, initial_location, colony):
self.path = [initial_location] # Path starts with initial location.
self.initial_location = initial_location
self.colony = colony
self.location = initial_location
self.distance_travelled = 0
self.get_grid()
"""
The ant gets a copy of the transition matrix.
This is also used to keep track of the places the ant has visited.
THe initial location has to be the last stop.
"""
def step(self):
transition_probabilities = self.matrix[self.location]
step = -1 # Intentionally crash the program if something is wrong.
# Weighted random sampling:
goal = np.random.uniform()*sum(transition_probabilities)
cumulative = 0
for i in range(0,len(transition_probabilities)):
cumulative += transition_probabilities[i]
if(cumulative>goal):
step = i
break
distance = get_distance(self.location, step) # Record distance travelled.
if self.colony.verbosity>2:
print("Travelling", distance, "km from", numerated[self.location+1], "to", numerated[step+1])
self.location = step # Move ant to the new location.
self.matrix[:,step] = 0 # Ensure ant will not visit this place again.
self.path.append(step)
self.distance_travelled += distance
def march(self):
for step in range(0,len(self.matrix)-1): # -1 since initial location is not available.
self.step()
# Finally, move back to initial location.
distance = get_distance(self.location, self.initial_location)
if self.colony.verbosity>2:
print("Travelling", distance, "km from", numerated[self.location+1], "to", numerated[self.initial_location+1])
self.path.append(self.initial_location)
self.distance_travelled += distance
self.location = self.initial_location
def get_grid(self):
self.matrix = np.empty_like(self.colony.grid)
self.matrix[:] = self.colony.grid
self.matrix[:,self.location]=0 # Prevent the ant from moving back to the initial location until the last step. |
import random
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
l = len(names)
i = random.randint(0,l-1)
print(names[i] + " is going to buy the meal today!" + str(l)) |
# Method 1
# with open("Working with CSV\weather_data.csv") as f:
# data = f.readlines()
# print(data)
# Method 2
# import csv
# with open("Working with CSV\weather_data.csv") as f:
# output = csv.reader(f)
# temperatures = []
# for row in output:
# if row[1]!="temp":
# temperatures.append(int(row[1]))
# print(temperatures)
# Method 3
# import pandas as p
# data = p.read_csv("Working with CSV\weather_data.csv")
# print(data["temp"])
# print(data.temp)
# data_dict = data.to_dict()
# print(data_dict)
# temp_list = data["temp"].to_list()
# print(sum(temp_list)/len(temp_list))
# print(data["temp"].mean())
# monday = data[data.day == "Monday"]
# print(monday)
# print(data[data.temp == data.temp.max()])
# print(monday.condition)
# print(monday["temp"]*2)
# Create a dataframe from scratch
# data_dict = {
# "students": ["Amy","James","Angela"],
# "scores": [76,89,56]
# }
# data = p.DataFrame(data_dict)
# data.to_csv("new_data.csv")
# print(data)
import pandas as p
data = p.read_csv("Working with CSV\Squirrel_Data.csv")
gray_squirrel = len(data[data["Primary Fur Color"]=="Gray"])
cinnamon_squirrel = len(data[data["Primary Fur Color"]=="Cinnamon"])
black_squirrel = len(data[data["Primary Fur Color"]=="Black"])
data_dict = {
"Fur color": ["Gray","Cinnamon","Black"],
"Count": [gray_squirrel,cinnamon_squirrel,black_squirrel]
}
df = p.DataFrame(data_dict)
df.to_csv("new_data.csv")
print(df) |
#Step 1
import random
from HangMan_Art import logo
from HangMan_Art import stages
from HangMan_Words import word_list
print(logo)
# word_list = ["aardvark", "baboon", "camel"]
#TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word.
word = random.choice(word_list)
l = []
for i in range(0,len(word)):
l += "-"
print(l)
#TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase.
#TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word.
lives = 7
end_of_game = False
while not end_of_game:
bFlag = False
guess = input("Guess a letter: ").lower()
#check the guessed letter in the word
ind = 0
for i in word:
if i==guess:
l[ind] = i
bFlag = True
ind += 1
print(f"{' '.join(l)}")
#Reduce a life if the guess is wrong
if not bFlag:
lives -= 1
print(stages[lives])
print("The guessed letter is wrong")
print(f"Lives left: {lives}")
else:
print("Your guess is correct")
#Check whether the answer is found
if "-" not in l:
end_of_game = True
print("You Win")
#End game if all lives are lost
if lives<1:
end_of_game = True
print(f"The correct word is: {word}")
|
from turtle import Turtle
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.level = 1
self.penup()
self.color("black")
self.goto(-280,250)
self.hideturtle()
self.updateScoreboard()
def updateScoreboard(self):
self.clear()
self.write(f"Level: {self.level}",align="Left",font=FONT)
def updateLevel(self):
self.level += 1
self.updateScoreboard()
def gameOver(self):
self.goto(0,0)
self.write(f"* * Game Over * *",align="Center",font=FONT) |
# Your program should print each number from 1 to 100 in turn.
# When the number is divisible by 3 then instead of printing the number it should print "Fizz".
# `When the number is divisible by 5, then instead of printing the number it should print "Buzz".`
# `And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"`
for i in range(1,101):
if i%3==0 and i%5==0:
print("FizzBuzz")
elif i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
else:
print(i) |
# Authors: Amulya Badineni, Michael Giordano, Rishi Konkesa, Jason Swick
# Filename: train.py
# Description: Implements a training example generator that generates random instances
import random
# TrainingExample object: will hold values for each attribute in a given training example. Also has "EnjoySport", which is whether or not the overall example is positive or negative. Will support the "example" function, which will allow for the generation of a random training example.
class TrainingExample:
# Class definition for TrainingExample object: will initialize each attribute to NULL unless a specific value is given, in which case each attribute will be initialized to said value.
def __init__(self, sky = "NULL", airTemp = "NULL", humidity = "NULL", wind = "NULL", water = "NULL", forecast = "NULL", EnjoySport = "NULL"):
# object parameter train: an array that holds the values for each attribute
self.train = [sky, airTemp, humidity, wind, water, forecast, EnjoySport]
# example function: a method that acts on a TrainingExample object. Will randomly assign a value to each attribute, then determine whether EnjoySport is positive or negative based on the target concept.
def example(self):
# Create a list of possible values for each attribute, then randomly choose a value.
sky_list = ['sunny', 'cloudy', 'rainy']
sky_choice = random.choice(sky_list)
air_temp = ['warm', 'cold']
air_choice = random.choice(air_temp)
humidity = ['normal', 'high']
humidity_choice = random.choice(humidity)
wind = ['strong', 'weak']
wind_choice = random.choice(wind)
water = ['warm', 'cool']
water_choice = random.choice(water)
forecast = ['same', 'change']
forecast_choice = random.choice(forecast)
# EnjoySport: a variable that is either "yes" or "no", representing whether the TrainingExample is positive or negative
# Set EnjoySport to "no" by default
EnjoySport = "no"
# Using the target concept, if the training example has the value 'sunny' for attribute "sky" and the value 'warm' for attribute "air" then set EnjoySport to yes, signifying a positive example
if (sky_choice == 'sunny') and (air_choice == 'warm'):
EnjoySport = "yes"
# Set the array to hold the newly generated values
self.train = [sky_choice,air_choice,humidity_choice,wind_choice,water_choice,forecast_choice,EnjoySport]
|
import random
print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi desert.")
print ("The natives want their camel back and are chasing you down!")
print ("Survive your desert trek and out run the native.")
done = False
miles_traveled = 0
thirst = 0
energy = 0
natives_distance = -20
water_in_canteen = 3
oasis = 1
while done == False:
print ("\n")
print ("A. Drink from your canteen")
print ("B. Ahead moderate speed.")
print ("C. Ahead full speed.")
print ("D. Stop for the night.")
print ("E. Status check.")
print ("Q. Quit.")
user_input = input("What is your choice? : ")
print ("\n")
user_input = user_input.upper()
if user_input == "Q":
done = True
elif user_input == "E":
print ("Miles traveled: " + str(miles_traveled))
print ("Drinks in canteen: " + str(water_in_canteen))
print ("The natives are %d miles behind you" % natives_distance)
print ("Your camel has used %s energy." % energy)
elif user_input == "D":
energy = 0
print ("The camel is happy")
rand = random.randrange(7, 15)
natives_distance += rand
elif user_input == "C":
rand = random.randrange(10, 21)
miles_traveled += rand
thirst += 1
rand = random.randrange(1, 4)
energy += rand
rand = random.randrange(7, 15)
natives_distance += rand
print ("You have travled %d miles" % miles_traveled)
elif user_input == "B":
rand = random.randrange(5, 13)
miles_traveled += rand
thirst += 1
energy += 1
rand = random.randrange(7, 15)
natives_distance += rand
print ("You have travled %d miles" % miles_traveled)
elif user_input == "A":
if water_in_canteen > 0:
water_in_canteen -= 1
thirst = 0
print ("You feel refreshed")
else:
print ("Error: You have no water left")
if thirst > 6:
print ("You died of thirst!")
print ("GAME OVER")
done == True
elif thirst > 4:
print ("You are thristy.")
if done == True:
pass
elif energy > 8:
print ("Your camel is dead.")
print ("GAME OVER")
done = True
elif energy > 5:
print ("Your camel is getting tired.")
if done == True:
pass
elif miles_traveled <= natives_distance:
print ("The natives have caught you!")
print ("GAME OVER")
done = True
elif miles_traveled - natives_distance < 15:
print ("the natives are getting close!")
elif miles_traveled >= 200:
print ("Congratulations you have won the game!")
done = True
if done == False:
desert_oasis = random.randrange(20)
if desert_oasis == oasis:
print ("Congratulations, you found an oasis!")
water_in_canteen = 3
thirst = 0
energy = 0
|
from enum import Enum
import random
from os import system, name
from time import sleep
def clear():
if name == 'nt':
_ = system('cls')
def attackDice(x):
if(x > 3):
return 3
elif(x == 3):
return 2
elif(x == 2):
return 1
else:
return 0
def defDice(x):
if(x >= 2):
return 2
elif(x > 0):
return 1
else:
return 0
def diceRoll(y):
return random.randint(1,y)
def combat(x):
ret = 0
hold = 0
for i in range(0,x):
hold = diceRoll(6)
if(hold > ret):
ret = hold
return ret
def attack(x):
dice = attackDice(x)
return combat(dice)
def defense(x):
dice = defDice(x)
return combat(dice)
class Player():
### Hold the data of each player
def __init__(self,x):
self.name = x
self.empire = []
self.armies_to_place = 0
def conquor(self,x):
self.empire.append(x)
def lose(self,x):
self.empire.remove(x)
def display(self):
for x in self.empire:
print(x.name)
def determine_armies_to_place(self):
x = int(len(self.empire) / 3)
if(x < 3):
self.armies_to_place = 3
else:
self.armies_to_place = x
class Nation():
### Hold the data of each country
def __init__(self,x):
self.name = x
self.ruler = ''
self.armies = 1
self.borders = []
def set_ruler(self, x):
self.ruler = x
def add_armies(self, x):
self.armies += x
def subtract_armies(self, x):
self.armies -= x
def set_borders(self, x):
self.borders = x
def define(self,ruler,armies,borders):
self.ruler = ruler
self.armies = armies
self.borders = borders
def attack(self, x):
attackRoll = attack(self.armies)
defenseRoll = defense(x.armies)
if(attackRoll > defenseRoll):
x.subtract_armies(1)
print(x.name + ' lost. -1 army' )
print()
print(x.name + ' has ' + str(x.armies) + ' remaining.')
elif(defenseRoll >= attackRoll):
self.subtract_armies(1)
print(self.name + ' lost. -1 army' )
print()
print(self.name + ' has ' + str(self.armies) + ' remaining.')
hold = input('')
def int_validation(prompt,invalid,max,min):
good_input = False
x = input(prompt)
while(good_input == False):
if(x.isnumeric()):
if(int(x) > max or int(x) < min):
x = input(invalid)
else:
good_input = True
else:
x = input(invalid)
return int(x)
def generate_players(players_count):
clear()
players = []
for x in range(1,players_count + 1):
players.append(Player(x))
return players
def name_players(players):
for x in range(0,len(players)):
players[x].name = input('Player ' + str(players[x].name) + ' enter your name: ')
def starting_nations(player_count,players,nations):
nations_per_player = int(len(nations) / player_count)
for x in players:
for _ in range(0,nations_per_player):
num = random.randint(0,(len(nations) - 1))
x.conquor(nations[num])
nations.remove(nations[num])
for x in range(0,len(nations)):
num = random.randint(0,len(players))
players[num].conquor(nations[x])
return players
def turn(player):
player.determine_armies_to_place()
while(player.armies_to_place > 0):
clear()
count = 1
print(player.name + ' you control the following nations:')
for x in player.empire:
print(str(count) + '. ' + x.name + ': ' + str(x.armies))
count += 1
print()
print('You have ' + str(player.armies_to_place) + ' armies to place')
print()
select = int_validation('What nation would you like to add armies to?\n','Please enter a number from the list above.\n',(len(player.empire)),1)
armies_to_add = int_validation('How many armies would you like to add to ' + player.empire[select - 1].name + '?\n','That is an invalid number of armies\n',player.armies_to_place,0)
player.empire[select - 1].armies += armies_to_add
print()
player.armies_to_place -= armies_to_add
attack = ''
while(attack != 'end'):
attack = input('Who would you like to attack? (Type end if you wish to end your turn)\n')
def main():
clear()
alaska = Nation('Alaska')
northwest_territory = Nation('Northwest Territory')
alberta = Nation('Alberta')
ontario = Nation('Ontario')
greenland = Nation('Greenland')
quebec = Nation('Quebec')
western_united_states = Nation('Western United States')
eastern_united_states = Nation('Eastern United States')
central_america = Nation('Central America')
venezuela = Nation('Venezuela')
peru = Nation('Peru')
argentina = Nation('Argentina')
brazil = Nation('Brazil')
iceland = Nation('Iceland')
great_britain = Nation('Great Britain')
scandinavia = Nation('Scandinavia')
ukraine = Nation('Ukraine')
northern_europe = Nation('Northern Europe')
southern_europe = Nation('Southern Europe')
western_europe = Nation('Western Europe')
north_africa = Nation('North Africa')
egypt = Nation('Egypt')
east_africa = Nation('East Africa')
congo = Nation('Congo')
south_africa = Nation('South Africa')
madagascar = Nation('Madagascar')
indonesia = Nation('Indonesia')
new_guinea = Nation('New Guinea')
western_australia = Nation('Western Australia')
eastern_australia = Nation('Eastern Australia')
middle_east = Nation('Middle East')
india = Nation('India')
siam = Nation('Siam')
china = Nation('China')
afganistan = Nation('Afganistan')
mongolia = Nation('Mongolia')
ural = Nation('Ural')
irkutsk = Nation('Irkutsk')
siberia = Nation('Siberia')
yakutsk = Nation('Yakutsk')
kamchatka = Nation('Kamchatka')
japan = Nation('Japan')
nations = [alaska,northwest_territory,alberta,ontario,greenland,quebec,western_united_states,eastern_united_states,central_america,\
venezuela, peru, argentina, brazil, iceland, great_britain, scandinavia, ukraine, northern_europe, southern_europe, western_europe,\
north_africa, egypt, east_africa, congo, south_africa, madagascar, indonesia, new_guinea, western_australia, eastern_australia, middle_east,\
india, siam, china, afganistan, mongolia, ural, irkutsk, siberia, yakutsk, kamchatka, japan]
player_count = int_validation('How many people are playing?\n','Please input a number between 2 and 7\n',7,2)
players = generate_players(player_count)
name_players(players)
players = starting_nations(player_count,players,nations)
while(True):
for x in players:
turn(x)
main()
|
with open("01_input.txt") as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
def calc_fuel(mass):
return (mass / 3) -2
content = [x.strip() for x in content]
total_fuel = 0
for mass in content:
this_fuel = calc_fuel(eval(mass))
print this_fuel
total_fuel+=this_fuel
while calc_fuel(this_fuel) >= 0:
this_fuel = calc_fuel(this_fuel)
print this_fuel
total_fuel += this_fuel
print "-----------"
print total_fuel
|
# choose your own adventure game
#background story for adventure
print ("You are feeling hungry and decide to eat an apple.")
print ("Little do you know, this apple has magical properties and transports you to another dimension.")
print ("You find yourself in a dark, mysterious woods, and are surrounded by tall trees.")
print ("You are surprised and shocked.")
print ("You finally realize that it was the apple that transported you here")
print ("And the only way to return home is to find a similar magical apple")
print ("Suddnely two weapons appear, along with a magical voice that starts asking all these questions...")
weapon = input ("Do you want to take the sword or the shield? ")
#if the user chooses sword
if weapon == "sword":
print ("Suddenly a fire breathing dragon pops out of nowhere!!")
print ("Once again that magical voice starts speakinng...")
answer1 = input ("Do you want to fight the dragon with your sword? ")
if answer1 == "yes" or answer1 == "Yes":
print ("Right choice!")
print ("You were able to defeat the dragon and realized it was guarding a magic apple tree!")
print ("This magic apple tree allowed you to go home! Good job!")
if answer1 == "no" or answer1 == "No":
print ("Wrong choice!")
print ("The dragon saw your sword and deemed you a threat!")
print ("It ended your life before you could even move...")
#if the user chooses shield
if weapon == "shield":
print ("Suddenly a fire breathing dragon pops out of nowhere!!")
print ("Once again that magical voice starts speakinng...")
answer1 = input ("Do you want to fight the dragon with your shield? ")
if answer1 == "yes" or answer1 == "Yes":
print ("Wrong choice!")
print ("The dragon was able to burn through your wooden shield and kill you")
if answer1 == "no" or answer1 == "No":
print ("Right choice!")
print ("You were able to escape before the dragon saw you, and were able to find the magic apple tree another way!")
print ("Great job getting back home!")
|
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1=[]
self.stack2=[]
def push(self, node):
# write code here
while(self.stack2):
self.stack1.append(self.stack2.pop())
self.stack1.append(node)
def pop(self):
# return xx
while(self.stack1):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
s = Solution()
s.push(4)
s.push(8)
print(s.pop())
print(s.pop())
|
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
if n==0:
return 0
if n <= 2:
return 1
num1 = 1
num2 = 1
while (n-2):
num1,num2 = num2,num1+num2
n -= 1
return num2
s = Solution()
print(s.Fibonacci(3))
|
#Tarea1.Ejercicio5
precio=float(input('Cuanto cuesta: '))
peso=float(input('Cuanto pesa: '))
descuento=0
if peso>=2.01 and peso<=5:
descuento=0.10
if peso>=5.01 and peso<=10:
descuento=0.15
if peso>=10.01:
descuento=0.20
pagar=peso*peso*(1-descuento)
print (pagar)
|
#Fibonacci
n=int(input('Termino n: '))
i=2
a=1
b=1
while not (i==n):
c=a+b
a=b
b=c
i=i+1
print (c)
|
#Cinematica
import numpy
import matplotlib.pyplot as plt
vx=float(input('Velocidad en x: '))
x0=float(input('Posicion inicial x: '))
vy=float(input('Velocidad en y: '))
y0=float(input('Posicion inicial y: '))
tfinal=float(input('Tiempo de observacion: '))
tiempo=numpy.zeros(tfinal,dtype=float)
posicionx=numpy.zeros(tfinal,dtype=float)
posiciony=numpy.zeros(tfinal,dtype=float)
i=0
while not i>=tfinal:
tiempo[i]=i
posicionx[i]=x0+(vx*tiempo[i])
posiciony[i]=y0+(vy*tiempo[i])+(0.5*-9.8*(tiempo[i]**2))
i=i+1
print(tiempo)
print(posicionx)
plt.plot(posicionx,posiciony,'ro')
plt.title('Tiro Parabolico')
plt.xlabel('desplazamiento x')
plt.ylabel('desplazamiento y')
plt.show()
|
#!/bin/python
"""
This program will summarize fasta files for sequence length.
Outputs total, median, mean, quartiles
"""
import sys
import numpy
def median(lst):
return numpy.median(numpy.array(lst))
def mean(lst):
return numpy.mean(numpy.array(lst))
def FASTA(filename):
try:
f = file(filename)
except IOError:
print "The file, %s, does not exist" % filename
return
order = []
sequences = {}
for line in f:
if line.startswith('>'):
name = line[1:].rstrip('\n')
name = name.replace('_', ' ')
order.append(name)
sequences[name] = ''
else:
sequences[name] += line.rstrip('\n')
return sequences
lengths = {}
seqs = FASTA(sys.argv[1])
#print(len(seqs))
for f in seqs.keys():
lengths[f] = len(seqs[f])
vals = lengths.values()
#print vals
med, avg, total,max,min = median(vals), mean(vals), len(vals),max(vals),min(vals)
print("median = " + str(med))
print("mean = " + str(avg))
print("sequences = " + str(total))
print("Max Length = " + str(max))
print("Min Length = " + str(min)) |
import json
JSONDATA = None
with open('base.json') as f:
JSONDATA = json.load(f)
origen = input("Nombre de la carpeta donde se busca el archivo: ")
destino = input("Nombre del archivo: ")
ruta=[]
def buscar(inicio,valor):
ruta.append(inicio)
if inicio==valor:
return valor
for i,v in JSONDATA['carpetas'].items():
if v==inicio:
resultado=buscar(i,valor)
if resultado:
return resultado
ruta.pop()
return 0
resultado=buscar(origen,destino)
if resultado:
print(ruta)
else:
print("Archivo no encontrado")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
def prepare():
cnt = 10
return [randint(0, cnt) for _ in range(cnt)]
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
# compare avg O(N^2) best O(N) worst O(N^2)
# swap avg O(N^2) best O(0) worst O(N^2)
def insertion_sort(arr):
length = len(arr)
for i in range(1, length):
for j in range(i, 0, -1):
if arr[j] < arr[j - 1]:
swap(arr, j - 1, j)
else:
break
def main():
arr = prepare()
print arr
insertion_sort(arr)
print arr
if __name__ == '__main__':
main()
|
name = input("What is your name?")
quest = input("What is your quest?")
color = input("What is your favorite color?")
print("poop")
print ("Ah, so your name is %s, your quest is %s, ")
print ("and your favorite color is %s." % (str(name), str(quest), str(color))
|
def Solution(put):
cities = list(range(len(put)))
solution = []
for i in range(len(put)):
CityA = cities[0]
solution.append(CityA)
cities.remove(CityA)
return solution
def routeLength(put, solution):
routeLength = 0
for i in range(len(solution)):
routeLength += put[solution[i - 1]][solution[i]]
return routeLength
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def getBestNeighbour(put, neighbours):
bestRouteLength = routeLength(put, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(put, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength
def hillClimbing(put):
currentSolution = Solution(put)
currentRouteLength = routeLength(put, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(put, neighbours)
while bestNeighbourRouteLength < currentRouteLength:
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(put, neighbours)
print("\nNajbolja ruta: ", currentSolution)
print("Cena: ", currentRouteLength)
def main():
put = [
[0, 7, 6, 10, 13],
[7, 0, 7, 10, 10],
[6, 7, 0, 8, 9],
[10, 10, 8, 0, 6],
[13, 10, 9, 6, 0]
]
print("Optimizacija puta trgovca: ", put)
hillClimbing(put)
if __name__ == "__main__":
main()
|
a = input("your name : ")
print("hello "+a+"!")
|
import numpy as np
class Reflection:
"""
Class for calculating the reflection of vector a, through the orthogonal matrix of vector v
"""
def __init__(self,v):
"""
Define the vector v
"""
self.v = v
def __mul__(self, a):
"""
Calculate the matrix product for the reflection through the plane with matrix H
"""
gamma = ((np.linalg.norm(self.v))**2)/2
vvtrans = self.v * np.transpose(self.v)
H = np.identity((len(self.v))) - (vvtrans/gamma)
reflection = np.dot( H, a)
return(reflection)
|
print("hello world")
print("/_____|")
print("/_____|")
print("/_____|")
print("/_____|")
Person_name = "John Doe"
Person_income = "4"
print(Person_name + " is a fine man with several income sources, " + Person_income + " of which comes from IT")
person_name = "Habeeb Hand"
# person_Income = "44";
person_Income = 4
# is_right = True
print("here is another man, you mean " + person_name + " with " + str(person_Income) + " sources of income from IT??")
# string manipulation
print("let\"s")
first_String = "Machine Learning ENGINEER"
print(first_String)
print(first_String.upper())
print(first_String.islower())
print(first_String.lower().islower())
print(len(first_String))
print(len('first_String'))
print(first_String[24])
print('first_String'[4])
print(first_String.index("l".upper()))
print(first_String.replace("Machine Learning", "AI"))
print(first_String.replace(" ", " TEST -- SEE "))
print(first_String.replace("e", "y"))
# number manipulation
print("2")
print(+2)
print(-2.2142058)
print(14 - 4.8822)
print(2 * 50 + 41)
my_Num = 14
print(my_Num % 3)
boyAge = -5
print("Boy is " + str(boyAge))
print(pow(5, 3))
print(abs(boyAge))
print(max(45,785), min(822,759,522,4878))
from math import *
print(floor(2.998))
print(ceil(2.221))
print(sqrt(144))
# getting user input
# name = input("Enter your name: ")
# age = input("How old are you? ")
# print("Hello " + name +". What does been " + age + " feels like?")
# number1 = int(input("Enter the first number: "))
# number2 = int(input("Enter the second number: "))
# print(number1 + number2)
# number1 = float(input("Enter the first number: "))
# number2 = float(input("Enter the second number: "))
# print(number1 + number2)
# mad libs game
# color = input("Enter your fav. color: ")
# color = color.replace(color[0], "\"" + color[0].upper()) + "\""
# # color[1] = color[1].upper()
# SOF = input("Enter your state of origin: ")
# SOF = SOF.replace(SOF[0], "*" + SOF[0].upper()) + "*"
# print("You seem to like " + color + ". You must be from " + SOF + ". Right?")
# lists
friends = ["Habeeb", "Ade", "Arnold", 1, False, "Tope", "Khair"]
print(friends[2], friends[-2], friends[-1], friends[2:], friends[2: 5])
friends[2] = "Billal Bn Rabba"
family = ["Abu", "Ummuh", "Taiye", "Kenny"]
# list functions
family.extend(friends)
print(family)
friends.append("Idris")
friends.insert(2, "Barakat")
friends.insert(2, ("Barakat","Aisha"))
print(friends)
friends.remove("Habeeb")
# friends.clear()
print(friends)
friends.pop()
print(friends)
print(friends.index("Ade"))
family.append(77)
print(family, family.index(77), friends.count("Barakat"))
numbers = [788, 0, 895, 89, 7823, 12, 13, 14, 25]
# numbers.sort()
numbers.reverse()
print(numbers)
# friends.sort()
friends.reverse()
print(friends)
# friends = ["Tade", "Bayo", "Tobi"]
print(friends)
friendsTwo = friends.copy()
print(friendsTwo)
# Tuples
priorities = ("Deen", "success")
# priorities[1] = "good" // throws error. tuple not mutable
priorities1 = ["anything else?", (74, "boy"), (7, 110)]
priorities1[2] = (744, "boy")
print(priorities1)
# function
def say_hello(user, age):
return ("Hello " + user + ". You're " + str(age) + ".")
# print("Hello " + user + ". You're " + str(age) + ".")
# say_hello("Tolani") // throws error because argument is not 2
print(say_hello("OlohunTower", 74))
# say_hello("OluwaTowa", "20")
def cube_number(num):
# return pow(num, 3)
return num * num * num
print(cube_number(3))
# if statement
# numb1 = int(input("Enter a number: "))
# numb2 = int(input("Enter a number: "))
# if numb1 > 0 and numb2 > 0:
# print(str(numb1) + " and " + str(numb2) + " are positive numbers.")
# elif numb1 > 0 or numb2 > 0:
# print("Either " + str(numb1) + " or " + str(numb2) + " is a positive number.")
# elif numb1 > 0 and numb2 < 0:
# print(str(numb1) + " is a positive number while " + str(numb2) + " is a negative number.")
# elif numb1 < 0 and numb2 > 0:
# print(str(numb1) + " is a negative number while " + str(numb2) + " is a positive number.")
# elif not(numb1 > 0 or numb2 > 0):
# print(str(numb1) + " and " + str(numb2) + " are negative numbers.")
def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num3 and num2 > num3:
return num2
else:
return num3
print(max_num(40, 58, 99))
# calculator
# first_num = int(input("Enter your first number: "))
# second_num = int(input("Enter your second number: "))
# ope = input("Enter your operator: ")
# def calculator(fnum1, ope, fnum2):
# if ope == "+":
# return fnum1 + fnum2
# elif ope == "-":
# return fnum1 - fnum2
# elif ope == "/":
# return fnum1 / fnum2
# elif ope == "*":
# return fnum1 * fnum2
# else:
# return "Operator is invalid"
# print(calculator(first_num, ope, second_num))
# Dictionaries
first_dico = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
'Jany': "April",
# LaFamilia: "babe", //error because a string has to be defined with a parentheses
True : "Yes",
45: "na no",
}
print(first_dico["Jany"])
print(first_dico.get("mar"))
print(first_dico.get("mar", "This key is not existent on this dictionary! Please check your spelling or include it in the dictionary with the value to assess its value."))
print(first_dico[45])
print(first_dico.get(True))
# while loop
i = 1
while i < 5:
print(i)
i += 1
# Guess Game
# guess_word = "cat"
# user_input = ""
# while user_input != guess_word:
# user_input = input("enter what you think the guess word is: ")
# print("Yaay, you guessed right. The guess word is " + user_input)
#
the_guess_word = "Jannah"
user_guess = ""
guess_count = 0
guess_status = False
# while user_guess != the_guess_word and not(guess_status):
# if guess_count != 3:
# user_guess = input("enter what you think the guess word is: ")
# guess_count += 1
# else:
# guess_status = True
# if guess_status:
# print("You just ran out of guesses dear!")
# print("Try again later!")
# else:
# print("Yaay, you guessed right. The guess word is " + user_guess)
# print("You win!")
# For Loop
for j in "JANNAH":
print(j)
for i in range(4):
print(i)
states = ["Kwara", "Lagos", "Kaduna"]
for state in range(len(states)):
print(states[state])
for i in range(3, 9):
print(i)
for state in range(3):
if state == 0:
print("This is the first state in the lits. Looks like you are from here. The state is " + states[state])
else:
print(states[state] + ": Other states")
# exponential function
print(2**3)
def power_num(base, power):
result = 1
for i in range(power):
result = result*base
return result
print(power_num(2, 4))
# nested List
nested_num = [
[4, 8],
[7, 9, 81],
[0]
]
for i in nested_num:
for j in i:
# for k in j:
print(j)
# vowel translator
def translate(phrase):
phrase = phrase.lower()
vowel = "aeiou"
translated = ""
for i in phrase:
if i in "aeiou":
translated += "g"
else:
translated += i
return translated.replace(translated[0], translated[0].upper())
# print(translate(input("Enter a phrase: ")))
# number = int(input("enter a number: "))
# print(number)
# print(10/0)
try:
value = 10/0
number = int(input("enter a number: "))
print(number)
except ValueError as error:
print(error)
except ZeroDivisionError:
print("not divisle by 0")
guess_word = "cat"
user_input = ""
# while user_input != guess_word:
# user_input = input("enter what you think the guess word is: ")
# print(user_input)
# print("Yaay, you guessed right. The guess word is " + user_input)
myName = "Abass"
userGuess = ""
userGuessCount = 0
userGuessStatus = True
while userGuess != myName and userGuessStatus:
if(userGuessCount != 3):
# userGuess = input("Enter what you think my name is: ")
# userGuessFirstLetter = userGuess[0].upper() //this converts the first letter of the user input into a capital letter.
# userGuess = userGuess.replace(userGuess[0], userGuess[0].upper()) // I'm trying to convert only the first letter to a capital letter here. the replace method converts the first letter in all places where it occurs. I believe a "splice or slice" method would work fine here.
print(userGuess)
userGuessCount +=1
else:
userGuessStatus = False
# if userGuess == myName:
# print("Heyy! You got the name right. You Win!")
# else:
# print("You ran out of guess count. Sorry, You lose.")
# Reading the contents of a file
fileUsage = open("test.txt", "r+")
print(fileUsage.writable())
print(fileUsage.readable())
# print(fileUsage.readlines()[9])
# print(len(fileUsage.readlines())) // not understood, how can be length of a non-empty list be returning zero.
for i in fileUsage.readlines():
print(i)
# print(fileUsage.read())
# print(fileUsage.readline())
fileUsage.close()
# Adding to the contents of a file --- writing a file
# fileUsage2 = open("test.txt2", "w")
fileUsage2 = open("test.txt2", "a")
print(fileUsage2.write("\nThis is a new line added to the file through the append mode with the line break character."))
fileUsage2.write("<h1>Let's convert all to a one line word. </h1>")
fileUsage3 = open("test.html", "w")
# fileUsage3.write("<h1>Welcome to the HTML zone. </h1>")
# fileUsage3.write("<h1>Welcome Back to the HTML zone. </h1>")
# overwriting the contents of a file.
fileUsage3.write("Well, is anything still here")
fileUsage3.close()
# classes and objects
from student import Student
student1 = Student("Abass", 25, "male", False)
student2 = Student("Salmah", 20, "female", True)
print(student1.age)
print(student2.name)
# multiple choice quiz
from Question import Question
question_prompts = [
"what colors are apples?? \n (a) Red \n (b) Grey \n (c) Yellow \n (d) Indigo \n \n",
"what colors are bananas?? \n (a) Red \n (b) Green \n (c) Yellow \n (d) Indigo \n \n",
"what colors are berries?? \n (a) Red \n (b) Blue \n (c) Yellow \n (d) Indigo \n \n"
]
questions = [
Question(question_prompts[0], "a"),
Question(question_prompts[1], "b"),
Question(question_prompts[2], "a")
]
def askQuestion(questions):
score = 0
for i in questions:
userAnswer = input(i.prompt)
if userAnswer == i.answer:
score += 1
print("You got " + str(score) + " out of " + str(len(questions)) + " right.")
askQuestion(questions) |
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import math
def productabc():
for x in range(math.ceil(math.sqrt(250)), math.ceil(math.sqrt(500))):
if (500-x*x)%x == 0:
n = x
m = (500-x*x)//x
break
return 2*m*n*(n**4-m**4)
print(productabc()) |
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def nthPrime(n):
x = 1
primes = []
while(len(primes) < n):
x += 1
for y in primes:
if x % y == 0:
break
else:
primes.append(x)
return x
print(nthPrime(10001)) |
#! python3
# Creating a circular queue
def ArrayQueue():
DEFAULT_SIZE = 10
def __init__(self):
self._data = [None]*DEFAULT_SIZE
self._size = 0
self._front = 0
def __len__(self):
return len(self._data)
def is_empty(self):
return self._data == 0
def first(self):
if self.is_empty():
raise Empty("The queue is empty")
else:
return self._first
def dequeue(self):
if self.is_empty():
raise Empty("The queue is empty")
else:
answer = self._data[self._front]
self._data[self._front] = None
self._front = (self._front+1)%len(self._data)
self._size -= 1
return answer
# This is used in case the array is full and we'd like to add another element to dequeue
def resize(self,cap):
old = self._data
self._data = [None]*cap
walk = self._front
for i in range(self._size):
self._data[i] = old[walk]
walk = (walk + 1)/len(old)
self._front = 0
def enqueue(self,e):
if(self._size == len(self._data)):
self._resize(2*len(self._data))
avail = (self._front + self._size)%len(self._data)
self._data[avail] = e
self._size += 1
|
#! python3
class PositionalList(_DoubleLL):
class Position:
def __init__(self,container,node): # What's a container
self._container = container
self._node = node
def element(self):
return self._node._element
def __eq__(self,other):
return self._node is other._node and type(self) is type(other)
def __ne__(self,other):
return not(self == other)
def _validate(self,p):
if not isinstance(p,self.Position):
raise TypeError("p must be proper type!!")
if p._container is not self:
raise ValueError("p does not belong to this container")
if p._node._next is None:
raise ValueError("p is not valid anymore")
return p._node
def _make_position(self,node):
if node is self._trailer or node is self._header:
return None
else:
return self.Position(self,node)
# Note - This will return the position of the first element, NOT the element
def first(self):
return self._make_position(self._header._next)
def last(self):
return self._make_position(self._trailer._prev)
def before(self,p):
node = self._validate(p)
return self._make_position(node._prev)
def after(self,p):
node = self._validate(p)
return self._make_position(node._next)
def __iter__(self):
cursor = self.first()
while cursor is not None:
yield cursor.element()
cursor = self.after(cursor)
def _insert_between(self,e,predacessor,successor):
node = super()._insert_between(e,predacessor,successor)
return self._make_position(node)
def _add_first(self,e):
return self._insert_between(e,self._header,self._header._next)
def _add_last(self,e):
return self._insert_between(e,self._trailer._prev,self._trailer)
def _add_after(self,p,e):
valid = self._validate(p)
return self._insert_between(e,valid,valid._next)
def _add_before(self,p,e):
valid = self._validate(p)
return self._insert_between(e,valid._prev,valid)
def delete(self,p):
valid = self._validate(p)
return self._delete_node(valid)
def replace(self,p,e):
valid = self._validate(p)
if valid:
if valid.element() == e:
return "The element is the same"
else:
old = valid.element()
valid._element = r
return old
|
__author__ = 'adm'
from datetime import *
import time
class TimeCounter:
def get_zero_year(self, seconds):
current_year = datetime.now().year
one_year_in_seconds = 365*24*60*60
years_passed = int(seconds / one_year_in_seconds)
zero_year = current_year - years_passed
return zero_year
def my_get_zero_year(self, seconds_from_zero):
return (datetime.now() - timedelta(seconds=seconds_from_zero)).year
counter = TimeCounter()
seconds = time.time()
zero_year = counter.get_zero_year(seconds)
print(zero_year)
|
#!/usr/bin/env python
# coding: utf-8
"""
author -- ToxaZ
Couresera Machine Learning Introduction 2nd week assignement
1 - https://www.coursera.org/learn/vvedenie-mashinnoe-obuchenie/programming/u08ys/priedobrabotka-dannykh-v-pandas
2 - https://www.coursera.org/learn/vvedenie-mashinnoe-obuchenie/programming/DVbEI/vazhnost-priznakov
"""
import pandas as pd
import numpy as np
from utils import write_submission
from sklearn.tree import DecisionTreeClassifier
def pandas_assignment():
data = pd.read_csv('data/titanic.csv', index_col='PassengerId')
subm11 = data['Sex'].value_counts()
write_submission(
' '.join([str(x) for x in subm11]),
'11')
write_submission(
int(data['Survived'].value_counts(normalize=True).to_dict()[1]*100),
'12')
write_submission(
int(data['Pclass'].value_counts(normalize=True).to_dict()[1]*100),
'13')
subm14 = []
subm14.append(round(float(data['Age'].mean()), 1))
subm14.append(int(data['Age'].median()))
write_submission(
' '.join([str(x) for x in subm14]),
'14')
write_submission(
round(data.corr('pearson')['SibSp']['Parch'], 2),
'15')
write_submission(
data['Name'].str.extract('(Miss\. |Mrs\.[A-Za-z ]*\()([A-Za-z]*)')[1]
.value_counts().head(n=1).to_string()
.split(' ', 1)[0],
'16')
def trees_assignment():
data = pd.read_csv('data/titanic.csv', index_col='PassengerId')
data21 = data.dropna(subset=['Pclass', 'Fare', 'Age', 'Survived', 'Sex'])
pd.options.mode.chained_assignment = None # suppress false positive warn
data21['Sex'] = data21['Sex'].map({'female': 0, 'male': 1})
pd.options.mode.chained_assignment = 'warn' # turning warn back
feature_names = ['Pclass', 'Fare', 'Age', 'Sex']
X = data21[feature_names]
y = data21[['Survived']]
clf = DecisionTreeClassifier(random_state=241)
clf.fit(X, y)
importances = clf.feature_importances_
indices = np.argsort(importances)[::-1]
subm21 = [feature_names[f] for f in indices][:2]
write_submission([x for x in subm21], '21')
def main():
pandas_assignment()
trees_assignment()
if __name__ == '__main__':
main()
|
import json
f = open('org.json')
data = json.load(f)
x = input()
target1= x
y = input()
target2 = y
p1=[]
#recursive function to find parent
def find_p(e1):
for element in reversed(data):
#print(data[element])
li=data[element]
print(li)
# print(li[0]['name'])
for item in range(len(li)):
if(li[item]['name'] == e1):
if(li[item].get('parent') != None):
x=li[item]['parent']
p1.append(x)
else:
return
find_p(x)
find_p(x)
mylist1=p1
p1=[]
find_p(y)
mylist2=p1
print(mylist1)
print(mylist2)
flag =0
for i in range(0,len(mylist1)):
for j in range(0,len(mylist2)):
if mylist1[i] == mylist2[j]:
print(mylist1[i])
print("leader "+str(mylist1[i])+" is "+str(i+1)+" level(s) above from " + str(target1))
print("leader "+str(mylist2[j])+" is "+str(j+1)+" level(s) above from " + str(target2))
flag = 1
break
if flag==1:
break
if flag == 0:
print("leader not found")
f.close() |
#REFERENCE
# SLIDES: http://www.cs.jhu.edu/~langmea/resources/lecture_notes/hidden_markov_models.pdf
# SOURCE CODE: https://nbviewer.jupyter.org/gist/BenLangmead/7460513
import numpy as np
import math
class HMM(object):
''' Simple Hidden Markov Model implementation. User provides
transition, emission and initial probabilities in dictionaries
mapping 2-character codes onto floating-point probabilities
for those table entries. States and emissions are represented
with single characters. Emission symbols comes from a finite. '''
def __init__(self, A, E, I):
''' Initialize the HMM given transition, emission and initial
probability tables. '''
# put state labels to the set self.Q
self.Q, self.S = set(), set() # states and symbols
for a, prob in A.items():
asrc, adst = a.split('|')
self.Q.add(asrc)
self.Q.add(adst)
# add all the symbols to the set self.S
for e, prob in E.items():
eq, es = e.split('|')
self.Q.add(eq)
self.S.add(es)
self.Q = sorted(list(self.Q))
self.S = sorted(list(self.S))
# create maps from state labels / emission symbols to integers
# that function as unique IDs
qmap, smap = {}, {}
for i in range(len(self.Q)): qmap[self.Q[i]] = i
for i in range(len(self.S)): smap[self.S[i]] = i
lenq = len(self.Q)
# create and populate transition probability matrix
self.A = np.zeros(shape=(lenq, lenq), dtype=float)
for a, prob in A.items():
asrc, adst = a.split('|')
self.A[qmap[asrc], qmap[adst]] = prob
# make A stochastic (i.e. make rows add to 1)
self.A /= self.A.sum(axis=1)[:, np.newaxis]
# create and populate emission probability matrix
self.E = np.zeros(shape=(lenq, len(self.S)), dtype=float)
for e, prob in E.items():
eq, es = e.split('|')
self.E[qmap[eq], smap[es]] = prob
# make E stochastic (i.e. make rows add to 1)
self.E /= self.E.sum(axis=1)[:, np.newaxis]
# initial probabilities
self.I = [ 0.0 ] * len(self.Q)
for a, prob in I.items():
self.I[qmap[a]] = prob
# make I stochastic (i.e. adds to 1)
self.I = np.divide(self.I, sum(self.I))
self.qmap, self.smap = qmap, smap
def viterbi(self, x):
''' Given sequence of emissions, return the most probable path
along with its probability. '''
x = list(map(self.smap.get, x)) # turn emission characters into ids
nrow, ncol = len(self.Q), len(x)
mat = np.zeros(shape=(nrow, ncol), dtype=float) # prob
matTb = np.zeros(shape=(nrow, ncol), dtype=int) # backtrace
# Fill in first column
for i in range(0, nrow):
mat[i, 0] = self.E[i, x[0]] * self.I[i]
# Fill in rest of prob and Tb tables
for j in range(1, ncol):
for i in range(0, nrow):
ep = self.E[i, x[j]]
mx, mxi = mat[0, j-1] * self.A[0, i] * ep, 0
for i2 in range(1, nrow):
pr = mat[i2, j-1] * self.A[i2, i] * ep
if pr > mx:
mx, mxi = pr, i2
mat[i, j], matTb[i, j] = mx, mxi
# Find final state with maximal probability
omx, omxi = mat[0, ncol-1], 0
for i in range(1, nrow):
if mat[i, ncol-1] > omx:
omx, omxi = mat[i, ncol-1], i
# Backtrace
i, p = omxi, [omxi]
for j in range(ncol-1, 0, -1):
i = matTb[i, j]
p.append(i)
p = ''.join(map(lambda x: self.Q[x], p[::-1]))
return omx, p # Return probability and path
def main():
#Feed in transition, emission, and intiail probabilities
hmm = HMM({"F|F":0.9, "F|L":0.1, "L|F":0.1, "L|L":0.9}, # transition matrix A
{"F|H":0.5, "F|T":0.4, "L|H":0.75, "L|T":0.15}, # emission matrix E
{"F":0.5, "L":0.5}) # initial probabilities I
# Now we experiment with viterbi decoding
obs_heads_tails = "TTTTTHHHHHTTTHHHHHTHTHTHHHHHHHH"
print("Heads/Tails observations: ", obs_heads_tails, '\n')
jprobOpt, path = hmm.viterbi(obs_heads_tails)
print("Best path probability: ", jprobOpt, '\n')
print("Best path: ", path, '\n')
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
import sys
for line in open(sys.argv[1]):
if line[0]==">":
name=line.strip()
else:
l = len(line.strip())
if l >= int(sys.argv[2]):
print(name)
print(line.strip())
|
# How much longer am I expected to live, given my sex, age, and country?
import requests
import csv
import datetime
import math
# PARAMETERS:
# sex
sex = ['male', 'female']
# country
c_url = 'http://api.population.io:80/1.0/countries' # get the available list of countries
c = requests.get(c_url)
c_list = c.json()
c_available = c_list['countries']
country = input('Country? Preferably its official name, and in proper English. ') # get user's input
if country not in c_available:
for each in c_available:
print(each)
country = input('Sorry, what you typed is invalid. :/ Here is a list of the available countries, with, hopefully, the correct version of your country on there. Either you misspelled, did not capitalize properly, forgot the official name of your country, or you live in a smaller country. Try again. ')
# age
age = []
for num in range(81):
age.append(str(num) + 'y')
# date
date = str(datetime.date.today())
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# FUNCTION TO CONVERT FROM YEARS DECIMAL TO 'YEARS, MONTHS, DAYS':
# set empty variable
life_expectancy = 'blah'
# define function
def years(remaining):
global life_expectancy
rem = float(remaining) # convert 'remaining' to a float
year = math.floor(rem) # number of full years
m = (rem - year) * 12 # months left over
month = math.floor(m) # number of full months
d = (m - month) * 30.4375 # days left over (30.4375 is the average number of days per month)
day = math.floor(d) # number of full days
life_expectancy = str(year) + ' years, ' + str(month) + ' months, ' + str(day) + ' days'
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# FUNCTION FOR THE REMAINING LIFE API:
# set empty variable
remaining = 'blah'
# define function
def api():
global remaining
endpoint = 'http://api.population.io:80/1.0/life-expectancy/remaining/' # remaining lifetime api
url = endpoint + s + '/' + country + '/' + date + '/' + a
r = requests.get(url)
stats = r.json()
remaining = stats['remaining_life_expectancy']
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# CSV:
# new csv file
lifechart = open('lifechart.csv', 'w', newline='')
# create the writer
w = csv.writer(lifechart, delimiter=',')
# write to the file
w.writerow(['age', 'sex', 'life remaining'])
for a in age:
for s in sex:
api() # call api function for remaining life expectancy
years(remaining) # call years converter function
w.writerow([a, s, life_expectancy]) # write 'age', 'sex', and 'remaining life expectancy' to the file
# close file
lifechart.close() |
def main():
# Numerical datatype
# whole number - int - integer
value = 13
number = 7
# float = decimal number
float_value = 4.20
# str - strings
name = "Emma"
other_name = "Mary"
# complex number
# logical datatype
# Boolean - bool
done = False
run = True
# sequence types
# list
# list mutable - can be changed
values = [1, 2, 3, 4, 5, 6, 77]
values.pop(6)
values.sort()
names = ['sara', 'mia', 'maria']
things = [1, 'mia', 3, 'Samir']
print(things[1])
list_of_lists = [
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9],
[10, 11, 12]
]
]
print(list_of_lists[1])
print(list_of_lists[0][1][2])
# Tuple constant content
# Tuple immutable = can't be changed
numbers = (1, 2, 3)
print(numbers[2])
# Set
# mutable and was unordered until version 3.6 and can still be unordered don't expect order
# can only store unique values
set_values = {1, 2, 3, 4, 1, 2, 3}
more_values = {2, 3, 7, 9}
list_values = [13, 22, 42, 43, 42, 39]
unique_values = list(set(list_values))
print(set_values.intersection(more_values))
print(list_values)
print(unique_values)
# ascii and unicode
# mapping type
# dictionary - dict
# keys in dictionary are unique
# one can make a list of multiple dictionaries
person = {"Name": "Emma Jarlvi Skog", "Age": 31, "Email": "[email protected]"}
print(person["Email"])
print(person["Age"])
if __name__ == '__main__':
main()
|
try:
name = input("Insira o nome do produto: ")
qunt = int(input("Insira a quantidade comprada: "))
value = float(input("Insira o valor da unidade: "))
percent = float(input("Insira a porcentagem do desconto (entre 0 e 100): "))
print("Você comprou %s e gastou R$%.2f " % (name, qunt*value*(percent/100)))
except ValueError:
print("Os valores requisitados não conseguiram ser convertidos! Tente novamente!")
|
num = input("Insira o número: ")
count = 0
for char in num:
count+= 1
print("O número tem %d dígitos" %(count))
|
num = int(input("Insira o número: "))
actual = 0
previous = 0
result = ''
count = 0
while(count != num+1 ):
if count == 0:
result +=str(actual+previous)+' ,'
previous = 0
actual = 1
elif count == 1:
result +=str(actual+previous)+' ,'
else:
result += str(actual+previous)+", "
temp = previous
previous = actual
actual = actual+temp
count+=1
print(result) |
p = tuple(map(float, input("Insira as coordenadas do ponto: ").split()))
if p[0] * p[1] > 0:
if p[0] > 0:
print("Primeiro quadrante " + str(p[0]) + " " + str(p[1]))
else:
print("Terceiro quadrante " + str(p[0]) + " " + str(p[1]))
elif p[0] * p[1] < 0:
if p[0] < 0:
print("Segundo quadrante " + str(p[0]) + " " + str(p[1]))
else:
print("Quarto quadrante " + str(p[0]) + " " + str(p[1]))
else:
if p[0] == 0 == p[1]:
print("0 " + str(p[0]) + " " + str(p[1]))
else:
print("-1 " + str(p[0]) + " " + str(p[1]))
|
class GeneralizationTreeNode:
def __init__(self, value):
self.father = None
self.level = 0
self.value = value
self.son = None
self.bro = None
self.tree_height = None
def search_node_value(self, value):
node = None
if value == self.value:
node = self
if node is None and self.son is not None:
node = self.son.search_node_value(value)
if node is None and self.bro is not None:
node = self.bro.search_node_value(value)
return node
def __add_son__(self, son_node):
if self.son is None:
self.son = son_node
return
if self.son.value == son_node.value:
raise Exception("[!!] A node with value {} at this level already exists".format(node.value))
node = self
while node.bro is not None:
if node.value == son_node.value or node.bro.value == son_node.value:
raise Exception("[!!] A node with value {} at this level already exists".format(node.value))
node = node.bro
node.bro = son_node
def add_son(self, father_value, value):
father = self.search_node_value(father_value)
if father is None:
raise Exception("[--] Cannot use this node as father: a node with value {} doesn't exists".format(father_value))
new_son = GeneralizationTreeNode(value)
new_son.father = father
new_son.level = father.level + 1
father.__add_son__(new_son)
def __height__(self):
if self.son is None and self.bro is None:
return 1
if self.son is not None:
return 1 + self.son.height()
if self.bro is not None:
return 1 + self.bro.height()
def height(self):
if self.tree_height is None:
self.tree_height = self.__height__()
return self.tree_height
def __generalize__(self):
if self.father is None:
return self.value
return self.father.value
def generalize(self, value, level=None):
result = None
if self.value == value and (level is None or level == self.level):
result = self.__generalize__()
if result is None and self.son is not None:
result = self.son.generalize(value,level)
if result is None and self.bro is not None:
result = self.bro.generalize(value,level)
return result
def print_tree(self):
print("[--] (lvl: {}\t value: {})".format(self.level, self.value))
if self.son is not None:
self.son.print_tree()
if self.bro is not None:
self.bro.print_tree()
|
## Adapted from http://scikit-learn.org/stable/auto_examples/plot_learning_curve.html
import matplotlib.pyplot as plt
from sklearn.learning_curve import learning_curve
import numpy as np
def graphLearningCurves(forest, X, y):
# assume classifier and training data is prepared...
train_sizes, train_scores, test_scores = learning_curve(
forest, X, y, cv=10, n_jobs=-1, train_sizes=np.linspace(.1, 1., 5), verbose=0)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.figure()
plt.title("RandomForestClassifier")
plt.legend(loc="best")
plt.xlabel("Training examples")
plt.ylabel("Score")
plt.ylim((0.6, 1.01))
plt.gca().invert_yaxis()
plt.grid()
# Plot the average training and test score lines at each training set size
plt.plot(train_sizes, train_scores_mean, 'o-', color="b", label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="Test score")
# Plot the std deviation as a transparent range at each training set size
plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
alpha=0.1, color="b")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
alpha=0.1, color="r")
# Draw the plot and reset the y-axis
plt.draw()
plt.show()
plt.gca().invert_yaxis() |
import algorithm
spc_to_name = 37
spc_to_sent = 25
script_name = "shrek.txt"
subs_name = "shreksubs.txt"
num_of_max = 3
num_of_min = 3
# Functions done on TXT files (srt and script) preparing for analysing
algorithm.script_clean(script_name, spc_to_name, spc_to_sent)
algorithm.clean_subtitles(subs_name)
algorithm.creating_files_for_compare("clean_subtitles.txt", "clean_script.txt", spc_to_name)
# Functions done on CSV files or create a CSV file
algorithm.csv_two_clks("clean_script.txt", spc_to_name, spc_to_sent)
algorithm.extract_clks("mycsv.csv")
algorithm.normal_clks("clks.csv")
# Functions used to analyze the data
normal_critical_word_list = algorithm.derivative_and_find_index("n_clks.csv", num_of_max, num_of_min)
srt_sentence_index = algorithm.find_word_index_with_matching_sequences\
(normal_critical_word_list, "comparison_script.txt", "comparison_srt_1.txt")
critical_ts_list = algorithm.find_ts_with_word_index(srt_sentence_index, "clean_subtitles.txt")
print(len(critical_ts_list)) # The number of matches we found in the SRT
algorithm.similarity_srt_script("comparison_script.txt", "comparison_srt_1.txt")
algorithm.graph_plot("n_clks.csv")
|
def fib(n):
if n < 2:
return n
else:
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b
def fib_big(n):
n = n % 60
print(fib(n) % 10)
n = int(input())
fib_big(n)
|
HIGHEST_NUMBER = 1000
def isprime(number):
#print "Checking isprime() for:", number
if number < 1:
return False
for i in range(2,number):
if number%i == 0:
return False
return True
for number in reversed(range(1,HIGHEST_NUMBER+1)):
#print "Current number is: ", number
if isprime(number):
number_string = str(number)
reversed_number_string = number_string[::-1]
if number_string == reversed_number_string:
print number_string
break
|
import os
import csv
election_data = os.path.join("..","Python-challenge","PyPoll","Resources","election_data.csv")
#csvpath = os.path.join("\\Users\\Propietario\\Desktop\\TASKS_SGL\\Python\\Python-challenge\\PyPoll\\Resources\\election_data.csv")
#In addition, your final script should both print the analysis to the terminal and export a text file.
output_txt = os.path.join("..","Python-challenge","PyPoll","output.txt")
# Defining lists and initiate the counter of the total votes
candidates = []
numbervotes = []
percentagev = []
totalvotes = 0
# Open the CSV and read the CSV
with open(election_data) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for x in csvreader:
#Total number of votes
totalvotes += 1
#If the candidate is not in the list, then add the new name in the new list with his/her vote, if not just sum..
#..the vote to the same name.
if x[2] not in candidates:
#Generate the new list
candidates.append(x[2])
index = candidates.index(x[2])
numbervotes.append(1)
else:
index = candidates.index(x[2])
numbervotes[index] += 1
# Add to percentagev list
for y in numbervotes:
percentage = (y/totalvotes) * 100
percentage = "%.3f%%" % percentage
#Generate a new list
percentagev.append(percentage)
# Find the winning candidate
winner = max(numbervotes)
index = numbervotes.index(winner)
wincandidate = candidates[index]
# Displaying results
print("Election Results")
print("--------------------------")
print(f"Total Votes: {str(totalvotes)}")
print("--------------------------")
for i in range(len(candidates)):
print(f"{candidates[i]}: {str(percentagev[i])} ({str(numbervotes[i])})")
print("--------------------------")
print(f"Winner: {wincandidate}")
print("--------------------------")
#In addition, your final script should both print the analysis to the terminal and export a text file.
# write to text file
text_file = open(output_txt, "w")
text_file.write("--------------------------")
text_file.write("\nElection Results")
text_file.write("\n--------------------------")
text_file.write(f"\nTotal Votes: {str(totalvotes)}")
text_file.write("\n--------------------------")
for i in range(len(candidates)):
text_file.write(f"\n {candidates[i]}: {str(percentagev[i])} ({str(numbervotes[i])})")
text_file.write("\n--------------------------")
text_file.write(f"\nWinner: {wincandidate}")
text_file.write("\n--------------------------")
text_file.close()
|
#DSC 510
#Week 10
#Final Project
#Author Tiffany Tesoro
#08/09/2020
#TO USE API TO GET DATA
import json
import requests
#Use the Requests library in order to request data from the webservice.
#DEFINE USER_INPUT FUNCTION
def user_input():
print()
#Create a Python Application which asks the user for their zip code or city.
#originally had separate functions for user to choose from current weather OR 5-day weather AND
#city OR zipcode search, but found it easier to combine the two questions into one function
while True:
forecast_type = input('Please input one of the following numbers then press enter: \n'
'1 - search for CURRENT weather forecast by zip code \n'
'2 - search for CURRENT weather forecast by city \n'
'3 - search for 5-DAY weather forecast by zip code \n'
'4 - search for 5-DAY weather forecast by city \n')
if forecast_type == '1':
#CALL TO ZIP_CURRENT FUNCTION
zip_current()
elif forecast_type == '2':
#CALL TO CITY_CURRENT FUNCTION
city_current()
elif forecast_type == '3':
#CALL TO ZIP_FORECAST FUNCTION
zip_forecast()
elif forecast_type == '4':
#CALL TO CITY_FORECAST FUNCTION
city_forecast()
else:
print('Invalid response. Please try again.')
print()
print()
continue
#DEFINE ANOTHER_INPUT FUNCTION
def another_input():
#Allow the user to run the program multiple times to allow them to look up weather conditions for multiple locations.
while True:
another_selection = input(
'Would you like to look for another weather forecast? Type Y [OR] N then press enter.\n').lower()
if another_selection == 'y':
#CALL TO USER_INPUT FUNCTION
user_input()
elif another_selection == 'n':
#GOODBYE GREETING
print()
print(
'--- Thank you for using the OpenWeather Forecast Application. Have a wonderful day! ---')
exit()
else:
print('Invalid response. Please try again.')
print()
print()
continue
#DEFINE ZIP_CURRENT FUNCTION
#to avoid repetitiveness, most comments are made in zip_current function
#but they are applicable to city_current/zip_forecast/city_forecast too
def zip_current():
print()
#Use the zip code in order to obtain weather forecast data from OpenWeatherMap.
print()
zip_input = input('Type in a zip code then press enter: \n')
#change input to string to append to url
zip_code = str(zip_input)
#base url for search type
zip_current_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' + zip_code + ',us'
while True:
lang_input = input(
'Please type in a preferred language code for display results then press enter - ex. for English put EN [OR] for Spanish put ES: \n').upper()
#Validate whether the user entered valid data. If valid data isn’t presented notify the user.
#language options - if/elif/else statements to ensure question is answered correctly and direct to next step
#for all list items included in program, i found it easier to put it after 'in' instead of a separate variable like lang = ['AF', etc.]
if lang_input in ['AF', 'AL', 'AR', 'BG', 'CA', 'CZ', 'DA', 'DE', 'EL', 'EN', 'EU', 'FA', 'FI', 'FR', 'GL',
'HE', 'HI', 'HR', 'HU', 'ID', 'IT', 'JA', 'KR', 'LA', 'LT', 'MK', 'NO', 'NL', 'PL', 'PT',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'PT_BR', 'RO', 'RU', 'SV', 'SE', 'SK', 'SL', 'SP', 'ES', 'SR', 'TH', 'TR', 'UA', 'UK', 'VI',
'ZH_CN', 'ZH_TW', 'ZU']:
#updates url with added elements
zip_current_url = zip_current_url + '&lang=' + lang_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
#unit options
unit_input = input(
'Please enter a preferred unit, imperial [OR] metric, for display results then press enter: \n').lower()
if unit_input == 'imperial':
zip_current_url = zip_current_url + '&units=' + unit_input
break
elif unit_input == 'metric':
zip_current_url = zip_current_url + '&units=' + unit_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
api_key = '&appid=3da266a93ce5e67bd3cd607043e5863f'
zip_url = zip_current_url + api_key
zip_response = requests.get(zip_url)
#Use try blocks when establishing connections to the webservice. You must print a message to the user indicating whether or not the connection was successful.
data = zip_response.text
parsed = json.loads(data)
try:
#REFERENCE - https://www.geeksforgeeks.org/convert-json-to-dictionary-in-python/
#i tried to use a nested dictionary FOR LOOP to print data but had trouble finding the key-value pairs
#for i in parsed['weather']:
#print("Description:", i['description'])
#description printed correct information, but the others i did not end up figuring out so used a different printing method
#REFERENCE - https://stackoverflow.com/questions/52808939/python-parsing-and-iterating-through-json-data
#in order to get the right keys, i had to run program multiple times til i got the right combination
#might not be the most efficient way, but it was what worked for me
city = parsed['name']
zip_desc = parsed['weather'][0]['description']
zip_temp = parsed['main']['temp']
zip_feel = parsed['main']['feels_like']
zip_min = parsed['main']['temp_min']
zip_max = parsed['main']['temp_max']
zip_humid = parsed['main']['humidity']
zip_cloud = parsed['clouds']['all']
zip_wind = parsed['wind']['speed']
print()
#Display the weather forecast in a readable format to the user.
print('--- Current Weather for ' + city + ' ---')
print('Description: ' + zip_desc)
print('Current Temperature: ' + str(zip_temp))
print('Feels Like: ' + str(zip_feel))
print('Temperature Low: ' + str(zip_min))
print('Temperature High: ' + str(zip_max))
print('Humidity: ' + str(zip_humid))
print('Cloud Cover: ' + str(zip_cloud))
print('Wind speed: ' + str(zip_wind))
print()
print()
# CALL TO ANOTHER_INPUT FUNCTION
another_input()
except ValueError:
print("Zip code not found. Please try again.")
print()
print()
#DEFINE CITY_CURRENT FUNCTION
def city_current():
print()
#Use the city name in order to obtain weather forecast data from OpenWeatherMap.
print()
city_input = input('Type in a city name then press enter - ex. New York: \n').upper()
city_current_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_input
while True:
state_input = input(
'Type in a state code then press enter - ex. FL (if the city is outside of the United States, please type in US for default setting): \n').upper()
if state_input in ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO',
'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR',
'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY', 'US'] :
city_current_url = city_current_url + ',' + state_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
country_input = input('Type in a country code then press enter - ex. FR: \n').upper()
if country_input in ['AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ',
'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BJ', 'BM', 'BT', 'BO', 'BQ', 'BA', 'BW', 'BV',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'CX', 'CC', 'CO', 'KM', 'CD', 'CG', 'CK', 'CR', 'HR', 'CU', 'CW', 'CY', 'CZ', 'CI', 'DK',
'DJ', 'DM', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'SZ', 'ET', 'FK', 'FO', 'FJ', 'FI',
'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GD', 'GP', 'GU',
'GT', 'GG', 'GN', 'GW', 'GY', 'HT', 'HM', 'VA', 'HN', 'HK', 'HU', 'IS', 'IN', 'ID', 'IR',
'IQ', 'IE', 'IM', 'IL', 'IT', 'JM', 'JP', 'JE', 'JO', 'KZ', 'KE', 'KI', 'KP', 'KR', 'KW',
'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MG', 'MW', 'MY', 'MV',
'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'MA',
'MZ', 'MM', 'NA', 'NR', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'NU', 'NF', 'MP', 'NO',
'OM', 'PK', 'PW', 'PS', 'PA', 'PG', 'PY', 'PE', 'PH', 'PN', 'PL', 'PT', 'PR', 'QA', 'MK',
'RO', 'RU', 'RW', 'RE', 'BL', 'SH', 'KN', 'LC', 'MF', 'PM', 'VC', 'WS', 'SM', 'ST', 'SA',
'SN', 'RS', 'SC', 'SL', 'SG', 'SX', 'SK', 'SI', 'SB', 'SO', 'ZA', 'GS', 'SS', 'ES', 'LK',
'SD', 'SR', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'TZ', 'TH', 'TL', 'TG', 'TK', 'TO', 'TT',
'TN', 'TR', 'TM', 'TC', 'TV', 'UG', 'UA', 'AE', 'GB', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE',
'VN', 'VG', 'VI', 'WF', 'EH', 'YE', 'ZM', 'ZW', 'AX'] :
city_current_url = city_current_url + ',' + country_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
lang_input = input(
'Please enter a preferred language code for display results then press enter - ex. for English type EN [OR] for Spanish type in ES: \n').upper()
if lang_input in ['AF', 'AL', 'AR', 'BG', 'CA', 'CZ', 'DA', 'DE', 'EL', 'EN', 'EU', 'FA', 'FI', 'FR', 'GL',
'HE', 'HI', 'HR', 'HU', 'ID', 'IT', 'JA', 'KR', 'LA', 'LT', 'MK', 'NO', 'NL', 'PL', 'PT',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'PT_BR', 'RO', 'RU', 'SV', 'SE', 'SK', 'SL', 'SP', 'ES', 'SR', 'TH', 'TR', 'UA', 'UK', 'VI',
'ZH_CN', 'ZH_TW', 'ZU']:
city_current_url = city_current_url + '&lang=' + lang_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
unit_input = input(
'Please enter a preferred unit, imperial [OR] metric, for display results then press enter: \n').lower()
if unit_input == 'imperial':
city_current_url = city_current_url + '&units=' + unit_input
break
elif unit_input == 'metric':
city_current_url = city_current_url + '&units=' + unit_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
api_key = '&appid=3da266a93ce5e67bd3cd607043e5863f'
city_url = city_current_url + api_key
city_response = requests.get(city_url)
data = city_response.text
parsed = json.loads(data)
try:
city_desc = parsed['weather'][0]['description']
city_temp = parsed['main']['temp']
city_feel = parsed['main']['feels_like']
city_min = parsed['main']['temp_min']
city_max = parsed['main']['temp_max']
city_humid = parsed['main']['humidity']
city_cloud = parsed['clouds']['all']
city_wind = parsed['wind']['speed']
print()
#Display the weather forecast in a readable format to the user.
print('--- Current Weather for ' + city_input + ', ' + state_input + ', ' + country_input + ' ---')
print('Description: ' + city_desc)
print('Current Temperature: ' + str(city_temp))
print('Feels Like: ' + str(city_feel))
print('Temperature Low: ' + str(city_min))
print('Temperature High: ' + str(city_max))
print('Humidity: ' + str(city_humid))
print('Cloud Cover: ' + str(city_cloud))
print('Wind speed: ' + str(city_wind))
print()
print()
# CALL TO ANOTHER_INPUT FUNCTION
another_input()
except ValueError:
print("Zip code not found. Please try again.")
print()
print()
#DEFINE ZIP_FORECAST FUNCTION
def zip_forecast():
print()
#Use the zip code in order to obtain weather forecast data from OpenWeatherMap.
print()
zip_input = input('Type in a zip code then press enter: \n')
zip_code = str(zip_input)
zip_current_url = 'http://api.openweathermap.org/data/2.5/forecast?zip=' + zip_code + ',us'
while True:
lang_input = input(
'Please enter a preferred language code for display results then press enter - ex. for English type EN [OR] for Spanish type in ES: \n').upper()
if lang_input in ['AF', 'AL', 'AR', 'BG', 'CA', 'CZ', 'DA', 'DE', 'EL', 'EN', 'EU', 'FA', 'FI', 'FR', 'GL',
'HE', 'HI', 'HR', 'HU', 'ID', 'IT', 'JA', 'KR', 'LA', 'LT', 'MK', 'NO', 'NL', 'PL', 'PT',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'PT_BR', 'RO', 'RU', 'SV', 'SE', 'SK', 'SL', 'SP', 'ES', 'SR', 'TH', 'TR', 'UA', 'UK', 'VI',
'ZH_CN', 'ZH_TW', 'ZU']:
zip_current_url = zip_current_url + '&lang=' + lang_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
unit_input = input(
'Please enter a preferred unit, imperial [OR] metric, for display results then press enter: \n').lower()
if unit_input == 'imperial':
zip_current_url = zip_current_url + '&units=' + unit_input
break
elif unit_input == 'metric':
zip_current_url = zip_current_url + '&units=' + unit_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
api_key = '&appid=3da266a93ce5e67bd3cd607043e5863f'
zip_url = zip_current_url + api_key
zip_response = requests.get(zip_url)
data = zip_response.text
parsed = json.loads(data)
try:
#similar to previous comment, this might not be the most efficient but it was what worked for me at the moment
#min/max were chosen based on approximate highest/lowest temperature when viewing API in web browser
#i'm not sure whether they are the true high/low because the data is always being updated
date_one = parsed['list'][5]['dt_txt']
desc_one = parsed['list'][5]['weather'][0]['description']
max_one = parsed['list'][5]['main']['temp_max']
min_one = parsed['list'][2]['main']['temp_min']
date_two = parsed['list'][13]['dt_txt']
desc_two = parsed['list'][13]['weather'][0]['description']
max_two = parsed['list'][13]['main']['temp_max']
min_two = parsed['list'][10]['main']['temp_min']
date_three = parsed['list'][21]['dt_txt']
desc_three = parsed['list'][21]['weather'][0]['description']
max_three = parsed['list'][21]['main']['temp_max']
min_three = parsed['list'][18]['main']['temp_min']
date_four = parsed['list'][29]['dt_txt']
desc_four = parsed['list'][29]['weather'][0]['description']
max_four = parsed['list'][29]['main']['temp_max']
min_four = parsed['list'][26]['main']['temp_min']
date_five = parsed['list'][37]['dt_txt']
desc_five = parsed['list'][37]['weather'][0]['description']
max_five = parsed['list'][37]['main']['temp_max']
min_five = parsed['list'][34]['main']['temp_min']
print()
print()
#Display the weather forecast in a readable format to the user.
#originally printed temperature min/max as separate from each other but sometimes data would print with values switched
#i'm not sure why even though in the web browser i checked multiple times that temp_max and temp_min were correct
#range at least ensures a rough estimate temperature but i know it is technically not accurate
print('--- 5-DAY FORECAST FOR ' + zip_code + ' ---')
print()
print('TOMORROW')
print(str(date_one))
print('Description: ' + desc_one)
print('Approximate Temperature Range: ' + str(max_one) + ' to ' + str(min_one))
print()
print('2 DAYS FROM TODAY')
print(str(date_two))
print('Description: ' + desc_two)
print('Approximate Temperature Range: ' + str(max_two) + ' to ' + str(min_two))
print()
print('3 DAYS FROM TODAY')
print(str(date_three))
print('Description: ' + desc_three)
print('Approximate Temperature Range: ' + str(max_three) + ' to ' + str(min_three))
print()
print('4 DAYS FROM TODAY')
print(str(date_four))
print('Description: ' + desc_four)
print('Approximate Temperature Range: ' + str(max_four) + ' to ' + str(min_four))
print()
print('5 DAYS FROM TODAY')
print(str(date_five))
print('Description: ' + desc_five)
print('Approximate Temperature Range: ' + str(max_five) + ' to ' + str(min_five))
print()
print()
# CALL TO ANOTHER_INPUT FUNCTION
another_input()
except ValueError:
print("Zip code not found. Please try again.")
print()
print()
#DEFINE CITY_FORECAST FUNCTION
def city_forecast():
print()
#Use the city name in order to obtain weather forecast data from OpenWeatherMap.
print()
city_input = input('Type in a city name then press enter - ex. New York: \n').upper()
city_current_url = 'http://api.openweathermap.org/data/2.5/forecast?q=' + city_input
while True:
state_input = input(
'Type in a state code then press enter - ex. FL (if the city is outside of the United States, please type in US for default setting): \n').upper()
if state_input in ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO',
'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR',
'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY', 'US']:
city_current_url = city_current_url + ',' + state_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
country_input = input('Type in a country code then press enter - ex. FR: \n').upper()
if country_input in ['AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ',
'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BJ', 'BM', 'BT', 'BO', 'BQ', 'BA', 'BW', 'BV',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'CX', 'CC', 'CO', 'KM', 'CD', 'CG', 'CK', 'CR', 'HR', 'CU', 'CW', 'CY', 'CZ', 'CI', 'DK',
'DJ', 'DM', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'SZ', 'ET', 'FK', 'FO', 'FJ', 'FI',
'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GD', 'GP', 'GU',
'GT', 'GG', 'GN', 'GW', 'GY', 'HT', 'HM', 'VA', 'HN', 'HK', 'HU', 'IS', 'IN', 'ID', 'IR',
'IQ', 'IE', 'IM', 'IL', 'IT', 'JM', 'JP', 'JE', 'JO', 'KZ', 'KE', 'KI', 'KP', 'KR', 'KW',
'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MG', 'MW', 'MY', 'MV',
'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'MA',
'MZ', 'MM', 'NA', 'NR', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'NU', 'NF', 'MP', 'NO',
'OM', 'PK', 'PW', 'PS', 'PA', 'PG', 'PY', 'PE', 'PH', 'PN', 'PL', 'PT', 'PR', 'QA', 'MK',
'RO', 'RU', 'RW', 'RE', 'BL', 'SH', 'KN', 'LC', 'MF', 'PM', 'VC', 'WS', 'SM', 'ST', 'SA',
'SN', 'RS', 'SC', 'SL', 'SG', 'SX', 'SK', 'SI', 'SB', 'SO', 'ZA', 'GS', 'SS', 'ES', 'LK',
'SD', 'SR', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'TZ', 'TH', 'TL', 'TG', 'TK', 'TO', 'TT',
'TN', 'TR', 'TM', 'TC', 'TV', 'UG', 'UA', 'AE', 'GB', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE',
'VN', 'VG', 'VI', 'WF', 'EH', 'YE', 'ZM', 'ZW', 'AX']:
city_current_url = city_current_url + ',' + country_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
lang_input = input(
'Please enter a preferred language code for display results then press enter - ex. for English type EN [OR] for Spanish type in ES: \n').upper()
if lang_input in ['AF', 'AL', 'AR', 'BG', 'CA', 'CZ', 'DA', 'DE', 'EL', 'EN', 'EU', 'FA', 'FI', 'FR', 'GL',
'HE', 'HI', 'HR', 'HU', 'ID', 'IT', 'JA', 'KR', 'LA', 'LT', 'MK', 'NO', 'NL', 'PL', 'PT',
'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'KY', 'CF', 'TD', 'CL', 'CN',
'PT_BR', 'RO', 'RU', 'SV', 'SE', 'SK', 'SL', 'SP', 'ES', 'SR', 'TH', 'TR', 'UA', 'UK', 'VI',
'ZH_CN', 'ZH_TW', 'ZU']:
city_current_url = city_current_url + '&lang=' + lang_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
while True:
unit_input = input(
'Please enter a preferred unit, imperial [OR] metric, for display results then press enter: \n').lower()
if unit_input == 'imperial':
city_current_url = city_current_url + '&units=' + unit_input
break
elif unit_input == 'metric':
city_current_url = city_current_url + '&units=' + unit_input
break
else:
print('Invalid response. Please try again.')
print()
print()
continue
api_key = '&appid=3da266a93ce5e67bd3cd607043e5863f'
city_url = city_current_url + api_key
city_response = requests.get(city_url)
data = city_response.text
parsed = json.loads(data)
try:
date_one = parsed['list'][5]['dt_txt']
desc_one = parsed['list'][5]['weather'][0]['description']
max_one = parsed['list'][2]['main']['temp_max']
min_one = parsed['list'][5]['main']['temp_min']
date_two = parsed['list'][13]['dt_txt']
desc_two = parsed['list'][13]['weather'][0]['description']
max_two = parsed['list'][10]['main']['temp_max']
min_two = parsed['list'][13]['main']['temp_min']
date_three = parsed['list'][21]['dt_txt']
desc_three = parsed['list'][21]['weather'][0]['description']
max_three = parsed['list'][18]['main']['temp_max']
min_three = parsed['list'][21]['main']['temp_min']
date_four = parsed['list'][29]['dt_txt']
desc_four = parsed['list'][29]['weather'][0]['description']
max_four = parsed['list'][26]['main']['temp_max']
min_four = parsed['list'][29]['main']['temp_min']
date_five = parsed['list'][37]['dt_txt']
desc_five = parsed['list'][37]['weather'][0]['description']
max_five = parsed['list'][34]['main']['temp_max']
min_five = parsed['list'][37]['main']['temp_min']
print()
print()
#Display the weather forecast in a readable format to the user.
print('--- 5-DAY FORECAST FOR ' + city_input + ', ' + state_input + ', ' + country_input + ' ---')
print()
print('TOMORROW')
print(date_one)
print('Description: ' + desc_one)
print('Approximate Temperature Range: ' + str(max_one) + ' to ' + str(min_one))
print()
print('2 DAYS FROM TODAY')
print(date_two)
print('Description: ' + desc_two)
print('Approximate Temperature Range: ' + str(max_two) + ' to ' + str(min_two))
print()
print('3 DAYS FROM TODAY')
print(date_three)
print('Description: ' + desc_three)
print('Approximate Temperature Range: ' + str(max_three) + ' to ' + str(min_three))
print()
print('4 DAYS FROM TODAY')
print(date_four)
print('Description: ' + desc_four)
print('Approximate Temperature Range: ' + str(max_four) + ' to ' + str(min_four))
print()
print('5 DAYS FROM TODAY')
print(date_five)
print('Description: ' + desc_five)
print('Approximate Temperature Range: ' + str(max_five) + ' to ' + str(min_five))
print()
print()
#CALL TO ANOTHER_INPUT FUNCTION
another_input()
except ValueError:
print("Zip code not found. Please try again.")
print()
print()
#DEFINE MAIN FUNCTION
def main():
#HELLO GREETING
print()
print('--- Welcome to the OpenWeather Forecast Application! ---')
#Use functions including a main function.
#CALL TO USER_INPUT FUNCTION
user_input()
#CALL TO MAIN FUNCTION
if __name__ == "__main__":
main() |
#DSC 510
#Week 10
#Programming Assignment Week 10
#Author Tiffany Tesoro
#08/09/2020
#TO FORMAT TOTAL PRICE
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
#locale.setlocale(locale.LC_ALL, '') did not work for me
#REFERENCE https://stackoverflow.com/questions/14547631/python-locale-error-unsupported-locale-setting
#DEFINE CASHREGISTER CLASS
class CashRegister(object):
#CASHREGISTER INSTANCE
def __init__(self):
self.itemCount = 0
self.totalPrice = 0
#ADDITEM INSTANCE METHOD
def addItem(self, price):
self.totalPrice += float(price)
self.itemCount += 1
#@property GETTOTAL GETTER METHOD
#tried to use it based on Python OOP Tutorial 6: Property Decorators - Getters, Setters, and Deleters
#TypeError: 'float' object is not callable when I include this in code
def getTotal(self):
return self.totalPrice
#@property GETCOUNT GETTER METHOD
def getCount(self):
return self.itemCount
#TRIED TO MAKE A LIST TO PRINT THE PRICE OF EACH ITEM AT THE END BUT DID NOT WORK OUT
#BASED FUNCTION FROM WEEK 6 ASSIGNMENT
#def user_input(prices):
#while True:
#try:
#input_price = input('Input price of item in and press enter: USD$ ')
#price = input_price
#prices.append(float(price))
#except ValueError:
#print('Please try again.')
#print()
#DEFINE MAIN FUNCTION
def main():
#WELCOME MESSAGE
print()
print('Welcome to the Bellevue Cash Register!')
print()
#CALL TO CASHREGISTER CLASS
checkout = CashRegister()
while True:
addAnother = input('Would you like to add an item? Type YES or NO then press enter: ').upper()
if addAnother == 'YES' or addAnother == 'Y':
try:
price = float(input('Input price of item in and press enter: USD$ '))
#CALL TO ADDITEM METHOD
checkout.addItem(price)
except ValueError:
print('Please try again.')
print()
#ATTEMPT AT WHAT WOULD'VE BEEN IF LIST ACCEPTED
#while True:
#prices = []
#print()
#prices = user_input(prices)
#print()
#HAD TROUBLE INCORPORATING CALL TO ADDITEM METHOD
#CashRegister.addItem(price)
#break
elif addAnother == 'NO' or addAnother == 'N':
print()
#CALL TO GETTOTAL METHOD
print('Transaction total: ' + locale.currency(checkout.getTotal()))
#REFERENCE https://pymotw.com/3/locale/
#CALL TO ITEMCOUNT METHOD
print('Total number of items: ' + str(checkout.getCount()))
print()
print('Thank you for using Bellevue Grocery. Have a wonderful day!')
exit()
else:
print('Please try again.')
print()
#CALL TO MAIN FUNCTION
if __name__ == "__main__":
main() |
# Katie Simek
# 26/07/2020
# Create a program that imports a txt file, then calculate the total words, and output
# the number of occurrences of each word in the file.
# Create separate print function to make modification changes easier
# Have program write to a user named file with just the length of the dictionary
import string # use to eliminate punctuation in file
# Function to add words to dictionary called "counts"
# and count occurrences of each word
def add_word(word, counts):
counts[word] = counts.get(word, 0) + 1
# Function to process the file lines, parsing the string to separate words
def process_line(line, counts):
line = line.rstrip() # removes extra spaces
line = line.lower() # makes all words lowercase
# makes a list of all words, removes punctuation
line = line.translate(line.maketrans('', '', string.punctuation))
words = line.split() # splits words in the line
for word in words: # adds words to dictionary
add_word(word, counts)
# Function to set print format for dictionary
def pretty_print(counts):
print('-' * 20)
print('{:^20}'.format('Word : Count'))
# sorts by value, then for same value sorts key alpha
for [key, value] in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
print('{:13} {:>3}'.format(key, value))
# Function to open and read file.
# Get user input for name of new file to write to
# Write the length of the dictionary in the new file
def process_file(counts):
# open file to create dict
gba = 'gettysburg.txt'
with open(gba, 'r') as gba_file:
for line in gba_file:
process_line(line, counts)
# asks user for file name, creates new file and prints length of dict
filename = input('What would you like to call the file?')
with open(filename, 'w') as fileHandle:
fileHandle.write('Length of the dictionary: ' + str(len(counts)))
# Creates empty dictionary, opens file to read and process line to add
# words to dictionary.
def main():
counts = dict()
gba = 'gettysburg.txt'
with open(gba, 'r') as gba_file:
for line in gba_file:
process_line(line, counts)
process_file(counts) # gets file name, creates file and writes dict length
pretty_print(counts) # prints dictionary and counts in program
main()
|
#DSC 510
#Week 9
#Programming Assignment Week 9
#Author Tiffany Tesoro
#08/02/2020
#TO USE API TO GET DATA
import json
import requests
#^^ had some trouble using this until i figured out how to install pip via terminal on my mac
#DEFINE JOKE_REQUEST FUNCTION
def joke_request():
while True:
hearajoke = input('Would you like to hear a joke? Type Y or N then press enter.\n')
if(hearajoke == 'Y' or hearajoke == 'y'):
#CALL TO CNJOKES FUNCTION
cn_jokes()
elif(hearajoke == 'N' or hearajoke == 'n'):
print('Program will now end. Thank you for using the Random Chuck Norris Jokes Generator!')
exit()
else:
print('Invalid response. Please try again.')
print()
print()
continue
#REFERENCE FOR 'OR' USAGE IN 'IF' STATEMENT - https://www.datacamp.com/community/tutorials/python-if-elif-else
#DEFINE CNJOKES FUNCTION
def cn_jokes():
#REFERENCE FOR EXTRACTING DATA FROM API - https://python.gotrained.com/python-json-api-tutorial/
#Create a program which uses the Request library to make a GET request of the following API: Chuck Norris Jokes.
response = requests.get('https://api.chucknorris.io/jokes/random')
#The program will receive a JSON response which includes various pieces of data.
data = response.text
#You should parse the JSON data to obtain the “value” key.
parsed = json.loads(data)
value = parsed['value']
#chose value because that is where the joke is listed under in the api
#PRETTY PRINT FORMAT?
print()
print('Here\'s a joke for you...')
#The data associated with the value key should be displayed for the user (i.e., the joke).
print(value)
print()
print()
#CALL TO JOKE_AGAIN FUNCTION
joke_again()
#DEFINE JOKE_AGAIN FUNCTION
#Your program should allow the user to request a Chuck Norris joke as many times as they would like.
def joke_again():
while True:
anotherjoke = input('Would you like to hear another joke? Type Y or N then press enter.\n')
if(anotherjoke == 'Y' or anotherjoke == 'y'):
cn_jokes()
elif(anotherjoke == 'N' or anotherjoke == 'n'):
print('Program will now end. Thank you for using the Random Chuck Norris Jokes Generator!')
exit()
else:
print('Invalid response. Please try again.')
print()
print()
continue
#DEFINE MAIN FUNCTION
def main():
#WELCOME MESSAGE
print()
print('Welcome to the Random Chuck Norris Jokes Generator!')
#CALL TO JOKE_REQUEST FUNCTION
joke_request()
#CALL TO MAIN FUNCTION
if __name__ == "__main__":
main() |
# credit to my homework from Coursera:
# Neural Networks and DeepLearning,
# Hyperparameter tuning, Regulation and Optimization
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
def sigmoid(x):
"""
Compute the sigmoid of x
"""
s = 1 / (1 + np.exp(-x))
return s
def relu(x):
"""
Compute the relu of x
"""
s = np.maximum(0, x)
return s
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
bl -- bias vector of shape (layer_dims[l], 1)
"""
np.random.seed(1)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) / np.sqrt(
layer_dims[l - 1]) # *0.01
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert (parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))
assert (parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
def initialize_adam(parameters):
"""
Initializes v and s as two python dictionaries with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Arguments:
parameters -- python dictionary containing your parameters.
parameters["W" + str(l)] = Wl
parameters["b" + str(l)] = bl
Returns:
v -- python dictionary that will contain the exponentially weighted average of the gradient.
v["dW" + str(l)] = ...
v["db" + str(l)] = ...
s -- python dictionary that will contain the exponentially weighted average of the squared gradient.
s["dW" + str(l)] = ...
s["db" + str(l)] = ...
"""
L = len(parameters) // 2 # number of layers in the neural networks
v = {}
s = {}
# Initialize v, s. Input: "parameters". Outputs: "v, s".
for l in range(L):
v["dW" + str(l + 1)] = np.zeros_like(parameters["W" + str(l + 1)])
v["db" + str(l + 1)] = np.zeros_like(parameters["b" + str(l + 1)])
s["dW" + str(l + 1)] = np.zeros_like(parameters["W" + str(l + 1)])
s["db" + str(l + 1)] = np.zeros_like(parameters["b" + str(l + 1)])
return v, s
def random_mini_batches(X, Y, mini_batch_size=64, seed=0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)
mini_batch_size -- size of the mini-batches, integer
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
np.random.seed(seed) # To make your "random" minibatches the same as ours
m = X.shape[1] # number of training examples
mini_batches = []
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X.values[:, permutation]
shuffled_Y = Y[:, permutation].reshape((1, m))
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(
m / mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[:, k * mini_batch_size: (k + 1) * mini_batch_size]
mini_batch_Y = shuffled_Y[:, k * mini_batch_size: (k + 1) * mini_batch_size]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[:, (mini_batch_size * num_complete_minibatches):]
mini_batch_Y = shuffled_Y[:, (mini_batch_size * num_complete_minibatches):]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def predict(parameters, X, y=None):
"""
This function is used to predict the results of a n-layer neural network.
Arguments:
X -- data set of examples you would like to label
Returns:
p -- predictions for the given dataset X
"""
m = X.shape[1]
p = np.zeros((1, m), dtype=np.int)
# Forward propagation
# a3, caches = forward_propagation(X, parameters)
AL, parameters, Z, A = forward_propagation(X, parameters)
# convert probas to 0/1 predictions
for i in range(0, AL.shape[1]):
if AL[0, i] > 0.5:
p[0, i] = 1
else:
p[0, i] = 0
# print results
if y is not None:
print("Accuracy: " + str(np.mean((p[0, :] == y[0, :]))))
return p
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
Returns:
cost -- cross-entropy cost
"""
epsilon = 1e-7
m = Y.shape[1]
# Compute loss from aL and y.
cost = (1. / m) * (-np.dot(Y, np.log(AL + epsilon).T) - np.dot(1 - Y, np.log(1 - AL + epsilon).T))
cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
assert (cost.shape == ())
return cost
def compute_cost_with_regularization(AL, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
AL -- post-activation, output of forward propagation, of shape (output size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
parameters -- python dictionary containing parameters of the model
Returns:
cost - value of the regularized loss function (formula (2))
"""
m = Y.shape[1]
L = len(parameters) // 2
cross_entropy_cost = compute_cost(AL, Y) # This gives you the cross-entropy part of the cost
sum = 0
for l in range(L):
sum += np.sum(np.square(parameters["W" + str(l + 1)]))
L2_regularization_cost = lambd * sum / (2 * m)
cost = cross_entropy_cost + L2_regularization_cost
return cost
def forward_propagation(X, parameters):
"""
Implements the forward propagation (and computes the loss) presented in Figure 2.
Arguments:
X -- input dataset, of shape (input size, number of examples)
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", ...:
W1 -- weight matrix of shape ()
b1 -- bias vector of shape ()
...
Returns:
loss -- the loss function (vanilla logistic loss)
"""
L = len(parameters) // 2
Z = {}
A = {}
A["0"] = X
# LINEAR -> RELU -> LINEAR -> RELU -> ... -> LINEAR -> SIGMOID
for l in range(L - 1):
Z[str(l + 1)] = np.dot(parameters["W" + str(l + 1)], A[str(l)]) + parameters["b" + str(l + 1)]
A[str(l + 1)] = relu(Z[str(l + 1)])
Z[str(L)] = np.dot(parameters["W" + str(L)], A[str(L - 1)]) + parameters["b" + str(L)]
A[str(L)] = sigmoid(Z[str(L)])
return A[str(L)], parameters, Z, A
# def backward_propagation_with_regularization(X, Y, cache, lambd):
def backward_propagation_with_regularization(X, Y, parameters, Z, A, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation()
lambd -- regularization hyperparameter, scalar
Returns:
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
L = len(parameters) // 2
dZ = {}
dW = {}
db = {}
dA = {}
dZ[str(L)] = A[str(L)] - Y
dW[str(L)] = 1. / m * np.dot(dZ[str(L)], A[str(L - 1)].T) + (lambd * parameters["W" + str(L)]) / m
db[str(L)] = 1. / m * np.sum(dZ[str(L)], axis=1, keepdims=True)
for l in reversed(range(1, L)):
dA[str(l)] = np.dot(parameters["W" + str(l + 1)].T, dZ[str(l + 1)])
dZ[str(l)] = np.multiply(dA[str(l)], np.int64(A[str(l)] > 0))
dW[str(l)] = 1. / m * np.dot(dZ[str(l)], A[str(l - 1)].T) + (lambd * parameters["W" + str(l)]) / m
db[str(l)] = 1. / m * np.sum(dZ[str(l)], axis=1, keepdims=True)
return dZ, dW, db, dA
def update_parameters_with_adam(parameters, dZ, dW, db, dA, v, s,
t, learning_rate, beta1, beta2, epsilon):
"""
Update parameters using Adam
Arguments:
v -- Adam variable, moving average of the first gradient, python dictionary
s -- Adam variable, moving average of the squared gradient, python dictionary
learning_rate -- the learning rate, scalar.
beta1 -- Exponential decay hyperparameter for the first moment estimates
beta2 -- Exponential decay hyperparameter for the second moment estimates
epsilon -- hyperparameter preventing division by zero in Adam updates
Returns:
parameters -- python dictionary containing your updated parameters
v -- Adam variable, moving average of the first gradient, python dictionary
s -- Adam variable, moving average of the squared gradient, python dictionary
"""
L = len(parameters) // 2 # number of layers in the neural networks
v_corrected = {} # Initializing first moment estimate, python dictionary
s_corrected = {} # Initializing second moment estimate, python dictionary
# Perform Adam update on all parameters
for l in range(L):
# Moving average of the gradients. Inputs: "v, grads, beta1". Output: "v".
v["dW" + str(l + 1)] = beta1 * v["dW" + str(l + 1)] + (1 - beta1) * dW[str(l + 1)]
v["db" + str(l + 1)] = beta1 * v["db" + str(l + 1)] + (1 - beta1) * db[str(l + 1)]
# Compute bias-corrected first moment estimate. Inputs: "v, beta1, t". Output: "v_corrected".
v_corrected["dW" + str(l + 1)] = v["dW" + str(l + 1)] / (1 - np.power(beta1, t))
v_corrected["db" + str(l + 1)] = v["db" + str(l + 1)] / (1 - np.power(beta1, t))
# Moving average of the squared gradients. Inputs: "s, grads, beta2". Output: "s".
s["dW" + str(l + 1)] = beta2 * s["dW" + str(l + 1)] + (1 - beta2) * np.power(dW[str(l + 1)], 2)
s["db" + str(l + 1)] = beta2 * s["db" + str(l + 1)] + (1 - beta2) * np.power(db[str(l + 1)], 2)
# Compute bias-corrected second raw moment estimate. Inputs: "s, beta2, t". Output: "s_corrected".
s_corrected["dW" + str(l + 1)] = s["dW" + str(l + 1)] / (1 - np.power(beta2, t))
s_corrected["db" + str(l + 1)] = s["db" + str(l + 1)] / (1 - np.power(beta2, t))
# Update parameters.
# Inputs: "parameters, learning_rate, v_corrected, s_corrected, epsilon". Output: "parameters".
parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * v_corrected[
"dW" + str(l + 1)] / np.sqrt(s_corrected["dW" + str(l + 1)] + epsilon)
parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * v_corrected[
"db" + str(l + 1)] / np.sqrt(s_corrected["db" + str(l + 1)] + epsilon)
return parameters, v, s
def model(X, Y, layers_dims, optimizer, learning_rate=0.0007, mini_batch_size=64, beta=0.9,
beta1=0.9, beta2=0.999, epsilon=1e-8, num_epochs=10000, print_cost=False, lambd=0):
"""
L-layer neural network model which can be run in different optimizer modes.
Arguments:
X -- input data, of shape (#attributes, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)
layers_dims -- python list, containing the size of each layer
learning_rate -- the learning rate, scalar.
mini_batch_size -- the size of a mini batch
beta -- Momentum hyperparameter
beta1 -- Exponential decay hyperparameter for the past gradients estimates
beta2 -- Exponential decay hyperparameter for the past squared gradients estimates
epsilon -- hyperparameter preventing division by zero in Adam updates
num_epochs -- number of epochs
print_cost -- True to print the cost every 1000 epochs
Returns:
parameters -- python dictionary containing your updated parameters
"""
L = len(layers_dims) # number of layers in the neural networks
costs = [] # to keep track of the cost
t = 0 # initializing the counter required for Adam update
seed = 10
# Initialize parameters
parameters = initialize_parameters_deep(layers_dims)
# Initialize the optimizer
if optimizer == "momentum":
pass
# v = initialize_velocity(parameters)
elif optimizer == "adam":
v, s = initialize_adam(parameters)
# Optimization loop
for i in range(num_epochs):
# Define the random minibatches. We increment the seed to reshuffle differently the dataset after each epoch
seed = seed + 1
minibatches = random_mini_batches(X, Y, mini_batch_size, seed)
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
# Forward propagation
AL, parameters, Z, A = forward_propagation(minibatch_X, parameters)
# Compute cost
cost = compute_cost_with_regularization(AL, minibatch_Y, parameters, lambd)
# Backward propagation
dZ, dW, db, dA = backward_propagation_with_regularization(minibatch_X, minibatch_Y, parameters, Z, A, lambd)
# Update parameters
if optimizer == "gd":
pass
# parameters = update_parameters_with_gd(parameters, grads, learning_rate)
elif optimizer == "momentum":
pass
# parameters, v = update_parameters_with_momentum(parameters, grads, v, beta, learning_rate)
elif optimizer == "adam":
t = t + 1 # Adam counter
parameters, v, s = update_parameters_with_adam(parameters, dZ, dW, db, dA, v, s,
t, learning_rate, beta1, beta2, epsilon)
# Print the cost every 1000 epoch
if print_cost and i % 1000 == 0:
print ("Cost after epoch %i: %f" % (i, cost))
if print_cost and i % 100 == 0:
costs.append(cost)
# plot the cost
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('epochs (per 100)')
plt.title("Learning rate = " + str(learning_rate))
plt.show()
return parameters
|
import pandas as pd
import numpy as np
import streamlit as st
#import the dataset and create a checkbox to shows the data on your website
df1 = pd.read_csv("df_surf.csv")
if st.checkbox('Show Dataframe'):
st.write(df1)
#Read in data again, but by using streamlit's caching aspect. Our whole app re-runs every time we make small changes, which is infeasible the more complicated our code becomes. So this is the recommended way to import the data.
df = st.cache(pd.read_csv)("df_surf.csv")
#create side bars that allow for multiple selections:
age = st.sidebar.multiselect("Select age", df['surfer_age'].unique())
st.write("Age selected", age)
weekly_surfs = st.sidebar.multiselect("Surfer Exercise frequency", df['surfer_exercise_frequency'].unique())
st.write("Frequency selected", weekly_surfs)
surfer_experience = st.sidebar.multiselect("Surfer Experience", df['surfer_experience'].unique())
st.write("Experience selected", surfer_experience)
surfer_gender = st.sidebar.multiselect("Surfer Gender", df['surfer_gender'].unique())
st.write("Gender selected", surfer_gender)
wave_height = st.sidebar.multiselect("Wave height", df['wave_height'].unique())
st.write("Wave height selected", wave_height)
board_type = st.sidebar.multiselect("Board Type", df['board_type'].unique())
st.write("Board type selected", board_type)
#create a sidebar to select the variable output you want to see after making your multiple selections
variables = st.sidebar.multiselect("Select what you want to see for your selection", df.columns)
st.write("You selected these variables", variables)
# return the sub-set data of variables you want to see
selected_data = df[(df['surfer_age'].isin(age))]
subset_data = selected_data[variables]
data_is_check = st.checkbox("Display the data of selected variables")
if data_is_check:
st.write(subset_data) |
seq = ""
with open("sequence.protein.2.fasta",'r') as fr:
for line in fr:
if line.startswith(">"):
continue
else:
seq += line.strip()
while True:
position = input("Position: ")
if position == "XXX":
print("Okay, I will stop.")
break
else:
seq_len = len(seq)
try:
position = int(position)
except:
print ("Please input Position nummber")
continue
if 1 <= position <= seq_len-3:
sliced_seq = seq[position-1:position+2]
print("Three amino acids: "+sliced_seq)
else:
print("Invalid range position value")
|
message1 = input("Enter a string: ")
message2 = input("Enter another: ")
if message1 != message2:
print(message1+message2)
else:
print("Two strings are identical.")
|
H = raw_input('enter hour: ')
M = raw_input('enter rate: ')
if H >= 100:
print 'pay:',int(H)*int(M)*2
else:
print 'pay:',int(H)*int(M)
|
print 'Score Grade \n>=0.9 A \n>=0.8 B \n>=0.7 C \n>=0.6 D \n <0.6 F \n'
score = raw_input('Enter score: ')
try:
ss = float(score)
if 0.0 <= ss <= 1.0:
if ss >= 0.9:
print 'A'
elif ss >= 0.8:
print 'B'
elif ss >= 0.7:
print 'C'
elif ss >= 0.6:
print 'D'
elif ss < 0.6:
print 'F'
else:
print 'Bad score'
except:
print 'Bad score'
|
def reverse_message(string):
return (string[::-1])
message = input("Enter a string: ")
reverse = reverse_message(message)
print ("Reversed string: "+reverse)
|
tabela = ('Atlético - MG', 'São Paulo', 'Flamengo', 'Internacional',
'Palmeiras', 'Santos','Grêmio', 'Fluminense', 'Fortaleza',
'Ceará', 'Corinthians', 'Athletico - PR', 'Bahia','Atlético - GO ',
'Bragantino', 'Sport', 'Vasco', 'Coritiba','Botafogo', 'Goiás ')
print("-="* 50)
print(f"A lista dos times do brasilheirão são{tabela}")
print("-="* 50)
print(f'Os primeiros 5 times são {tabela[:5]}')
print("-="* 50)
print(f'Os ultimos 4 são {tabela[-4:]}')
print("-="* 50)
print(f"Times em ordem alfabetica {sorted(tabela)}")
print("-="* 50)
print("O Santos esta na {}ª posição".format(tabela.index("Santos")+ 1)) |
pessoa = dict()
galera = list()
soma = media = 0
while True:
pessoa["nome"] = str(input("Nome: "))
while True:
pessoa["sexo"] = str(input("sexo:[M/F] ")).upper()[0]
if pessoa["sexo"] in "MF":
break
print("Erro! Por favor digite M ou F")
pessoa["idade"] = int(input("Idade: "))
soma += pessoa["idade"]
galera.append(pessoa.copy())
while True:
resp = str(input("Deseja continuar?[S/N] ")).upper()[0]
if resp in "SN":
break
print("ERRO! Por favor digite S ou N")
if resp == "N":
break
print(f"Ao todo foram {len(galera)} pessoas cadastradas.")
media = soma / len(galera)
print(f"A media de idade é de {media:5.2f} anos.")
print("As mulherem cadastradas foram: ", end="")
for p in galera:
if p["sexo"] == "F":
print(f"{p['nome']}", end=" e ")
print()
print("Lista de pessoa que estao acima da media: ", end="")
print()
for p in galera:
if p["idade"] >= media:
for k, v in p.items():
print(f"{k} = {v}")
print() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.