text stringlengths 37 1.41M |
|---|
a, b, c = map(int, input().split())
if a > (b and c):
print('A is greatest')
elif b > c:
print('B is greatest')
else:
print('C is graetest')
|
def main():
number_of_ingredients = int(input())
quantity_of_ingredients_required = list(map(int,input().split()))
quantity_of_ingredients_present = list(map(int, input().split()))
minimum_no_of_ppfgirls = quantity_of_ingredients_present[0]//quantity_of_ingredients_required[0]
for i in range(1, number_of_ingredients):
minimum_no_of_ppfgirls = min(minimum_no_of_ppfgirls, quantity_of_ingredients_present[i]//quantity_of_ingredients_required[i])
print(minimum_no_of_ppfgirls)
main()
|
import pandas as pd
import os
import csv
import Extractor
import FeatureExtractorServer
ORIGINAL_DATASET_PATH = "genres/"
genres = 'blues classical jazz metal pop rock'.split()
def extract_features_from_original_dataset():
"""
Function used to extract all the possible features from the audio signals in the original dataset
In output we will have the data.csv file, that will be our dataset
"""
# construct the header of the table
header = 'chroma_stft rms spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
# There are 20 MFCC, we will call them mfcc0, mfcc1, ecc
for i in range(1, 21):
header += f' mfcc{i}'
# Finally we need the "label" column
header += ' label'
header = header.split()
# data.csv will be the new dataset
file = open('data.csv', 'w', newline='')
with file:
writer = csv.writer(file)
writer.writerow(header) # Write the header
for g in genres:
for filename in os.listdir(ORIGINAL_DATASET_PATH + f'{g}'):
song_name = ORIGINAL_DATASET_PATH + f'{g}/{filename}'
to_append = Extractor.extract_feature(song_name)
to_append += f' {g}' # finally the genre is inserted
# Insert the new calculated values of this song in the file
file = open('data.csv', 'a', newline='')
with file:
writer = csv.writer(file)
writer.writerow(to_append.split())
def show_dataset():
data = pd.read_csv('data.csv')
print(data.head())
if __name__ == '__main__':
FeatureExtractorServer.start_server()
|
import ipaddress
import math
import os
class Subnet:
net_ip = ""
nsubs = 0
subnets = []
def classful(self):
self.net_ip = str(input("Enter Classful Network IP: "))
if self.checkIP(self.net_ip) == False:
return
self.nsubs = int(input("Enter the number of subnets: "))
prefix_diff = int(math.log(self.nsubs)/math.log(2)) #bits to modify
list_ip = self.net_ip.split(".")
if(int(list_ip[0]) <= 127):
class_id = "A"
elif(int(list_ip[0]) >= 128 and int(list_ip[0]) < 192):
class_id = "B"
elif(int(list_ip[0]) >= 192 and int(list_ip[0]) < 223):
class_id = "C"
else:
print("Class D and E addresses are not allowed")
return
print("The Network IP belongs to Class " + class_id)
dict_masks = { "A": "255.0.0.0", "B" : "255.255.0.0", "C" : "255.255.255.0" }
subnet_mask = dict_masks[class_id]
print("Therefore default subnet mask is: " + subnet_mask)
if(class_id == "A"):
prefix_diff += 8
self.net_ip = self.net_ip + "/8"
elif(class_id == "B"):
prefix_diff += 16
self.net_ip = self.net_ip + "/16"
elif(class_id == "C"):
prefix_diff += 24
self.net_ip = self.net_ip + "/24"
self.subnets = list(ipaddress.ip_network(self.net_ip).subnets(int(math.log(self.nsubs)/math.log(2))))
calc_ssbmask = self.calcSubnetMask(prefix_diff)
print("Calculated Subnet Mask is: " + calc_ssbmask)
self.display()
def calcSubnetMask(self,prefix_diff):
ssbmask = []
if(prefix_diff in range(0,8)):
ssbmask.append(str(sum( 2**(8 - x) for x in range(1,prefix_diff+1))))
ssbmask.append(0)
ssbmask.append(0)
ssbmask.append(0)
elif(prefix_diff in range(8,16)):
ssbmask.append(255)
ssbmask.append(str(sum( 2**(8 - x) for x in range(1,prefix_diff+1-8))))
ssbmask.append(0)
ssbmask.append(0)
elif(prefix_diff in range(16,24)):
ssbmask.append(255)
ssbmask.append(255)
ssbmask.append(str(sum( 2**(8 - x) for x in range(1,prefix_diff+1-16))))
ssbmask.append(0)
elif(prefix_diff in range(24,32)):
ssbmask.append(255)
ssbmask.append(255)
ssbmask.append(255)
ssbmask.append(str(sum( 2**(8 - x) for x in range(1,prefix_diff+1-24))))
calc_ssbmask = str(ssbmask[0]) + "." + str(ssbmask[1]) + "." + str(ssbmask[2]) + "." + str(ssbmask[3])
return calc_ssbmask
def classless(self):
self.net_ip = str(input("Enter Classless Network IP: "))
self.nsubs = int(input("Enter the number of subnets: "))
first_split = self.net_ip.split("/")
if self.checkIP(first_split[0]) == False:
return
list_ip = first_split[0].split(".")
mask_bits = first_split[1]
print(list_ip)
print(mask_bits)
prefix_diff = int(math.log(self.nsubs)/math.log(2))
calc_ssbmask = self.calcSubnetMask(int(mask_bits)+prefix_diff)
print("Calculated Subnet Mask: " + calc_ssbmask)
self.subnets = list(ipaddress.ip_network(self.net_ip).subnets(prefix_diff))
self.display()
choice = int(input("\nDo you want to find whether and IP is within subnet[0/1]: "))
if(choice == 1):
self.findwithinSubnet()
def display(self):
c = 1
for i in self.subnets:
print("Subnet "+str(c)+" \t "+str(i[0])+" \t "+str(i[-1]))
c = c + 1
def findwithinSubnet(self):
key = str(input("Enter the IP Address to find: "))
c = 0
for i in self.subnets:
c += 1
for j in i:
if(key == str(j)):
print("Found IP in: " + str(c) + " Subnet");
break;
def setIP(self):
ip = str(input("Enter the IP you want to set: "))
os.system("ifconfig")
inteface = str(input("Enter your interface: "))
try:
os.system("sudo ifconfig "+inteface+" "+ip)
except Exception as e:
print(e)
print("IP Address " + ip + " was assigned to the system.")
def pingIP(self):
ip = str(input("Enter the ip address: "))
try:
x = os.system("ping "+ip+" -c 1")
except Exception as e:
print(e)
if(x == 512):
print("Host is down!")
elif(x == 0):
print("Host is up!")
def checkIP(self, ip):
list_ip = ip.split(".")
if not '.' in ip:
print("IP Address invalid")
return False
else:
for i in list_ip:
if(int(i) > 255 or int(i) < 0):
print("The IP address values ranges between 0 and 255")
return False
break
return True
if __name__ == "__main__":
subnet = Subnet()
print("Welcome to Subnetter")
print("Select any one option from the following")
print("1. Find Subnets Ranges using classless IP")
print("2. Find SUbnets Ranges using classful IP")
choice = int(input("Enter your choice: "))
if(choice == 1):
subnet.classless()
else:
subnet.classful()
subnet.setIP()
choice = int(input("\nDo you want to ping an ip address[0/1]: "))
if(choice == 0):
exit()
elif(choice == 1):
subnet.pingIP()
|
import random
use =[]
for x in range(10):
i=random.randint(1,11)
use.append(i)
print(use)
for x in range(10):
print(use+1)
|
import time
import sys
start_time = time.time()
base_num=raw_input("What's your num?")
squared_nat=0
sum_squared=0
for i in xrange(1,int(base_num)+1):
squared_nat = squared_nat + i **2
sum_squared = sum_squared + i
print sum_squared**2, squared_nat
print (sum_squared**2 - squared_nat)
print("--- %s seconds ---" % (time.time() - start_time))
sys.exit()
|
def check(max):
for j in range(3,i):
if i%j == 0:
return 0
return 1
import math
base_num=raw_input("What's your max number?")
max=1
for i in range (2, int(math.ceil(int(base_num)**0.5))):
if int(base_num)%i == 0:
if check(i) == 1:
max = i
print max |
print("______________________Welcome________________________")
print("If you want to find a job, please fill in the form!!!")
file_info = open("finfo.txt", "w")
name = input("What is your name? ")
surname = input("What is your surname ")
age = int(input("How old are you? "))
city = input("Where do you live? ")
previous_job = input("Where did you work? ")
experience = input("What is your work experience? ")
name_surname = name + ' ' + surname
list_bye = ['Goodbye', name, surname]
info = "Thank you %s, your age is %i. \n We will try to find work in the city %s." \
" \n Job vacancy - %s \n Experience - %s" % (name_surname, age, city, previous_job, experience)
print(info)
print("We will send you letter, check your postbox.")
print (list_bye)
file_info.write(info)
file_info.close() |
name = input("What is your name?")
city = input("Where do you live?")
age = input("How old are you?")
street = input("Write your street")
all_answers = (
'Your name is: %s \n You live in: %s \n You are: %s \n Your street is named: %s' % (name, city, age, street))
doFile = open('Answers.txt', "w")
doFile.write(all_answers)
doFile.close()
|
class User(object):
def __init__(self, email, first_name, last_name, user_role):
self.email = email
self.first_name = first_name
self.last_name = last_name
self.user_role = user_role
def __str__(self):
return "email: %s, first_name: %s, last_name: %s, user_role: %s" % (self.email, self.first_name, self.last_name, self.user_role)
def full_name(self):
return "%s %s" % (self.first_name, self.last_name)
|
# This file contain functions which used for creating JSON and XML files
import json
import xml.etree.cElementTree as Tree
full = {}
def writer(num, answ1, answ2, status): # this fn is creating dict with attr.
val = (answ1, answ2, status)
full[num] = val
def write_to_json(k): # this fn is writing dict created by "writer" in JSON-file
with open('plain.json', 'w') as f:
json.dump(k, f, indent=4)
def write_to_xml(num): # this fn is writing dict created by "writer" in XML-file
root = Tree.Element("root")
for i in range(1, num+1):
number = Tree.SubElement(root, "number", name=str(i))
l = full[i]
Tree.SubElement(number, "model").text = l[0]
Tree.SubElement(number, "color").text = l[1]
Tree.SubElement(number, "fuel").text = l[2]
tree = Tree.ElementTree(root)
tree.write("plain.xml")
|
print ("Hello i want ask you something. Are you ok whith this? y/n")
Helo_answer=str(input())
false=(str("n"))
true=(str("y"))
if Helo_answer==(false):
print ("Ok! No problem! Bye!")
quit()
if Helo_answer==(true):
print ("OK! Lets start")
print ("What is your name?")
name=str(input())
print ("What is your second name?")
second_name=str(input())
print ("How old are you?")
age=int(input())
print ("Where are you from?")
city=str(input())
print ("Lets check your answers")
correction=("You are -" + name +"." +
"Your second name is " + second_name + "." +
"You are from " + city + ".")
print (correction)
print ("Oh!just forget. You are %i years old" %(age) )
print ("Is this correct answers? y/n")
correct_answer=str(input())
if correct_answer==false:
print ("You need to change your answers,please,start this programm again and change them")
quit()
if correct_answer==true:
file = open("saved_data.txt","w")
file.write("Name - %s, Second name - %s, age - %i, City - %s, \n"%(name,second_name,age,city))
file.close()
print("Thanks! I saved your data to file")
else: print("Please answer y/n")
print("Lets have more data from you")
#Collection
list_privateinfo=[]
Email=input(str("Enter your email please: "))
list_privateinfo.append(Email)
Phone=input(str("Enter your phone please: "))
list_privateinfo.append(Phone)
Hobby=input(str("Enter one your hobby please: "))
list_privateinfo.append(Hobby)
print(list_privateinfo)
print("Lets make your phone number more secure")
del list_privateinfo[2]
list_privateinfo.pop(1)
list_privateinfo.extend(Phone)
list_privateinfo.append(Hobby)
print(list_privateinfo)
print("Lets save these data to the file")
file = open("saved_data.txt","a")
file.write("\n".join(list_privateinfo))
print("Successfully saved")#
#Dictionary
print("Lets add more data in other format")
dict_data={}
wife_name=input(str("Enter your wife`s name please: "))
dict_data['wifes_name']=wife_name
wife_dob=input(str("Enter your wife`s date of birth please: "))
dict_data['wifes_dob']=wife_dob
son_name=input(str("Enter your son`s name:"))
dict_data['sons_name']=son_name
sons_dob=(input(str("Enter your son`s date of birth:")))
dict_data['sons_dob']=sons_dob
print("Lets save these data to the file")
import json
with open("saved_data.txt","a") as f:
json.dump(dict_data, f)
print("Data was successfully saved. Thanks")
#Control Flow
print("Lets Play with IF and ELSE and RANGE")
print("How old are you?")
ages=int(input())
if ages in range(0,2):
print("Oh you are baby!")
elif ages in range(2,14):
print("You are child!")
elif ages in range(14,21):
print ("You are teenager!")
elif ages in range(21,30):
print ("You are young!")
elif ages in range(30,45):
print ("You are adult")
else:
print("You are old!")
# (WHILE)
print("Lets count your age")
Age_counter=0
while Age_counter <= int(ages - 1):
Age_counter +=1
print(Age_counter)
print("Lets show your age with a help of CONTINUE")
Age_counter_2=0
while Age_counter_2 <= int(ages - 1):
Age_counter_2 += 1
if Age_counter_2 < int(ages):
continue
elif Age_counter_2==int(ages):
print(Age_counter_2)
quit() |
file1= open ('hello.txt','r')
data=file1.read()
print(data)
file1.close()
dict={}
dict['name']=input("Hello, what is you name?")
dict['soname']=input("Hello, what is you soname?")
live=input("We do you live?")
dict['hobby']=input('Talk about your hobby?')
print(dict)
answer=("Hello guy,your name is %s,you soname is %s you live in %s, your hobby is %s " % (dict['name'], dict['soname'],live, dict['hobby']))
print('OK, check data')
print (answer)
list=[]
list=dict['hobby']
print(list)
file2= open ('hobby.txt','w')
data1=file2.write(answer)
file2.close() |
#! usr/bin/env Python3
print ('Hello !') # collect users data
name = str(input('what is your name ?'))
surname = str(input('what is your surname ?'))
age = str(input('Ok! how old are you ?'))
city = str(input('Where are you from ?'))
mind = str(input('What do your think about Masters Academy ?'))
full_name = name +' '+surname # create users data
data = 'Name: '+full_name + '\n' +'Age:'+age+ '\n' +'City: '+city+ '\n' +'My mind about Masters Academy : '+mind+ '\n'
print('Ok! your data is:') # printing users data
print(data)
a_file = open('data.txt','w') # open file and save data in txt-file
a_file.write(data)
a_file.close()
print ('Your data saved in file "data.txt".')
|
print ("Please write about your favorite books \n")
name = input("What is your name?\n ")
age = int(input("What is your age?\n "))
book = input("What is your favorite book?\n ")
#results
result = ("Your name is %s, You are %i years old, your favorite book is %s. Thank you." % ( name, age, book ))
print (result)
print("Please give us with the additional information")
author = input("What is your favorite author?\n")
det = input("What is your favorite getective story\n")
novel = input("What is your favorite novel\n")
#dictionaries
dict_a = {
'Name': name,
'Age': age,
'book': book
}
dict_a['profession'] = ['books lover']
dict_b = {
'author': author,
'det': det,
'novel': novel
}
dict_a['new information'] = dict_b
print(dict_a)
|
class Ork():
def __init__(self, name, warclass, weapon):
self.name = name
self.warclass = warclass
self.weapon = weapon
def fight_the_enemy(self):
print("I'm fight enemy with my " + self.weapon)
def about_ork(self):
return "This is furious and strong ork. He's name - %s, his warclass is - %s and his favorite weapon of death is - %s" %(self.name, self.warclass, self.weapon) |
name = input("What is your name? ")
age = int(input("How old are you? "))
city = input("Where do you live? ")
print("Ah, so your name is %s, your age is %i, "
"and you live in %s. Fantastic!" % (name, age, city)) |
name = input("What is your name?")
surname = input("What is your surname?")
age = input("How old are you?")
profession = input("What is your profession?")
data = " My name is %s %s. I'm %s years old and I'm %s" % (name,surname, age, profession)
print(data)
file = open("data.txt", "wt")
file.write(data)
|
from Car import Car
class Truck(Car):
def __init__(self, count_wheels, engine, body, max_weight):
Car.__init__(self, count_wheels, engine, body)
self.max_weight = max_weight
self.loaded_weight = 0
def load_weight(self, weight):
self.loaded_weight += weight
if self.loaded_weight < self.max_weight:
return "load complete"
else:
return "max_weight exceeded"
def drive(self):
if self.engine_status == True:
return 'Wroom Wroom'
else:
return 'start engine before'
|
print('Hello! You must enter some personal data.')
fileName = 'data.txt'
accessMode='w'
name = input('Your full name')
mobile = int(input('Phone'))
address = input('Home address')
email = input('e-mail')
resultA = ('Dear %s, tomorrow your parcel will be delivered to the address %s.\n' % (name, address))
resultB = ('We will send you the message to mobile %i or e-mail %s with the exact time of delivery.' % (mobile, email))
File = open(fileName,accessMode)
File.write(resultA)
File.write(resultB)
File.close()
print('Our congratulations!') |
from Car import Car
class Automobile(Car):
def __init__(self, count_wheels, engine, body, max_passengers):
Car.__init__(self, count_wheels, engine, body)
self.max_passengers = max_passengers
self.loaded_passengers = 0
def load_passenger(self, passeng_count):
self.loaded_passengers += passeng_count
if self.loaded_passengers < self.max_passengers:
return "load passengers completed"
else:
return "max_passengers exceeded"
|
#homework-2
name = input("What is your name? ")
lastName = input ("What is your lastname? ")
age = int(input("How old are you? "))
country = input("Where do you live (country)? ")
dict1= {'Name': name,
'Last Name': lastName,
'age':age,
'country':country}#
# print all keys and values
#print ("Dictionary, key and value: ", dict1)
# print only values
#print ("Dictionary only values: ", dict1.values())
# homework-4
if len(name) < 2:
print ('Name too short!')
elif len (name) > 2 and len (name) < 10:
print ('Your name is normal leihgt')
else:
print ('Your name is too long!!!')
for w in name:
if w=='a' or w=='A':
print ("Name content letter A or a!")
break
else:
print("Name not content letter a")
i=0
while i < age:
print (i)
i=i+1
|
accept = input("Let's start")
if accept:
name = str(input("What is your name?\n"))
surname = str(input("Your surname ?\n"))
age = int(input("How old are you?\n"))
data = [name, surname, age]
while not name:
name = str(input("What is your name?\n"))
if age < 18:
print("You are too small for this shit")
elif age > 100:
print("WTF!!!?!?!")
for thing in data:
if not thing:
print("I didn't get enough data")
break
else:
print("Good luck!")
|
# Ask user some questions and write answers to file
# Define variables
answers = {}
full_name = ''
salary = ''
age = ''
# Questions and answers about user
print('Hello, dear customer! We need some info to register you.')
print('')
print('Please, enter your full name which must contain at least 1 character: ')
while len(full_name) < 1:
full_name = input('What is your full name? ')
answers['Full name'] = full_name
print('')
print('Please, enter your age which we believe is greater than 0: ')
while not age.isdigit():
age = input('What is your age? ')
if int(age) <= 0:
age = '1'
print('So you did not listen! Now your age is 1.')
elif int(age) in range(1, 21):
print('Your age is ' + age + '. That means no alcohol.')
else:
print('Wow, you are old enough to drink alcohol. Enjoy!')
answers['Age'] = age
print('')
print('Please, enter your salary which must contain only digits: ')
while not salary.isdigit():
salary = input('What is your approximate salary(USD)? ')
answers['Salary'] = salary
print('')
answers['Answer'] = input('What is the Answer to the Ultimate Question of Life, the Universe, and Everything? ')
# Printing
print('')
print('')
print('Your name is %s, and you are %s years old, your approximate salary is %s USD, '
'and the Answer to the Ultimate Question of Life, the Universe, '
'and Everything is %s.' % (answers['Full name'], answers['Age'], answers['Salary'], answers['Answer']))
print('Thank you! Have a nice day!')
# Operations with file in the current working directory
f = open("answers.txt", "w")
f.write(' === Information about user === \n')
for k, v in answers.items():
f.write(k + ': ' + v + '\n')
f.write(' === End of file === ')
f.close()
|
# so simple hometask
print("Please answer following questions");
full_name = input("Full name: ")
age = int(input("Age: "))
e_mail = input("E-Mail for lettering: ")
print("Here may be endless questionarie but that's anough for today");
print()
# string formatting template
human_friendly_string_template = """That guy name is %s.
Born in late %d year.
Now is %d years old.
You can E-Mail on %s"""
# calculating year of birth
current_year = 2016
year_of_birth = current_year - age
ready_string = human_friendly_string_template % (full_name, year_of_birth, age, e_mail)
my_dict = { "name": full_name, "age": age, "yob": year_of_birth, "email": e_mail }
print("Dictionary:", my_dict);
print()
print("Data lines (list):", ready_string.split("\n")) |
# Homework №1
name = input("What is your name? ")
surname = input("What is your surname? ")
age = input("How old are you? ")
city = input("Where do you live? ")
file_out = open('User_profile.txt', 'w')
# Write in file
file_out.write("**********User profile*************\n")
file_out.write("My name is: "+name+'\n')
file_out.write("My surname is: "+surname+'\n')
file_out.write("I am "+age+" year old"+'\n')
file_out.write("I live in: "+city+'\n')
file_out.write("*************************************")
file_out.close()
# Print on screen
file_in = open('User_profile.txt', 'r')
for line in file_in:
print(line, end='')
|
#!/usr/bin/env python3
print ("Hello! Welcome to our game!")
print ("")
name = str(input ("What is your name?"))
nickname = str(input ("What is your best feature you like?"))
place = str(input ("What is your favourite country?"))
gender = str(input ("What is your gender? (m/f)"))
if gender == 'm':
gen = ("Sir")
elif gender == 'f':
gen = ("Miledy")
else:
gen = ("crazy")
print ("")
print ("We congratulate you, "+gen+" "+name+" "+nickname+" from the "+place+"!")
print ("")
print ("Please, check the info")
list1 = [gen, name, nickname, place]
for i in list1:
print ('-' + str(i))
print ("")
print ("Your scared servants from Africa will call you the next way.....")
all = (gen, name, nickname)
for i in all: print (i * 2, end='')
print ("")
print ("Your dog will call you the next way.....")
for i in all: print ("Gaff gaff gaff", end='')
print ("")
age = int(input ("How old are you?"))
while age <= 14:
print ("This game have bloody scenes. Go and do your homework!")
else:
print ("Have fun!")
print ("")
print ("")
print ("Dear " + gen +" " + name +" " + nickname +" from the " + place + " ! You are the Lord of very rich castle! You have a lot of servants, your fields are full of harvest, your bank is full of money, your daughter is the most beautifil in the world. But once an evil Dragon have stolen your daughter. You are trying to resque her.")
choise1 = str(input ("You are leaving the castle and go ahead to the crossroad. What way will you chose: Left (L), Straight(S), Right(R) or Back(B)?"))
print ("")
if choise1 == "L":
print ("You came to the river. The waves are very big, it is stormy. You are going to swim to the opposite side. You swim good, but storm is very strong. Your people saved you, but your daughter is lost")
print ("Try again later!")
elif choise1 == "S":
print ("You came straight and see a big castle. It is bigger than yours. You came into and forgot your daughter. The witch are leaving here and she are going to eat you.")
print ("Try again later!")
elif choise1 == "R":
print ("You came to the Dragon cave. After heavy battle you beated the Dragon and saved your daughter!")
print ("You are the champion!!!!")
elif choise1 == "B":
print ("Are you sure? Your daughter is in danger!")
print ("Try again later!")
else:
print ("You are not serios! Your kingdom is in danger!!!")
input ("Press Enter to finish") |
import collections
# Application for collecting personal details for flight company
# Collecting personal data from client and storing it in Ordered Dictionary
personalData = collections.OrderedDict()
print('--- Someone will get to you shortly. Please Stand By ---')
personalData['name'] = str(input('Please state your full name: ')).title()
doublePrice = 0
for i in personalData['name'].split():
if i == 'Donald':
print("We are sorry to inform you but all clients with the name Donald must pay double price.")
doublePrice = 1
break
elif i == 'Hillary':
print("Lady, you are not better. Price doubled")
doublePrice = 1
break
else:
pass # TODO Add some greetings to the approved client in text form
personalData['age'] = int(input('How old are you? '))
personalData['address'] = str(input('Where you do you live? ')).title()
print('Let me pronounce your address, to be sure we get it right: ')
symbol = 0
while symbol < len(personalData['address']):
print("'%s'" % personalData['address'][symbol])
symbol += 1
addressVerification = str(input('Please confirm your address, y/n'))
if addressVerification.capitalize() == 'Y':
print('Proceed to the next question')
elif addressVerification.capitalize() == 'N':
personalData['address'] = str(input('Repeat your address')).title()
else:
print('You typed something gibberish. Proceed')
personalData['dest'] = str(input('Where are you heading? ')).title()
# Saving in variable and showing formatted data to the client
summaryMessage = ' Name: %s\n Age: %s\n Home address: %s\n Destination: %s'\
% (personalData['name'], personalData['age'], personalData['address'], personalData['dest'])
print(summaryMessage + '\n Thank you for your time ')
|
import numpy as np
import matplotlib.pyplot as plt
def integrand(x):
'''
Takes in a numpy array of x-values in 8 dimensions
Returns integrand value
'''
return (10 ** 6) * np.sin(np.sum(x))
def monte_carlo(N):
'''
Takes in your desired number of sample points to be generated
Returns Monte-Carlo estimate with theoretical error
'''
eight_d_points = np.array(np.random.rand(N, 8) * (np.pi / 8)) # Generates 8-D random points within range
integrand_of_points = np.apply_along_axis(integrand, 1,
eight_d_points) # Calculates integrand for each of these points
f_mean = (1 / N) * np.sum(integrand_of_points)
f_squared = (1 / N) * np.sum(np.square(integrand_of_points))
volume = ((np.pi / 8) ** 8)
integral_estimate = volume * f_mean
error_estimate = volume * np.sqrt((f_squared - f_mean ** 2) / N)
return [integral_estimate, error_estimate]
def multiple_runs(N_max, sep, n_t):
'''
Takes in (Maximum number of sample points N_max, Different Ns to be tested from 2 to N_max,
Number of times each N is tested)
Returns a list of results containing lists in the form of
(Sample points, Mean integral estimate, Overall Scatter, Overall Theoretical Error)
'''
list_of_Ns = np.array(np.logspace(2, N_max, num=sep)) # Creates logarithmacally spaced values from 2 to N_max
list_of_Ns = list_of_Ns.astype(int) # and converts it into an integer list
print(list_of_Ns)
results = []
for N in list_of_Ns:
mean_accu = 0
error2_accu = 0
integrated_list = np.array([])
for i in range(n_t):
run = monte_carlo(N)
mean_accu += run[0]
error2_accu += (run[1] ** 2)
integrated_list = np.append(integrated_list, run[0])
print(integrated_list)
results.append([N, mean_accu / n_t, np.std(integrated_list) / np.sqrt(n_t), np.sqrt(error2_accu / n_t)])
print("N = " + str(N) + " computation complete!")
print(results)
return results
results_table = multiple_runs(6, 25, 25)
values_of_N = [l[0] for l in results_table]
scatter_errors = [l[2] for l in results_table]
theoretical_errors = [l[3] for l in results_table]
coeffs_scatter = np.polyfit(np.log(values_of_N), np.log(scatter_errors), deg=1) # Fits scatter error values
coeffs_theoretical = np.polyfit(np.log(values_of_N), np.log(theoretical_errors), deg=1) # Fits theoretical error values
poly_scatter = np.poly1d(coeffs_scatter)
poly_theoretical = np.poly1d(coeffs_theoretical)
yfit_scatter = lambda x: np.exp(poly_scatter(np.log(x)))
yfit_theoretical = lambda x: np.exp(poly_theoretical(np.log(x)))
print(poly_scatter)
print(poly_theoretical)
plt.loglog(values_of_N, scatter_errors, 'o', markersize=2, color='blue',
label="Standard Deviation of Monte-Carlo estimates")
plt.loglog(values_of_N, yfit_scatter(values_of_N), color='blue',
label="Standard Deviation of Monte-Carlo estimates (Best-fit)")
plt.loglog(values_of_N, theoretical_errors, 'o', markersize=2, color='orange',
label="Theoretical error of Monte-Carlo estimates")
plt.loglog(values_of_N, yfit_theoretical(values_of_N), color='orange',
label="Theoretical error of Monte-Carlo estimates (Best-fit)")
plt.legend(prop={'size': 8})
plt.xlabel("N")
plt.ylabel("Error")
plt.title("Errors of the Monte-Carlo method against number of sample points N")
plt.savefig("Core1.pdf")
|
from HuffmanNode import *
class HuffmanEncoder:
#Class responsible for encoding a text file based on the Huffman Greedy Algorithm.
def __str__(self):
return "Huffman Encoder"
def encode(self, inFile, outFile):
print ("encode")
try:
nodeList = self.parseInput(inFile)
header = self.createHeader(nodeList)
if len(nodeList) == 0:
#Case where file is empty.
print ("File is empty, there is nothing to encode.")
elif len(nodeList) == 1:
#Case where file only has one character, the header is only written to the encoded file.
out = open(outFile, 'w')
out.write(header)
out.close()
else:
#Case where file is not empty and has more than one character.
tree = self.buildTree(nodeList)
characterList = self.characterListEncode(tree)
file = open(inFile, 'r')
out = open(outFile, 'w')
out.write(header)
out.write("\n")
for line in file:
for character in line:
out.write(characterList[ord(character)])
file.close()
out.close()
except IOError:
print ("Sorry File Does not Exist")
def parseInput(self, inFile):
#Method that parses the input file and returns a list containing the Huffman Nodes of characters in the input file.
counter = 0
initialList = []
finalList = []
while (counter < 256):
initialList.append(Node(chr(counter), 0))
counter = counter + 1
file = open(inFile, "r")
for line in file:
for charachter in line:
node = initialList[ord(charachter)]
node.setFrequency(node.getFrequency() + 1)
file.close()
for node in initialList:
if node.getFrequency() > 0:
finalList.append(node)
return finalList
def comesBefore(self, node1, node2):
#Method that determines which node amongst the two arguments should come before during sorting.
if node1.getFrequency() < node2.getFrequency():
return node1
elif node1.getFrequency() > node2.getFrequency():
return node2
else:
if node1.getMinimum() < node2.getMinimum():
return node1
else:
return node2
def mergeSort(self, nodeList):
#Method that sorts a list of Huffman Nodes using the merge sort algorithm.
#Nodes are sorted from highest frequency to lowest frequency.
if len(nodeList) > 1:
mid = len(nodeList) // 2
lefthalf = nodeList[:mid]
righthalf = nodeList[mid:]
self.mergeSort(lefthalf)
self.mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if self.comesBefore(lefthalf[i], righthalf[j]) == lefthalf[i]:
nodeList[k] = lefthalf[i]
i = i + 1
else:
nodeList[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
nodeList[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
nodeList[k] = righthalf[j]
j = j + 1
k = k + 1
return nodeList
def buildTree(self, nodeList):
#Method that build a HuffmanTree needed for Encoding.
self.mergeSort(nodeList)
while(len(nodeList) > 2):
first = nodeList.pop(0)
second = nodeList.pop(0)
node = Node(None, first.getFrequency() + second.getFrequency())
if self.comesBefore(first, second) == first:
node.left = first
node.right = second
else:
node.left = second
node.right = first
if node.getLeft().getMinimum() > node.getRight().getMinimum():
node.setMinimum(node.getRight().getMinimum())
else:
node.setMinimum(node.getLeft().getMinimum())
nodeList.append(node)
self.mergeSort(nodeList)
first = nodeList.pop(0)
second = nodeList.pop(0)
node = Node(None, first.getFrequency() + second.getFrequency())
if self.comesBefore(first, second) == first:
node.left = first
node.right = second
else:
node.left = second
node.right = first
if node.getLeft().getMinimum() > node.getRight().getMinimum():
node.setMinimum(node.getRight().getMinimum())
else:
node.setMinimum(node.getLeft().getMinimum())
return node
def characterListEncode(self, treeNode):
#Method that returns a list representing the path needed to get to characters in the HuffmanTree, during the encoding process.
#Path can be obtained by using the ASCII value of a character, as an index in the characterList.
characterList = [""] * 256
self.charachterListEncodeHelper(characterList, treeNode, "")
return characterList
def charachterListEncodeHelper(self, characterList, node, inString):
#Helper Method for the characterListEncode method.
if (node.getLeft() == None) and (node.getRight() == None):
characterList[ord(node.getCharacter())] = inString
else:
self.charachterListEncodeHelper(characterList, node.getLeft(), inString + "0")
self.charachterListEncodeHelper(characterList, node.getRight(), inString + "1")
def createHeader(self, nodeList):
header = ""
for node in nodeList:
header = header + str(ord(node.getCharacter())) + " " + str(node.getFrequency()) + " "
header = header[:-1]
return header
|
answer = 43
if answer != 42:
print("That is not correct answer. Please try again")
else:
print("You WIN!")
|
# name = input("Please enter your name: ")
# print("Hello, " + name + "!")
# promt = 'If you tell us who you are, we can personalize the messages you see.'
# promt += "\nWaht is your first name? "
# name = input(promt)
# print("n\Hello, " + name + "!")
# age = input("How old are you? ")
# age = int(age)
# if age >= 18:
# print("age >= 18")
# else:
# print("Эмалолетка")
# def great_user(username, username_2):
# print("hello, " + username.title() + "! " + username_2.title())
# great_user('maaaaax', 'dfddfdf')
# username = input('\nВведите имя 1: ')
# username_2 = input('\nВведите имя 2: ')
# great_user(username, username_2)
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
f_name = input("First name: ")
l_name = input("Last name: ")
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!") |
#!/usr/bin/env python
def tribonacci(n):
if n == 1:
return 1
if n == 2:
return 1
if n == 3:
return 2
return (tribonacci(n - 3) + tribonacci(n - 2) + tribonacci(n - 1))
print(tribonacci(int(input())))
|
import streamlit as st
import streamlit_lottie from st_lottie
import pandas as pd
import requests
password_attempt = st.text_input('Please Enter The Password')
if password_attempt != 'example_password':
st.write('Incorrect Password!')
st.stop()
def load_lottieurl(url: str):
r = requests.get(url)
if r.status_code != 200:
return None
return r.json()
lottie_airplane = load_lottieurl('https://assets4.lottiefiles.com/packages/lf20_jhu1lqdz.json')
st_lottie(lottie_airplane, speed=1, height=200, key="initial")
st.title('Major US Airline Job Application')
st.write('by Tyler Richards')
st.subheader('Question 1: Airport Distance')
'''
The first exercise asks us 'Given the table of airports and
locations (in latitude and longitude) below,
write a function that takes an airport code as input and
returns the airports listed from nearest to furthest from
the input airport.' There are three steps here:
1. Load Data
2. Implement Distance Algorithm
3. Apply distance formula across all airports other than the input
4. Return sorted list of airports Distance
'''
airport_distance_df = pd.read_csv('airport_location.csv')
with st.echo():
#load necessary data
airport_distance_df = pd.read_csv('airport_location.csv')
'''
From some quick googling, I found that the haversine distance is
a good approximation for distance. At least good enough to get the
distance between airports! Haversine distances can be off by up to .5%,
because the earth is not actually a sphere. It looks like the latitudes
and longitudes are in degrees, so I'll make sure to have a way to account
for that as well. The haversine distance formula is labeled below,
followed by an implementation in python
'''
st.image('haversine.png')
with st.echo():
from math import radians, sin, cos, atan2, sqrt
def haversine_distance(long1, lat1, long2, lat2, degrees=False):
#degrees vs radians
if degrees == True:
long1 = radians(long1)
lat1 = radians(lat1)
long2 = radians(long2)
lat2 = radians(lat2)
#implementing haversine
a = sin((lat2-lat1) / 2)**2 + cos(lat1) * cos(lat2) * sin((long2-long1) / 2)**2
c = 2*atan2(sqrt(a), sqrt(1-a))
distance = 6371 * c #radius of earth in kilometers
return(distance)
#execute haversine function definition
from math import radians, sin, cos, atan2, sqrt
def haversine_distance(long1, lat1, long2, lat2, degrees=False):
#degrees vs radians
if degrees == True:
long1 = radians(long1)
lat1 = radians(lat1)
long2 = radians(long2)
lat2 = radians(lat2)
#implementing haversine
a = sin((lat2-lat1) / 2)**2 + cos(lat1) * cos(lat2) * sin((long2-long1) / 2)**2
c = 2*atan2(sqrt(a), sqrt(1-a))
distance = 6371 * c #radius of earth in kilometers
return(distance)
'''
Now, we need to test out our function! The
distance between the default points is
18,986 kilometers, but feel free to try out
your own points of interest.
'''
long1 = st.number_input('Longitude 1', value = 2.55)
long2 = st.number_input('Longitude 2', value = 172.00)
lat1 = st.number_input('Latitude 1', value = 49.01)
lat2 = st.number_input('Latitude 2', value = -43.48)
test_distance = haversine_distance(long1 = long1, long2 = long2,
lat1 = lat1, lat2 = lat2, degrees=True)
st.write('Your distance is: {} kilometers'.format(int(test_distance)))
'''
We have the Haversine distance implemented, and we also have
proven to ourselves that it works reasonably well.
Our next step is to implement this in a function!
'''
def get_distance_list(airport_dataframe, airport_code):
df = airport_dataframe.copy()
row = df[df.loc[:,'Airport Code'] == airport_code]
lat = row['Lat']
long = row['Long']
df = df[df['Airport Code'] != airport_code]
df['Distance'] = df.apply(lambda x: haversine_distance(lat1=lat, long1=long,
lat2 = x.Lat, long2 = x.Long, degrees=True), axis=1)
return(df.sort_values(by='Distance').reset_index()['Airport Code'])
with st.echo():
def get_distance_list(airport_dataframe, airport_code):
df = airport_dataframe.copy() #creates a copy of our dataframe for our function to use
row = df[df.loc[:,'Airport Code'] == airport_code] #selects the row from our airport code input
lat = row['Lat'] #get latitude
long = row['Long'] #get longitude
df = df[df['Airport Code'] != airport_code] #filter out our airport, implement haversine distance
df['Distance'] = df.apply(lambda x: haversine_distance(lat1=lat, long1=long,
lat2 = x.Lat, long2 = x.Long, degrees=True), axis=1)
return(df.sort_values(by='Distance').reset_index()['Airport Code']) #return values sorted
'''
To use this function, select an airport from the airports provided in the dataframe
and this application will find the distance between each one, and
return a list of the airports closest to furthest.
'''
selected_airport = st.selectbox('Airport Code', airport_distance_df['Airport Code'])
distance_airports = get_distance_list(
airport_dataframe=airport_distance_df, airport_code=selected_airport)
st.write('Your closest airports in order are {}'.format(list(distance_airports)))
'''
This all seems to work just fine! There are a few ways I would improve this if I was working on
this for a longer period of time.
1. I would implement the [Vincenty Distance](https://en.wikipedia.org/wiki/Vincenty%27s_formulae)
instead of the Haversine distance, which is much more accurate but cumbersome to implement.
2. I would vectorize this function and make it more efficient overall.
Because this dataset is only 7 rows long, it wasn't particularly important,
but if this was a crucial function that was run in production we would want to vectorize it for speed.
'''
st.subheader('Question 2: Representation')
'''
For this transformation, there are a few things
that I would start with. First, I would have to define
what a unique trip actually was. In order to do this, I would
group by the origin, the destination, and the departure date
(for the departure date, often customers will change around
this departure date, so we should group by the date plus or
minus at least 1 buffer day to capture all the correct dates).
Additionally, we can see that often users search from an entire city,
and then shrink that down into a specific airport. So we should also
consider a group of individual queries from cities and airpots in the
same city, as the same search, and do the same for destination.
From that point, we should add these important columns to each unique search.
'''
example_df = pd.DataFrame(columns=['userid', 'number_of_queries', 'round_trip', 'distance', 'number_unique_destinations',
'number_unique_origins', 'datetime_first_searched','average_length_of_stay',
'length_of_search'])
example_row = {'userid':98593, 'number_of_queries':5, 'round_trip':1,
'distance':893, 'number_unique_destinations':5,
'number_unique_origins':1, 'datetime_first_searched':'2015-01-09',
'average_length_of_stay':5, 'length_of_search':4}
st.write(example_df.append(example_row, ignore_index=True))
'''
For answering the second part of the question, we should take the euclidian distance
on two normalized vectors. There are two solid options for comparing two
entirely numeric rows, the euclidian distance (which is just the straight line
difference between two values), and the manhattan distance (think of this as the
distance traveled if you had to use city blocks to travel diagonally across manhattan).
Because we have normalized data, and the data is not high dimensional or sparse, I
would recommend using the euclidian distance to start off. This distance would tell
us how similar two trips were.
'''
|
#!/usr/bin/env python3
"""Matrix concatenation"""
import numpy as np
def np_cat(mat1, mat2, axis=0):
"""Concatenates two n-dimensional matrices. Depends on the given axis.
Args:
mat1 (numpy.ndarray): first matrix.
mat2 (numpy.ndarray): second matrix.
axis (int): 0 concatenates rows, 1 concatenates cols.
Returns:
numpy.ndarray: concatenated matrix.
"""
return np.concatenate((mat1, mat2), axis=axis)
|
#!/usr/bin/env python3
"""Class Normal"""
e = 2.7182818285
pi = 3.1415926536
class Normal():
""" Class to calculate Normal distribution"""
def __init__(self, data=None, mean=0., stddev=1.):
"""Initialize the distribution
Args:
data (list): values of distribution.
mean (float): mean of distribution.
stddev (float): standard deviation of distribution.
"""
self.mean = float(mean)
self.stddev = float(stddev)
if data is None:
if self.stddev <= 0:
raise ValueError("stddev must be a positive value")
else:
if isinstance(data, list):
if len(data) > 1:
self.mean = sum(data) / len(data)
n = len(data)
variance = sum([(n - self.mean) ** 2 for n in data]) / n
self.stddev = variance ** 0.5
else:
raise ValueError("data must contain multiple values")
else:
raise TypeError("data must be a list")
def z_score(self, x):
"""Calculates z
Args:
x (float): x-value.
Returns:
float: z value
"""
return (x - self.mean) / self.stddev
def x_value(self, z):
"""Calculates x from z
Args:
z (float): z-score
Returns:
float: x-score
"""
return z * self.stddev + self.mean
def pdf(self, x):
"""Calculates the function
Args:
x (float): x-value.
Returns:
float: the probability at x-value.
"""
constant = 1 / (self.stddev * (2 * pi) ** 0.5)
exponent = e ** -(((x - self.mean) ** 2) / (2 * self.stddev ** 2))
return constant * exponent
def cdf(self, x):
""" Calculates the cummulative distribution function.
Args:
x (float): x-value.
Returns:
float: the CDF.
"""
b = (x - self.mean) / (self.stddev * (2 ** 0.5))
erf = (2 / (pi ** 0.5)) * \
(b - (b ** 3) / 3 + (b ** 5) / 10 - (b ** 7) / 42 +
(b ** 9) / 216)
return 0.5 * (1 + erf)
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
fruit = np.random.randint(0, 20, (4, 3))
index = ('Farrah', 'Fred', 'Felicia')
fruits = ('apples', 'bananas', 'oranges', 'peaches')
colors = ('red', 'yellow', '#ff8000', '#ffe5b4')
width = 0.5
for i in range(fruit.shape[0]):
plt.bar(index, fruit[i], width,
bottom=np.sum(fruit[:i], axis=0),
color=colors[i],
label=fruits[i])
plt.ylabel('Quantity of Fruit')
plt.yticks(np.arange(0, 90, step=10))
plt.title("Number of Fruit per Person")
plt.legend()
plt.show()
|
#!/usr/bin/env python3
"""
Markov chain
"""
import numpy as np
def absorbing(P):
""" determines if a markov chain is absorbing.
Args:
P (np-ndarray): of shape (n, n) representing the transition matrix.
- P[i, j] is the probability of transitioning from
state i to state j.
- n is the number of states in the markov chain.
Returns:
a numpy.ndarray of shape (1, n) containing the steady state
probabilities, or None on failure.
"""
if type(P) is not np.ndarray or len(P.shape) != 2 or \
P.shape[0] != P.shape[1]:
return None
if np.all(np.diag(P) == 1):
return True
if not np.any(np.diagonal(P) == 1):
return False
for i in range(len(P)):
for j in range(len(P[i])):
if (i == j) and (i + 1 < len(P)):
if P[i + 1][j] == 0 and P[i][j + 1] == 0:
return False
return True
|
#!/usr/bin/env python3
"""
Gaussian
"""
import numpy as np
class GaussianProcess():
"""
Gaussian Class
"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor
Args:
X_init (np.ndarray): shape (t, 1) representing the inputs already
sampled with the black-box function.
Y_init (np.ndarray): shape (t, 1) representing the outputs of the
black-box function for each input in X_init.
l (int): the length parameter for the kernel.
sigma_f (int): the standard deviation given to the output of the
black-box function.
"""
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
def kernel(self, X1, X2):
"""calculates the covariance kernel matrix between two matrices
Args:
X1 (np.ndarray): shape (m, 1)
X2 (np.ndarray): shape (n, 1)
Returns:
the covariance kernel matrix as a numpy.ndarray of shape (m, n).
"""
a = np.sum(X1 ** 2, 1).reshape(-1, 1)
sqdist = a + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
return self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)
|
#!/usr/bin/env python3
"""Binomial Normal"""
e = 2.7182818285
pi = 3.1415926536
def factorial(n):
"""Calculates factorial of integer
/9
Args:
n (int): number
Returns:
int: n! = 1 * 2 * ... * n
"""
ans = 1
if n == 0:
return 1
for n in range(1, n + 1):
ans *= n
return ans
class Binomial():
"""Class Binomial"""
def __init__(self, data=None, n=1, p=0.5):
"""Initializes the distribution.
Args:
data (list): distribution data
n (int): Bernoulli number.
p (float): success probability.
"""
self.n = int(n)
self.p = float(p)
if data is None:
if self.n < 1:
raise ValueError("n must be a positive value")
elif self.p <= 0 or self.p >= 1:
raise ValueError("p must be greater than 0 and less than 1")
else:
if isinstance(data, list):
if len(data) > 1:
self.data = data
mean = sum(self.data) / len(self.data)
variance = (sum([(num - mean) ** 2 for num in self.data]) /
len(self.data))
p = 1 - variance / mean
self.n = int(round(mean / p))
self.p = mean / self.n
else:
raise ValueError("data must contain multiple values")
else:
raise TypeError("data must be a list")
def pmf(self, k):
""" Calculates the pmf at a given k
Args:
k (int): point to calculate.
Returns:
float: probability at point k.
"""
x = int(k)
if x > self.n or x < 0:
return 0
else:
n = int(self.n)
combination = factorial(n) / (factorial(x) * factorial(n - x))
probability = (self.p ** x) * ((1 - self.p) ** (n - x))
return combination * probability
def cdf(self, k):
""" Calculates the cdf.
Args:
k (int): point to calculate.
Returns:
float: probability at point k.
"""
x = int(k)
if x > self.n or x < 0:
return 0
cdf = 0
for i in range(x + 1):
cdf += self.pmf(i)
return cdf
|
#!/usr/bin/env python3
"""
Identity block
"""
import tensorflow.keras as K
def identity_block(A_prev, filters):
"""Builds an identity block as described in Deep Residual Learning for
Image Recognition (2015).
Args:
A_prev (Keras layer): the output from the previous layer.
filters (list or tuple): [F11, F3, F12]
F11 is the number of filters in the first 1x1
convolution.
F3 is the number of filters in the 3x3
convolution.
F12 is the number of filters in the second
1x1 convolution as well as the 1x1
convolution in the shortcut connection.
Returns:
The activated output of the identity block.
"""
conv1 = K.layers.Conv2D(filters=filters[0],
kernel_size=1,
padding='same',
kernel_initializer='he_normal')(A_prev)
batch1 = K.layers.BatchNormalization()(conv1)
relu1 = K.layers.Activation('relu')(batch1)
conv2 = K.layers.Conv2D(filters=filters[1],
kernel_size=3,
padding='same',
kernel_initializer='he_normal')(relu1)
batch2 = K.layers.BatchNormalization()(conv2)
relu2 = K.layers.Activation('relu')(batch2)
conv3 = K.layers.Conv2D(filters=filters[2],
kernel_size=1,
padding='same',
kernel_initializer='he_normal')(relu2)
batch3 = K.layers.BatchNormalization()(conv3)
adding = K.layers.Add()([batch3, A_prev])
output = K.layers.Activation('relu')(adding)
return output
|
#!/usr/bin/env python3
"""
Vanilla Encoder
"""
import tensorflow.keras as keras
def autoencoder(input_dims, filters, latent_dims):
"""creates a convolutional autoencoder:
input_dims is a tuple of integers containing the dimensions of the model
input
filters is a list containing the number of filters for each convolutional
layer in the encoder, respectively
the filters should be reversed for the decoder
latent_dims is a tuple of integers containing the dimensions of the latent
space representation
Each convolution in the encoder should use a kernel size of (3, 3) with
same padding and relu activation, followed by max pooling of size (2, 2)
Each convolution in the decoder, except for the last two, should use a
filter size of (3, 3) with same padding and relu activation, followed by
upsampling of size (2, 2)
The second to last convolution should instead use valid padding
The last convolution should have the same number of filters as the
number of channels in input_dims with sigmoid activation and no
upsampling
Returns: encoder, decoder, auto
encoder is the encoder model
decoder is the decoder model
auto is the full autoencoder model
"""
input_encoder = keras.Input(shape=input_dims)
encoded = keras.layers.Conv2D(filters=filters[0],
kernel_size=3,
padding='same',
activation='relu')(input_encoder)
encoded_pool = keras.layers.MaxPool2D(pool_size=(2, 2),
padding='same')(encoded)
for i in range(1, len(filters)):
encoded = keras.layers.Conv2D(filters=filters[i],
kernel_size=3,
padding='same',
activation='relu')(encoded_pool)
encoded_pool = keras.layers.MaxPool2D(pool_size=(2, 2),
padding='same')(encoded)
latent = encoded_pool
encoder = keras.models.Model(input_encoder, latent)
input_decoder = keras.Input(shape=(latent_dims))
decoded = keras.layers.Conv2D(filters=filters[i],
kernel_size=3,
padding='same',
activation='relu')(input_decoder)
decoded_pool = keras.layers.UpSampling2D(size=(2, 2))(decoded)
for i in range(len(filters) - 2, -1, -1):
if i == 0:
decoded = keras.layers.Conv2D(filters=filters[i],
kernel_size=3,
padding='valid',
activation='relu')(decoded_pool)
decoded_pool = keras.layers.UpSampling2D(size=(2, 2))(decoded)
else:
decoded = keras.layers.Conv2D(filters=filters[i], kernel_size=3,
padding='same',
activation='relu')(decoded_pool)
decoded_pool = keras.layers.UpSampling2D(size=[2, 2])(decoded)
decoded = keras.layers.Conv2D(filters=1, kernel_size=3,
padding='same',
activation='sigmoid')(decoded_pool)
decoder = keras.models.Model(input_decoder, decoded)
input_autoencoder = keras.Input(shape=(input_dims))
encoder_outs = encoder(input_autoencoder)
decoder_outs = decoder(encoder_outs)
autoencoder = keras.models.Model(inputs=input_autoencoder,
outputs=decoder_outs)
autoencoder.compile(optimizer='Adam', loss='binary_crossentropy')
return encoder, decoder, autoencoder
|
#!/usr/bin/env python3
"""
Mean and covariance
"""
import numpy as np
def likelihood(x, n, P):
"""Calculates the likelihood of obtaining this data given various
hypothetical probabilities of developing severe side effects.
Args:
x (int): number of patients that develop severe side effects.
n (int): total number of patients observed.
P (np.ndarray): 1D containing the various hypothetical
probabilities of developing severe side
effects.
Returns:
1D numpy.ndarray containing the likelihood of obtaining the data, x
and n, for each probability in P, respectively.
"""
if not isinstance(n, int) or (n <= 0):
raise ValueError("n must be a positive integer")
if not isinstance(x, int) or (x < 0):
raise ValueError(
"x must be an integer that is greater than or equal to 0")
if x > n:
raise ValueError("x cannot be greater than n")
if not isinstance(P, np.ndarray) or len(P.shape) != 1:
raise TypeError("P must be a 1D numpy.ndarray")
if not np.all((P >= 0) & (P <= 1)):
raise ValueError("All values in P must be in the range [0, 1]")
combination = np.math.factorial(n) / (np.math.factorial(n - x) *
np.math.factorial(x))
lik = combination * (P ** x) * ((1 - P) ** (n - x))
return lik
|
#!/usr/bin/env python3
"""
Bias correction
"""
def moving_average(data, beta):
"""Calculates the weighted moving average of a data set.
Args:
data (list): data to calculate the moving average of.
beta (float): weight used for the moving average.
Returns:
list: moving averages of data.
"""
Vt = 0
W_averages = []
for i in range(len(data)):
Vt = beta * Vt + (1 - beta) * data[i]
b_correction = 1 - beta ** (i + 1)
W_averages.append(Vt / b_correction)
return W_averages
|
#!/usr/bin/env python3
"""
Retrieving passengers
"""
import requests
def availableShips(passengerCount):
"""returns the list of ships that can hold a given number of passengers.
Args:
passengerCount (int): number of passengers to hold
Returns:
list of ships.
"""
ships = []
url = 'https://swapi-api.hbtn.io/api/starships/'
while url:
r = requests.get(url)
for ship in r.json()['results']:
passengers = ship['passengers'].replace(',', '')
if passengers.isnumeric() and int(passengers) >= passengerCount:
ships.append(ship['name'])
url = r.json()['next']
return ships
|
from flask import Flask, jsonify, request
app = Flask (__name__) # Created an object of flask using a unique name
stores = [
{
'name': 'MyStore',
'items':[
{
'name': 'MyItem',
'price': '15.00'
}
]
}
]
#POST /store data: {name:} - creates a new store
@app.route('/store',methods = ['POST'])
def create_store():
request_data = request.get_json()
new_store = {
'name' : request_data['name'],
'items' : []
}
stores.append(new_store)
return jsonify(new_store)
#Gets the name of the store specified
@app.route('/store/<string:name>')
def get_store(name):
#Iterate over stores
#if the store name matches, return it
#else note match return error
found = False
for store in stores:
if store['name'] ==name :
return jsonify(f'{name} was found as a store')
return("The of the store you passed was not found")
#Gets the name of all the stores
@app.route('/store')
def get_stores():
return jsonify({'stores': stores})
#Creates an Item in the specificed store
@app.route('/store/<string:name>/item', methods=['POST'])
def create_item_in_store(name):
request_data = request.get_json()
for store in stores:
if store['name'] == name:
new_item = {
'name' : request_data['name'],
'price' : request_data['price']
}
store['items'].append(new_item)
return jsonify(new_item)
return jsonify({'message' : 'store not found'})
#Gets an Item in the specificed store
@app.route('/store/<string:name>/item')
def get_items_in_store(name):
for store in stores:
if store['name'] == name :
return jsonify({'items': store['items']})
return jsonify("This item was not found")
app.run(port = 5000) #port for our application to run on |
import cv2
import numpy as np
img = cv2.imread("/Users/heguangqin/Pictures/source_1.jpg")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rows,cols = img_gray.shape
minimum = img_gray.copy()
print "starting"
for r in range(1,rows-1):
for c in range(1,cols-1):
minimum[r, c] = img_gray[r-1:r+2,c-1:c+2].min()
print "end"
cv2.imshow("gray",img_gray)
cv2.imshow("minimum 3*3",minimum)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
import time
from functools import reduce
#Global Variabel
currentYear = int(time.strftime ('%Y'))
userData = []
#Get Age Function
getAge = lambda born : abs (currentYear - born)
#input from console
inputNewData = 'Y'
while(inputNewData.lower() == 'y') :
userObjek = {}
print('Masukkan nama :')
userObjek ['name'] = input ()
print ('Masukkan tahun lahir : ')
userObjek['born'] = int(input())
userData.append (userObjek)
userObjek = {}
print ('Ingin menambah user? [Y/N]')
inputNewData = input ()
#Filter user by youngest
userData = sorted(userData, key = lambda x : getAge(x['born']), reverse = True)
#Find user by oldest
olderUser = reduce(lambda x, y : x
if getAge(x['born']) > getAge(y['born'])
else y, userData)
#print result to console
print ("\n\n====================\n")
print (f"{olderUser['name']} adalah orang paling tua dengan umur { getAge(olderUser['born']) } tahun")
print ("====================")
#Compare oldest user with another user
for index, user in enumerate (userData) :
if user ['name'] != olderUser ['name'] :
print (f"No : { index }")
print (f"Nama : { user['name'] }")
print(f"Umur : {getAge(user['born'])} tahun")
print (f"Perbedaan umur : { abs(getAge(user['born']) - getAge(olderUser['born'])) } tahun")
print ("====================") |
about = {}
isInsert = 'Y'
hobbies = []
# Nama
print('Siapa nama kamu ?')
about['nama'] = input()
# #nim
print('Brapa NIM kamu ?')
about['nim'] = input()
# #alamat
print('Dimana kamu tinggal ?')
about['alamat'] = input()
#hobby
while(isInsert.lower() == 'y' ) :
print('Masukan Hobby kamu : ')
newHobby = input()
hobbies.append(newHobby)
print('Isi hobby lagi ? : [Y/N] ')
isInsert = input()
about['hobbies'] = hobbies
# Output
print('\n\n========= Output =========\n\n')
for key, value in about.items():
# check instance is list
if isinstance(value, list):
print('Hobby Kamu adalah : ')
#looping hobbies
for index, hobby in enumerate(value):
print('\t' + str(index + 1) + '. ' + hobby)
else:
print(key.capitalize() + ' kamu adalah :' + value + '\n') |
import sqlite3
import datetime
import os
def CreateTable():
#creates tables to log info if it doesn't exists. Will be run first time, or if it moves.
conn = sqlite3.connect('log.db')
c = conn.cursor()
c.execute("CREATE TABLE log (date datetime, project varchar(255), timeTaken varchar(255));")
conn.commit()
conn.close()
def GetProjects():
#fetches unique list of projects to choose from, and sorts into alphabeticl order
conn = sqlite3.connect('log.db')
c = conn.cursor()
c.execute("Select distinct project from log")
MyProjects = [i[0] for i in c.fetchall()]
MyProjects.sort()
conn.commit()
conn.close()
return MyProjects
def InsertProjects(sqlDate,sqlProject,sqlTimeLength):
conn = sqlite3.connect('log.db')
c = conn.cursor()
c.execute("INSERT INTO log VALUES (?,?,?)", (sqlDate,sqlProject,sqlTimeLength))
conn.commit()
conn.close()
def run():
if not os.path.isfile('log.db'):
CreateTable()
ProjectNumbers = int(input("""How many projects have you worked on today?\n
Include internal work like learning or MBD projects) """))
for i in range(ProjectNumbers):
projectList = GetProjects()
print("Choose from previous projects, or enter new project \n")
for idNo,project in enumerate(projectList):
print (f"{idNo}: {project}")
xProject = input(f"\nEnter number or new project: ")
try:
xProject = int(xProject)
xProject = projectList[xProject]
except:
pass
TimeLength = input("How long did you spend? ")
if not i == (ProjectNumbers -1):
print("\n---Next Project---\n")
InsertProjects(datetime.datetime.now(),xProject.strip(),TimeLength)
if __name__ == "__main__":
run() |
# Towers of Hanoi
# Hayden Smedley
import os
import keyboard
import time
import random
# Empty spot on the board
blank = " "
# Hidden value at end of each tower to simplify placing blocks
ender = "###########"
# Standardized divider
divider = "---------------------------------"
# Blocks used in game
blocks = [" # ", " ### ", " ##### ", " ####### ", "#########"]
# Example of a completed tower for comparison
completed = [" # ", " ### ", " ##### ", " ####### ", "#########", ender]
# Creates board
def createBoard(inBlocks, inBoard):
for block in inBlocks:
col = random.randint(0,2)
row = random.randint(0,4)
# Checks if random spot is already filled
while inBoard[col][row] != blank:
col = random.randint(0,2)
row = random.randint(0,4)
inBoard[col][row] = block
# Sorts board
inBoard[0].sort()
inBoard[1].sort()
inBoard[2].sort()
# Checks if created board is in a win state
if checkWin(inBoard[0], inBoard[1], inBoard[2]):
inBoard = createBoard(inBlocks, inBoard)
return(inBoard)
# Checks OS and clears terminal
def clear():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
# Display the current board
def display(in1, in2, in3, sel, selb, count):
clear()
print(divider)
# Display number of moves if not on game opening
if count == 0:
print("Welcome to Towers of Hanoi")
else:
print("Moves: " + str(count))
print(divider)
# Display block selected
print("Selected Block: " + selb)
print(divider)
# Display which tower is selected
if sel == 1:
print(" [A] " + " B " + " C ")
elif sel == 2:
print(" A " + " [B] " + " C ")
elif sel == 3:
print(" A " + " B " + " [C] ")
else:
print("Selector out of bounds")
# Display board
print(" " + in1[0] + " " + in2[0] + " " + in3[0] + " ")
print(" " + in1[1] + " " + in2[1] + " " + in3[1] + " ")
print(" " + in1[2] + " " + in2[2] + " " + in3[2] + " ")
print(" " + in1[3] + " " + in2[3] + " " + in3[3] + " ")
print(" " + in1[4] + " " + in2[4] + " " + in3[4] + " ")
print(divider)
print("Control via arrow keys, left and \nright to select tower, up to \nselect block, down to deposit \nselected block, ESC to quit")
print(divider)
# Check if move is valid
def validMove(inPiece, inTower):
if inTower[0] != blank:
return(False)
elif inTower[1] < inPiece and inTower[1] != blank:
return(False)
elif inTower[2] < inPiece and inTower[2] != blank:
return(False)
elif inTower[3] < inPiece and inTower[3] != blank:
return(False)
elif inTower[4] < inPiece and inTower[4] != blank:
return(False)
else:
return(True)
# Check if board is in a win state
def checkWin(in1, in2, in3):
if in1 == completed:
return(True)
elif in2 == completed:
return(True)
elif in3 == completed:
return(True)
else:
return(False)
def runGame():
# Stores which tower is selected
selector = 1
# Stores a block when one is selected
selected = blank
# Current win state
win = False
# How many moves have been taken
moves = 0
# Towers
tower1 = [blank, blank, blank, blank, blank, ender]
tower2 = [blank, blank, blank, blank, blank, ender]
tower3 = [blank, blank, blank, blank, blank, ender]
# Array for generating a board
board = [tower1, tower2, tower3]
endGame = False
# Create initial board
board = createBoard(blocks, board)
# Assign created towers
tower1 = board[0]
tower2 = board[1]
tower3 = board[2]
# Display opening board
display(tower1, tower2, tower3, selector, selected, moves)
# Run game
while win is not True:
# change selected tower to the left
if keyboard.is_pressed("left"):
time.sleep(0.1)
selector = selector - 1
# Check if looped around
if selector < 1:
selector = 3
display(tower1, tower2, tower3, selector, selected, moves)
# change selected tower to the right
if keyboard.is_pressed("right"):
time.sleep(0.1)
selector = selector + 1
# Check if looped around
if selector > 3:
selector = 1
display(tower1, tower2, tower3, selector, selected, moves)
# Selecting a block
if keyboard.is_pressed("up"):
time.sleep(0.1)
# Check if something is already selected
if selected == blank:
board = [tower1, tower2, tower3]
for i, block in enumerate(board[selector - 1]):
# Find first non blank spot that is not the hidden end piece
if block != blank and i != (len(board[selector - 1]) - 1):
selected = block
board[selector - 1][i] = blank
tower1 = board[0]
tower2 = board[1]
tower3 = board[2]
display(tower1, tower2, tower3, selector, selected, moves)
break
# Deposit block
if keyboard.is_pressed("down"):
time.sleep(0.1)
# Check if something is actually selected
if selected != blank:
board = [tower1, tower2, tower3]
# Deposit if move is valid
if validMove(selected, board[selector - 1]):
for i, block in enumerate(board[selector - 1]):
# Find first non blank spot
if block != blank:
board[selector - 1][i - 1] = selected
selected = blank
moves += 1
tower1 = board[0]
tower2 = board[1]
tower3 = board[2]
display(tower1, tower2, tower3, selector, selected, moves)
break
# End game early
if keyboard.is_pressed("esc"):
print("Game Ended")
break
# Check if the game has been won and end the game
if checkWin(tower1, tower2, tower3):
win = True
print("YOU WIN")
print(divider)
break
# Close program after ESC is hit or start a new one if Space is hit
if win and endGame is not True:
print("Press 'ESC' to end program or 'Space' to start a new one.")
while endGame is not True:
if keyboard.is_pressed("esc"):
endGame = True
if keyboard.is_pressed("space"):
runGame()
endGame = True
runGame()
|
def rearrangedString(s):
# Write your code here
s = [c for c in s if c.isalnum()]
dict = {}
for c in s:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
a = [(key, val) for key, val in dict.items()]
a.sort(key=lambda x: x[1], reverse=True)
prev_count = -1
temp_list = []
result = []
block_count = 0
for (char, count) in a:
if count < prev_count:
if block_count % 2 == 0:
result.append(str(prev_count) + ''.join(sorted(temp_list)))
else:
result.append(str(prev_count) +
''.join(sorted(temp_list, reverse=True)))
temp_list = []
block_count += 1
temp_list.append(char)
prev_count = count
if block_count % 2 == 0:
result.append(str(prev_count) + ''.join(sorted(temp_list)))
else:
result.append(str(prev_count) +
''.join(sorted(temp_list, reverse=True)))
return ','.join(result)
if __name__ == '__main__':
s = input()
result = rearrangedString(s)
print(result)
|
import itertools
def intcode(program: list):
i = 0
while True:
try:
code = program[i]
except IndexError:
print("Something's borked")
break
else:
# print(code)
if code == 99:
break
else:
first_index = program[i + 1]
second_index = program[i + 2]
new_index = program[i + 3]
if code == 1:
new_n = program[first_index] + program[second_index]
elif code == 2:
new_n = program[first_index] * program[second_index]
program[new_index] = new_n
i += 4
return program[0]
def which_words(filename: str, n: int):
with open(filename) as f:
content = f.read()
test_values = list(itertools.product(range(100), range(100)))
for t in test_values:
noun = t[0]
verb = t[1]
code = [int(x.strip()) for x in content.split(",")]
code[1] = noun
code[2] = verb
if intcode(code) == n:
return noun, verb
return None
noun, verb = which_words("input.txt", 19690720)
print(f"100*{noun}+{verb}={(100*noun)+verb}")
|
def mass_calc(n: int):
mass = (n // 3) - 2
if mass > 0:
return mass
else:
return 0
def fuel_calc(n: int):
mass = 0
further_fuel_needed = mass_calc(n)
while further_fuel_needed != 0:
mass += further_fuel_needed
further_fuel_needed = mass_calc(further_fuel_needed)
return mass
with open("input.txt") as f:
content = f.readlines()
mass = sum([fuel_calc(int(x)) for x in content])
print(mass)
|
import streamlit as st
import datetime
import requests
'''
# TaxiFareModel front
'''
#st.markdown('''
#Remember that there are several ways to output content into your web page...
#Either as with the title by just creating a string (or an f-string). Or as with this paragraph using the `st.` functions
#''')
#'''
## Here we would like to add some controllers in order to ask the user to select the parameters of the ride
#'''
# - date and time
d = st.date_input(
"Seleccione la fecha",
datetime.date(2001, 4, 23))
t = st.time_input('Seleccione la hora', datetime.time(8, 00))
pickup_datetime = (f'{d} {t}UTC')
key = pickup_datetime
# - pickuplongitude
pickup_longitude = st.text_input('pickup longitude', '40.7614327')
#- pickup latitude
pickup_latitude = st.text_input('pickup latitude', '73.9798156')
#- dropoff longitude
dropoff_longitude = st.text_input('Dropoff Longitude', '40.6513111')
#- dropoff latitude
dropoff_latitude = st.text_input('Dropoff Latitudes', '73.8803331')
#- passenger count
passenger_count = st.slider('Cantidad de pasajeros', 1, 8, 2)
#'''
### Once we have these, let's call our API in order to retrieve a prediction
#See ? No need to load a `model.joblib` file in this app, we do not even need to know anything about Data Science in order to retrieve a prediction...
#🤔 How could we call our API ? Off course... The `requests` package 💡
#'''
# Se presiona el boton para llamar al api
if st.button('Predecir el precio'):
params = {
'key':key,
'pickup_datetime':pickup_datetime,
'pickup_longitude':pickup_longitude,
'pickup_latitude':pickup_latitude,
'dropoff_longitude':dropoff_longitude,
'dropoff_latitude':dropoff_latitude,
'passenger_count':passenger_count
}
params
url = 'https://taxifare.lewagon.ai/predict_fare/'
response = requests.get(
url, params=params
).json()
response
# print is visible in server output, not in the page
|
#========Desafio 011 Calculando área por m²#
larg = float(input('Largura da parede: '))
alt = float(input('Altura da parede: '))
área = larg * alt
print('Sua parede tem a dimesão de {:.2f} x {:.2f} e sua áre é de {}m². '.format(larg, alt, área))
tinta = área / 2
print('Para pintar essa parede você precirá de {}l de tinta.'.format(tinta)) |
class Lista_enl:
def __init__(self):
self.primero = None
def definir_primero(self, valor): # Para definir el primero
nuevo_nodo = Nodo(valor) # Creo un nodo nuevo
actual_primero = self.primero # guardo el primero de la lista en una variable auxiliar
nuevo_nodo.proximo = actual_primero #indico que el siguiente o vecino del nodo nuevo recién creado es el anterior primero de la lista
self.primero = nuevo_nodo # se define que el primero de la lista será el nuevo nodo recién creado
return self
def definir_ultimo(self, valor): # Para definir el último
if self.primero == None: # Antes de definir el último se revisa si es que existen otros elementos en la lista
self.definir_primero(valor) # Se define como primero el nuevo valor
return self # No se ejecuta el resto del código
nuevo_nodo = Nodo(valor) # Se crea un nodo nuevo instanciando la clase Nodo
recorrer = self.primero # Se define una variable que recorrerá toda la lista, empezando por el primero
while recorrer.proximo != None: # Si es que existe un vecino, se sigue iterando
recorrer = recorrer.proximo # Recorrer pasa desde el valor actual, al siguiente (el primero en la priemra iteración al segundo)
recorrer.proximo = nuevo_nodo # Cuando el vecino siguiente es igual a None, es decir no existe, el siguiente vecino se define cmo el nuevo nodo creado
return self
def imprimir_valores(self):
recorrer = self.primero
while recorrer != None:
print(recorrer.valor)
recorrer = recorrer.proximo # La iteración avanza desde el valor actual al sguiente
return self
class Nodo:
def __init__(self, valor):
self.valor = valor
self.proximo = None
lista1=Lista_enl().definir_primero("PO").definir_primero("OLA").definir_ultimo("OLVIDONA").imprimir_valores() |
# To do: Briefs, Parameters and beta test
"""
Problem:
https://en.wikipedia.org/wiki/Convex_hull
Solutions:
Brute force
DnC
"""
from typing import Iterable, List, Set, Union
class Point:
"""
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'pi'
"""
def __init__(self, x, y):
self.x, self.y = float(x), float(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return f"({self.x}, {self.y})"
def __hash__(self):
return hash(self.x)
def _construct_points(
list_of_tuples: Union[List[Point], List[List[float]], Iterable[List[float]]]
) -> List[Point]:
"""
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points: List[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points
def _validate_input(points: Union[List[Point], List[List[float]]]) -> List[Point]:
"""
Examples
-------
>>> _validate_input([[1, 2]])
[(1.0, 2.0)]
>>> _validate_input([(1, 2)])
[(1.0, 2.0)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2.0, 1.0), (-1.0, 2.0)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not hasattr(points, "__iter__"):
raise ValueError(
f"Expecting an iterable object but got an non-iterable type {points}"
)
if not points:
raise ValueError(f"Expecting a list of points but got {points}")
return _construct_points(points)
def _det(a: Point, b: Point, c: Point) -> float:
"""
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100.0
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points: List[Point]) -> List[Point]:
"""
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k != i and k != j:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
else:
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
if points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points: List[Point]) -> List[Point]:
"""
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(
points: List[Point], left: Point, right: Point, convex_set: Set[Point]
) -> None:
"""
Parameters
...
"""
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def convex_hull_melkman(points: List[Point]) -> List[Point]:
"""
Examples
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for i in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[i]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[i])
convex_hull.append(points[i])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf)
if __name__ == "__main__":
main() |
# codewars task1 - 'Grasshopper - Summation'- SoftServe8 - Lesson8
#1.2 lambda expression
def summation(number):
if number > 0:
return sum(list(filter(lambda x: x+x, [i for i in range (1, number+1)])))
else:
pass
number = int(input ('Enter a number: '))
print (summation(number))
#1.2 map
def summation(num):
return sum (list ( map (int, range(1, num+1) ) ) )
num = int(input ('Enter some number: '))
print (summation(num))
#1.3 cycle for
def summation(num):
b=[]
for i in range(0, num+1):
b=b+[i] # наповнення списку елементами заданими в циклі
return sum(b)
num = int(input ('Enter some number: '))
print (summation(num))
|
import sys
import time
#classwork2 27.08 - SoftServe#5 - Lesson5
# 5.1 Create the list of integers, determine 'max' and 'min'
num = input ('Type some number: ')
int_lst = [int(x) for x in str(num)] # creating the list of integers using 'LC'
print (int_lst) # creating the list
print ('The maximum number in the list is: ', max(int_lst))
print ('The minimum number in the list is: ', min(int_lst))
#5.2 In the range from 1-10 determine even numbers, odd numbers which divides to 3 (apart - 1), numbers which not divides to 2 or 3
# USING 'LC'
def number(num):
even_lst = [ str(i) for i in range (1, num) if i%2 == 0 ]
odd_lst = [ str(i) for i in range (1, num) if i%2 == 1 ]
non_div = [ str(i) for i in range (1, num) if i%3 != 0 and i%2 != 0 ]
even_lst.insert (0, 'This is the list of evens:')
odd_lst.insert (0, '. This is the list od odds:')
non_div.insert (0, '. This is the list of 2∕3 not divisible:')
total = even_lst + odd_lst + non_div
total2 = ' '.join(total)
return total2
num = int(input ('Please type the last digit in your range: ')) + 1 # our latter digit in the range should be 11
print (number(num))
#5.3.1 Function (program that counts factorial)
def factor(n):
i = 1 # assign our variable before condition, otherwise 'UnboundLocalError: local variable 'i' referenced before assignment'
while n > 1:
i = i * n
n = n - 1
return i
n = int(input ('Type the factorial number U want to count:'))
print(factor(n))
#5.3.2 Using 'for' cycle (program that counts factorial)
#Example2
def factor2(n):
factorial = 1
for i in range (1, n+1):
factorial = factorial * i
#n = n -1
return (' The factorial of {0} is {1}'.format(n, factorial)) # форматування виведеного тексту
n = int(input ('Type the factorial number U want to count:'))
print (factor2(n) )
#5.3.3 Function (program that counts factorial)
#Example3
#def factor(n):
#i = 1
#while n >= 0:
#i = n * ( n - 1 )
#return i
#n = int(input ('Type the factorial number U want to count:'))
#print(factor(n))
# DOESN'T WORK
#5.4.1 Login/Password
def psw_key(psw):
psw_list = ['First!']
b = 3
while b > 0:
b = b - 1
if b == 0: #relates to formula # all after this attement will execute b-times according to a formula
break
# EXECUTION ########################################################################################
if psw in psw_list: # relates to a key
return ('CORRECT. ACCESS GRANTED')
exit()
if not psw in psw_list: # relates to a key
psw = input ('ACCESS DENIED. PROVIDE A KEY: ')
if b == 1 and psw != 'First!':
return ('YOUR ACCOUNT HAS BEEN BLOCKED FOR 10 MINUTES')
if b == 1 and psw == 'First!':
return ('HUHHH!. ACCESS GRANTED')
psw = input ('PROVIDE A KEY: ') # will execute b-times (3) as in the cycle (including specific condition when b == 1)
print(psw_key(psw))
# 3 ATTEMPTS TO SIGHN-IN - Login/Password using 'while' cycle
#5.4.2 Login/Password
#Example2
password = input ('PLEASE ENTER A PASSWORD:')
if password == 'User123':
print('Correct. Access granted')
exit()
def check_psw():
time.sleep(2)
print('Correct. Access granted')
trial2 = input ('PLEASE SELECT A PROPER PASSWORD:')
if trial2 == 'User123':
check_psw() # 2nd trial check
if not trial2 == 'User123':
trial3 = input ('PLEASE SELECT A PROPER PASSWORD:')
if trial3 == 'User123':
check_psw() # 3rd trial check
if not trial3 == 'User123':
time.sleep(2)
print ('YOU HAVE NOT CHOSEN A CORRECT ANSWER. PLEASE TRY AGAIN IN 10 MINUTES')
pass
# 3 ATTEMPTS TO SIGHN-IN - Login/Password using while cycle
#### UGLY VERSION - NON-RELEVANT WITH 'PYTHON-ZEN'
#5.4.3 # 3 ATTEMPTS TO SIGHN-IN - Login/Password using while cycle
#Example3
def sighn_in(psw):
if psw == 'User123':
print ('Correct. Access granted')
exit()
b = 2 # function will execute 2 times more
while psw != 'User123':
b = b - 1
psw = input ('Acces Denied. Please enter the password:') #1st step
##############################################################################################
if psw == 'User123': #2nd condition
print ('Access granted')
exit()
elif b == 1: #2nd condition2
psw = input ('Acces Denied. This your last attempt. Please provide a correct password:')
################################################################################################
if psw == 'User123':
print ('Access granted')
exit()
else:
print ('Soryy U haven\'t provided a correct answer.') #3rd condition 3d step
exit()
psw = input ('Please enter the password:') #1st step
print(sighn_in(psw))
# 3 ATTEMPTS TO SIGHN-IN - Login/Password using while cycle
|
# codewars task6 - 'Is this my tail'- SoftServe5 - Lesson5
#1.1 Correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit!
def correct_tail(body,tail):
#block1: let's try to convert an appropriate body part. As our equality depends on the last letter of body, which simoultaneosly = the first part of tail.
body_end = [ str(i) for i in str(body)] [-1] # first element selection
tail_beg = [ str(i) for i in str(tail)] [0] # last element selection
if body_end == tail_beg or body_end == tail_beg.upper() or body_end.upper() == tail_beg:
return True
else:
return False
#print (type(body_end))
#print (type(tail_beg))
body = input ('Please select the body of the animal: ')
tail = input ('Please select the tail of the animal: ')
print (correct_tail(body, tail))
# RELEVANT WITH CODEWARS
#1.1
def correct_tail(body,tail):
# DO THE SAME IN SIMPLER WAY INDEXING STRINGS
b = body [-1] # first element selection
t = tail [0] # last element selection
if b == t or b == t.upper() or b.upper() == t:
return True
else:
return False
correct_tail(body, tail)
# RELEVANT WITH CODEWARS
|
import re
import string
# codewars task7 - Valid HK Phone Number - 7kyu KATA
'''
In Hong Kong, a valid phone number has the
format xxxx xxxx where x is a decimal digit (0-9).
For example:
Define two functions, isValidHKPhoneNumber and has
Valid HK Phone Number, that returns whether a given
string is a valid HK phone number and
contains a valid HK phone number respectively
(i.e. true/false values).
all([i.isdigit() for i in condition]) - list comprehension
that will work like a sorting loop
Option #2.1 Using re.serach:
will return <span object> which equals True
faster way
Option #2.2 Using re.findall:
will return the list, we need to check the list
in addition
'''
# RELEWANT WITH CODEWARS
# Option #1.1
def is_valid_HK_phone_number(number):
condition = (number.strip('"')).split(' ')
if len(condition[0]) == 4 and \
len(condition[1]) == 4 and \
all([i.isdigit() for i in condition]):
return True
else:
return False
number = input('Type the text U r going to check: ')
print(is_valid_HK_phone_number(number))
# Option #2.1
def has_valid_HK_phone_number(number):
# building own pattern with re.compile()
pattern = re.compile(r'\d{4}\s\d{4}')
result = pattern.search(number)
return True if result else 0
# in order to get a final-sliced number
#final_number = ' '.join(pattern.findall(number))
# return final_number
number = input('Type the text U r going to check: ')
print(has_valid_HK_phone_number(number))
# Option #2.2 Using findall
'''
print(condition) - will return the list of digits
as the pattern may be digits only, the last thing
is just to check if the list == True
[] - False
['2359 1478'] - True
'''
def has_valid_HK_phone_number(number):
# your code here
lst = (number.strip('"')).split(' ')
return True if re.findall(r"\d{4}\s\d{4}", number) else 0
number = input('Type the text U r going to check: ')
print(has_valid_HK_phone_number(number))
|
# codewars task2 - 'Reverse List Order'- SoftServe7 - Lesson7
#1.2.1 In this kata you will create a function that takes-in a list and returns a list with the reverse order.
def reverse_list(l):
lambda_lst = list(map(lambda x: x, l)) # using lambda function
lambda_lst.reverse()
return lambda_lst
l = input ('Enter some parts of your list: ')
print (reverse_list(l))
#RELEWANT WITH CODEWARS
#1.2.2
#Example2
def reverse_list(l):
return [i for i in l ][::-1] # using list slice
l = input ('Enter some parts of your list: ')
print (reverse_list(l))
#RELEWANT WITH CODEWARS
|
''' This program is for fetching the weather of a given city'''
import requests
def gettemperature(data):
out = []
attr = ['<temp_c>','<wether>','<wind_mph']
for line in data.readlines():
for x in attr:
if x in line:
i1 = line.find(">")
i2 = line.find("</")
out.append(x+" "+line[i1+1:i2])
return out
if __name__ == '__main__':
getin = input("Enter the type of input. Web/File")
getcity = input("Enter the city name")
if getin == "file":
readdata = open(getcity+".xml", "r")
out = gettemperature(readdata)
if len(out)>0:
print("\n".join(out))
elif getin == "web":
url = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query="
readdata = requests.get(url+getcity.lower()).text
filex = open("file.xml","w")
filex.write(readdata)
filex.close()
readdata = open("file.xml","r")
out = gettemperature(readdata)
if len(out)>0:
print("\t".join(out))
|
# https://www.acmicpc.net/problem/3062
# 2020-06-11 / 3062. 수 뒤집기 / Bronze II
for _ in range(int(input())):
x = input()
y = int(x) + int(x[::-1])
if str(y) == str(y)[::-1]:
print("YES")
else:
print("NO")
|
# https://www.acmicpc.net/problem/15881
# 2021-06-28 / 15881. Pen Pineapple Apple Pen / Bronze II
# 1.
# 주의해야 하는 TC: pPApPAP, pppPAp, pPPApPAp 등.
_ = input()
S = input()
cnt = 0
stat = 0
for c in S:
if stat < 3 and c == "p":
stat = 1
elif stat == 1 and c == "P":
stat = 2
elif stat == 2 and c == "A":
stat = 3
elif stat == 3 and c == "p":
stat = 0
cnt += 1
else:
stat = 0
print(cnt)
|
# Python routine to read CD/CL profile from a text file
# Created by Francisco Capristan
def reader(filename):
inputFile = open(filename,'r')
# The format expected is Minf -> first column. Cd or Cl -> second column
M = [] # Minf
Cx = []# coefficient CL or CD
for line in inputFile:
key = line.split()
if len(key)>0:
if (line[0]!='#'):# this way "#" can be used to comment an entire line
M.append(float(key[0]))
Cx.append(float(key[1]))
n = len(M)
inputFile.close()
return (M,Cx,n) |
# -1: ( ).
# ( ).
# :
# * while;
# * for.
number = int(input('Enter a number '))
i = 0
while i < len(number):
print(number[i])
i += 1
print("The programm has been successfully executed")
#or ***to complete***
number = int(input('Enter a number '))
for i in number:
i = 0
print(number[i])
i += 1
print("The programm has been successfully executed")
# -2: .
# . .
# :
# *
#
# :
# print("a = ", b, "b = ", a) - !
a = int(input("Enter a number a: "))
b = int(input("Enter a number b: "))
print("a = " , a, " b = " , b)
a,b = b,a
print(" a = ", a, " b = ", b)
#or
a = int(input("Enter a number a: "))
b = int(input("Enter a number b: "))
print("a = " , a, " b = " , b)
c = a
print("c = " , b, " b = " , c)
# -3: .
# 18 , : " ",
# ", 18 "
user_age = "18"
permission = int(input("Enter your age: "))
if permission >= int(user_age):
print("You are welcome to use our service")
else:
print("Sorry, the service is not avaliable for people under 18")
#or
user_age = int(input("Enter your age: "))
if user_age < 18:
access = False
print("Sorry, the service is not avaliable for people under 18")
else:
access = True
print("You are welcome to use our service")
# homework/ normal
# -1: , .
# , x = 58375.
# , .. 8.
# , .
# .
# :
# * while;
# * for.
x = 98765
print("Max number in the string" , x, end = " ")
max_number = 9
while True:
if max_number = 9:
break
else:
continue
print(max_number)
max_number +=1
#or
x = 98765
print("Max number in the string" , x, end = " ")
max_number = 9
max_number = str(x)
for digit in x:
print(digit)
# -2: .
# . .
# , .
# :
# * ;
# * Python.
a = int(input("Enter a number a: "))
b = int(input("Enter a number b: "))
a = b
b = a
print(a,b)
# -3: ,
# ax** + bx + c = 0.
# .
# sqrt() math:
# import math
# math.sqrt(4) - 4
import math
ax** + bx + c = 0
a = int(input("Enter number for a "))
x = int(input("Enter number for x"))
b = int(input("Enter number for b"))
c = int(input("Enter number for c"))
# -1:
# :
# : a == a**2
# : True
# : a == a*2
# : True
# : a > 999999
# : True
# : a,
# , ?
bool True False
bool= False if
bool (0)
bool (' ')
bool (False)
# a > 999999 bool = True
|
#!/usr/bin/python
import sys
if len(sys.argv) > 1:
strInput = sys.argv[1]
strOutput = ""
intLength = len(strInput)
for count in range(intLength):
if count > 0:
strOutput = strOutput + "|"
strChar = str(strInput[count])
print(strChar)
if strChar == "_":
strChar = "32"
elif strChar == "#":
strChar = "35"
else:
strChar = str(ord(strChar))
strOutput = strOutput + strChar
strOutput = strOutput + "|13|10"
print(strOutput)
else:
print("Usage:\n# = numeric values to be read.\n_ = space.\n@ = Ignore.")
print("Example: T_@_######### kg")
|
myNum = 5
myDenom = 0
try:
print(myNum/myDenom)
except ZeroDivisionError:
print( "Error: Cannot divide by zero (", myNum,"/", myDenom, ")" )
|
import re
myString = input("Enter your name: ")
hold = re.search(r'(.*)Les(.*)',myString)
if hold:
print("\nYes")
else:
print("\nNo") |
"""
Material complementar do Curso: Estatística com Python
Ano: 2020
Nível: Básico
Aluno: Paulo Freitas Nobrega
Professor: Rodrigo Fernando Dias
Plataforma: Alura Cursos Online
Parte I: Frequências e Medidas
https://cursos.alura.com.br/course/estatistica-distribuicoes-e-medidas
Parte II: Probabilidade e Amostragem
https://cursos.alura.com.br/course/estatistica-probabilidade-e-amostragem
Material auxiliar:
- Data Science do Zero (Joel Grus)
- Estatísitica Prática para Cientistas de Dados (Peter Bruce)
- Estatística Básica (Sonia Vieira)
- Estatística Básica (Valéria Ferreira)
- Estatística Aplicada (Abraham Laredo Sicsú)
- Matemática com Python (Guilherme A. Barucke)
- Python para Análise de Dados (Wes Mckinney)
Objetivo:
Conjunto de funções desenvolvidas para fins exclusivamente didáticos.
Todas funções são baseadas em bibliotecas estatísticas reconhecidas.
O foco deste script, é compreender parcialmente a composição interna,
de forma matemática, estatística e programatório, dos métodos
utilizados em Data Science.
Utilize este script como um material básico de apoio.
"""
# Parte I: Frequências e medidas
def aparagem(conjunto: list, corte: float = 0) -> list:
"""
Remove as extremidades de um conjunto de dados, com base
na porcentagem de corte que varia entre 0 e 1
"""
c, n, p = sorted(conjunto), len(conjunto), round(corte*10)
if n <= p*2:
raise ValueError("Proporção de corte muito grande")
return c[p:n-p]
def media(conjunto: list) -> float:
"""
Calcula a média aritmética de um conjunto de dados
"""
n = len(conjunto)
return sum(conjunto) / n if n else 0
def media_aparada(conjunto: list, corte: float = 0) -> float:
"""
Calcula a média aritmética aparada de um conjunto de dados
"""
return media(aparagem(conjunto, corte))
def media_ponderada(conjunto: list, pesos: list) -> float:
"""
Calcula a média aritmética ponderada de um conjunto de dados
"""
if len(conjunto) != len(pesos):
raise ValueError("Conjuntos com números de registros diferentes")
mult = [registro*pesos[i] for i, registro in enumerate(conjunto)]
return sum(mult) / sum(pesos)
def mediana(conjunto: list) -> float:
"""
Calcula a mediana de um conjunto de dados
"""
c, n = sorted(conjunto), len(conjunto)
# impariedade
impariedade = True if n % 2 else False
# ref centro do conjunto
meio = n//2
return c[meio] if impariedade else media([c[meio-1], c[meio]])
def percentis(conjunto: list, percentis: list) -> list:
"""
Calcula os percentis de um conjunto de dados
"""
c, n = sorted(conjunto), len(conjunto)
# divisao
# (i*n/100) - contudo os percentis são atribuidos em
# em porcentagem. [.5] = 50%. Assim ignora-se a divisão.
p = [i*n for i in percentis]
# Se a divisão resultar num número fracionário, arredonde-o
# para cima (em programação, por índices começarem em 0, se
# arredonda para baixo) e o valor do quartil será a observação
# encontrada nesta posição.
# Se a divisão for um número inteiro, o quartil será a media
# aritmética da observação que ocupar a posição encontrada
# com a observação que ocupar a posição imediatamente seguinte.
return [c[int(x)] if x % 2 else media([c[int(x)-1], c[int(x)]]) for x in p]
def desvio_medio_absoluto(conjunto: list) -> float:
"""
Calcula o desvio médio absoluto de um conjunto de dados
"""
# desvios
desvios = [abs(x-media(conjunto)) for x in conjunto]
return sum(desvios) / len(conjunto)
def desvio_absoluto_mediano(conjunto: list, fator: float = 1.4826) -> float:
"""
Calcula o desvio absoluto mediano da mediana de um conjunto de dados
"""
# desvios
desvios = [abs(x-mediana(conjunto)) for x in conjunto]
# fator = fator de escalamento constante
return mediana(desvios) * fator
def variancia(conjunto: list, amostral: bool = True) -> float:
"""
Calcula a variância de um conjunto de dados
"""
# desvios
desvios = [(x-media(conjunto))**2 for x in conjunto]
# amostral ou populacional
n = len(conjunto)-1 if amostral else len(conjunto)
return sum(desvios)/n
def desvio_padrao(conjunto: list, amostral: bool = True) -> float:
"""
Calcula o desvio padrão de um conjunto de dados
"""
return variancia(conjunto, amostral)**.5
# Parte II: Probabilidade e Amostragem
def fatorial(n: int) -> int:
"""
Calcula o produto de todos os inteiros positivos menores
ou iguais a n
"""
return 1 if n < 1 else n * fatorial(n-1)
def permutacoes(conjunto: list) -> float:
"""
Calcula a quantidade de arranjos possíveis, onde cada arranjo,
possui a totalidade dos elementos do conjunto
"""
n = len(conjunto)
# quantidade de arranjos totalitaria
permutacoes = fatorial(n)
# se houver elementos repetidos no conjunto
if n > len(set(conjunto)):
# então para cada elemento com frequência > 1,
# calcula-se o fatorial desta frequência
repeticoes = [fatorial(y)
for y in [conjunto.count(x)
for x in set(conjunto)] if y > 1]
# e o produtorio destas repetiçoes, torna-se
# um denominador para o todo
produtorio = 1
for x in repeticoes:
produtorio *= x
permutacoes /= produtorio
return permutacoes
def arranjos(n, k: int) -> float:
"""
Calcula a quantidade de sequências ordenadas, formada
de k elementos distintos, tomados k a k, escolhidos entre
os n existentes.
Cada arranjo difere dos demais:
pela sua natureza (1,3) != (3,5)
pela sua ordem (1,3) != (3,1)
"""
# quando n for um conjunto de elementos (list), então
# atribui à n a quantidade de elementos do conjunto
n = len(n) if isinstance(n, list) else n
return fatorial(n) / fatorial(n-k)
def combinacoes(n, k: int) -> float:
"""
Calcula a quantidade de conjuntos, formados de k elementos possíveis,
tomados k a k, escolhidos entre os n existentes
Cada combinação difere das demais apenas:
pela sua natureza (1,3) != (3,5)
"""
return arranjos(n, k) / fatorial(k)
def dist_binomial_pmf(s, n: int, p: float) -> list:
"""
Determina a probabilidade de observar k sucessos em n
ensaios, em que a probabilidade de sucesso para cada
ensaio seja p
"""
# n = número de ensaios
# p = probabilidade de sucesso
# q = probabilidade de fracasso
# k = número de sucesso desejado
q = 1 - p
# s é um variável auxiliar
# poderá conter um valor inteiro ou uma lista de inteiros
if not isinstance(s, list):
s = [s]
return [combinacoes(n, k) * (p**k) * (q**(n-k)) for k in s]
def dist_binomial_cdf(k: int, n: int, p: float) -> float:
"""
Determina a probabilidade de se observar k sucessos
ou menos em n ensaios, em que a probabilidade de
sucesso para cada ensaio seja p
"""
# sucessos = [0, ..., k+1]
sucessos = [i for i in range(k+1)]
return sum(dist_binomial_pmf(sucessos, n, p))
def dist_binomial_sf(k: int, n: int, p: float) -> float:
"""
Determina a probabilidade de se observar k sucessos
ou mais em n ensaios, em que a probabilidade de
sucesso para cada ensaio seja p
"""
return 1 - dist_binomial_cdf(k, n, p)
|
#!/usr/bin/python3
import math as mp
def digits(x):
return (mp.log(x) / mp.log(10)) + 1
a = 1
b = 1
x = 1
p = 0
NOD = 1000
while(digits(a) < NOD):
x = x + 1
c = a + b
a = b
b = c
print('The first fibonacci number with ',NOD,'digits is',a,' and it is in ' + str(x) + 'th position')
|
# File: pyScript09.py
# Learning Python (Python version: 3)
# Topics:
# - While loops and files
# *** w2file.txt needs to be created ahead of time! ***
# Learn how to write data to a text file, and then read data from the text file
# -- writing data to a file
outFile = open('w2file.txt', 'w')
outFile.write('This is line 1 in w2file\n')
outFile.write('This is line 2 in w2file\n')
outFile.close()
print("Done! Look at file: 'w2file.txt' in working directory")
|
# File: pyScript11.py
# Learning Python (Python version: 3)
# Topics:
# - For-loops with files
# - Example using nested for-loops with files
## Using for-loops to process a file
# Reading a file line by line using readline():
#inFile = open('text.txt', 'r') # open file for reading
#line = inFile.readline() # read a line
#while(line): # while there is data to read
# print(line)
# line = inFile.readline() # read another line
# Another example
#for line in open('text.txt'):
# print(line)
# Reading grades file ("w2filegrades.txt") and calculating the average
sum = 0
count = 0
for grade in open('w2filegrades.txt'):
print(grade)
sum = sum + int(grade)
count = count + 1
average = sum / count
print("Average: " + str(average))
print("=============================================")
# Example using nested for-loops to build a histogram of the set of grades
# Will represent 5 points by one asterisk (*)
# File: (Edit file to illustrate Histogram below)
# 90
# 77
# 85
# 65
# 100
print("\n\nHISTOGRAM:")
print("============================")
bar = "" # variable to hold the asterisks
for grade in open('w2filegrades.txt'): # loop through grades file
for i in range(1, int(grade)+1): # loop over range 1-(GR+1)
# to be inclusive of the actual number
if i % 5 == 0: # deciding if going to add an asterisk (using modulus)
bar = bar + "*"
print(bar, i) # print the bar
bar = "" # reset bar to empty string to begin collecting the next set of *'s
print("============================")
|
# given a linked list , we have to reverse it using recursion approach.
# 1->2->3 => 3->2->1
# defining the class node for the node of the linked list
class node:
def __init__(self,data):
self.data = data
self.next = None
# creating the nodes of the linked list by creating the objects of the class node
node1 = node(5)
node2 = node(6)
node3 = node(8)
node4 = node(2)
# linking the nodes to creat a linked list
node1.next = node2
node2.next = node3
node3.next = node4
# defining the function , we would the return the head of the reversed linked list
def reverse_linked_list(head_node,prev_node):
# base condition
if head_node == None:
return prev_node
next_node = head_node.next
head_node.next = prev_node
prev_node = head_node
head_node = next_node
return reverse_linked_list(head_node,prev_node)
# test case
print('Normal linked list before reversing')
temp_node = node1
while temp_node.next != None:
print(temp_node.data,end = '->')
temp_node = temp_node.next
print(temp_node.data)
head_node = node1
prev_node = None
head_after_reverse = reverse_linked_list(head_node,prev_node)
print('Linked List after reversing')
while head_after_reverse.next != None:
print(head_after_reverse.data,end='->')
head_after_reverse = head_after_reverse.next
print(head_after_reverse.data)
|
# Program pyta użytkownika, ile elementów ma zawierać zbiór niezhashowanych kluczy.
# Następnie prosi o podanie kluczy oraz o rozmiar listy
# w której mają się znaleźć zhashowane klucze.
# Zwraca zhashowaną listę według hashowania z adresowaniem liniowym:
# H(k) = (h(k) + count) mod m
# h(k) - funkcja hashująca
# h(k) = k mod m, gdzie k - niezhashowany klucz, m = rozmiar listy.
# Autor: Bartłomiej Pysiak
def greet():
print("Welcome in ListHash! Here you can hash your lists.\n")
def ask_how_many_elements():
while True:
try:
how_many = int(input("How many elements ?"))
return how_many
except ValueError as e:
print("Wrong value: ", e)
continue
def input_unhashed_elements(unhashed_collection, unhashed_size):
while True:
for i in range(unhashed_size):
try:
element = int(input("Please input unhashed element"))
unhashed_collection.append(element)
except ValueError as e:
print("Wrong value:", e)
continue
return unhashed_collection
def create_unhashed_collection():
unhashed_collection = []
unhashed_size = ask_how_many_elements()
input_unhashed_elements(unhashed_collection, unhashed_size)
return unhashed_collection
def create_empty_list():
my_list = []
list_size = ask_how_many_elements()
for i in range(list_size):
my_list.append(None)
return my_list
def hashing(unhashed_collection, my_list):
hashed_list = my_list
count = 0
while True:
for i in range(len(unhashed_collection)):
while True:
linear_addressing = ((unhashed_collection[i])%len(my_list)+count)%len(my_list)
if hashed_list[linear_addressing] == None:
hashed_list[linear_addressing] = unhashed_collection[i]
count = 0
break
else:
count += 1
continue
return hashed_list
def main():
greet()
print("Unhashed collection:")
unhashed_list = create_unhashed_collection()
print("Result list (size of m):")
my_list = create_empty_list()
print("This is your unhashed collection: ",unhashed_list)
my_list = hashing(unhashed_list, my_list)
print("This is your hashed list: ", my_list)
main()
|
x = input('Masukan panjang:')
y = input('Masukan lebar:')
z = input('Masukan tinggi:')
print('V= panjang x lebar x tinggi =', x*y*z,)
|
p = input('Masukan Panjang Persegi:')
l = input('Masukan Lebar Persegi:')
t = input('Masukan Tinggi Limas:')
print('Volume: 1/3 x Luas Alas x Tinggi', p*l*t/3,)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 16:57:19 2018
@author: Takuto
"""
def fib(m):
fib(0)=0
fib(1)=1
while n < m:
return fib(n-1) + fib(n-2)
n=n+1
print(fib(2018))
print(fib(5)) |
import copy
import time
# uncomment this to show the visualization (WARNING: runs very slowly!)
# from matplotlib import pyplot as plt
# Depth Limited Search for the puzzle
# Places the puzzle pieces onto the board in the order that they are listed in the pieces array.
# Recursively calls itself to search the entire search space for all valid solutions
# parameters:
# puzzle: a 2d array representing the state of the puzzle board
# pieces: an array of 2d puzzle pieces that will be put in the board
# currentDepth: the current depth of the DLS
# maxDepth: the maximum depth of the DLS
# pruneSize: the maximum size of islands that should be pruned. size can be 0, 1, 2, or 3+
# returns: void
def DepthLimitedSearch(puzzle, pieces, currentDepth, maxDepth, pruneSize, nodesExpanded):
prune = False
rows = len(puzzle)
cols = len(puzzle)
pieceRows = len(pieces[currentDepth])
pieceCols = len(pieces[currentDepth][0])
for i in range(rows):
# Check if piece will go out of bounds of the puzzle rows
if (i + pieceRows > rows):
break
for j in range(cols):
if puzzle[i][j] == -1:
break
# Check if piece will go out of bounds of the puzzle cols
if (j + pieceCols > cols):
break
# Put the piece down if this is a valid spot
tempPuzzle = copy.deepcopy(puzzle)
prune = False
for k in range(pieceRows):
if (prune):
break
for l in range(pieceCols):
if ((puzzle[i+k][j+l] != 0) and pieces[currentDepth][k][l] == 1):
prune = True
break
elif (pieces[currentDepth][k][l] == 1):
puzzle[i+k][j+l] = currentDepth + 1
# Reset the puzzle board if the piece won't fit at the current spot
if (prune == True):
puzzle = copy.deepcopy(tempPuzzle)
# prune if there is an island
else:
# Uncomment this to show the visualization
# plt.imshow(puzzle)
# plt.pause(0.000000001)
prune = Pruning(puzzle, pruneSize)
if (prune == True):
puzzle = copy.deepcopy(tempPuzzle)
# Recursively call the DLS function for the new depth if we aren't pruning
if (prune == False and currentDepth < maxDepth - 1):
nodesExpanded[0] = nodesExpanded[0] + 1
DepthLimitedSearch(puzzle, pieces, currentDepth + 1, maxDepth, pruneSize, nodesExpanded)
puzzle = copy.deepcopy(tempPuzzle)
# Base Case : we found a valid puzzle board. print the board and return True
elif (prune == False and currentDepth == maxDepth - 1):
for k in range (rows):
print(puzzle[k])
print("\n")
return
return
# Helper function for the Depth Limited Search
def BubblePuzzleAI(puzzle, pieces, pruneSize):
currentDepth = 0
maxDepth = len(pieces)
nodesExpanded = [0]
DepthLimitedSearch(puzzle, pieces, currentDepth, maxDepth, pruneSize, nodesExpanded)
return nodesExpanded[0]
# Pruning function
# counts the number of zeros around each zero to determine if an island of zeros exists
# parameters:
# puzzle: a 2d array representing the state of the puzzle board
# pruneSize: the maximum size of islands that should be pruned. size can be 0, 1, 2, or 3+
# returns:
# True if there is an island and the board should be pruned
def Pruning(puzzle, pruneSize):
if (pruneSize <= 0):
return False
for i in range(len(puzzle)):
for j in range(len(puzzle[i])):
if puzzle[i][j] == -1:
break
numZeros = 0
iOffset1 = 0
jOffset1 = 0
iOffset2 = 0
jOffset2 = 0
if (puzzle[i][j] == 0):
# Check the 4 neighbors of the current location for 0s
if (i-1 >= 0
and puzzle[i-1][j] == 0):
numZeros += 1
iOffset1 = -1
if (j-1 >= 0
and puzzle[i][j-1] == 0):
numZeros += 1
jOffset1 = -1
if (j+1 <= len(puzzle) - 1
and puzzle[i][j+1] == 0):
numZeros += 1
jOffset1 = 1
if (i+1 <= len(puzzle) - 1
and puzzle[i+1][j] == 0):
numZeros += 1
iOffset1 = 1
# return true if island of size 1
if (numZeros == 0):
return True
# if one neighbor is 0, check if there is an island of size 2
elif (numZeros == 1 and pruneSize >= 2):
# check the neighbors of the single neighboring zero
if (i-1+iOffset1 >= 0
and puzzle[i-1+iOffset1][j+jOffset1] == 0):
numZeros += 1
if (iOffset1 == -1):
iOffset2 = -1
if (j-1+jOffset1 >= 0
and puzzle[i+iOffset1][j-1+jOffset1] == 0):
numZeros += 1
if (jOffset1 == -1):
jOffset2 = -1
if (j+1+jOffset1 <= len(puzzle) - 1
and puzzle[i+iOffset1][j+1+jOffset1] == 0):
numZeros += 1
if (jOffset1 == 1):
jOffset2 = 1
if (i+1+iOffset1 <= len(puzzle) - 1
and puzzle[i+1+iOffset1][j+jOffset1] == 0):
numZeros += 1
if (iOffset1 == 1):
iOffset2 = 1
if (numZeros == 2):
return True
# check if there is an island of 3 in a straight line
elif(numZeros == 3 and pruneSize >= 3 and (iOffset1+iOffset2 == 2 or jOffset1+jOffset2 == 2)):
if (i-1+iOffset1+iOffset2 >= 0
and puzzle[i-1+iOffset1+iOffset2][j+jOffset1+jOffset2] == 0):
numZeros += 1
if (j-1+jOffset1+jOffset2 >= 0
and puzzle[i+iOffset1+iOffset2][j-1+jOffset1+jOffset2] == 0):
numZeros += 1
if (j+1+jOffset1+jOffset2 <= len(puzzle) - 1
and puzzle[i+iOffset1+iOffset2][j+1+jOffset1+jOffset2] == 0):
numZeros += 1
if (i+1+iOffset1+iOffset2 <= len(puzzle) - 1
and puzzle[i+1+iOffset1+iOffset2][j+jOffset1+jOffset2] == 0):
numZeros += 1
if (numZeros == 4):
return True
return False
# ----------------- main program ----------------------
if __name__ == "__main__":
# initial puzzle boards
# 0 means empty space, -1 means it's off the board
puzzle4x4 =[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, -1 ],
[ 0, 0, -1, -1 ],
[ 0, -1, -1, -1 ]
]
puzzle7x7 =[
[ 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, -1 ],
[ 0, 0, 0, 0, 0, -1, -1 ],
[ 0, 0, 0, 0, -1, -1, -1 ],
[ 0, 0, 0, -1, -1, -1, -1 ],
[ 0, 0, -1, -1, -1, -1, -1 ],
[ 0, -1, -1, -1, -1, -1, -1 ]
]
puzzle10x10 =[
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, -1, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, -1, -1, -1, -1, -1, -1, -1, -1, -1 ]
]
ninePuzzle10x10 =[
[ 0, 0, 0, 0, 10, 10, 12, 12, 12, 12 ],
[ 0, 0, 0, 0, 10, 10, 10, 11, 11, -1 ],
[ 0, 0, 0, 0, 0, 11, 11, 11, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, -1, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, -1, -1, -1, -1, -1, -1, -1, -1, -1 ]
]
elevenPuzzle10x10 =[
[ 0, 0, 0, 0, 0, 0, 12, 12, 12, 12 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, 0, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, 0, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, 0, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, 0, -1, -1, -1, -1, -1, -1, -1, -1 ],
[ 0, -1, -1, -1, -1, -1, -1, -1, -1, -1 ]
]
# list of pieces
p1 = [[ 1, 1 ], # light green
[ 1, 0 ],
[ 1, 0 ],
[ 1, 0 ]]
p2 = [[ 0, 1, 1 ], # red
[ 1, 1, 0 ],
[ 1, 0, 0 ]]
p3 = [[ 1, 1 ], # medium blue
[ 1, 0 ],
[ 1, 1 ]]
p4 = [[ 0, 1, 0 ], # white
[ 1, 1, 1 ],
[ 0, 1, 0 ]]
p5 = [[ 0, 1 ], # brown
[ 1, 1 ]]
p6 = [[ 1, 1, 1, 1 ], # dark green
[ 0, 0, 1, 0 ]]
p7 = [[ 1, 1, 1 ], # purple
[ 1, 0, 0 ],
[ 1, 0, 0 ]]
p8 = [[ 1, 1 ], # pink
[ 1, 1 ]]
p9 = [[ 1, 0 ], # orange
[ 1, 0 ],
[ 1, 1 ]]
p10 = [[ 1, 1, 0 ], # light blue
[ 1, 1, 1 ]]
p11 = [[ 0, 0, 1, 1 ], # dark blue
[ 1, 1, 1, 0 ]]
p12 = [[ 1, 1, 1, 1 ], # yellow
[ 0, 0, 0, 0 ]]
print("\nWelcome to the Daiso Bubble Puzzle Solver.")
print("When given the pieces used and initial state of the board, The Solver finds the solutions to a Daiso bubble puzzle")
print("The Solver will exhaust the search tree for the given board state to find all possible solutions.\n")
#pieces4x4 = [p2, p1]
#pieces7x7 = [p1, p2, p3, p4, p5, p6]
ninePiece10x10 = [p4, p3, p1, p6, p7, p2, p8, p9, p5]
elevenPiece10x10 = [p4, p11, p3, p1, p6, p7, p10, p2, p8, p9, p5]
twelvePieces10x10 = [p4, p11, p3, p1, p6, p7, p10, p2, p8, p9, p12, p5] # Fastest order found, runs for about 3 minutes when pruning
#BubblePuzzleAI(puzzle4x4, pieces4x4, 3)
print("Here is a puzzle with 3 pieces inserted into it:")
for i in range (len(ninePuzzle10x10)):
print(ninePuzzle10x10[i])
print("\n")
print("Finding solutions to the puzzle:")
start = time.time()
nodesExpanded = BubblePuzzleAI(ninePuzzle10x10, ninePiece10x10, 3)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded)
print("Here is a puzzle with 1 piece inserted into it:")
for i in range (len(elevenPuzzle10x10)):
print(elevenPuzzle10x10[i])
print("\n")
print("Finding solutions to the puzzle:")
start = time.time()
nodesExpanded = BubblePuzzleAI(elevenPuzzle10x10, elevenPiece10x10, 3)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded)
print("Here is an empty puzzle board with no pieces inserted into it:")
for i in range (len(puzzle10x10)):
print(puzzle10x10[i])
print("\n")
print("Finding solutions to the puzzle by pruning islands of up to size 3:")
start = time.time()
puzzle = copy.deepcopy(puzzle10x10)
nodesExpanded = BubblePuzzleAI(puzzle, twelvePieces10x10, 3)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded)
print("Finding solutions to the puzzle by pruning islands of up to size 2:")
start = time.time()
puzzle = copy.deepcopy(puzzle10x10)
nodesExpanded = BubblePuzzleAI(puzzle, twelvePieces10x10, 2)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded)
print("Finding solutions to the puzzle by pruning islands of up to size 1:")
start = time.time()
puzzle = copy.deepcopy(puzzle10x10)
nodesExpanded = BubblePuzzleAI(puzzle, twelvePieces10x10, 1)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded)
print("Finding solutions to the puzzle without pruning any islands:")
start = time.time()
puzzle = copy.deepcopy(puzzle10x10)
nodesExpanded = BubblePuzzleAI(puzzle, twelvePieces10x10, 0)
end = time.time()
seconds = end - start
print("Time taken: %.3f seconds" %seconds)
print("Number of nodes expanded: %s\n" %nodesExpanded) |
# This program will reverse the string that is passed
# to it from the main function
class Reverse(object):
def __init__(self, data):
self.data = data
self.index = len(data)
#returns an obect thar can iterated
def __iter__(self):
return self
#__next_gives the next value in the iteration
def __next__(self):
if self.index == 0:
#stops the iteration
raise StopIteration
self.index -= 1
return self.data[self.index]
def Main():
rev = Reverse('Waithira Kunene')
for char in rev:
print(char)
if __name__ == '__main__':
Main() |
import string
def test_score():
names = ["MARY", "PATRICIA", "LINDA"]
assert score(names) == 385
def names_scores_sequence(names, letter_score_key):
for position, name in enumerate(names):
yield (position + 1) * score_letters(name, letter_score_key)
def score_letters(name, letter_score_key):
return sum(letter_score_key[letter] for letter in name)
def score(names):
names.sort()
letter_score_key = {letter: score + 1 for score, letter in enumerate(string.letters)}
return sum(names_scores_sequence(names, letter_score_key))
|
import getNumericalData
from sklearn import preprocessing
import pandas as pd
train_set = pd.read_csv('dataTrain.csv')
test_set = pd.read_csv('dataTest.csv')
#drops the target column
y_train = train_set.final_score
x_train = train_set.drop(labels='final_score', axis=1)
y_test = test_set.final_score
x_test = test_set.drop(labels='final_score', axis=1)
#MinMax scaler, it does not distort data
mm_scaler = preprocessing.MinMaxScaler()
mm_scaled_x_train = mm_scaler.fit_transform(x_train)
mm_scaled_x_test = mm_scaler.fit_transform(x_test)
#Standard Scaler in case of the normal distribution
std_scaler = preprocessing.StandardScaler()
std_scaled_x_train = std_scaler.fit_transform(x_train)
std_scaled_x_test = std_scaler.fit_transform(x_test)
#Normalization of the data processed by Standard Scaler
normalized_std_train = preprocessing.normalize(std_scaled_x_train)
normalized_std_test = preprocessing.normalize(std_scaled_x_test)
|
import secrets
import string
import pyperclip
al = string.ascii_letters + string.digits
def inputHandler():
while True:
try:
n = input('How many characters? ')
if int(n) > 0:
return int(n)
else:
raise ValueError
except ValueError:
print('Please only enter positive integers.')
pyperclip.copy(''.join(secrets.choice(al) for i in range(inputHandler())))
print('Password has been copied to your clipboard!') |
# print(3.2*2)
import pysnooper
# 变量
@pysnooper.snoop()
def xuexi():
"""
笨办法学python
:return:
"""
# day 1
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_drivers = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
# print("there are", cars, "cars available.")
# print("there are only", drivers, "drivers available.")
# print("There will be", cars_not_drivers, "empty cars today.")
# print("we can transport", carpool_capacity, "people today.")
# print("we have", passengers, "to carpool today.")
# print("we need to put about", average_passengers_per_car, "in each car.")
# 格式化字符串,变量引用
my_name = 'zed A.Shaw'
my_age = 24 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'blue'
my_teeth = 'white'
my_hair = 'Brown'
print("Let's talk about %s. 渣渣辉" % my_name)
print("He's %d inches tall." % my_height)
print("He's %d pounds heavy." % my_weight)
print("Actually that's not too heavy.")
print("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print("His teeth are usually %s depending on the coffee." % my_teeth)
# this line is tricky, try to get it exactly right
print("If I add %d , %d, and %d I get %d." % (my_age, my_height, my_weight, my_age+my_height+my_weight))
def day2():
# 有10种类型的人
x = "There are %d types of people." % 10
#
binary = "binary"
do_not = "don't"
# 知道二元的人和不知道二元的人
y = "Those who know %s and those who %s." % (binary, do_not)
print(x)
print(y)
# 我说:有十种人
print("I said: %r." % x)
# 我还说:知道二元的人和不知道二元的人
print("I also said: '%s'." % y)
hilarious = False
joke_evaluation = "Isn't that joke so funny ?! % r"
# 这个笑话真的好笑吗?!假
print(joke_evaluation % hilarious)
w = "This is the left side of..."
e = "a string with a right side."
# 这是......右侧的字符串的左侧。
print(w + e)
print ("'.'* 10 # what'd that do?")
# Here's some new strange stuff ,remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun."
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("here are thr days:", days)
print("here are the months:", months)
print("""There's something going on here. With the three double-quotes.
we'll be able to type as much as we like. Even 4 lines if we want, or5, or6""")
if __name__ == '__main__':
#xuexi()
day2() |
a = 2
if a == 1:
print("OK")
elif a == 2:
print("2")
else:
print("NG")
|
import re
def main_1():
'''
1. 查找第一个匹配串
:return:
'''
s = 'i love python very much'
pat = 'python'
r = re.search(pat,s)
print(r.span()) # (7,13)
def main_2():
'''
re.findall()如果可以匹配返回的是一个列表,re.finditer()返回的是一个迭代器,
需要对其进行遍历,才能获取数据。
:return:
'''
s = '山东省潍坊市青州第1中学高三1班'
pat = '1' # 需要匹配的字符
r = re.finditer(pat, s)
#r = re.findall(pat, s)
# 将迭代出的结果添加至list中
list = [ ]
for i in r:
list.append(i.group())
print(list)
c = re.findall(pat,s)
print(c)
def main_3():
'''
匹配数字【0-9】
:return:
'''
s = '一共20行代码运行时间13.59s'
pat = '\d+' # +表示匹配数字(\d表示数字的通用字符)1次或多次
r = re.findall(pat, s)
print(r)
# ['20', '13', '59']
if __name__ == '__main__':
main_3() |
import time
def get_time_stamp(level=0):
t = time.time()
if level == 0:
return int(t)
elif level == 1:
return int(round(t * 1000)) # 毫秒级时间戳
elif level == 2:
return int(round(t * 1000000)) # 微秒级时间戳
numbers=[value for value in range(1,21)]
print(numbers)
numbers=[value for value in range(1,1000001)]
level = 1
startTime = get_time_stamp(level)
print('min=' + str(min(numbers)))
print('max=' + str(max(numbers)))
print('sum=' + str(sum(numbers)))
endTime = get_time_stamp(level)
print(str(endTime - startTime) )
print("---------打印奇数---------")
print(list(range(1,21,2)))
print("---------打印被3整除的数---------")
numbers = list(range(3,31))
for value in numbers:
if value%3==0:
print(value)
print("---------打印立方---------")
numbers = list(range(1,11))
for value in numbers:
print(str(value) + '立方=' + str(value**2*value))
print("---------解析立方---------")
numbers = [value**2*value for value in range(1,11)]
print(numbers) |
import requests #import requests
import json #import json
def city():
print ("Welcome" )
city = input("Enter A known City name: ")
api_key = ("077936f695f61908cd19a5a2452a97fb") #our public Api-key
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=077936f695f61908cd19a5a2452a97fb".format(city, api_key)) #api call
weather = response.json()
print ("The current weather in {0} is {1}".format(city, weather["weather"][0]["description"]) #the result
)
if __name__ == "__main__":
city()
|
#!/usr/bin/env python
#coding=utf-8
class TwoNums(object):
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
def practice1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i_index1 = 0
i_index2 = 0
for i_index in range(len(nums)):
i_subnum = nums[i_index]
i_othernum = target - i_subnum
if i_othernum in nums:
i_otherindex = nums.index(i_othernum)
if i_otherindex != i_index:
i_index1 = i_index
i_index2 = i_otherindex
break
return [i_index1, i_index2]
def practice2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i_index1 = 0
i_index2 = 0
for index, value in enumerate(nums):
i_othervalue = target - value
if i_othervalue in nums:
i_otherindex = nums.index(i_othervalue)
if index != i_otherindex:
i_index1 = index
i_index2 = i_otherindex
break
return [i_index1, i_index2]
class ThreeNums(object):
"""
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
def practice1(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
|
import sys, random
def mockText(str):
# iterate through string str and randomly capitalize text
newStr = ""
for i in range(0, len(str)):
# get random float between 0 and 1.0, inclusive
n = random.random()
# two routes: if character is uppercase, see if lowercase, and vice versa
# given random number, if n >= 0.5 then uppercase, else retain case
if str[i].islower():
if n >= 0.56:
newStr += str[i].upper()
else:
newStr += str[i]
else:
if n >= 0.54:
newStr += str[i].lower()
else:
newStr += str[i]
return newStr
def main():
for arg in sys.argv[1:]:
print(mockText(arg))
if __name__ == "__main__":
main()
|
import random
def gasolineres(n,b,d,p):
print "\nLlista de benzineres respecte a Sitges:",b,"kms"
i=0
j=0
p.append(0)
while j < n:
if b[0]> d: #Si la primera gasolinera esta a mas de 100kms
print "\n!!!GASOLINA INSUFICIENT!!!, el coche no pot continuar... es un trasto vell...no val per res..."
return 1
if b[j]-p[i] >= d : #Si la distancia que hay desde donde estoy a la siguiente es mayor que 100
i=i+1 #Hago una parada
p.insert(i,b[j-1]) #Añado a la lista de paradas la gasolinera
j=j+1
print "\nEl coche ha parat a les benzineres que estan a:",p[1:],"kms"
print "\nNumero de parades:",i
def main():
d=100
b=[]
p=[]
n=random.randint(5,10) #Genero entre 5 y 10 gasolineras de forma aleatoria
for k in range(n):
b.append(random.randint(1,400)) #Genero una gasolinera a distancia aleatoria y la añado a la lista
bOrdenada=sorted(b) #Ordeno de menor a mayor, la lista de distancias de gasolineras
gasolineres(n,bOrdenada,d,p)
main()
#El algoritmo recibe un nº de gasolineras y lista con las distancias de estas
#respecto al origen, la idea es parar cuanto mas tarde mejor y ir comparando la
#diferencia entre la gasolinera actual y la mas proxima y compararla con la gasolina
#que tiene el coche, segun el resultado, se para o no.
|
import time
class Calculator:
def step_one(self, number):
assert type(number) is int
time.sleep(3)
return number * 2
def step_two(self, number):
assert type(number) is int
time.sleep(3)
return number * 2
def step_three(self, number):
assert type(number) is int
time.sleep(3)
return number * 2
|
import tkinter as tk
from tkinter import simpledialog
def name(a):
return('Hello',a)
na=tk.Tk()
na.withdraw()
me=simpledialog.askstring(title='Test',prompt="What's Your Name:")
print(name(me))
|
from collections import defaultdict
class Node():
def __init__(self):
self.neighbors = []
class Graph():
def __init__(self):
self.graph = defaultdict(Node)
def add_edge(self, current: int, neighbor: int):
self.graph[current].neighbors.append(neighbor)
def bfs(self, start: int)->list:
visited = [start]
q = list(self.graph[start].neighbors)
while q:
n = q.pop(0)
if n not in visited:
visited.append(n)
q.extend(self.graph[n].neighbors)
return visited
def dfs(self, start: int)->list:
visited = set()
return self._dfs(start, visited)
def _dfs(self, start: int, visited: set):
result = []
if start not in visited:
visited.add(start)
result.append(start)
for n in self.graph[start].neighbors:
result.extend(self._dfs(n, visited))
return result
|
def binarysearch(arr: list[int], low: int, high: int, item: int) -> int:
if high >= low:
mid = int((high - low) / 2) + low
if item == arr[mid]:
return mid
elif item < mid:
return binarysearch(arr, low, mid - 1, item)
else:
return binarysearch(arr, mid + 1, high, item)
else:
return None |
file = open("test.txt", "r")
for line in file:
semi_index = line.index(";")
before_semi = line[:semi_index].split()
after_semi = line[semi_index + 1:].split()
quotient = int(after_semi[0])
remainder = int(after_semi[1])
numbers = list(map(int, before_semi))
numbers_sum = sum(numbers)
true_quotient = numbers_sum // len(numbers)
true_remainder = numbers_sum % len(numbers)
# :-1 чтобы убрать перенос строки в конце
print(line[:-1], end=" ")
print(quotient == true_quotient and remainder == true_remainder) |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 20:40:55 2020
@author: davi
"""
from random import *
# O random é pra inicializar os pesos com valores aleatórios
pesoInicial1 = random()
pesoInicial2 = random()
entrada1 = int(input('Digite entre 0 e 1'))
entrada2 = int(input('Digite entre 0 e 1'))
#somatoria = (entrada1*pesoInicial1)+(entrada2*pesoInicial2)
erro = 1
while erro != 0:
if entrada1 == 1 and entrada2 == 1:
resultadoEsperado = 1
else:
resultadoEsperado = 0
somatoria = (entrada1 * pesoInicial1) + (entrada2 * pesoInicial2)
if somatoria < 0:#o real é o zero 1 foi so na aula
resultado = 0
elif somatoria >= 0:# o real é com 0 1 foi so na aula
resultado = 1
print(f'resultado = {resultado}')
erro = resultadoEsperado - resultado
print(f'p1 = {pesoInicial1}')
print( f'p2 = {pesoInicial2}' )
pesoInicial1 = pesoInicial1 + (0.2*entrada1*erro)
pesoInicial2 = pesoInicial2 + (0.2 * entrada2 * erro)
print(f'erro = {erro}')
|
#import re
'''
We have record of the spam emails, using bloom filter algorithm, now
given a data stream contains many email usernames, we need to recognize
whether it is in the spam emails set or not, give the false_positive analysis based
on the number of hash functions.
'''
import hashlib
import random
#Open files
with open('listed_username_30.txt', 'r') as myfile1:
spam_emails_txt = myfile1.read()
with open('listed_username_365.txt', 'r') as myfile2:
stream = myfile2.read()
spam_emails_set = spam_emails_txt.split()
#print len(spam_emails_set)
stream_emails_set = stream.split()
#print len(stream_emails_set)
class Bloom:
def __init__(self, m, k, hash_fun):
"""
m: size of the vector (size of the targets)
k: number of hash functions to use
hash_fun: the hash function which hashs a string to a random number
in the range of [0, m-1]
vector: we use a int list to mimic the bit-array, initiate to all zeros
"""
self.m = m
self.k = k
self.hash_fun = hash_fun
self.vector = [0]*m
self.data = {}
self.false_positive = 0
def insert(self, key, value):
#save this key to the spam emails collection
self.data[key] = value
#use the k hash functions, set the vector[hash value] to 1
for i in range(self.k):
self.vector[self.hash_fun(key+str(i)) % self.m] = 1
def contains(self, key):
""" check if a key (string) should be filtered or not,
if for all the k hash functions, the vector has a 0 element
then this key must be a spam,
otherwise, it could be contained in the validated email set
"""
for i in range(self.k):
if self.vector[self.hash_fun(key+str(i)) % self.m] == 0:
return False
return True
def check(self, key):
if self.contains(key):
try:
return self.data[key]
except KeyError:
self.false_positive += 1
'''if key not in self.spam_emails:
self.false_positive += 1'''
def my_hash(x):
h = hashlib.sha256(x) # use sha256 just for this example
return int(h.hexdigest(),base=16)
'''generate random strings using the characters in chars, the length is n'''
def rand_data(n, chars):
return ''.join(random.choice(chars) for i in range(n))
#rand_keys = [rand_data(10,'abcde') for i in range(1000)]
#rand_keys2 = rand_keys + [rand_data(10,'fghil') for i in range(1000)]
def bloomTest(target_string_set, dart_string_set, k):
bloom = Bloom(10*len(target_string_set), k, my_hash)
for i in target_string_set:
bloom.insert(i, 'data')
for j in dart_string_set:
bloom.check(j)
#print bloom.false_positive
#print len(dart_string_set)
return float(bloom.false_positive)/len(dart_string_set)*100
'''
#print bloomTest(rand_keys,rand_keys2,1)
bloomTest(spam_emails_set,stream_emails_set,1)
'''
k = range(1,20)
percentage = [bloomTest(spam_emails_set,stream_emails_set,kk) for kk in k] # k is varying
# plotting the result of the test
from pylab import plot,show,xlabel,ylabel
plot(k,percentage,'--ob',alpha=.7)
ylabel('false positive %')
xlabel('k')
show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.