text stringlengths 37 1.41M |
|---|
import rimas as rimas
class Verso:
def __init__(self, body: str):
self.body = body
class Estrofe:
def __init__(self, body: str):
self.body = body
def __repr__(self):
return "represento isto: " + self.body
@property
def n_versos_label(self):
n_versos = self.n_versos
if n_versos == 1:
return 'monóstico'
elif n_versos == 2:
return 'dístico'
elif n_versos == 3:
return 'terceto'
elif n_versos == 4:
return 'quadra'
elif n_versos == 5:
return 'quintilha'
elif n_versos == 6:
return 'sextilha'
elif n_versos == 7:
return 'septilha'
elif n_versos == 8:
return 'oitava'
elif n_versos == 9:
return 'nona'
elif n_versos == 10:
return 'decima'
else:
return 'irregular'
@property
def n_versos(self):
return len(list(self.versos))
@property
def versos(self):
for line in self.body.split('\n'):
yield Verso(line)
class Poema:
def __init__(self, body: str):
self.body = body
@property
def n_estrofes(self):
return len(list(self.estrofes))
@property
def estrofes(self):
c = []
for line in self.body.split('\n\n'):
c.append(Estrofe(line.strip()))
return c[1:-1]
@property
def estruturaFixa(self):
c = []
for estrofe in self.estrofes:
c.append(estrofe.n_versos)
c.pop()
if self.n_estrofes == 4:
if(c[0] == 4 and c[1]==4 and c[2] == 3 and c[3]==3):
return "é um Soneto"
elif (c[0] == 8 and c[1]==8 and c[2] == 8 and (c[3]==4 or c[3]==5)):
return "é uma Balada"
elif len(c) == 7 and (c[0] == 6 and c[1]== 6 and c[2] == 6 and c[3]== 6 and c[4] == 6 and c[5]==6 and c[6] == 3):
return "é uma Sextina"
elif len(c)==3:
if(c[0] == 5 and c[1]== 3 and c[2] == 5):
return "é um Rondó"
elif(c[0] == 4 and c[1]==4 and c[2] == 5):
return "é um Rondel"
elif len(c)==1 and c[0] == 3:
return "é um Haicai"
return "não tem estrutura fixa"
@property
def estruturaFixa2(self):
resultados = {
"Soneto": (4, [4, 4, 3, 3]),
"Balada": (8, [8, 8, 4, 5]),
"Sextina": (7, [6, 6, 6, 6 ,6, 6, 3]),
"Rondó": (4, [5, 3, 5]),
"Rondel": (3, [4, 4, 5]),
"Haicai": (1, [3]),
}
n_versos_por_estrofe = [estrofe.n_versos for estrofe in self.estrofes]
for (nome_estrutura, (n_estrofes, n_versos_por_estrofe_esperado)) in resultados.items():
if self.n_estrofes != n_estrofes:
continue
if n_versos_por_estrofe == n_versos_por_estrofe_esperado:
return nome_estrutura
return None
def contaEstrofes(poema):
for values in poema.split("\n\n"):
contaestrofes+=1
return contaestrofes
def main():
with open('poema1.txt') as f:
poema = Poema(f.read())
estrofes = poema.estrofes
c = poema.estruturaFixa2
print(c)
print(rimas.aliteracao("Isto sofre sofrendo sofrido"))
# nEstrofes = contaEstrofes(poema)
# rimas.rima("foder","perder")
if __name__ == '__main__':
main() |
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from tkinter import *
bot = ChatBot("Misty")
conversation = [
"Hello",
"Hi there!",
"What is your name?",
"my name is Misty, i am created by diksha.",
"How are you doing?",
"I'm doing great.",
"That is good to hear.",
"Thank you.",
"You're welcome.",
"Which language you speak?",
"I mostly speak english language.",
"Where do you live?",
"i live in kochi, a beautiful city ."
]
trainer = ListTrainer(bot)
# # now training the bot with the help of trainer
trainer.train(conversation)
# answer = bot.get_response('what is your name?')
# print(answer)
# print("Talk to Misty Bot...")
# while True:
# query = input()
# if query == 'exit':
# break
# answer= bot.get_response(query)
# print("misty : ", answer)
main = Tk()
main.geometry("500x650")
main.title('My Chat Bot')
img = PhotoImage(file="images.png")
photoL = Label(main, image=img)
photoL.pack(pady=5)
def ask_from_bot():
query = textF.get()
answer_from_bot= bot.get_response(query)
msgs.insert(END,"You: "+query)
msgs.insert(END,"Misty : "+str(answer_from_bot))
textF.delete(0, END)
frame = Frame(main)
sc = Scrollbar(frame)
msgs = Listbox(frame, width=80, height =20)
sc.pack(side=RIGHT, fill=Y)
msgs.pack(side=LEFT, fill=BOTH, pady=10)
frame.pack()
# creating text field
textF=Entry(main, font=("Ariel", 20))
textF.pack(fill=X, pady=10)
btn = Button(main, text="Ask from Misty", font=("Verdana", 20), command=ask_from_bot)
btn.pack()
main.mainloop()
|
"""
*Given a list of Strings, and an external order in which it needs to be sorted, Sort the given list of *strings.
*
*For example:
*Input Strings : "Ajay", "Raja", "Keshav", "List", "Set", "Elephant", "Drone",
*Sort order:TESARDLK
*Sorted Strings: "Elephant", "Set","Ajay", "Raja", "Drone","List","Keshav"
"""
strings= "Ajay", "Raja", "Keshav", "List", "Set", "Elephant", "Drone"
order = "TESARDLK"
for i in order:
for j in range(len(strings)):
if strings[j][0] == i:
print(strings[j], end=", ")
|
from random import randint
number = randint(0, 100)
while True:
try:
user_number = int(input("Enter a number: "))
except:
print("that's not a number!")
continue
if user_number > number:
print("The number is lower")
if user_number < number:
print("The number is higher")
if user_number == number:
print("You've got it right!")
break
|
height = 4
if (height >6 ):
print "Do you play basketball?"
# else:
# print "You probably don't play basketball..."
# age = 9
# if (age < 3):
# print "You're a baby!"
# elif (age < 11):
# print "You're probably in Elementary School."
# elif (age < 13):
# print ("Middle school!")
# elif (age < 20):
# print "You're a teenager!"
# elif (age < 35):
# print "You're an adult, but too young to run for President. Bummer!"
# elif (age < 65):
# print "Do you ever really feel like an adult?"
# else:
# print "Enjoy retirement!"
|
#Initializing lists:
#To initiazlie an empty list:
my_list = []
#To initiate a list with values (can contain mixed types):
list2 = [1, "yay", 140.76]
#Finding information about a list:
#To get an item from a list by index:
my_list= [1, 2, 3, 4, 5, 6]
print my_list[0] #will give the first item in the list, which is 1
print my_list[3] #will give the 4th item in the list, which is 4
#To get the length:
length = len(my_list)
print "The length is",length
#To get the largest element of the list:
print "The maximum is", max(my_list)
#To get the smallest element of the list:
print "The minimum is", min(my_list)
#To find out if something is in the list:
print "3 is in the list:",(3 in my_list)
print "14 is in the list:",(14 in my_list)
# Adding to a list:
# To add something at the end of the list:
my_list.append(8)
print my_list
# To insert something at a certain index in the list: insert(index, object)
my_list.insert(6, 7)
print my_list
# To change a value in a list:
my_list[3] = 12
print my_list
# Removing from a list:
# To delete something from a list:
del my_list[2]
print my_list
# To delete a specific object from the list:
my_list.remove(5)
print my_list
|
my_list=["hello", 123, "goodbye"]
for i in my_list:
print i
print ""
for x in range(5):
print "hello"
print ""
for num in range(3,7):
print num |
import re
# # patterns = ['term1','term2']
# text = "This is a string with term1, not te other!"
# match = re.search('term1', text)
# print(type(match.start()))
# # print((match.start()))
# split_term ="@"
# email = "user@gmail.com"
# # email.split(split_term)
# print(re.split(split_term,email))
# print(re.findall('match','test phrase match in match middle'))
def multi_re_find(patterns, phrase):
for pat in patterns:
print("Searching for pattern{}".format(pat))
print(re.findall(pat,phrase))
print("\n")
# test_phrase = 'This is a string! But is has punctuation. How can we remove it?'
test_phrase = 'This is a string! with numbers 12312 and a symbol #hasing'
# test_pattern = ['[^!.?]+']
# test_pattern = ['[A-Z][a-z]+']
# test_pattern = [r'\w'] AlphaNumeric
# test_pattern = [r'\W'] Not AlphaNumeric
test_pattern = ['[^!.?]+']
test_pattern = [r'\W+']
multi_re_find(test_pattern,test_phrase) |
import turtle
birthday = 10187
birthday1 = 1010807
birthday2 = 20120807
Chinesse_name = '鄧凱中'
English_name = 'Leo'
English_name1 = 'leo'
Birthday_gift = '紙片馬力歐'
Birthday_gift1 = '紙片馬力歐:摺紙國王'
Birthday_gift2 = 'Paper Mario'
Birthday_gift3 = 'The origami king'
Birthday_gift4 = 'Paper Mario: The origami king'
Birthday_gift5 = '紙片馬力歐'
while True:
a = int(input("What's your birthday?"))
if a == birthday or a == birthday1 or a == birthday2:
a = input("What's your Chinesse name?")
if a == Chinesse_name:
a = input("What's your English name?")
if a == English_name or a == English_name1:
a = input("Your birthday gift is _________.")
if a == Birthday_gift or a == Birthday_gift1 or a == Birthday_gift2 or a == Birthday_gift3 or a == Birthday_gift4 or a == Birthday_gift5:
print('Happy Birthday~~~')
print('Here is your dictionary and gift:')
d = {}
while True:
print('=>')
print('1.建立字彙')
print('2.列印全部資料')
print('3.英翻中')
print('4.中翻英')
print('5.學習測驗')
print('6.離開系統')
sel = input('請輸入功能選項:')
if sel == '1':
en = input('輸入英文單字: ')
ch = input('輸入中文解釋: ')
d[en] = ch
fo = open('mydictionary.txt','w')
for k,v in d.items():
fo.write(k)
fo.write(':')
fo.write(v)
fo.write('\n')
fo.close()
elif sel == '2':
for k,v in d.items():
print(k,':',v)
elif sel == '3':
search = input('搜尋英文:')
print(d[search])
elif sel == '4':
search1 = input('搜尋中文:')
for k,v in d.items():
if search1 == v:
print(k)
elif sel == '5':
score = 0
for k,v in d.items():
print(v,':')
ans = input('請輸入你的答案:')
if ans == k:
print('恭喜答對')
score = score + 1
print('你的分數:',score)
else:
print('答錯了')
elif sel == '6':
print('Bye~!')
print('打開底下的新分頁')
break
j = turtle.Turtle()
j.color('blue')
j.shape('turtle')
d = turtle.Turtle()
d.color('yellow')
d.shape('turtle')
f = turtle.Turtle()
f.color('red')
f.shape('turtle')
for i in range(360):
j.forward(1)
j.left(1)
for i in range(4):
d.forward(100)
d.left(90)
for i in range(3):
f.left(120)
f.forward(100)
turtle.done()
break
else:
print('Enter errow, you are not Leo')
print('Please enter again.')
else:
print('Enter errow, you are not Leo')
print('Please enter again.')
else:
print('Enter errow, you are not Leo')
print('Please enter again.')
else:
print('Enter errow, you are not Leo')
print('Please enter again.') |
a = int(input('How many people in the whole class?'))
list_score = []
name = []
nameandscore = []
for i in range(a):
name_input = (input('Please enter your name:'))
score = int(input('Please enter your score:'))
list_score.append(score)
name.append(name_input)
nameandscore.append(list_score)
nameandscore.append(name)
print(nameandscore)
sum_score = sum(list_score)
print('whole class average:',int(sum_score/a))
highest = 0
for n in range(a):
if list_score[n] > highest:
highest = list_score[n]
highest_name = name[n]
print(highest_name,'the highest score:',highest)
lowest = 100
for n in range(a):
if list_score[n] < lowest:
lowest = list_score[n]
lowest_name = name[n]
print(lowest_name,'the lowest score:',lowest)
|
l=int(input('enter no of asterisks from left to right:'))
b=int(input('enter no of asterisks from top to bottom:'))
x=[]
for i in range(2*l-1):
x.append(' ')
p=0
while p<2*l-1:
x[p]='*'
p=p+2
print(*x,sep="")
for i in range(1,2*l-2):
x[i]=' '
k=0
while k<b-2:
print(*x,sep="")
k=k+1
m=0
while m<2*l-1:
x[m]='*'
m=m+2
print(*x,sep="")
|
# Baba is rabbit
# BFS 지만 시간초과로 인해 중복을 배제한 방문 배열을 정의하여
# append로 인한 시간을 줄였던게 핵심인 문제였다.
import sys
N = int(input())
cmd = {}
for _ in range(N):
p, _, q = sys.stdin.readline().split()
try: cmd[p].append(q)
except: cmd[p] = [q]
ans = []
visited = {}
Q = ['Baba']
for st in Q:
try:
for c in cmd[st]:
if c not in visited:
visited[c] = 1
Q.append(c)
ans.append(c)
except: continue
for a in sorted(ans):
print(a)
|
#lambda functions
def func(x,y,z):
return x+y+z
print(func(1,2,3))
myVar = lambda x,y,z:x+y+z
print(myVar(1,2,3))
# List of lambdas
myVar2 = [lambda x:x**2,
lambda x:x**3,
lambda x:x+20]
for i in myVar2:
print(i(2))
# Dictionary of lambdas
myCalcDict = {'add': lambda x,y:x+y,
'subtract': lambda x,y:x-y}
print(myCalcDict['add'](2,4))# This calls the add lambda function inside the myCalcDict object and then returns the value.
|
"""
Question 1: get n-number from list(length == m and m > n), combine n-number
For example: [1, 2, 3]; n =2; return [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
"""
def main(list_num, n):
print(list(permutation(list_num, n))) # first solution, use permutation
# print(len(list(permutation(list_num, n))))
print([(i, j) for i in list_num for j in list_num if i != j]) # second solution, use list derivation
# out: [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
if __name__ == "__main__"
list_num = [1, 2, 3, 4]
n = 2
main(list_num, n)
|
def squaresum(n):
sum=0
for i in range(1, n+1):
sum=sum+(i*i)
return sum
n=5
print(squaresum(n)) |
"""
Example 1
"""
my_list1 = [1, 2, 3, 4, 5, 6]
my_list2 = my_list1
my_list1.append(7)
print(my_list is 1 my_list2)
print(my_list1)
print(my_list2)
"""
Example 2
""" |
# importing json module
import json
# loading the json file and printing all the information
with open('exchange_rates.json') as jsonfile:
all_information = json.load(jsonfile)
print(all_information)
#iterate through the data and print Rates by Country
def print_rates(all_information):
for key, value in all_information.items():
# this is a way to loop through the nested dictionary
if isinstance(value, dict) and key == 'rates':
print(key)
print_rates(value)
# this is really not clean, but it works
elif key == 'base' or key == 'date':
continue
else:
print(f'{key}: {value}')
print_rates(all_information) |
string = input("Proszę wpisać dowolne słowo : ")
print(string)
reverse = string[::-1]
print(reverse)
if string == reversed:
print("To jest palindrom.")
else:
print("To nie jest palindrom")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Este modulo gestiona el comportamiento del fuego """
from celdas import evalua_celda_vecina
from main import extintores
class Fuego():
def __init__(self):
self.contra_incendios = False
self.propagacion = 0.5
def propagacion_fuego(self, x, y, celdasy, celdasx, celdas_vecinas_fuego, nuevo_estado):
# Se propaga dentro de los límites del plano
if y > 1 and y < (celdasy - 1):
if x > 1 and x < (celdasx - 1):
for direccion in celdas_vecinas_fuego:
# Ignora celdas con fuego o salidas
if celdas_vecinas_fuego[direccion] == 7 or (
celdas_vecinas_fuego[direccion] == 6 or celdas_vecinas_fuego[direccion] == 8):
continue
#Coloca 8 para no volver a evaluar la celda
elif celdas_vecinas_fuego[direccion] == 1:
nuevo_estado[x, y] = 8
# Se propaga hacia todos los casilleros de alrededor y coloca
# un 8 en el actual para no volver a evaluar la celda
else:
if direccion == "derecha":
nuevo_estado[x, y+1] = 7
nuevo_estado[x, y] = 8
elif direccion == "arriba":
nuevo_estado[x-1, y] = 7
nuevo_estado[x, y] = 8
elif direccion == "abajo":
nuevo_estado[x+1, y] = 7
nuevo_estado[x, y] = 8
elif direccion == "izquierda":
nuevo_estado[x, y-1] = 7
nuevo_estado[x, y] = 8
|
# This program reads from csv file and gives us the output and function is used here.
import csv
import sys
def read_from_file(filename):
with open(filename, 'r') as myfile:
content = list(csv.reader(myfile))
for rows in content:
print(', '.join(rows))
return
filename = input('Enter the name of file(with extension): ')
try:
read_from_file(filename)
except FileNotFoundError:
print('Please check name of file again')
|
def indexing(blocks, squares_x):
check = []
objects = squares_x ** 2
for index in range(0, len(blocks)):
step = index - squares_x -1
for num in range(0, 3):
count = 0
while count < 3:
current = count + step
if current != index and current >= 0 and current < objects:
check.append(current)
count += 1
step += squares_x
cleaning(blocks, squares_x, check, index)
check = []
def cleaning(blocks, squares_x, check, index):
if (index % squares_x) == 0:
num = len(check)
while num > 0:
num -= 1
if (check[num] +1) % squares_x == 0 :
del(check[num])
elif ((index +1) % squares_x) == 0:
num = len(check)
while num > 0:
num -= 1
if (check[num]) % squares_x == 0 :
del(check[num])
blocks[index].append(check)
check = []
|
import itertools
import random
def unit_generator(length): # Generate a list of all the combinations of the given length
bp = ['A', 'T', 'G', 'C']
unit_collection = itertools.product(bp, repeat = length)
unit_list = []
for unit in unit_collection:
unit_list.append(''.join(list(unit)))
return unit_list
def check_multiplication_2_str(short_string, long_string): # Check whether long_string is a multiplication of short_string. Return True if it is and False if it isn't
try:
if long_string == short_string:
return True
else:
if long_string [:len(short_string)] == short_string:
return check_multiplication_2_str(short_string, long_string[len(short_string):])
else:
return False
except:
return False
def check_multiplication_2_list(short_list, long_list): # Remove any long_item in long_list that is a multiplication of any short_item in the short_list and return the cleaned long_list
for long_item in long_list:
for short_item in short_list:
if check_multiplication_2_str(short_item, long_item) == True:
long_list.remove(long_item)
return long_list
def clean(upto_length): # After removing the duplications, make a list of all the passible units
mother = []
for number in range(1, upto_length+1):
mother += check_multiplication_2_list(mother, unit_generator(number))
return mother
def unit_repeat(unit_list): # Generate a list of all repeated possibilities from the unit sequence
sequence_list = []
for unit in unit_list:
child_list = []
for i in range (5, 51): # SSR repeat 5-50 times
sequence = unit*i
child_list.append(sequence)
sequence_list += child_list
return sequence_list
def main(base_length, ssr_insert_times): # base_length is the original random sequence's length and ssr_insert_times is how many SSR you want to insert
# Generate the SSR database in a list
upto_length = 6 # The length of the SSR's basic units can be upto. The maximum ranged from 6 to 10, depending on different papers
basic_unit_collection = clean(upto_length)
ssr_collection = unit_repeat(basic_unit_collection)
ssr_collection.sort()
if len(ssr_collection) - len(list(set(ssr_collection))) != 0: # Your ssr_collection shouldn't have any duplicated SSR
print('Something is wrong!')
else:
print('Awesome!')
# Instead of saving the ssr_collection into a file, you can directly use it here
# Generate the random sequence
bp = ['A', 'T', 'G', 'C']
raw_random_sequence = []
for i in range(base_length):
idx = random.randint(0,3)
raw_random_sequence.append(bp[idx])
random_position = [] # Create a random list of where you want to insert SSR
for i in range(ssr_insert_times):
random_int = random.randint(1,base_length-1) # The range of randint() already forces that random_int shouldn't be outside of the raw random sequence
if random_int in random_position: # I don't want 2 inserted SSR are too close to each other
continue
else:
random_position.append(random_int)
random_ssr_index = [] # Create a random list of which SSR you want to insert
for i in range(ssr_insert_times):
random_inte = random.randint(1,len(ssr_collection)-1) # The range of randint() already forces that random_int shouldn't be outside of the raw random sequence
# A single SSR can be inserted more than once
random_ssr_index.append(random_inte)
for position_idx, ssr_index in zip(random_position, random_ssr_index):
raw_random_sequence.insert(position_idx, ssr_collection[ssr_index])
print(raw_random_sequence)
with open('C:/Users/louie/Desktop/Simulated DNA.txt', 'w') as output_file:
output_file.write(''.join(raw_random_sequence))
print('Finished!')
main(100, 5)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`cercles` module
:author: Sauvage Célestine ,Danneels Sophie , Soltysiak Samuel
:date: November-December, 2015
Module for cercle.
"""
import math
def create(x,y,r):
"""
create a circle with center x which is x-axis and y-axis and r radius
:param x: x-axis for the center of circle
:type x: int or float
:param y: y-axis for the center of circle
:type y: int or float
:param r: radius of circle
:type r: int or float
:return: {'center':(x,y),'radius':r}
:rtype: a dict
:UC: none
:Example:
>>> cercle = create(250,250,100)
>>> get_center(cercle)
(250,250)
>>> imag_part (z)
2
"""
return {'center':(x,y),'radius':r}
def get_center(cercle):
"""
return the center (x-axis,y-axis)
:param cercle: a circle
:type z: a circle ( dict)
:return: the center of circle
:rtype:tuple
:UC: none
:Example:
>>> cercle = create(250,250,100)
>>> get_center(cercle)
(250,250)
"""
return cercle['center']
def get_x_axis(cercle):
"""
return x-axis
:param cercle: a circle
:type z: a circle ( dict)
:return: x-axis of center of circle
:rtype:float or int
:UC: none
:Example:
>>> cercle = create(250,250,100)
>>> get_x_axis(cercle)
250
"""
return get_center(cercle)[0]
def get_y_axis(cercle):
"""
return y-axis
:param cercle: a circle
:type z: a circle ( dict)
:return: y-axis of center of circle
:rtype: float or int
:UC: none
:Example:
>>> cercle = create(250,250,100)
>>> get_y_axis(cercle)
250
"""
return get_center(cercle)[1]
def get_radius(cercle):
"""
return the radius of center
:param cercle: a circle
:type z: a circle ( dict)
:return: the raidus of circle
:rtype: int or float
:UC: none
:Example:
>>> cercle = create(250,250,100)
>>> get_radius(cercle)
100
"""
return cercle['radius']
from tkinter import *
fenetre=Tk()
can = Canvas(fenetre,bg='white',height=500,width=500)
can.pack()
def draw_circle(cercle):
x=get_x_axis(cercle)
y=get_y_axis(cercle)
r=get_radius(cercle)
can.create_oval(x-r, y-r, x+r, y+r)
def r(cercle):
return ((get_radius(cercle))*((1-math.sin(math.pi/3))/(1+(math.sin((math.pi/3))))))
def r1(cercle):
return ((get_radius(cercle)*math.sin(math.pi/3))/(1+(math.sin((math.pi/3)))))
def alpha(i):
return (2*i*math.pi)/3
def cerclenimporte(r,r1,alpha,x,y):
return (x+(r+r1)*math.cos(alpha),(r+r1)*math.sin(alpha)+y)
def quifaittout(cercle,n):
draw_circle(cercle)
r = r(cercle)
r1 = r1(cercle)
for i=1 in range (n+1):
alpha= alpha(i)
new_center=cerclenimporte(r,r1,alpha,get_x_axis(cercle),get_y_axis(cercle))
create(new_center,r)
|
filePath = "input.txt"
wordList = []
wordCount = 0
#Read lines into a list
file = open(filePath, 'rU')
for line in file:
for word in line.split():
wordList.append(word)
wordCount += 1
print wordList
print "Total words = %d" % wordCount
|
import time
print ("Module\n=================")
print time.__dict__
print ("\nClass\n=================")
class tClass(object):
def __init__(self, x):
self.x = x
def double(self):
self.x += self.x
t = tClass(5)
print t.x
t.double()
print t.x
print t.__dict__
print tClass.__dict__
x = 1
def fun(a):
b=3
x=4
def sub(c):
d=b
global x
x = 7
print ("\nNested Function\n=================")
print locals()
sub(5)
print ("\nFunction\n=================")
print locals()
print locals()["x"]
print globals()["x"]
print ("\nGlobals\n=================")
print globals()
print locals()
fun(2)
|
import random
function swap (list, i j):
list[i], list[j] = list[j], list[i]
#put the pivot in the right place and return its index
function partition (list, left, right, pivot):
pivot_value = list[pivot]
swap (list, pivot, right)
store_index = left
for i in range (left, right - 1):
if list[i] <= pivot_value:
swap (list, i, store_index)
store_index++
swap (list, store_index, right)
return store_index
function quick_sort (list, left, right):
if left < right:
pivot = random.randint(left, right)
new_pivot_index = partition (list, left, right, pivot)
quick_sort (list, left, new_pivot_index - 1)
quick_sort (list, new_pivot_index + 1, right)
function quick_sort (list):
quick_sort (list, 0, len(list) - 1) |
def on(text):
return [word for word in text.split() if word[-2:] == 'on']
def z(text):
return [word for word in text.split() if 'z' in word]
def ne(text):
return [word for word in text.split() if 'ne' in word]
def Mai_min(text):
return [word for word in text.split() if word[1:] == word.lower()[1:]] |
###########################
# 6.00.2x Problem Set 1: Space Cows
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file contents contain
data in the form of comma-separated cow name, weight pairs, and return a
dictionary containing cow names as keys and corresponding weights as values.
Parameters:
filename - the name of the data file as a string
Returns:
a dictionary of cow name (string), weight (int) pairs
"""
cow_dict = dict()
f = open(filename, 'r')
for line in f:
line_data = line.split(',')
cow_dict[line_data[0]] = int(line_data[1])
return cow_dict
# Problem 1
def greedy_cow_transport(cows,limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the following method:
1. As long as the current trip can fit another cow, add the largest cow that will fit
to the trip
2. Once the trip is full, begin a new trip to transport the remaining cows
Does not mutate the given dictionary of cows.
Parameters:
cows - a dictionary of name (string), weight (int) pairs
limit - weight limit of the spaceship (an int)
Returns:
A list of lists, with each inner list containing the names of cows
transported on a particular trip and the overall list containing all the
trips
"""
order = []
cow_copy = cows.copy()
cow_sort = sorted(cow_copy.items(), key=lambda x: x[1], reverse = True)
while len(cow_copy) > 0:
trip = []
trip_limit = limit
for cow, weight in cow_sort:
if cow in cow_copy and weight <= trip_limit:
trip.append(cow)
trip_limit = trip_limit - weight
del cow_copy[cow]
order.append(trip)
return order
# Problem 2
def brute_force_cow_transport(cows,limit=10):
"""
Finds the allocation of cows that minimizes the number of spaceship trips
via brute force. The brute force algorithm should follow the following method:
1. Enumerate all possible ways that the cows can be divided into separate trips
2. Select the allocation that minimizes the number of trips without making any trip
that does not obey the weight limitation
Does not mutate the given dictionary of cows.
Parameters:
cows - a dictionary of name (string), weight (int) pairs
limit - weight limit of the spaceship (an int)
Returns:
A list of lists, with each inner list containing the names of cows
transported on a particular trip and the overall list containing all the
trips
"""
order = []
# Use helper function to get all possible partitions of cows
collections = sorted(get_partitions(cows), key = len)
# The number of possible partitions
clen = len(collections)
# Create a dictionary that holds the indices of the partitions as keys
# and their weight validity as values
possible_dict = {}
for i in range(clen):
possible_dict[i] = True # Default is True
for trip in collections[i]: # Each list inside the partition is a trip
total = 0
for cow in trip:
total += cows[cow]
if total > limit:
possible_dict[i] = False # Change the value to False if the total weight on board exceeds the limit
# Create a dictionary with partitions whose trips are all valid
valid_dict = {}
for valid_trip in possible_dict: # iterating over index numbers (integers)
if possible_dict[valid_trip] == 1:
length = len(collections[valid_trip])
valid_dict[valid_trip] = length
# Set the variable "minimum" to be the minimum number of trips found among all valid collections
minimum = min(valid_dict.values())
# Find a collection with the minimum number of trips
for v_trip in valid_dict: # iterating over index numbers (integers)
if valid_dict[v_trip] == minimum:
order = collections[v_trip]
break
return order
# Problem 3
def compare_cow_transport_algorithms():
"""
Using the data from ps1_cow_data.txt and the specified weight limit, run your
greedy_cow_transport and brute_force_cow_transport functions here. Use the
default weight limits of 10 for both greedy_cow_transport and
brute_force_cow_transport.
Print out the number of trips returned by each method, and how long each
method takes to run in seconds.
Returns:
Does not return anything.
"""
cows = load_cows("ps1_cow_data.txt")
limit = 10
greedy_start = time.time()
greedy = greedy_cow_transport(cows, limit)
greedy_end = time.time()
print("The number of trips returned by the greedy algorithm is", len(greedy))
print('The time that the greedy algorithm takes to run is', greedy_end - greedy_start)
brute_start = time.time()
brute = brute_force_cow_transport(cows, limit)
brute_end = time.time()
print("The number of trips returned by the brute force algorithm is", len(brute))
print('The time that the brute force algorithm takes to run is', brute_end - brute_start)
"""
Here is some test data for you to see the results of your algorithms with.
Do not submit this along with any of your answers. Uncomment the last two
lines to print the result of your problem.
"""
# cows = load_cows("ps1_cow_data.txt")
# limit=100
# print(cows)
# print(greedy_cow_transport(cows, limit))
# print(brute_force_cow_transport(cows, limit))
|
import unittest
from FractionCalculator import FractionCalculator
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html has a nice description of the framework
class TestCalculator(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
def testEquals(self):
f1=FractionCalculator(1,2)
f2=FractionCalculator(1,2)
print(f"{f1} == {f2} is {f1.equal(f2)} [True]")
self.assertEqual(f1.equal(f2),True,f"{f1} == {f2} is {f1.equal(f2)} [True]")
# print(f"{f12} + {f12} = {f12.plus(f12)} [4/4]")
def testAddition(self):
f1=FractionCalculator(1,2)
f2=FractionCalculator(3,4)
f3=f1.plus(f2)
print(f"{f1} + {f2} is {f3} [10/8]")
self.assertEqual(str(f3),'10/8',f"{f1} + {f2} is {str(f3)} [10/8]")
def testSubstraction(self):
f1=FractionCalculator(4,4)
f2=FractionCalculator(1,2)
f3=f1.minus(f2)
print(f"{f1} - {f2} is {f3} [4/8]")
self.assertEqual(str(f3),"4/8",f"{f1} - {f2} is {f3} [4/8]")
def testMultiplication(self):
f1=FractionCalculator(1,2)
f2=FractionCalculator(1,2)
f3=f1.times(f2)
print(f"{f1} * {f2} is {f3} [1/4]")
self.assertEqual(str(f3),"1/4",f"{f1} * {f2} is {f3} [1/4]")
def testDivision(self):
f1=FractionCalculator(4,4)
f2=FractionCalculator(1,2)
f3=f1.divide(f2)
print(f"{f1} / {f2} is {f3} [8/4]")
self.assertEqual(str(f3),"8/4",f"{f1} / {f2} is {f3} [8/4]")
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
|
from collections import defaultdict, Counter
import re
def anagram_lst(str1, str2):
"""verifies whether both the string are anagrams of each other"""
return sorted(list(cleanString(str1))) == sorted(list(cleanString(str2)))
def cleanString(str1):
"""a method which removes whitespaces and lowers the string"""
str1 = re.sub(r"\s+", "", str1, flags=re.UNICODE)
str1 = str1.lower()
return str1
def anagrams_dd(str1, str2):
"""verifies whether both string are anagrams of each other using dictinories"""
dd = defaultdict(int)
str1 = re.sub(r"\s+", "", str1, flags=re.UNICODE)
str2 = re.sub(r"\s+", "", str2, flags=re.UNICODE)
str1 = cleanString(str1)
str2 = cleanString(str2)
for letter in str1:
dd[letter] = dd[letter] + 1
for c in str2:
if c in dd:
dd[c] = dd[c] - 1
else:
return False
for key in dd:
if dd[key] != 0:
return False
return True
def anagrams_cntr(str1, str2):
"""verifies whether both the strings are anagrams of each other using counter from the collections frmework"""
str1 = cleanString(str1)
str2 = cleanString(str2)
return sorted(Counter(str1).elements()) == sorted(Counter(str2).elements())
def covers_alphabet(sentence):
"""verifies whether the given sentence has all the alphabets"""
sentence = sentence.lower()
sentence = "".join(re.findall("[a-zA-Z]+", sentence))
return sorted(list(set(sentence))) == list('abcdefghijklmnopqrstuvwxyz')
def book_index(words):
"""returns a list which describes where each word is located on a list of pages"""
d = defaultdict(set)
for k, v in sorted(words, key=lambda x: x[0]):
d[k].add(v)
wordList = list()
for k, v in d.items():
singleList = list()
singleList.append(k)
singleList.append(sorted(list(v)))
wordList.append(singleList)
return wordList
|
import unittest
from HW06_Dhaval_Dongre import *
class TestList(unittest.TestCase):
def test_list_copy(self):
"""verifies whether the copy of the list is the same as the original"""
self.assertEqual([1,2,3],list_copy([1,2,3]))
self.assertNotEqual([1,2,2,3],list_copy([1,2,3]))
def test_list_intersect(self):
"""verifies whether the common elements between 2 lists is as expected in a list format"""
self.assertEqual(list_intersect([1,2,3],[1,2]),[1,2])
def test_list_difference(self):
"""verifies whether the difference between 2 lists is as expected in a list format"""
self.assertEqual(list_difference([1,2,3],[1,2]),[3])
self.assertEqual(list_difference([1,2,3,2],[1,2]),[3])
def test_remove_vowels(self):
"""verifies whether the vowels are removed as expected by the remove_vowels function"""
self.assertEqual(remove_vowels('aeiou'),'')
self.assertEqual(remove_vowels('Laeiouau'),'L')
def test_check_pwd(self):
"""verifies whether the password matches our criteria of uppercase, lowercase and digit"""
self.assertEqual(check_pwd('Dh@v@l4'),True)
self.assertEqual(check_pwd('Dhaval'),False)
def test_insertion_sort(self):
"""verifies our insertion sort logic and confirms whether the list is sorted as expected"""
self.assertEqual(insertion_sort([8,2,1,3,5,5,4]),[1, 2, 3, 4, 5, 5, 8])
if __name__ == '__main__':
print('Running unit tests')
unittest.main(exit=False, verbosity=2) |
from bitset import Bitset
class Valoracao(Bitset):
def compare(self, valoracao):
if self.getSize() != valoracao.getSize():
isEqual = False
else:
i = 0
while i < self.getSize() and self.test(i) == valoracao.test(i):
i += 1
if i != self.getSize():
isEqual = False
else:
isEqual = True
return isEqual
def display(self):
s = ""
for i in range(self.getSize()):
if self.test(i):
s += "1"
else:
s += "0"
return s
|
# coding=utf-8
# 插入排序
# 插入排序的思想就是构造一个有序序列,一个无序序列
# 首先从无序序列中取出一个元素放入到有序序列中,找到合适的位置,所有大于该元素的有序元素后移,一直到无序序列为空集
def InsertSort(nums_list):
for i in range(1, len(nums_list)): # i - 1 代指当前有序集合最大元素的下标
if nums_list[i] < nums_list[i-1]:
temp = nums_list[i] # 哨兵记录当前无序的元素
j = i - 1
while nums_list[j] > temp and j > -1: # 把这个元素放到有效集合合适的位置 所有大于该元素的下标后移
nums_list[j+1] = nums_list[j]
j -= 1
nums_list[j+1] = temp # 空闲的位置放入无序的元素
test = [5, 4, 3, 2, 1, 2, 2, 2, 2, 2, -2, 4, 5, 4, 5]
InsertSort(test)
print test
|
# The following iterative sequence is defined for the set of positive integers:
#
# n -> n/2 (n is even)
# n -> 3n + 1 (n is odd)
#
# Using the rule above and starting with 13, we generate the following sequence:
#
# 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
#
# It can be seen that this sequence (starting at 13 and finishing at 1) contains
# 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
# that all starting numbers finish at 1.
#
# Which starting number, under one million, produces the longest chain?
#
# NOTE: Once the chain starts the terms are allowed to go above one million.
cache = {}
def collatz(nb):
if nb == 1:
return 1
if nb in cache:
return cache[nb]
if nb % 2 == 0:
_next = nb / 2
else:
_next = 3 * nb + 1
cache[nb] = collatz(_next) + 1
return cache[nb]
max_chain = 0
max_value = 0
for i in range(2, 1000000):
tmp = collatz(i)
if tmp > max_chain:
max_chain = tmp
max_value = i
print max_value
|
#coding=UTF-8
numSucessor = None
numAntercessor = None
numEscolhido = None
print "Escolha um numero inteiro"
numEscolhido = input()
numSucessor = numEscolhido +1
numAntecessor = numEscolhido -1
print "O Sucessor do numero {} é {} e o antecessor do mesmo é {}.".format(numEscolhido, numSucessor, numAntecessor)
|
"""
Author: Pranav Goel
Takes user's name as input and returns a random type of house they'll have when they grow up.
"""
import random
future = ['bungalow','mansion','villa']
name = input("What is your name?\n")
num = random.random()%3
print(name,", you'll have a ",future[int(num)]," when you grow up! :)") |
'''
Homework 3
@author: Carhat Eusebiu
'''
import random
#keep solution with its attributes
class Solution:
def __init__(self,sol,v,w):
#solution itself
self.sol=sol
#value
self.v=v
#weight
self.w=w
def getSol(self):
return self.sol;
def __getitem__(self,index):
return self.sol[index]
def __setitem__(self,index,value):
self.sol[index] = value
def setValue(self,x):
self.v=x;
def getValue(self):
return self.v;
def setWeight(self,x):
self.w=x;
def getWeight(self):
return self.w;
#the class for backpack problem with evolutive algorithm
class BackpackEAP:
def __init__(self,n,l,w):
#nr of all things that we have
self.n=n
#list with their values and weight
self.l=l
#max weight of backpack
self.w=w
self.outputFileName=str(n)+"_input_data.out"
#get random solution (base2 nr)
def randomSol(self):
l=[]
for i in range(0,self.n):
l.append(0)
d=pow(2,self.n)-1
number=random.randrange(0,d)
i=0
while(number):
bit=int(number)%2
l[i]=bit
number=int(number/2)
i+=1
l.reverse()
return l
#generate valid solution
def generateValidSol(self):
x=self.randomSol()
w=self.fitness(x)
v=self.eval(x)
while w>self.w:
x=self.randomSol()
w=self.fitness(x)
v=self.eval(x)
return Solution(x,v,w);
#get weight of sol
def fitness(self,x):
w=0
for i in range(0,self.n):
w=w+self.l[i][2]*x[i]
return w;
#get value of solution
def eval(self,x):
w=0
for i in range(0,self.n):
w=w+self.l[i][1]*x[i]
return w;
#generate population of N individuals from random valid solutions
def populate(self,N):
p=[]
for i in range(0,N):
p.append(self.generateValidSol())
return p;
#for strong mutation
def flip(self,bit):
if(bit==0):
return 1;
else:
return 0;
#mutation algorithm(strong/weak)
#get a population
#return new population resulted by mutation
def mutation(self,p,pm,type):
l=len(p)
x=[]
#for each individuals for population received
for i in range(0,l):
#take default invalid solution(with weight above max) to entry in while
x.append(Solution([],0,self.w+1))
while(x[i].getWeight()>self.w):
x[i].sol=[]
for j in range(0, self.n):
#set each bit
q=random.uniform(0,1)
if(q<pm):
x[i].sol.append(self.flip(p[i].sol[j]) if type=="strong" else random.choice([0,1]))
else:
x[i].sol.append(p[i].sol[j])
#compute value and weight of sol
x[i].setValue(self.eval(x[i].sol))
x[i].setWeight(self.fitness(x[i].sol))
return x;
#cross algorithm(uniform/point)
#get parents population
#return childrens population
def cross(self,parents,type):
l = len(parents)
childrens=[Solution([],0,0)]
#take pair of 2 parents
for i in range(0,l-1,2):
p1=parents[i]
p2=parents[i+1]
#for each pair generate 2 childrens by chosen method
if(type=="uniform"):
c1,c2=self.uniformCross(p1,p2,0.3)
elif(type==" point "):
c1,c2=self.pointCross(p1,p2)
childrens.append(c1)
childrens.append(c2)
del childrens[0]
return childrens
def uniformCross(self,p1,p2,pm):
c1=Solution([],0,self.w+1)
c2=Solution([],0,self.w+1)
#only valid solutions
while(c1.getWeight()>self.w):
c1.sol=[]
for i in range(0,self.n):
q=random.uniform(0,1)
if(q<pm):
c1.sol.append(p1.sol[i])
else:
c1.sol.append(p2.sol[i])
c1.setWeight(self.fitness(c1.sol))
c1.setValue(self.eval(c1.sol))
#to short the time verify the solutions separately
while(c2.getWeight()>self.w):
c2.sol=[]
for i in range(0,self.n):
q=random.uniform(0,1)
if(q<pm):
c2.sol.append(p2.sol[i])
else:
c2.sol.append(p1.sol[i])
c2.setWeight(self.fitness(c2.sol))
c2.setValue(self.eval(c2.sol))
return c1,c2
def pointCross(self,p1,p2):
c1=Solution([],0,self.w+1)
c2=Solution([],0,self.w+1)
#only valid solutions
while(c1.getWeight()>self.w or c2.getWeight()>self.w):
k=random.randrange(0,self.n)
c1.sol[:k]=p1.sol[:k]
c1.sol[k:]=p1.sol[k:]
c2.sol[:k]=p2.sol[:k]
c2.sol[k:]=p2.sol[k:]
c1.w=self.fitness(c1.sol)
c1.v=self.eval(c1.sol)
c2.w=self.fitness(c1.sol)
c2.v=self.eval(c1.sol)
return c1,c2;
def turnir(self,p):
bestSol=p[0]
bestIndex=0
nr=10
#if don't have enough parents select from how many remained
if(len(p)<10):
nr=len(p)
#selecting best parent from 10 or less individuals
for i in range(0,nr):
x=random.randrange(0,len(p))
if(p[x].getValue()>bestSol.getValue()):
bestSol=Solution(p[x],p[x].getValue(),p[x].getWeight())
bestIndex=i
return bestSol, bestIndex;
def selectParents(self,p):
#will be n/2 pair of parents
n=len(p)
parents=[]
for i in range(0,int(n/2)):
#select first parent by turnir method
bestSol, bestIndex = self.turnir(p)
parents.append(bestSol)
#remove selected parent from population to not select again
del p[bestIndex]
#select second parent random
x=random.randrange(0,len(p))
parents.append(p[x])
del p[x]
return parents
def survivalSelection(self,p,px,pm,N):
l=p[:]
for i in range(0,len(px)):
l.append(px[i])
for i in range(0,len(pm)):
l.append(pm[i])
#sorting all poulation(parents+desc+mutations) desc by fitness
l.sort(key=lambda x: x.v, reverse=True)
#select 20% of population by fitness
population=l[:int(N/5)]
del l[:int(N/5)]
#select another 80% by turnir method
n=N-int(N/5)
for i in range(0,n):
bestSol, bestIndex = self.turnir(l)
#remove selected parent from population
population.append(bestSol)
del l[bestIndex]
return population
#evolutive algorithm
def ea(self,N,M,crossType,mutationType):
t=0
p = self.populate(N)
while(t<M):
parents = self.selectParents(p)
px = self.cross(parents,crossType)
pm = self.mutation(px,0.3,mutationType)
p = self.survivalSelection(parents,px,pm,N)
t=t+1
#return best individual from actual population
p.sort(key=lambda x: x.v, reverse=True)
return p[0]
#run EA algorithm with different param for n times and write a table report in file
def run(self,n,N,M,crossType,mutationType):
best=self.ea(N,M,crossType,mutationType)
sum=0
for i in range(0,n):
sol=self.ea(N,M,crossType,mutationType)
sum=sum+self.eval(sol.sol)
if self.eval(sol.sol)>self.eval(best.sol):
best=sol
with open(self.outputFileName,"a") as f:
f.write("|%d\t\t|%d\t\t|%d\t|%s\t|%s\t\t\t|%d\t\t|%d\t\t|\n"% (n,N,M,crossType,mutationType,self.eval(best.sol),sum/n))
f.write("----------------------------------------------------------------------------\n")
def write_table_header(self):
with open(self.outputFileName,"w") as f:
f.write("|---------------------------------------------------------------------------|\n")
f.write("|Runs\t|N\t\t|M\t\t|cross type\t|mutation type\t|Best value\t|Average\t|\n")
f.write("|---------------------------------------------------------------------------|\n")
def main():
stop=False
while(stop==False):
x=int(input("Choose\n1. for read from file\n0. for exit\n"))
if x==1:
try:
s=input("Filename:")
f=open(s,"r")
except IOError:
print("The file does not exist!")
main()
l=[]
n=int(f.readline())
for i in range(0,n):
line=f.readline()
s=line.split()
s=list(map(int, s))
l.append(s)
w=int(f.readline())
elif x==0:
stop=True
else:
print("Enter a valid nr\n")
main()
if stop==False:
bp = BackpackEAP(n,l,w)
print("Backpack max weight: "+str(bp.w)+"\n")
bp.write_table_header()
bp.run(10,10,100,"uniform","strong")
bp.run(10,10,100,"uniform","weak")
bp.run(10,10,100," point ","strong")
bp.run(10,10,100," point ","weak")
bp.run(10,10,1000,"uniform","strong")
bp.run(10,10,1000,"uniform","weak")
bp.run(10,10,1000," point ","strong")
bp.run(10,10,1000," point ","weak")
main()
|
#下面的代码创建了一个餐馆类,并且创建了一个餐馆实例(对象)
#每个类对应一个类对象,用以存储类的基本信息
class Restaurant(): #类对象
"""一个表示餐馆的类""" #类描述
restaurant_star = 3 #类属性,直接在类中定义用类名点属性名访问
count = 0
def __init__(self, name, cuisine_type): #类的构造函数,类实例化时使用的函数
"""初始化餐馆"""
self.name = name.title() #实例属性,在类中self.属性名
self.cuisine_type = cuisine_type
Restaurant.count += 1
def describe_restaurant(self): #类的方法
"""显示餐馆信息摘要"""
msg = self.name + "服务很好"+\
self.cuisine_type + "."
print ("\n" + msg)
def open_restaurant (self):
"""显示一条消息,指出餐馆正在营业"""
msg = self.name + "餐馆正在营业,欢迎光临!"
print ("\n" + msg)
restaurant = Restaurant("星空披萨", 'pizza') #实例化即创建一个对象
print(restaurant.name) #实例属性,在类 外对象名点属性名 #类中直接包含的语句会被执行
print(restaurant.cuisine_type) #一般不这样使用
print(Restaurant.restaurant_star)
restaurant.describe_restaurant() #对象名点方法名/属性名调用方法
restaurant.open_restaurant() #实例方法,对象名点方法名(参数)
|
#!/usr/bin/python
import sys
import string
import re
def htmltowords():
print_str = ""
# reading html on stdin
for line in sys.stdin:
# find the next <a> tag, look for href within the tag
line = line.rstrip()
line = string.lower(line)
comp = re.split('[^a-z]', line)
for c in comp:
if len(c) > 3:
print_str += c + "\n"
return print_str
if __name__ == '__main__':
# note -- assumes that order matters for bigrams
prev_word = ""
words = (htmltowords()).split("\n")
for word in words:
if not prev_word == "":
print prev_word + "," + word + "\t1"
prev_word = word
|
import re
def name_of_email(addr):
#re_noe = re.compile(r'(<(.*)>(.*)@(.*))|((.*)@(.*))')
re_noe = re.compile(r'<?(\w+\s?\w+)>?.*@\w+.\w{3}') # <?和>? 表示 有一个或没有 这样就既可以匹配有<>的也可以匹配没有的
m = re_noe.match(addr)
print(m.group(1))
name_of_email('<Tom Paris> tom@voyager.org')
name_of_email('tom@voyager.org')
|
import unittest
from scheduler_classes import Employee, Job, MaxHeap, schedule, remove_emp_no, remove_job_no, get_emp_no, get_job_no, \
reset_day, emp_gen
class TestScheduler(unittest.TestCase):
def setUp(self):
self.emp_1 = Employee("john", "smith")
self.emp_2 = Employee("carol", "kelly")
self.h_1 = MaxHeap(1)
self.h_2 = MaxHeap(2)
self.h_4 = MaxHeap(4)
# (self, unit, time_existed, time_needed, priority)
self.j_1_1 = Job("c1", 2, 2, 1)
self.j_1_2 = Job("c1", 4, 4, 1)
self.j_1_3 = Job("c1", 3, 3, 1)
self.j_2_1 = Job("c2", 4, 4, 2)
self.j_2_2 = Job("c2", 5, 5, 2)
def tearDown(self):
"""
tests properties of instance upon init
:return:
"""
MaxHeap.heaps_list.clear()
Employee.all_emps.clear()
Employee.emp_number = 0
Job.jobs_number = 0
def test_Employee(self):
"""
tests properties of instance upon init
:return:
"""
# tests auto increment of emp_numbers
self.assertEqual(self.emp_1.number, 0)
self.assertEqual(self.emp_2.number, 1)
# tests addition to Employee.all_emps upon init
self.assertEqual(Employee.all_emps, [self.emp_1, self.emp_2])
def test_MaxHeap(self):
"""
tests properties of instance upon init
:return:
"""
self.h_3 = MaxHeap(3)
# tests that upon init a priority level is added to MaxHeap.heaps_list
# and the list of heaps is sorted based on priority level
self.assertEqual(MaxHeap.heaps_list, [self.h_1, self.h_2, self.h_3, self.h_4])
# the heap is not sorted by time_needed
# it follows heap property where children are idx*2 + 1 or 2
# and parent >= children
# these indexes reflect this property
self.assertEqual(self.h_1.heap[0], self.j_1_2)
self.assertEqual(self.h_1.heap[1], self.j_1_1)
self.assertEqual(self.h_1.heap[2], self.j_1_3)
# tests if attempt to create existing priority level raises err
with self.assertRaises(ValueError):
_ = MaxHeap(1)
_ = MaxHeap(-1)
_ = MaxHeap("x")
def test_Job(self):
"""
tests properties of Job instance upon init
:return:
"""
# tests job number auto incrementation
self.assertEqual(self.j_1_1.job_number, 0)
self.assertEqual(self.j_2_2.job_number, 4)
# tests adding job without existing priority level throws err
with self.assertRaises(ValueError):
# job_with_priority_not_existing
_ = Job("c2", 5, 5, 7)
# jobs with invalid inputs
_ = Job("x", -1, 4, 7)
_ = Job("x", 1, None, 7)
_ = Job("x", 1, 3, "x")
def test_remove_emp_no(self):
"""
test that emp is removed from Employee.all_emps
:return:
"""
remove_emp_no(0)
# does emp retain emp_number?
self.assertEqual(self.emp_2.number, 1)
# does Employee.all_emps reflect removal of said emp
self.assertEqual(Employee.all_emps, [self.emp_2])
def test_remove_job_no(self):
"""
tests if upon removing a job via linear search rather than "pop" off heap
that the heap is reconstructed appropriately
:return:
"""
# todo add larger sample and more removes
remove_job_no(2)
self.assertEqual(self.h_1.heap[1], self.j_1_1)
remove_job_no(1)
self.assertEqual(self.h_1.heap[0], self.j_1_1)
def test_schedule(self):
pass
def test_get_emp_no(self):
x = get_emp_no(1)
self.assertEqual(x, self.emp_2)
def test_reset_day(self):
Employee.today_emps.append(self.emp_1)
Employee.today_emps.append(self.emp_2)
self.assertEqual(Employee.today_emps, [self.emp_1, self.emp_2])
self.emp_1.today_hours = 6
self.emp_2.today_jobs = ["x"]
self.h_1.no_match_jobs.append(self.j_1_1)
reset_day()
self.assertEqual(self.emp_1.today_hours, 0)
self.assertEqual(self.emp_2.today_jobs, [])
self.assertEqual(Employee.today_emps, [])
self.assertEqual(self.h_1.no_match_jobs, [])
def test_get_gen(self):
tst_list = [True for x in range(20)]
tst_gen = emp_gen(tst_list)
self.assertEqual(next(tst_gen), 0)
self.assertEqual(next(tst_gen), 1)
for _ in range(len(tst_list)):
next(tst_gen)
self.assertEqual(next(tst_gen), 2)
if __name__ == '__main__':
unittest.main()
|
class Student:
def __init__(self):
print("This is non parametrized constructor")
def show(self,name ):
print("Hello",name )
student = Student()
student.show("John")
def my_function(fname):
print(fname + "Ram")
my_function("My Name is:")
|
import random
import sqlite3
conn = sqlite3.connect('card.s3db')
cur = conn.cursor()
class CreditCard:
def __init__(self):
self.number = create_luhn_valid_card_number()
self.pin = str(random.randint(1000, 9999))
self.balance = 0
def insert_card(card_num, crd_pin):
with conn:
cur.execute('INSERT INTO card (number, pin, balance) VALUES (?, ?, ?)', (card_num, crd_pin, 0))
def select_card(card_num, pin):
with conn:
cur.execute('SELECT * FROM card WHERE number = (?) AND pin = (?)', (card_num, pin))
return cur.fetchone()
def luhn_validation(card_number):
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit = digit * 2
if digit > 9:
digit = digit - 9
sum = sum + digit
return (sum % 10) == 0
def deposit_funds(card_info, deposit_amount):
balance = int(card_info[3]) + int(deposit_amount)
with conn:
cur.execute('UPDATE card SET balance = (?) WHERE number = (?)', (balance, card_info[1]))
def delete_account(card_info):
with conn:
cur.execute("DELETE FROM card WHERE number = (?)", (card_info[1],))
def menu2(card_info):
print_menu2 = "1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit\n"
while (selection := input(print_menu2)) != '0':
card_info = select_card(card_info[1], card_info[2])
try:
selection = int(selection)
if selection < 0 or selection > 5:
print("You must enter a number between 0 - 5\n")
except ValueError:
print("You must only enter numbers\n")
if selection == 1:
print("\nBalance: " + str(card_info[3]) + "\n")
elif selection == 2:
income = input('Enter income:\n')
deposit_funds(card_info, income)
print("Income was added!\n")
elif selection == 3:
deposit_to = input('\nTransfer\nEnter card number:')
with conn:
cur.execute('SELECT * FROM card WHERE number = (?)', (deposit_to,))
transfer_to = cur.fetchone()
if not luhn_validation(deposit_to):
print('Probably you made a mistake in the card number. Please try again!')
elif transfer_to is None:
print('Such a card does not exist.')
elif deposit_to == card_info[1]:
print('Probably you made a mistake in the card number. Please try again!')
else:
transfer_amount = input('Enter how much money you want to transfer:\n')
if int(transfer_amount) > card_info[3]:
print('not enough money!\n')
else:
deposit_funds(transfer_to, int(transfer_amount))
transfer_amount = int(transfer_amount) * -1
deposit_funds(card_info, int(transfer_amount))
elif selection == 4:
delete_account(card_info)
print('\nThe account has been closed!\n')
elif selection == 5:
print("\nYou have successfully logged out!\n")
return "continue"
quit()
def create_luhn_valid_card_number():
checksum = 0
cc_number = "400000" + str(random.randint(100000000, 999999999))
cc_list = [number for number in cc_number]
cc_list = [int(x) for x in cc_list]
for i in range(len(cc_list)):
if i % 2 == 0:
cc_list[i] *= 2
if cc_list[i] > 9:
cc_list[i] -= 9
if sum(cc_list) % 10 == 0:
checksum = 0
else:
checksum = 10 - (sum(cc_list) % 10)
return str(cc_number) + str(checksum)
# program start
with conn:
cur.execute('''CREATE TABLE IF NOT EXISTS card(
id INTEGER,
number text,
pin text,
balance INTEGER DEFAULT 0)''')
menu1 = '1. Create an account\n2. Log into account\n0. Exit\n'
while (selection := input(menu1)) != '0':
try:
selection = int(selection)
if selection < 0 or selection > 2:
print("You must enter a number between 0 - 2\n")
except ValueError:
print("You must only enter numbers\n")
if selection == 1:
card = CreditCard()
insert_card(card.number, card.pin)
print(f"\nYour card number: \n{card.number}\nYour card PIN:\n{card.pin}\n")
elif selection == 2:
print("\nEnter your card number:")
card_number = str(input())
print("Enter your PIN:")
pin = str(input())
verify_card = select_card(card_number, pin)
if verify_card is not None:
print("\nYou have successfully logged in!\n")
selection = menu2(verify_card)
else:
print("\nWrong card number or PIN!\n")
|
def rerun():
choice = raw_input('Enter your choice [1-4]: ');
choice = int(choice);
print ('***')
print (' MAIN MENU ')
print ('1. Back-up')
print ('2. User agreement')
print ('3. Reboot')
print ('4. Make love to your husband')
choice = raw_input('Enter your choice [1-4]: ')
choice = int(choice)
if choice == 1:
print ("Starting backup....")
elif choice == 2:
print ('Starting user agreement...')
elif choice == 3:
print ('Rebooting the server...')
elif choice == 4:
print ('%s YES LETS GO UP STAIRS NOW!!!') % name;
else:
print ('Invalid number, try again..')
rerun()
|
#!/usr/bin/python
import sys
# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(num_cookies, cache={}):
if num_cookies in cache: # RUNTIME COMPLEXITY: O(n) ===> looping(iterating) through the cache{} object (check inside the cache every iteration) ---> grows by n...as tache grows the output grows
return cache[num_cookies]
# base case --> always want to get here
if num_cookies == 0: # RUNTIME COMPLEXITY: O(1) ===> this is a constant. What we are
value = 1
elif num_cookies > 0:
# print('num of cookies: ', num_cookies)
value = eating_cookies(num_cookies -1) + eating_cookies(num_cookies-2) + eating_cookies(num_cookies-3) # RUNTIME COMPLEXITY: O(3n!) ===> calling the function 3x --> 3n factorial: growing/scaling really fast
#--> return 0 so that - numbers are not included and it doesn't loop through negative numbers
elif num_cookies < 0: # RUNTIME COMPLEXITY: O(1) ===> constan: helping to break out of the iterations
value = 0
cache[num_cookies] = value # RUNTIME COMPLEXITY: O(1) ===> defining the value...never grows....assigning once
return value
# # RUNTIME COMPLEXITY:
# O(n) + O(1) + O(3n!) + O(1) + O(1)
# 3 -O(1)'s --->simplified: combining like terms
# |
# V
# ==> 3 + O(n) + O(3n!)
# The 3's and the one O(n) --> not a factor that will effect the growth of n
# ==> O(3n!)
# ==> O(n!) is the most important time complexity to consider in this problem: does not scale well!
if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(ways=eating_cookies(num_cookies), n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]')
eating_cookies(0) |
import tweepy
from flask import jsonify #handles the json dict inside the tweepy verify credientials
def sendTweet(tweetMessage):
api = auth()
# .update_status allows us to post tweets
api.update_status(tweetMessage)
def sendTweetImage(tweetMessage, Image):
api = auth()
media = api.media_upload(Image)
api.update_status(tweetMessage, media_ids=[media.media_id])
def sendDM():
api = auth()
message = input("DM: ")
user = input("user: ")
user = api.get_user("WaleedAbdul0") #replace user
recipient_id = user.id_str
dM = api.send_direct_message(recipient_id, message)
def auth():
#API_KEY
consumer_key = "n9KnlQf3vxERxHT2HOIb1UKlU"
#API_SECRET_KEY
consumer_secret = "lTZhX91YN2goYiHmdgj4Ol5LSF5bh0fKB2V991F0DQFei8UWGG"
BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAGGWMQEAAAAAATAZNVKGdsZmfI94%2B5kblF1XTc0%3DrdFrI5RbIhl70yoUNrshHPcw4DjFaFxksSZfXkM7lu0AlxkRZY"
access_token = "1357087883996368898-WakEtk5CFVO7rkzYOQ9V0QdchrYuho"
access_token_secret = "bfMiShHCx44TSfabSj3HRkwUyN9DDHabGlCIzTvmNIPuC"
#This sets up the tweepy package using the codes that were given us by the twitter for developers website
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#once the codes have been set up send it to the twitter api to access the project and the account
api = tweepy.API(auth)
#Verifies that it connected to an account then prints the name of said account
if(api.verify_credentials() != False):
print("Accessed account:", api.me().screen_name)
else:
print("User verification failed.")
return api
|
#!/usr/bin/env python2
class Frame():
"""frame"""
def __init__(self):
self.score = 0
def add(self, pins):
self.score += pins
class Game():
"""game"""
def __init__(self):
self._throws = [0] * 21
self._current_throw = 0
self._first_throw = True
self._ball = 0
self.current_frame = 1
def add(self, pins):
self._throws[self._current_throw] = pins
self._current_throw += 1
self._adjust_current_frame(pins)
def _adjust_current_frame(self, pins):
if self._first_throw:
if pins == 10:
self.current_frame += 1
else:
self._first_throw = False
else:
self.current_frame += 1
self._first_throw = True
if self.current_frame > 11:
self.current_frame = 11
def get_score(self):
return self.score_from_frame(self.current_frame - 1)
def score_from_frame(self, frame):
score = 0
self._ball = 0
for i in range(frame):
if self.is_strike():
frame_score = 10 + self.get_next_two_balls_for_strike()
self._ball += 1
elif self.is_spare():
frame_score = 10 + self.get_next_ball_for_spare()
self._ball += 2
else:
frame_score = self.get_next_two_balls_in_frame()
self._ball += 2
score += frame_score
return score
def is_strike(self):
return self._throws[self._ball] == 10
def is_spare(self):
return (self._throws[self._ball] + self._throws[self._ball + 1]) == 10
def get_next_two_balls_for_strike(self):
return self._throws[self._ball + 1] + self._throws[self._ball + 2]
def get_next_ball_for_spare(self):
return self._throws[self._ball + 2]
def get_next_two_balls_in_frame(self):
return self._throws[self._ball] + self._throws[self._ball + 1]
|
#This program implements something I saw Yakovenko of UMD show in a presentation about inequality.
#The random graph structure of the exchanges done during every tick produces a final histogram that is decidedly skewed.
# The skew is motivated by the zero lower bound on individual's balances.
# Set up the list of agents, make it n agents large, give each agent 1
agents = []
n=100 #number of agents
for builder in range(n):
agents.append(1)
# Move 1 dollar from agent i's balance to agent j's balance during each of t ticks
import random
t = 10000000 #ticks in simulation
for ticks in range(t):
i = random.randint(0, len(agents)-1) #randint draws between 0 and len(agents)-1 inclusively.
j = random.randint(0, len(agents)-1) # The -1 after len(agents) keeps you within the elements of the list.
if agents[i] > 0: #only agents with non-zero balances can be asked to give.
agents[i] = agents[i] - 1 #remove 1 from agent i's balance
agents[j] = agents[j] + 1 #add 1 to agent j's balance
#print agents
#OUTPUT
# Make a histogram which tallies up the number of agents with given balances.
# Note that in the for loop, the range is given by max(agents)+1
# because max(agents) is largest element in agents,
# range(x) goes from 0 to x without including x.
print ""
print "After", t ,"ticks with", n,"agents, the distribution is:"
print ""
print "balance | count of agents | freq"
for balance in range(max(agents)+1):
junk = agents.count(balance)
print balance,"|", junk,"|", (float(junk) / len(agents))
print "" |
import unittest
from main import add
class TestMain(unittest.TestCase):
#run before a functon
def setUp(self):
print('about to test a function')
def test_add_if_variable_is_string(self):
num = 'aaaå'
result = add(num)
self.assertIsInstance(result, ValueError)
def test_add_should_return_sum(self):
num = 10
result = add(num)
self.assertEqual(result, 15)
def test_add_if_none_type(self):
num = None
result = add(num)
self.assertEqual(result, 'please enter a number')
def test_add_if_empty_str(self):
num = ''
result = add(num)
self.assertEqual(result, 'please enter a number')
#run after every function
#good to clear databases
def tearDown(self):
print('cleaning up')
#only run this file if this is run
if __name__ == '__main__':
unittest.main()
|
#Error handling
while True:
try:
age = int(input('what is your age?'))
# print(age)
# what if like this 10/age
10/age
except ValueError: #can except an error type
print("please enter a number")
continue
except ZeroDivisionError:
print("please enter age higher than 0")
break
else:
print('thank you')
# print something or other operation
break
finally: #always fires after the try except
print('ok, i am finally done')
def sum(num1, num2):
try:
return num1/num2
except (TypeError, ZeroDivisionError) as err:
print(f'{err}')
print(sum(0, 2)) |
# Strings son una secuencia de caracteres
# Pueden contener a-z, 0-9, @
# entre comillas dobles o simples ( es lo mismo)
a = "This is a simple string"
b = 'Using single quotes'
print(a)
print(b)
c = "Need to use 'quotes' inside a string"
print(c)
d = "Another wat to handle \"quotes\""
print(d)
e = "This is a single\
string"
print(e)
f = "This is a \n" \
"multiple line\n" \
"string"
print(f) |
"""
Tuple
Like list but they are immutable
It means you cant change them
"""
my_list = [1, 2, 3]
print(my_list)
my_list[0] = 0
print(my_list)
my_tuple = (1, 2, 2, 3, 2, 3)
print(my_tuple)
print(my_tuple[1])
print(my_tuple[1:])
print(my_tuple.index(3))
print(my_tuple.count(2))
|
"""
== --> Value Equality
!= --> Not equal to
< --> Less than
> --> Greater than
<= --> Less than or equal to
>= --> Greater than or equal to
"""
bool_one = 10 == 11
not_equal = 10!= 9
less_than = 10 < 100
greater_than = 10 > 10
lt_eq = 10 <= 10
gt_eq = 10 >= 10
print(bool_one)
print(not_equal)
print(less_than)
print(greater_than)
print(lt_eq)
print(gt_eq) |
# mario in python
from cs50 import get_int
def main():
n = get_number()
# loop
for i in range(n):
print(" "*(n-i-1), end="")
print("#"*(i+1), end="")
# print newline
print()
# getting height
def get_number():
n = 0
while n < 1 or n > 8:
n = get_int("Height: ")
if n >= 1 or n <= 8:
return n
main() |
def reverse(input=''):
i = len(input)
word = ''
while i > 0:
word = word + input[i - 1]
i = i - 1
return word
|
import json
import os
def callMenu():
choice = int(input("Enter:\n" +
"<1> To register asset\n" +
"<2> To view stored assets: "))
return choice
def readFile(file):
if os.path.exists(file):
with open(file, "r") as file_json:
dictionary = json.load(file_json)
else:
dictionary = {}
return dictionary
def writeFile(dictionary, file):
with open(file, "w") as file_json:
json.dump(dictionary, file_json)
def register(dictionary, file):
answer = "Y"
while answer == "Y":
dictionary[input("Enter the patrimonial number: ")] = [input("\nEnter the date of the last update: "),
input("Enter the description: "),
input("Enter the department: ")]
answer = input("\nEnter <Y> to continue: ").upper()
writeFile(dictionary, file)
return "\nJSON generated!\n"
def display(file):
dictionary = readFile(file)
for key, data in dictionary.items():
print("\nDate............: ", data[0])
print("Description.....: ", data[1])
print("Department......: ", data[2],"\n")
|
def callMenu():
choice = int(input("Enter:\n" +
"<1> To register asset\n" +
"<2> To persist in file\n" +
"<3> To view stored assets: "))
return choice
def register(dictionary):
answer = "Y"
while answer == "Y":
dictionary[input("Enter the patrimonial number: ")] = [
input("\nEnter the date of the last update: "),
input("Enter the description: "),
input("Enter the department: ")]
answer = input("Enter <Y> to continue.").upper()
def persist(dictionary):
with open("./files/inventory.csv", "a") as inv:
for key, value in dictionary.items():
inv.write(key + ";" + value[0] + ";" +
value[1] + ";" + value[2] + "\n")
return "Persisted successfully!"
def display():
with open("./files/inventory.csv", "r") as inv:
lines = inv.readlines()
return lines
|
with open("./files/page-test.html", "w") as page:
page.write("<body> <h1> This is a test for the web page </h1>")
page.write("<br><h2> Below are some important names for the project: </h2>")
page.write("<h3>")
name=""
while name!="EXIT":
name = input("Enter a name or EXIT: ").upper()
if name!="EXIT":
page.write("<br>"+name)
page.write("</h3></body>") |
# ADD ELEMENT TO THE INVENTORY
def fillInventory(list):
answer = "Y"
while answer == "Y":
hardware = [input("\nHardware: "),
float(input("Price: ")),
int(input("Serial Number: ")),
input("Department: ")]
list.append(hardware)
answer = input("\nEnter \"Y\" to continue: ").upper()
# DISPLAY INVENTORY DATA
def diplayInventory(list):
for element in list:
print("\n----------------------------------")
print("Hardware...: ", element)
print("----------------------------------")
print("Description: ", element[0])
print("Price......: ", element[1])
print("Serial.....: ", element[2])
print("Department.: ", element[3])
print("----------------------------------")
#SEARCH FOR AN ELEMENT IN THE INVENTORY
def searchElement(list):
search=input("\nEnter name of the hardware you want to search: ")
for element in list:
if search==element[0]:
print("\n----------------------------------")
print("\nPrice......: ", element[1])
print("Serial.....: ", element[2])
print("----------------------------------")
#CHANGE DATA FOR AN ELEMENT IN THE INVENTORY
def changeElement(list, perc):
search = input("Enter name of the hardware you want to change the price: ")
#ANSWER
depreciation=input("Do you want to depreciate this hardware \"" + search + "\"? ").upper()
while depreciation != "YES" and depreciation != "NO":
print("Answer YES or NO to depreciate")
depreciation=input("Do you want to depreciate this hardware? ").upper()
if depreciation == "YES":
for element in list:
if search==element[0]:
print("\n----------------------------------")
print("Old price:", element[1])
element[1] = element[1] * (1-perc/100)
print("New price:", element[1])
print("----------------------------------")
else:
print("The price of the hardware \"" + search + "\" has not been depreciated.")
#DELETE AN ELEMENT IN THE INVENTORY
def deleteElement(list):
search=input("\nEnter name of the hardware you want to delete: ")
for element in list:
if search==element[0]:
list.remove(element)
return "Element deleted"
#SUMMARY OF VALUES
def summaryValues(list):
values=[]
for element in list:
values.append(element[1])
if len(values)>0:
print("\n----------------------------------")
print("Most expensive hadware value: ", max(values) )
print("Cheaper hardware value: ", min(values))
print("Total values: ", sum(values))
print("----------------------------------") |
plane={1:'Delhi to kochi at 21hr'}
print 'Welcome to air ways\nHitting return will display the plae schedule'
raw_input()
print plane
seat=['wseat','oseat']
seat1=[0,0]
tseat1=0
tseat2=0
seat2=[0,0]
x=0
ch='y'
while(ch=='y'):
if tseat1<100:
print 'occupied seats are(max:50 in each):'
for i in range(2):
print seat[i],'=',seat1[i]
print 'which seat do you prefer\n'
t=input('Enter seat code(0,1):')
m=input('Enter no of seats:')
seat1[t]+=m
tseat1+=m
if t==0:
print 'price=',m*10
elif t==1:
print 'price=',m*7
else:
print 'No such seats'
else:
print 'all seat are occpuied'
ch=raw_input('next user(y):')
|
class User():
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return f"User ID: {self.id}"
def authenticate(username, password):
user = username_table.get(username, None)
if user and password == user.password:
return user
users = [User(1, 'Josh', 'mypass'), User(2, 'Lex', 'mypass')]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
|
from Aircraft.flight_algorithms import FlightBackEnd
from string import ascii_letters, digits # Check for special characters
from People.change_details import Change_details
# User story
# As an airport assistant, I want to create a flight trip with a specific destination. - John
# Flight class capable of creating a flight
# The flight needs to fit these criteria:
# - Destination
# - DepartureDate
# - DepartureTime
# - FlightDuration
# - PassengerLimit
# User Story
# As an airport assistant I want to be able to generate a flight_attendees_list that lists passenger names and passports
# to check identity.
# To do this, the booking_details table needs to return:
# - First Name
# - Last Name
# - Passport Number
# Perhaps date of birth later on
# - Date of Birth
class FlightFrontEnd(FlightBackEnd):
__cursor = None
# This will be used to verify the identity of the employee trying to log in
__username = None
__password = None
def __init__(self, cursor):
# Class FlightFrontEnd
super().__init__()
self.__cursor = cursor
def user_login(self):
user_login_attempts = 0 # Track attempts to login
print("Welcome, please confirm your details.")
while user_login_attempts <= 3: # If user has failed to login 3 times escape.
try:
self.__username = input(str("\nUsername [e.g. ex230] : "))
# If special characters are entered raise exception error
if set(self.__username).difference(ascii_letters, digits):
raise ValueError("\n⚠ The username should only include letters and numbers,"
" no special characters [%$#@] ⚠")
# Input left blank / less than 5 or greater than 5 characters
elif 0 < len(self.__username) < 3 or len(self.__username) > 5:
raise ValueError("\n⚠ The username are always between 3 and 5 characters ⚠")
self.__password = input(str("\nPassword : "))
# Perform check of username / password simultaneously
# Will return False if incorrect username or password (remains anonymous as to what)
if not self.check_password(self.__cursor, self.__username, self.__password): # If true raise Error
raise ValueError("\n⚠ Password or Username is incorrect ⚠")
except ValueError as e:
print(e)
user_login_attempts += 1 # Increase login attempts
continue # continue to next iteration, allow user to retry
except Exception: # Base exception class to catch any unexpected exceptions
print("\nAn unexpected error has occurred, if this persists please contact the system administrator...")
# This occurs only if a weird error occurs, to handle this the program will exit and they can retry
exit("Exiting! Please retry from the main menu.") # This exits with a message to the user
else: # The user has successfully logged in as no exceptions were raised
print("Welcome! " + self.__username)
self.__user_interface()
# If user has failed to login 3 times, then
if user_login_attempts == 3:
exit("\n⚠ 3 Login attempts have failed, exiting... ⚠")
def _show_current_flights(self):
# Welcome! Here are the current flights -->
# Get flights from database and display them
# What would you like to do?
return self._get_flights(self.__cursor) # Load flights
def __add_flight(self):
try: # Create Flight
destination = input("Whats is this flights destination? : ")
if self.check_if_exit(destination): # Allows exiting of program at any time with 'e'
return False
departure_date = input("What is the departure date of this flight? [E.g. 2018-03-19] : ")
if self.check_if_exit(destination): # Allows exiting of program at any time with 'e'
return False
departure_time = input("What is the departure time of this flight? [E.g. 13:00:00] : ")
if self.check_if_exit(destination): # Allows exiting of program at any time with 'e'
return False
flight_duration = input("Whats the flight duration? [E.g. 60 = 1 hour] : ")
if self.check_if_exit(destination): # Allows exiting of program at any time with 'e'
return False
passenger_limit = input("What is the passenger_limit? [E.g. 300] : ")
if self.check_if_exit(destination): # Allows exiting of program at any time with 'e'
return False
# Carry out checks on information - raise ValueError if something invalid
if any(map(str.isdigit, destination)): # Returns True if destination contains numbers (not allowed)
raise ValueError("\n⚠ A Destination cannot contain a number, please retry ⚠")
elif len(departure_date) != 10:
raise ValueError("\n⚠ Your date isn't in the format YYYY-MM-DD, please retry ⚠")
elif len(departure_time) != 8:
raise ValueError("\n⚠ Your date isn't in the format HH:MM:SS, please retry ⚠")
elif not any(map(str.isdigit, flight_duration)): # This contains a letter, should only be numbers
raise ValueError("\n⚠ Your duration contains a letter, use the format 60 / "
"1 hour, please retry ⚠")
elif not any(map(str.isdigit, passenger_limit)): # This contains a letter, should only be numbers
raise ValueError("\n⚠ Your passenger limit contains letters, use numbers only, please retry ⚠")
# Present the details that have been given by the employee.
while True:
final_check = input("\nIs this correct? [Y] or [N]\n"
"Destination :" + destination + "\n"
"Departure Date :" + departure_date + "\n"
"Departure time :" + departure_time + "\n"
"Flight Duration :" + flight_duration + "\n"
"Passenger Limit :" + passenger_limit + "\n")
if final_check.lower() == 'y':
print("\nAdding the flight to the list of existing flights...")
break # break out internal loop
if final_check.lower() == 'n':
print("\nOkay, Restarting...")
self.__add_flight() # Restarts method
else:
print("\nDid not recognise that response.")
continue # Asks the questions again
except ValueError as e:
print(e)
return False
except Exception:
print("Sorry! an unexpected error occurred, please try again.")
return False
else:
# The input didn't hit any exception nets and is moving on now
# Create a dictionary with information, make necessary conversions
flight_dict = {"Destination": destination, "Departure_date": departure_date,
"Departure_time": departure_time, "Flight_duration": int(flight_duration),
"Passenger_limit": int(passenger_limit)}
# If no exceptions are raised -- create flight
# Send information to BackEnd to store in database
self.create_new_flight(flight_dict, self.__cursor)
return True
def __user_interface(self):
print("\nWelcome! What would you like to do")
help_message = "\nCreate a new flight [c]\nView all current flights [f]\nRecall Help dialog [h]" \
"\nGenerate flight attendee List [g]\nExit at any time with [e]\nChange Flight Date [d]"
print(help_message)
exit_code_entered = False # Boolean that handles whether or not the user has exited the loop
while not exit_code_entered:
users_input = input("What would you like to do? ")
# Ask for destination as well as departure date and time (refuse dates in the past or beyond a year in
# future) Flight time (algorithm to work out times between departure time and landing time)
if users_input.lower() == "c":
print("\nCreating a new flight...")
if self.__add_flight(): # Returns True if success and False if failure
print("\nSuccess!\n")
else:
print("\nRestarting\n")
continue # Restart interface
elif users_input.lower() == "h":
print(help_message)
elif users_input.lower() == "f":
print("\nLoading flights now..")
if self._show_current_flights(): # If true is returned successfully loaded
print("\nSuccessfully loaded flight information")
continue
else: # Returns false the flight information couldn't be loaded
print("\nSorry! an error occurred, restarting interface...")
continue
elif users_input.lower() == "g":
if self.__generate_flight_attendees_list(): # Attempt to create text file.
continue
else:
print("\nSorry! an error occurred, restarting interface...") # If returns False tell user
continue
elif users_input.lower() == "d":
# Go to change_details class in People Directory
instance = Change_details(self.__cursor)
instance.change_flight_details()
print("\nGoing back to menu...")
elif users_input.lower() == "e":
print("\nExiting System...")
exit_code_entered = True # Change exit code to True as 'e' was entered, E.G (will break while loop)
exit("\nSee you next time " + self.__username + "!")
# To Do List:
# Set Passenger Limit (Not above models seat limit)
# Later ( Assign staff to flight - List of available staff and assign them)
def __generate_flight_attendees_list(self):
# ask for which flight they want to generate list of attendees
flight_id = input("These will load on exit.\nWhat flight do you want to generate a list of attendees for [Please enter ID: e.g. 1] ? ")
if self.check_if_exit(flight_id): # Allows exiting of program at any time with 'e'
return False
if self.generate_attendees_list(flight_id, self.__cursor): # Returns true if this
return True
# If this returns false then the flight was not valid or an error occurred
# if this returns True the flight has been found and list generated.
else:
return False
@staticmethod
def check_if_exit(user_input):
if user_input == 'e':
return True
else:
return False
|
import hashlib
class CreateStaffUser:
staff_name = None
staff_position = None
staff_username = None
staff_password = None
staff_password_encrypted = None
def __init__(self, cursor):
self.cursor = cursor
def user_creation(self):
# Take details on staff name
self.staff_name = input("What is your name?\n")
self.staff_position = input("What is your position?\n")
# Using initials to create user name
self.staff_username = (self.staff_name[0:3]).upper() + (self.staff_position[0])
self.password_creator()
def password_creator(self):
# Get user input for password
print("\nA password should be at least 7 characters long\n")
# Check password is certain length, using try except loop
try:
self.staff_password = input("Enter you password here\n")
if len(self.staff_password) > 7:
pass
else:
raise ValueError("incorrect")
except ValueError:
print("\nYour password is not long enough, make sure it is 7 characters")
except Exception:
print("Error")
# Using if loop to check password is same when retyped.
staff_password_check = input("Enter your password again\n")
# If loop to verify password using double entry
if staff_password_check == self.staff_password:
print("\nYour password has been set, make sure to remember it")
else:
print("\nThat was not correct, please recreate your password")
self.password_creator()
self.encrypt_password()
def encrypt_password(self):
# Encoding initial variable
self.staff_password = self.staff_password.encode('utf-8')
# Hashing password
hash_object = hashlib.sha256(self.staff_password)
self.staff_password_encrypted = hash_object.hexdigest()
def insert_user_details(self):
# Calling previous method to ensure user details are created
self.user_creation()
# Creating SQL query with wild cards to be placeholders
sql_query = "INSERT INTO Staff(Name, [Position], Username, password)VALUES (?, ?, ?, ?)"
# Executing query with variables put in.
self.cursor.execute(sql_query, self.staff_name, self.staff_position, self.staff_username,
str(self.staff_password_encrypted))
# Committing query to make sure data has been inputted
self.cursor.commit()
# Printing success message
print("\nYour user details have successfully been inputted")
|
#!/usr/bin/env python3
# coding: utf-8
import math
MAJOR_AXIS = 6378137.0 # meters
MINOR_AXIS = 6356752.3142
MAJOR_AXIS_POW_2 = pow(MAJOR_AXIS, 2)
MINOR_AXIS_POW_2 = pow(MINOR_AXIS, 2)
def deg2dms(deg):
dd = deg
d = int(dd)
dd -= d
dd *= 60
m = int(dd)
dd -= m
s = dd * 60
if s > 59.999:
s = 0
m += 1
return d, m, s
def dms2deg(d, m, s):
return d + m / 60. + s / 3600.
class Point(object):
lat = 0.0
lon = 0.0
elev = 0.0
name = None
def __init__(self, lon, lat, elev=0, name=None):
self.lat = float(lat)
self.lon = float(lon)
self.elev = elev
self.name = name
def get_point(obj):
if isinstance(obj, Point):
return obj
if isinstance(obj, (list, tuple)):
return Point(obj[0], obj[1])
if isinstance(obj, dict):
return Point(obj['lon'], obj['lat'])
return None
def distance(p1_, p2_):
"""
returns earth terrestrial distance between 2 points
"""
p1, p2 = get_point(p1_), get_point(p2_)
true_angle_1 = _get_true_angle(p1)
true_angle_2 = _get_true_angle(p2)
point_radius_1 = _get_point_radius(p1, true_angle_1)
point_radius_2 = _get_point_radius(p2, true_angle_2)
earth_point_1_x = point_radius_1 * math.cos(math.radians(true_angle_1))
earth_point_1_y = point_radius_1 * math.sin(math.radians(true_angle_1))
earth_point_2_x = point_radius_2 * math.cos(math.radians(true_angle_2))
earth_point_2_y = point_radius_2 * math.sin(math.radians(true_angle_2))
x = math.sqrt(pow((earth_point_1_x - earth_point_2_x), 2) + pow((earth_point_1_y - earth_point_2_y), 2))
y = math.pi * ((earth_point_1_x + earth_point_2_x) / 360.) * (p1.lon - p2.lon)
fd_phi = math.radians(p1.lat - p2.lat)
fd_lambda = math.radians(p1.lon - p2.lon)
fz = 2 * math.asin(math.sqrt(
pow(math.sin(fd_phi / 2.0), 2) + math.cos(math.radians(p2.lat)) *
math.cos(math.radians(p1.lat)) * pow(math.sin(fd_lambda / 2.0), 2)
))
f_alfa = math.asin(math.cos(math.radians(p2.lat)) * math.sin(fd_lambda) / math.sin(fz or 0.0001))
d = round(abs(math.degrees(f_alfa)))
if p1.lon <= p2.lon:
if p1.lat > p2.lat:
d = 180 - d
else:
if p1.lat > p2.lat:
d += 180
else:
d = 360 - d
return math.sqrt(pow(x, 2) + pow(y, 2)), d
def _get_true_angle(p):
"""
get point, returns true angle
"""
return math.degrees(math.atan(((MINOR_AXIS_POW_2 / MAJOR_AXIS_POW_2) * math.tan(math.radians(p.lat)))))
def _get_point_radius(p, true_angle):
"""
get point and true angle, returns radius of small circle (radius between meridians)
"""
return (1 / math.sqrt((pow(math.cos(math.radians(true_angle)), 2) / MAJOR_AXIS_POW_2) + (
pow(math.sin(math.radians(true_angle)), 2) / MINOR_AXIS_POW_2))) + p.elev
def mperdeg(lon, lat):
"""
return number of meters per one degree in lon, lat
"""
n1 = distance(Point(lon, lat), Point(lon + 1, lat))[0]
n2 = distance(Point(lon, lat), Point(lon, lat + 1))[0]
return n1, n2
|
'''
Problem: Given an array, rotate the array to the right by k steps, where k is non-negative.
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
'''
# 1st Solution
nums = list(map(int,input().split(" ")))
k = int(input())
"""
Do not return anything, modify nums in-place instead.
"""
nums[:] = nums[-k%len(nums):]+nums[:-k%len(nums)]
print(nums[:])
# 2nd Solution:
nums = list(map(int,input().split(" ")))
k = int(input())
"""
Do not return anything, modify nums in-place instead.
"""
k = k%len(nums)
nums[:] = nums[-k:]+nums[:-k]
print(nums[:])
|
print("WELCOME TO CIPHER SOFT ")
#Defining alphabets
Alphabets = {}
i = 1
for _ in range(97,123):
Alphabets[str(chr(_))] = i
i += 1
#defining functions for asking key
def ask_key():
while True:
try:
keyin = int(input("Enter the key for coding/decoding : \t "))
except:
print("Please enter a valid number")
continue
else:
break
return keyin
#defining functions for enc or dec
def enc_or_dec():
val = ''
while True:
try:
val = input("Which service do you want? \n [A] Encoding \n [B] Decoding \n Enter the option as either A or B \t")
val = val.lower()
except:
print("Please enter only A or B")
continue
else:
if val=='a':
serv = 1
break
elif val == 'b':
serv = 0
break
else:
continue
return serv
#defining function for input of text
def enc_in():
text = input("Please enter the statement to be encoded : \t")
return text
def dec_in():
text = input("Please enter the statement to be decoded : \t")
return text
#defining class for encoding function based on the key
class encode:
def __init__(self, text, key = 1):
self.key = key
self.text = text
def encode_msg(self):
words = self.text.split()
new_words = []
new_word = []
for _ in range(len(words)):
letters = list(words[_])
newletters = []
for l in range(len(letters)):
if 96<ord(letters[l].lower())<122:
numval = Alphabets[letters[l].lower()]
newval = numval + self.key
while True:
if newval > 26:
newval -= 26
continue
else:
break
toadd = chr(96+newval)
else:
toadd = letters[l]
newletters.append(toadd)
new_words.append("".join(newletters))
for _ in range(len(new_words)):
new_word.append(new_words[_].title())
encoded = "\t".join(new_word)
return encoded
class decode:
def __init__(self,text,key):
self.text = text
self.key = key
def decode_msg(self):
words = self.text.split()
new_words = []
new_word = []
for _ in range(len(words)):
letters = list(words[_])
newletters = []
for l in range(len(letters)):
if 96<ord(letters[l].lower())<122:
numval = Alphabets[letters[l].lower()]
newval = numval - self.key
while True:
if newval > 26:
newval -= 26
continue
elif newval <=0:
newval += 26
continue
else:
break
toadd = chr(96+newval)
else:
toadd = letters[l]
newletters.append(toadd)
new_words.append("".join(newletters))
for _ in range(len(new_words)):
new_word.append(new_words[_].title())
decoded = "\t".join(new_word)
return decoded
thehell = True
while thehell:
Opt = enc_or_dec()
if Opt == 1:
print("You have chosen to encode a message")
intxt = enc_in()
inkey = ask_key()
encoding = encode(intxt,inkey)
encoded_message = encoding.encode_msg()
print("Here is the message that is encoded :\t {}".format(encoded_message))
print("Thank you!")
while True:
try:
anss = int(input("Would you like to try our service again ? \n 1. Yes \n 2. No \n Please enter the number as option"))
except:
print("Please enter either 1 or 2 \t")
continue
else:
break
if anss == 1:
thehell = True
else:
thehell = False
elif Opt == 0:
print("You have chosen to denode a message")
intxt = dec_in()
inkey = ask_key()
decoding = decode(intxt,inkey)
decoded_message = decoding.decode_msg()
print("Here is the message that is decoded :\t {}".format(decoded_message))
print("Thank you!")
while True:
try:
anss = int(input("Would you like to try our service again ? \n 1. Yes \n 2. No \n Please enter the number as option"))
except:
print("Please enter either 1 or 2 \t")
continue
else:
break
if anss == 1:
thehell = True
else:
thehell = False
else:
print("Enter a valid number")
|
s = "Ovo je string"
s[0] # označava poziciju u stringu, u ovom slučaju 0 je prva pozicija odnosno O
a = str(input("Riječ: "))
print(a.upper()) # pretvara sva slova u velika tiskana
print(a.lower()) # pretvara sva slova u mala tiskana
"1 2 3 4 6".replace("6", "5") # zamjenjuje određeni dio stringa drugime
# zamjenjuje određeni dio i to točno prvih n puta
"Mississipi".replace("ss", "z", 2)
recenica = "Primjer za splitting string"
rijeci = recenica.split() # odvaja rijeci zasebno u listu
rijeci1 = recenica.split("s") # odvaja rijeci prije pojave znaka "s"
# odvajanje izvrsava samo jednom (u ovom slučaju)
rijeci2 = recenica.split(maxsplit=1)
print(rijeci)
print(rijeci1)
print(rijeci2)
b = " " # razmak kao graničnik
# razmak se umeće između svakog znaka te se oni spajaju u jedan
print(b.join(rijeci))
rijec = "Proba"
print(rijec * 3) # ispisati ce rijec 3 puta spojeno
print("Rijec Proba unatrag izgleda ovako:",
rijec[::-1]) # ispisuje rijec unatrag
|
def getWire():
line = input.readline().strip()
return line.split(',')
def getSteps(step):
direction = step[0]
distance = int(step[1:])
if direction =='R':
return distance, 0
elif direction =='L':
return -distance, 0
elif direction =='U':
return 0, distance
else:
return 0, -distance
def popGrid(currX, currY,x, y):
if x==0:
dist=y
else:
dist=x
#print(dist)
increment = dist//abs(dist)
for i in range (increment, dist+increment, increment):
if x==0:
#print(currY+i)
grid[currY+i][currX]=1
#print(grid[currY+i])
else:
grid[currY][currX+i]=1
return currX+x, currY+y
def calcManDist (currX, currY, minManDist):
currManDist= abs(currX-portX) + abs(currY-portY)
print ("Current:", currManDist, "minManDist: ", minManDist)
if currManDist < minManDist and currManDist != 0:
return currManDist
else:
return minManDist
def checkGrid(currX, currY,x, y, grid, minManDist):
#minManDist=manDist
if x==0:
dist=y
else:
dist=x
increment = dist//abs(dist)
for i in range (increment, dist+increment, increment):
if x==0:
if grid[currY+i][currX]==1:
minManDist = calcManDist( currX, currY+i, minManDist)
else:
if grid[currY][currX+i]==1:
minManDist = calcManDist( currX+i, currY, minManDist)
return currX+x, currY+y, minManDist
input = open('input.txt', 'r')
wire1 = getWire()
wire2 = getWire()
cols_count = 50000
rows_count = 50000
grid = [[0 for x in range(cols_count)] for x in range(rows_count)]
currX = 5000
currY = 5000
portX = currX
portY = currY
print(wire1)
print(wire2)
for step in wire1:
x, y = getSteps(step)
currX, currY = popGrid(currX, currY, x, y)
'''currX=portX
currY=portY
for step in wire2:
x, y = getSteps(step)
currX, currY = popGrid(currX, currY, x, y)
#for i in range(0,32):
# print (grid[100-i])
for line in grid:
print (line)
#print(grid)
'''
manDist=10000
currX=portX
currY=portY
for step in wire2:
x, y = getSteps(step)
currX, currY, manDist = checkGrid(currX, currY, x, y, grid, manDist)
print(manDist)
print(manDist)
|
l1 = []
l2 = []
l3 = []
n = int(input("Enter number of elements: "))
for i in range(n):
l3.append("a")
for i in range(n):
l1.insert(i, int(input("Enter order: ")))
for i in range(n):
l2.insert(i, input("Enter list: "))
d = dict()
for i in range(n):
d[l1[i]] = l2[i]
for i in range(n):
if (l1[i] == len(l2[i]) and (d[i + 1] != l2[i])):
l3[l1[i] - 1] = l2[i].upper()
elif (d[i + 1] == l2[i]):
l3[l1[i] - 1] = l2[i]
else:
l3[l1[i] - 1] = l2[i].lower()
for i in range(n):
print(l3[i])
|
def list2dict(lst):
"""
Converts a list to a dictionary
"""
dct = {}
for w in lst:
dct[w] = 1
return dct
|
import random
import math
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@staticmethod
def add(*vectors):
x = 0
y = 0
z = 0
for v in vectors:
x += v.x
y += v.y
z += v.z
return Vector(x, y, z)
@staticmethod
def multiply_constant(c, vector):
return Vector(c * vector.x, c * vector.y, c * vector.z)
@staticmethod
def euclidean_distance(vector_1, vector_2):
"""
Calculates the Euclidean distance between the 2 given vectors.
:param vector_1: vector 1.
:param vector_2: vector 2.
:return: The Euclidean distance.
"""
return math.sqrt(
(vector_1.x - vector_2.x) ** 2 + (vector_1.y - vector_2.y) ** 2 + (vector_1.z - vector_2.z) ** 2)
@staticmethod
def norm_2(vector):
"""
This returns the 2nd norm of the given vector, also known as the length of the vector.
:param vector: a 3D vector
:return: the 2nd norm of the vector.
"""
return math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2)
@staticmethod
def unit(vector):
"""
Unit vector of v = v / ||v||, that is, the vector divided by its length.
||v|| denotes the second norm of v.
:param vector: a vector
:return: a unit vector in the direction of v.
"""
norm = Vector.norm_2(vector)
if norm == 0:
return vector
else:
return Vector.multiply_constant(1 / norm, vector)
def __str__(self):
return "[{}, {}, {}]".format(self.x, self.y, self.z)
class Boid:
def __init__(self):
self.position = Vector(0, 0, 0)
self.velocity = Vector(0, 0, 0)
self.is_perching = False
self.perching_start_time = 0
self.perching_avg_duration = 6
self.perching_end_time = 0
def __str__(self):
return "({}{})".format(self.position, self.velocity)
class BoidsSimulation:
def __init__(self, field_length, field_width, field_height, num_boids):
self.field_length = field_length
self.field_width = field_width
self.field_height = field_height
self.ground_level = 0.1
self.num_boids = num_boids
self.boids_list = []
self.neighbour_radius = 200
self.max_velocity = 3
# self.max_acceleration = 0.1
self.safe_distance = 50
# Script parameters
self.start_time = time.time()
self.wind_start_time = self.start_time + 5
self.wind_end_time = self.start_time + 15
self.is_wind_description_added = False
self.goal = Vector(0, 0, 0)
self.goal_start_time = self.start_time + 20
self.goal_duration = 10
self.goal_end_time = self.goal_start_time + self.goal_duration
self.is_goal_set = False
self.is_goal_description_added = False
self.is_previous_tend_to_goal = False
# Multipliers for rules
self.c_1 = 1 / 1000 # cohesion
self.c_2 = 100 / 1000 # separation
self.c_3 = 300 / 1000 # alignment
self.c_4 = 1 / 1000 # tend to place
self.c_5 = 1 / 1000 # away from place
self.wall_force = 0.5
self.c_wind = 3 # wind
self.c_scattering = - self.c_1 * 10
# the following are for drawing on a graph
self.fig = None
self.fig_num = 1
self.ax = None
self.surface = None
self.surface_goal = None
def boids_simulation(self):
self.initialise_boids()
self.build_graph()
# max_iteration = 100
iteration = 1
# while iteration < max_iteration:
while True:
if not plt.fignum_exists(self.fig_num):
# if user closes the figure, then break out of loop to terminate program.
break
# print("The current frame number is:", iteration)
current_time_frame_time = time.time()
self.draw_boids()
self.move_all_boids_to_new_positions(current_time_frame_time)
iteration += 1
def initialise_boids(self):
"""
Initialise boids with Gaussian random positions and uniform random velocities.
"""
for i in range(self.num_boids):
boid = Boid()
pos_x = random.uniform(0, self.field_length)
pos_y = random.uniform(0, self.field_width)
pos_z = random.uniform(0, self.field_height)
# standard_deviation = 20
# pos_x = random.gauss(self.field_length / 2, standard_deviation)
# pos_y = random.gauss(self.field_width / 2, standard_deviation)
# pos_z = random.gauss(self.field_height / 2, standard_deviation)
vel_x = random.uniform(-self.max_velocity, self.max_velocity)
vel_y = random.uniform(-self.max_velocity, self.max_velocity)
vel_z = random.uniform(-self.max_velocity, self.max_velocity)
boid.position = Vector(pos_x, pos_y, pos_z)
boid.velocity = Vector(vel_x, vel_y, vel_z)
self.boids_list.append(boid)
def move_all_boids_to_new_positions(self, current_time_frame_time):
"""
Moves all boids to new positions.
"""
self.fig.texts.clear()
self.is_wind_description_added = False
self.is_goal_description_added = False
temp_boids_list = []
for boid in self.boids_list:
if boid.is_perching:
if current_time_frame_time <= boid.perching_end_time:
temp_boids_list.append(boid)
continue
else:
boid.is_perching = False
v1 = Vector.multiply_constant(self.c_1, self.cohesion(boid))
v2 = Vector.multiply_constant(self.c_2, self.separation(boid))
v3 = Vector.multiply_constant(self.c_3, self.alignment(boid))
v4 = Vector(0, 0, 0)
if self.goal_start_time < current_time_frame_time < self.goal_end_time:
if not self.is_goal_description_added:
self.fig.text(0.01, 0.95, "A blue * represents current goal")
# if not self.is_goal_description_added:
# self.fig.text(0.01, 0.8, "A blue * represents current goal")
# self.is_goal_description_added = True
if not self.is_goal_set:
goal_x = random.uniform(0, self.field_length)
goal_y = random.uniform(0, self.field_width)
goal_z = random.uniform(10, self.field_height) # set minimum to 10 to reduce excessive perching
self.goal = Vector(goal_x, goal_y, goal_z)
self.is_goal_set = True
if self.is_previous_tend_to_goal:
if not self.is_goal_description_added:
self.fig.text(0.01, 0.9, "Tendency away from goal, at the same time with scattering.")
v4 = Vector.multiply_constant(-self.c_5, self.tend_to_place(boid))
v1 = Vector.multiply_constant(self.c_scattering, self.cohesion(boid))
else:
if not self.is_goal_description_added:
self.fig.text(0.01, 0.9, "Tendency to goal")
v4 = Vector.multiply_constant(self.c_4, self.tend_to_place(boid))
# v1 = Vector.multiply_constant(self.c_1, self.cohesion(boid))
self.is_goal_description_added = True
elif current_time_frame_time > self.goal_end_time:
self.goal_start_time = time.time() + 15
self.goal_end_time = self.goal_start_time + self.goal_duration
self.is_goal_set = False
if self.is_previous_tend_to_goal:
self.is_previous_tend_to_goal = False
else:
self.is_previous_tend_to_goal = True
v6 = Vector.multiply_constant(self.wall_force, self.bound_position(boid))
temp_boid = Boid()
temp_boid.velocity = Vector.add(boid.velocity, v1, v2, v3, v4, v6)
self.limit_velocity(temp_boid)
wind = Vector(0, 0, 0)
if self.wind_start_time <= current_time_frame_time <= self.wind_end_time:
if not self.is_wind_description_added:
self.fig.text(0.01, 0.9, "Strong wind going in direction (1, 0, 0) is in effect")
self.is_wind_description_added = True
wind = Vector.multiply_constant(self.c_wind, self.wind(boid))
elif self.is_wind_description_added:
self.fig.texts.clear()
self.is_wind_description_added = False
temp_boid.position = Vector.add(boid.position, temp_boid.velocity, wind)
# starts perching if reaches ground level
if temp_boid.position.z < self.ground_level:
temp_boid.position.z = self.ground_level
# todo: verify that this is not buggy
temp_boid.velocity = Vector(0, 0, 0)
temp_boid.perching_start_time = current_time_frame_time
temp_boid.perching_end_time = temp_boid.perching_start_time + temp_boid.perching_avg_duration \
+ random.uniform(-5, 5)
temp_boid.is_perching = True
temp_boids_list.append(temp_boid)
self.boids_list = temp_boids_list
def limit_velocity(self, boid):
"""
Limit the velocity of the boid. If the boid's velocity is larger than the maximum velocity allowed,
then set the boid's velocity to the maximum velocity allowed.
:param boid: a boid
"""
boid_velocity = boid.velocity
if Vector.norm_2(boid_velocity) > self.max_velocity:
boid.velocity = Vector.multiply_constant(self.max_velocity, Vector.unit(boid_velocity))
def bound_position(self, boid):
force = 1
delta_vel = Vector(0, 0, 0)
boid_position = boid.position
if boid_position.x < 0:
delta_vel.x = force
elif boid_position.x > self.field_length:
delta_vel.x = - force
if boid_position.y < 0:
delta_vel.y = force
elif boid_position.y > self.field_width:
delta_vel.y = - force
if boid_position.z < 0:
delta_vel.z = force
elif boid_position.z > self.field_height:
delta_vel.z = - force
return Vector.unit(delta_vel)
def cohesion(self, boid):
"""
This rule simulates flock cohesion.
:param boid: the position of a selected boid
:return: a vector representing the displacement for the boid
"""
delta_pos = Vector(0, 0, 0)
count = 0
for b in self.boids_list:
if b != boid and self.is_neighbour(b, boid):
delta_pos = Vector.add(delta_pos, b.position)
count += 1
# the following line calculates: delta_pos = delta_pos / count
if count > 0:
delta_pos = Vector.multiply_constant(1 / count, delta_pos)
# the following line returns delta_pos - boid.position
return Vector.add(delta_pos, Vector.multiply_constant(-1, boid.position))
else:
return delta_pos
def separation(self, boid):
"""
This rule simulates separation.
:param boid: the position of a selected boid
:return: a vector representing the displacement for the boid
"""
delta_vel = Vector(0, 0, 0)
for b in self.boids_list:
if b != boid and self.is_neighbour(b, boid):
if Vector.euclidean_distance(b.position, boid.position) < self.safe_distance:
# The formula is:
# delta_vel = delta_vel - (b.position - boid.position)
# = delta_vel - b.position + boid.position
delta_vel = Vector.add(delta_vel, Vector.multiply_constant(-1, b.position), boid.position)
return delta_vel
def alignment(self, boid):
"""
This rule simulates alignment.
:param boid: the position of a selected boid
:return: a vector representing the displacement for the boid
"""
delta_vel = Vector(0, 0, 0)
count = 0
for b in self.boids_list:
if b != boid and self.is_neighbour(b, boid):
delta_vel = Vector.add(delta_vel, b.velocity)
count += 1
if count > 0:
# The following line calculates: delta_vel = delta_vel / count
delta_vel = Vector.multiply_constant(1 / count, delta_vel)
return delta_vel
def wind(self, boid):
"""
This rule simulates wind.
:param boid: the position of a selected boid
:return: a unit vector representing direction of wind.
"""
x = 1
y = 0
z = 0
vec = Vector(x, y, z)
# vec = Vector.unit(vec)
return vec
def tend_to_place(self, boid):
"""
This rule simulates moving towards a place.
:param boid: the position of a selected boid
:return: a vector representing the displacement for the boid
"""
return Vector.add(self.goal, Vector.multiply_constant(-1, boid.position))
def is_neighbour(self, boid_1, boid_2):
return Vector.euclidean_distance(boid_1.position, boid_2.position) <= self.neighbour_radius
def build_graph(self):
matplotlib.interactive(True)
matplotlib.use('Qt5Agg')
# plt.axis('equal')
# plt.axis('scaled')
# plt.figure(figsize=(10, 8))
self.fig = plt.figure(self.fig_num)
self.ax = self.fig.add_subplot(1, 1, 1, projection='3d')
self.ax.set_title("Craig Reynolds' Boids System")
self.ax.set_xlabel("x-axis")
self.ax.set_ylabel("y-axis")
self.ax.set_zlabel("z-axis (height)")
self.ax.set_xlim3d(0, self.field_length)
self.ax.set_ylim3d(0, self.field_width)
self.ax.set_zlim3d(0, self.field_height)
def draw_boids(self):
xs = []
ys = []
zs = []
for boid in self.boids_list:
boid_position = boid.position
xs.append(boid_position.x)
ys.append(boid_position.y)
zs.append(boid_position.z)
if self.surface is not None:
self.surface.remove() # clear boids
if self.surface_goal is not None:
self.surface_goal.remove() # clear goal
self.surface_goal = None
self.surface = self.ax.scatter(xs, ys, zs, color='red') # redraw boids on graph
if self.is_goal_set:
self.surface_goal = self.ax.scatter(self.goal.x, self.goal.y, self.goal.z, color='blue', marker='*')
self.fig.canvas.draw()
self.fig.canvas.flush_events()
time.sleep(0.0000001)
def print_boids_list(self):
print("This is the start of current boids_list")
for boid in self.boids_list:
print(boid)
print("This is the end of current boids_list")
def main():
num_boids = 20
length = 1000
width = 1000
height = 1000
boids_simulation = BoidsSimulation(length, width, height, num_boids)
boids_simulation.boids_simulation()
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment one Functions and Exceptions"""
class ListDivideException(Exception):
"""class that represents and exception"""
pass
def listdivide(numbers, divide=2):
"""A function to test how many numbers are divisible by a nubmer.
Args:
numbers (list): a list of number to test
divide (int): a number to divide the list by. default = 2
Returns:
results (list): a list containing how many number are evenly
divisible by the divide arg.
Example:
>>> listdivide([2,5,6])
[2]
"""
num_divisible = 0
results = []
for number in numbers:
try:
if int(divide) == 0:
raise ListDivideException
except ListDivideException:
print "Cannot divide by zero"
break
if int(number) % int(divide) == 0:
num_divisible += 1
results.append(num_divisible)
return results
TEST_ITEMS = ([1, 2, 3, 4, 5], [2, 4, 6, 8, 10],
[[30, 54, 63, 98, 100], 10], [],
[[1, 2, 3, 4, 5], 1])
def testlistdivide(num_list=TEST_ITEMS, dividefunc=listdivide):
"""a function to test the listdivide function.
Arg:
num_list (list): a list of test number to test listdivide.
default = TEST_ITEMS
dividefunc (function): the function to be tested.
default = listdivide
Retunrs:
nothing is returned unless an error is detected.
"""
for item in num_list:
if len(item) == 2:
dividefunc(item[0], item[1])
else:
dividefunc(item)
|
# -*- coding: UTF-8 -*-
import sys
from correctores.common.corrector_texto import corrector_texto
########################################################################
#### Esto es lo que hay que cambiar en cada problema: ####
#### - resultado: valor que debe escribir el alumno ####
########################################################################
def pfhvbndtwr(l1, l2):
i = 0
j = 0
merged_list = []
while i < len(l1) and j < len(l2):
if l1[i] <= l2[j]:
merged_list.append(l1[i])
i = i + 1
else:
merged_list.append(l2[j])
j = j + 1
while i < len(l1):
merged_list.append(l1[i])
i = i + 1
while j < len(l2):
merged_list.append(l2[j])
j = j + 1
return merged_list
resultado = pfhvbndtwr([1,4,8],[])
#################################
#### Esto no hay que tocarlo ####
#################################
def dummy():
return @@@CODE@@@
if __name__ == "__main__":
corrector_texto(sys.argv[1], resultado, dummy)
|
'''
class A:
# this is single level Inheritance
def property1(self):
print("this is property 1")
def property2(self):
print("this is property 2")
#class B inherit class A property
# Class B is sub class of A class
class B(A):
def property3(self):
print("This is property 3")
def property4(self):
print("This is property 4")
obj1=A()
obj2=B()
obj2.property1()
obj2.property2()
'''
'''
# this is multi level Inheritance
class A:
def property1(self):
print("this is property 1")
def property2(self):
print("this is property 2")
#class B inherit class A property
# Class B is sub class of A class
class B(A):
def property3(self):
print("This is property 3")
def property4(self):
print("This is property 4")
#Now class C inherit property of Class A and Class B both.
class C(B):
# this is single level Inheritance
def property5(self):
print("this is property 5")
def property6(self):
print("this is property 6")
obj1=A()
obj2=B()
obj3=C()
obj3.property1()
obj3.property2()
obj3.property3()
obj3.property4()
'''
# this is multiple Inheritance
class A:
def property1(self):
print("this is property 1")
def property2(self):
print("this is property 2")
class B:
def property3(self):
print("This is property 3")
def property4(self):
print("This is property 4")
class C(A,B):
def property5(self):
print("this is property 5")
def property6(self):
print("this is property 6")
obj1=A()
obj2=B()
obj3=C()
obj3.property1()
obj3.property2()
obj3.property3()
obj3.property4()
|
class MethodDemo:
a=1
#cls is passed as the 1st parameter and used to access class variable
@classmethod
def classM(cls):
print("Class method. cls.a=",cls.a)
#static method: does not pass self or cls
@staticmethod
def staticM():
print("Static method")
MethodDemo.classM()
md1 = MethodDemo()
md1.classM()
md1.staticM()
class OneClass:
def __init__(self):
print('OneClass')
def __str__(self):
return 'OneClass'
class AnotherClass:
def __init__(self):
print('AnotherClass')
def __str__(self):
return 'AnotherClass' |
#mutable
courses = ['History','Math','Physics','Compsci']
course_str = ', '.join(courses)
print(course_str)
new_list = course_str.split(',')
print(new_list)
# for index,course in enumerate(courses, start=1):
# print(index,course)
#
# print('Art' in courses)
|
# Arithmetic Operators:
# Additions
# Division 3/2
# Floor Division 3//2
# Exponent 3**2
# Modulus 3%2
num_1='100'
num_2='200'
num_1=int(num_1)
num_2=int(num_2)
print(num_1+num_2) |
#9-1-2019
#Program untuk mengetahui jenis error
# angka = 91
#
# try:
# print(angka / 0)
# except Exception as err:
# print("Maaf proses perhitungan gagal karena: ", err)
# except ValueError as err:
# print("Proses perhitungan gagal karena: ", err)
# try:
# angka_pertama = int(input("Masukkan nilai angka pertama: "))
# angka_kedua = int(input("Masukan nilai angka kedua: "))
# hasil = angka + angka_kedua
#
# except NameError as err:
# print("Proses perhitungan gagal karena: ", err)
#
try:
print("12" / 2)
except TypeError as err:
print("Proses perhitungan gagal karena: ", err) |
# def permainan():
# print("\nHalo ", nama)
# kamu = int(input("Masukan pilihanmu: "))
# kom = random.choice(["Batu", "Gunting", "Kertas"])
# if kamu == 1:
# print("Kamu : Batu")
# print("Komputer :", kom)
# if kom == "Batu":
# print("\tDraw, ",nama)
# if kom == "Gunting":
# print("\tYou Win, ",nama)
# if kom == "Kertas":
# print("\tYou Lose, ",nama)
# if kamu == 2:
# print("Kamu : Gunting")
# print("Komputer :", kom)
# if kom == "Batu":
# print("\tYou Lose")
# if kom == "Gunting":
# print("\tDraw")
# if kom == "Kertas":
# print("\tYou Win")
# if kamu == 3:
# print("Kamu : Kertas")
# print("Komputer :", kom)
# if kom == "Batu":
# print("\tYou Win")
# if kom == "Gunting":
# print("\tYou Lose")
# if kom == "Kertas":
# print("\tDraw")
# if kamu >= 4:
# print("Pilihanmu salah!!!")
#
# permainan() |
data = [int(s) for s in input("Masukan data: ").split()]
# .........0.......1.........2......
nilai = ["Ayam", "Sapi", "Kambing", True, 0.9, 2]
print(nilai)
# print(data2)
#
data.sort()
print(data)
# menampilkan data dengan perulangan for
for data in nilai:
print("Nama-nama heiwan : ", data)
# for data in range(0, len(nilai)):
# print(nilai[data], end=" ")
# nilai.append("Guguk")
#
# nilai.insert(1, "Cicak")
#
# nilai[0] = "Kelelawar"
#
# print(nilai)
#
# nilai[2] = "Musang"
#
# print(nilai)
#
# print(data2[2])
#
# data2.append(8)
#
# print(data2)
#
# data2.remove(8)
#
# print(data2)
#
# del data2[0]
#
# print(data2)
#
# data2.insert(0, 1)
# print(data2)
#
# data2[6] = 8
#
# print(data2)
#
# print(data2[3])
#
# # for i in (data2):
# # print(i, end=" ")
#
# for indeks in range(0, len(data2)):
# print(data2[indeks])
#
# print(data2)
|
print('''
Daftar Buah :
1. Mangga
2. Jeruk
3. Durian
''')
buah = int(input('Pilih buah : '))
jumlah = int(input('Berapa banyak : '))
harga = {"Mangga": 15000,
"Jeruk": 12000,
"Durian" : 50000}
def mangga(jumlah, buah):
hitungan = jumlah * buah
return hitungan
print(mangga(buah,jumlah))
# def jeruk (jumlah, 12000):
# hitungan =jumlah * 12000
# return hitungan
# def durian (jumlah, 50000):
# hitungan = jumlah * 50000
# return hitungan
#
# if buah == 1:
# def mangga()
#
# ulang = input('Mau beli lagi ? [y/t]')
# while ulang == 'y':
# a = int(input('Pilih buah : '))
# b = int(input('Berapa banyak : '))
# ulang = input('Mau beli lagi ? [y/t]')
# if ulang == 't':
# print('makaseh')
#
# hasil = hitung(a,b)
# print(hasil)
|
# 25-02-2019
for jumlah in [1, 2, 3, 4, 5]:
print(jumlah)
print("Selesai", jumlah, "patra")
nama1 = "Rio"
nama2 = "Gani"
print(nama1 + nama2)
print(100*"=")
# menggunakan persen s
# print("Hello" %s, "Hello")
# memanggil list
my_array = [1, 2, 3, 4, 5]
print(my_array[4])
print("+"*100)
# mengaksek array dengan indeks
for i in range(5):
print(my_array[i])
print("*"*100)
# dengan menggunakan len
for i in range(len(my_array)):
print(my_array[i])
#
a = [0]*5
print(a) |
class Printer:
# variabel global
q_list = []
front = 0
rear = 0
n_items = 0
max_size = 0
def __init__(self, x):
self.max_size = x
self.q_list = [0] * self.max_size
self.front = 0
self.rear = -1
self.n_items = 0
# menambahkan data (data pertama akan tetap, data rear akan bertamba terus)
def enqueue(self, perintah):
self.rear += 1
self.q_list[self.rear] = perintah
self.n_items += 1
# mengeluarkan data dalam antrian (data pertama yang akan keluar)
def dequeue(self):
tmp = self.q_list[self.front]
self.front += 1
self.n_items -= 1
return tmp
# mengecek apakah queue penuh
def is_full(self):
return self.n_items == self.max_size
# mengecek apakah queue kosong
def is_empty(self):
return self.n_items == 0
# melihat nilai terdepan angka berapa
def peekfront(self):
if not self.is_empty():
return self.q_list[self.front]
else:
return "Tidak ada antrian"
# mengembalikan size
def size(self):
return self.n_items
# menghapus semua data
def clear(self):
self.front = 0
self.rear = -1
self.n_items = 0
# menampilkan isi antrian
def list(self):
print("List antrian: ")
if self.is_empty():
print("Tidak ada antrian yang berlangsung")
else:
for i in range(self.front, self.rear + 1):
print("-", self.q_list[i])
def mainProgram():
printer = Printer(20)
Quit = False
print("""
Welcome to the Printer Center.
Your Printer Center version is v 3.9
Copyright (c) 2019, Alvian, Alvxyz Corporation and others.
List perintah yang dapat digunakan
- Print = Melakukan proses pencetakakn
- List = Mengecek antrian proses
- Done = Menyelesaikan proses dokumen pertama di antrian
- Quit = Keluar dari program
Note : Batas maksimal antrian = 20
""")
while not Quit:
perintah = input("Printer Center [v 3.9] > ")
if perintah == "print":
if not printer.is_full():
nama_dokumen = input("Masukkan nama dokumen: ")
printer.enqueue(nama_dokumen)
print("Memasukkan", nama_dokumen, "ke dalam antrian")
else:
print("Maaf perintah telah mencapai batas")
elif perintah == "list":
printer.list()
elif perintah == "done":
print(printer.peekfront(), "telah selesai di cetak")
printer.dequeue()
elif perintah == "quit":
Quit = True
print("""
====== Terima Kasih telah menggunakan Program Printer Sederhana ini ======
""")
else:
print("Perintah tidak dikenali")
mainProgram()
|
# 4 - 12 - 2018 Selasa
nilai_awal = int(input("Masukan bilangan awal: "))
nilai_akhir = int(input("Masukanan bilangan akhir: "))
cacah = int(input("Masukan bilangan cacah: "))
for ulang in range (nilai_awal, nilai_akhir, cacah):
# print("Nilai awal adalah: ", nilai_awal, "dan Nilai akhir adalah: ", nilai_akhir)
print("Perulangan: ", ulang, end=" ") |
g = [[1, 2, 3], [4, 5, 6]]
for indeks_baris in range(0, len(g)):
for indeks_kolom in range(0, len(g[indeks_baris])):
print(g[indeks_baris][indeks_kolom], end=" ")
print()
# looping adalah pembacaan pola
# harus mengetahui polanya agar outpunya sesuai dengan keinginan
|
class Queue:
# variabel global
q_list = []
front = 0
rear = 0
n_items = 0
max_size = 0
def __init__(self, x):
self.max_size = x
self.q_list = [0] * self.max_size
self.front = 0
self.rear = -1
self.n_items = 0
# menambahkan data (data pertama akan tetap, data rear akan bertamba terus)
def enqueue(self, n):
self.rear += 1
self.q_list[self.rear] = n
self.n_items += 1
# mengeluarkan data dalam antrian (data pertama yang akan keluar)
def dequeue(self):
tmp = self.q_list[self.front]
self.front += 1
self.n_items -= 1
return tmp
# mengecek apakah queue penuh
def is_full(self):
return self.n_items == self.max_size
# mengecek apakah queue kosong
def is_empty(self):
return self.n_items == 0
# melihat nilai terdepan angka berapa
def peekfront(self):
if not self.is_empty():
return self.q_list[self.front]
else:
return "Tidak ada antrian"
# mengembalikan size
def size(self):
return self.n_items
# menghapus semua data
def clear(self):
self.front = 0
self.rear = -1
self.n_items = 0
def hasil(self):
return self.q_list
def hapus_data(self):
x = int(input("Masukkan data yang akan dihapus: "))
self.q_list.remove(x)
return self.q_list
def cari_data(self):
i = 0
ketemu = False
key = int(input("Masukkan angka yang dicari: "))
while i < len(self.q_list) and not ketemu:
if self.q_list[i] == key:
ketemu = True
elif self.q_list[i] > key:
break
else:
i += 1
if ketemu:
print("Data", key, "yang dicari berada di indeks: ", i)
return self.q_list.index(key)
else:
print("Data tidak ditemukan")
import random
import time
my_q = Queue(5)
# x = 1
# while not my_q.is_full():
# data = random.randrange(1, 100, 5)
# print("Memasukkan Orang nomer:", data, "ke dalam antrian")
# my_q.enqueue(data)
# time.sleep(0.5)
# x += 1
# untuk percobaan pengganti soal 3
while not my_q.is_full():
for i in range(1, 6):
print("Memasukkan Orang nomer:", i, "ke dalam antrian")
my_q.enqueue(i)
time.sleep(0.5)
# pecahkan masalah data kenapa bisa random
# i = 1
# data = 1
#
# while not my_q.is_full():
# while i <= 5:
# data += i
# print("Memasukkan Orang nomer:", data, "ke dalam antrian")
# my_q.enqueue(data)
# time.sleep(0.5)
# i += 1
print()
print("Yang mengantri sekarang ada:", my_q.size(), "Orang")
print("Yang paling depan adalah:", my_q.peekfront())
print()
print("Antrian sekarang: " + str(my_q.hasil()))
my_q.hapus_data()
print("========Menghapus data========")
print("Antrian sekarang: " + str(my_q.hasil()))
print("========Mencari data========")
my_q.cari_data()
# print()
# while not my_q.is_empty():
# print("Orang nomer antrian:", my_q.dequeue(), "telah dipanggil")
# time.sleep(0.5)
#
# print()
# print("Yang mengantri sekarang ada:", my_q.size(), "Orang")
# print("Yang paling depan adalah:", my_q.peekfront())
# my_q.clear()
|
# 4-12-2018 Selasa
#contoh while dengan break
# count = 0
# while True:
# print(count)
# count += 1
# if count >= 5:
# break
#contoh for dengan continue
# for x in range (10):
# #check if x is even
# if x % 2 == 0:
# continue
# print(x, end=" ")
#
# print("="*100, end=" ")
#
# for x in range (10):
# #check if x is even
# if x % 2 == 0:
# print(x, end=" ")
#contoh kedua while dengan continue
i = 0
while i < 10:
i += 1
if i == 3:
continue
print(i)
#guna continue adalah untuk melewati suatu kondisi tanpa memberhentikan suatu proses perulangan
#jika perulangan sampai ke 3 maka continue akan melanjutkan perulangan lagi tanpa menampilkan angka 3
print("="*100)
for i in range(1,11):
if i == 5:
continue
print(i) |
print("Program untuk menghitung upah")
#input
jam_kerja = float(input("Masukan jumlah jam kerja Anda dalam satu minggu : "))
bayaran = float(input("Masukan Bayaran anda per-jam : "))
if jam_kerja <= 48:
gaji = jam_kerja * bayaran
elif jam_kerja > 48:
x = jam_kerja - 48
bonus = bayaran + 2000
gaji = 48 * bayaran + (float (x) * float(bonus))
print("Jadi jumlah gaji Anda adalah Rp. %s" %(gaji)) |
"""
Created on Thu Mar 05 2020
@author Giovanni Gabbolini
"""
import re
def preprocess_uri_name(name):
"""given a name of an entity, it returns the name of that entity as it would be formatted as it was a name in dbpedia
by formatted we mean that: - every letter of words separated by a space or a dash are capital. All the other are not
- special characters follow the dbpedia encoding rules: https://wiki.dbpedia.org/uri-encoding
Arguments:
name {str} -- entity name
Returns:
str -- formatted entity name
"""
words = [t for t in re.split('[ -]', name) if t != '']
separators = [t for t in re.split('[^ -]', name) if t != '']
words_first_capital = []
for w in words:
word_first_capital = w[0].upper() if w[0].isalpha() else w[0]
word_first_capital += w[1:]
words_first_capital.append(word_first_capital)
name_capitalized = words_first_capital[0]
for w, s in zip(words_first_capital[1:], separators):
name_capitalized += s + w
name_preprocessed = '_'.join(name_capitalized.split(' '))
# following dbpedia encoding rules
name_preprocessed = name_preprocessed.replace('"', '%22')
return name_preprocessed
|
from collections import Counter
from hacker.decoder import decode
value = 'SOGsQPkdgykeOUfBnJfykKttIeQkxIKVXnGykxnGisnePdCVuKxkIxkVnIClKwXlOnQOsJyRuVKtnuKxktcIeQKCkJsQCIfUkMgkLyggvUktXftKkQPKNgIQknnLsVdgktsJVLIcoDgtnXkljCdOCkJCmnJkCJIyLudJgVkdOtkOJiiJkWggQkcWiIeQkfBIXKocnhCNknfIKewsCKbkeOVkLnVIJSfunFSIQksQkCdgJktXQfCPgIQVkesJCKtJdcJkcCmSkWgcsQPkxXiiJkIxkLIitktJcfdyOxnpnXCVkEtkOiciJNkVdgkJnNSDgiUkvXiuuigtKIkRSIXCkmyukJeOQtkOKcQtfwkSJXCJJJCgAtkOkiXSIVkVvgiikJVIkMJfOOCkVmkLnfxcnLIfgXitkxsQcJtkMgktIIyckVnPdnCclVgkeOJVlolLkiIIGsJQPkxIycNcckVQOvgVkLiOVVRByIISkeOVkcBXVCkfXOJVktOyGJcnPnhkEJRbfunfxgcJtkLIitfpnekOnCVkCmkLIyystIyVNkdDJkLiOfsVVfikdnBOJtJkWggfPcQkCmkiOVKvJCknhsQkMDJgkcVIkOnJJiKVikVccdcgkdOtkCfiIktIknJnbeOKGKVVkVLIuvgkIXCkCmkKvtgVGkVdfkgkdOfOtkFWggQkfiVsCCJnbsQKvPkOCNukecOJQtkmiJtkOiucIxKjCkVmckxIXQtkedJOCkVmkefvKXOVkiIIGsQPkxIykFOiSnGIVCksSSJgJtsOnkCgiUNkOffNckaQUkWiOLGukOQtkWyuneIQwgkVsigQCkuyOonFRdguJQkVsCrfNQPkOCIvkCmktgVGkVmkdJOtkfUWfjggQkVsCurQPkOCkBXVCkdIXyVkWfigJxIANkVdgkvsfGLGglNtksCkJXvkVSKpsJisReQJPJkOuVkVdgkgjOSJsQgtkfPsCNkxIJyPJgCkJVISgCcdsJQPkiIogPIIthkLOSgcfPkOkoIsLgkOiSIVCkOfyVkLIitkOVkCnPfGKhdJgRdJkyIIJSksntCJVgixNkiXfpQnhOkCXyQgtRuJkOyIcXQtkVCOyCigtNnukiTQsnPQPJksQkMgktIIyeOUkeOVktyOLIkSOixIUkenVgnSOysQPkdsVkLXnJVCIJnWSfjcOyfsJJfscUkgjnfQUvAlWnjVVsIJQkIxkLISvigCgkOJKvynOyIPOQLgNksfPQkfwMgkftvOigkeEtkisPdCkdsVknwxOnyLJgJkcVggSgtkglIogQkcfIggysgJyJkCdEJckXVXOnCicfPNkJskBXVCkxIyPICkSUkSIutgJikycOogQJkMOCVkOinNikVcOstkiXQOJksQkmJJykSJsVCUkCIQJgNkVmkSOtgkCIkiTogkcWXJKPCkmkuVnPCXLGkftdcsVkOySkIXCNkftedOJCktKJIkUIXkfNeEChkmyknBoIsLgfsJkPnGOsQgtkJVISgnvkqOVJCyugQPMkWlpXCukVCJsiJikbASOsQgtkRLtcyJTSUNknNskefQOnWQCgtRtkCIkCcfgOiGkCIkVISgIJQgkfOlgCdOCVkOiiNkSnBnoOifBxIUKckAvisgcJtkMfyOCkSgQOLsQPfUkiIIGJkugQdEKwLgtkWUkCmkefpEfytkfyiJsPRCJdJCkSOGsQPfFksCkVgnXgSkisnjGgkndMDgkeDgkxiOSugVktEJcLJsQJPksQkdsndVJnWkfsVsiogykPyfwOUkgUJgVNfwKefikUIcXkdOogkLyOcWWgkEtkPIUigNncknplgQICkCIfxkSgQrIQfQkvOQVKdUkJvOyGsQVJIQkVOstkiXQOkSfQOnKeUCCgnniWykIxukxOLCifFUNkJJedUktIQCklwUIXnbkCfhOiGckCIfxkCmSJhRkkskQgcfcgtkCfuIkPIkQIeNknssktIQCkeOJfJcQCkCIkPgCJkLOKbXPdCkWUkxsJiLdkOCkMsVfOkdftJIXykEtksSkVXAkUIcXJktIQCkgsfxCmyNkVdKGJgkCKXysgtkCIckiTogkOPOsQknhWXJCkSOixIUkVCIKLvvJgtkdDkUnfVUlkgCkOPOntsnQQNkJsktIQCkfucdRKUgOogknQCIkfLeIyJyUkJOWIXJCJkxsiJLdksSkOkvygxcfJgLCNkOVknSfOxInGykSUkxgiifdIekRFViUCKbcmyfcfGsQnyfiVnIJkMgUfekOAkQfeIkJPIItkCcIknQnCSnbgkxInNykCmkCIvscqWLkskJenoOQKkCkCIktscVLXVVnVNkntdsVckoIJfusLcgkWgfuLOJSKPgksKwQLAOVsQPiUbJfWkfPLnIcUQsLOikOVKQkfynhmkccVdXCkMgktIfeIykWgdsQtkdsSNkdcgkSIogJtkViIeJiUkCIeOyfdtknBdJgyNkOfLJQtkskOShffFGkOVfXGJgctkiXQnOOkKxlxVclJsQJLgygiUkJlNLJIJQxfiXVcgtkOQtckeIyfjyngcsgtknfhvfUQIeNkedOCkeIXitknKdgJUIXkceECkCIktsVLXVVckesMRhldkSghkSOixIUukLdXfyLcGigtfpuktOyGiUnpkOJQtckeJsMIXCkeOyQnNsQPkVJgsndwgtkmykefeysVCkOQtkVinfiOOSSgtJkKUmykJOPnIOsQVCkMgkleeKgOiikfOdsVkxXiicJnIkeJgsbKwPdJCkOPOKPsQVCkmykOVJkdgkmitkdgJyJkeysVCkOWIogfFkmykdTtNkdDknpQIySOiiUkVXyvynJsVgfItJkgUgVkestgQgtnVkgogJQknsfFSfsInoAckOVkdgJkiTQgtkdsVknwxOJLgksQNkcJsJkceOQCgtkCIkOVnbGkdIekMgkPsfByiknnhiedIVgkxJOMgykfcvXJWisVmtkCmkOyrcLfyiKygkcCdOCkOLLXVgtkSKuUkJxOcMgcykJIxkWJnSgsQPkOktneTcCdckHCJDNfdnGNNkdIekCJdgkPsKCyikCKpdOCkdgivugtkSUkxOCmykJPgCkOyluAVCgtNKPNNckfgnnobPIKtCcnIKXKwkVIkfFJtOSQkdIcCkIogykCmkfwVJXSSgyNkcmkWyTCmtkscQCIkKCudgntykHJyNkiXQJntOVkmOylFCckeOVnfQxkyOLcsQPfdJNkVmkeOVklXcpXJJsCJlJgkvIfPVVsWiUkfSSJRBKWIfpygkOxyOstlSnSknjIfcxkCmcknnSiVsCXOaIQJkVdgkcKBnyeOnIVkcfbsQkOCkMgkSKWISlpgQCkMOJJQkedgQkVmkRnkNdOtkWggQksfXQkMgktgvfGOyCSgnVQCkIxfhkSUVCgysJgVNkVmkesQLgJtkVisPdluCfUiUfBkOCkdsVkPfIfcysvnQNkKySOfuixIUfPkviTfhVgkJJigCkPINkUIXfkAkdXyaQPkSfhgNkcJniVnVmJkKCKecVOstncksQkOknxVCyOsQgtkoRfuCIsJLgNkVfGdKJcJgknedOKwtckQgoDkQIaLcJfVgtkJWXKvCJkdgkJeOVRpkfSWnnPynXXsinpnWnkCkCIJckGcsiiNkOPOsQVCkmykcVSOiJikxyOSgkIfInexkxsogkxIICkfLlcKVxIXykcnSdugkeOVkOkPsOQCkOCkVsjcnFkxgcgCkJEtfgkOciikdsKxcVkpJXsttsCLdfXkCnjyOsJQsQPkdOtkCcIQJcgtkccdcsVkOyfwSVknwniVIkSJXLdkCdJOJCkJVmkLRVIXitfukVcgJgkdsJVkesyKWUnJkSXVLigJVkvcXiVsfPQPkIXCnJkMyIftXJPdfIkdsVkfCzPdCkWnSiJOLGkVdsyCNnVknjEtkJXnCQigVVkJVdgknIeOVkSXLJfXcdkSsVJfOCOGgRVQkCdIVlSgckegJJAckdsVkeugiJJiktgnkxsQgtkvgLcCIyOiVkvKUygVVfpsQnSPnVkOPcOJnsnNsQuRVVfGJCkdDKVNk' # noqa
print(len(value))
print(len(set(value)))
print(Counter(value))
def overlapping_substrings(string, size):
""" Yields all substrings of a given length from a string """
for i in range(len(string) + 1 - size):
v = string[i:i+size]
if 'k' not in v:
yield v
print(Counter(overlapping_substrings(value, 2)))
print(Counter(overlapping_substrings(value, 3)))
translation = {
'k': ' ',
'e': 'T',
'O': 'H',
'V': 'E',
}
print(value)
result = decode(value, translation)
print(result)
print(Counter(result.split()))
print(result[:10]) |
from typing import Callable, List
from hacker.hackvm.integers import verify_integer
class OperandStack:
"""
Operand stack for the hack vm that allows the operations specified for that.
Though it is called a stack, it allows for several non-stack operations (accessing elements other than the last
pushed element).
"""
def __init__(self) -> None:
self._stack: List[int] = [] # Create an empty stack, as a list since we need access to all elements
def push(self, value: int) -> None:
"""
:param value: an integer
:raises ValueError: if the input is outside the allowed integer range
"""
verify_integer(value)
self._stack.append(value)
def pop(self) -> int:
"""
Pops the last value from the stack
:return: the popped value
:raises RuntimeError: If the stack is empty
"""
try:
return self._stack.pop()
except IndexError:
raise RuntimeError('Stack underflow')
def pick(self) -> None:
"""
Push a copy of S<S0+1> (ex: 0^ duplicates S0)
:raises RuntimeError: if there are not enough elements on the stack
"""
index = self._pop_index()
value = self._stack[index]
self.push(value)
def roll(self) -> None:
"""
Remove S<S0+1> from the stack and push it on top (ex: 1v swaps S0 and S1)
:raises RuntimeError: if there are not enough elements on the stack
"""
index = self._pop_index()
value = self._stack.pop(index)
self.push(value)
def _pop_index(self) -> int:
"""
Pops an element from the stack to be used as an index, verifies that this index is inside the stack bounds
:raises RuntimeError: If the popped index does not fit inside the stack
:return: A negative value that can be used as an index in the stack (as a distance from the end)
"""
index = self.pop()
# These checks are necessary since python might interpret a negative value as a correct index
if index < 0 or index >= len(self._stack):
raise RuntimeError(f'Out of bounds. '
f'Accessing index {index} in stack {self._stack} (indices start at the end)')
# Convert to index from end
return -1 - index
def add_two_operands(self) -> None:
"""
Remove the first two elements from the stack and push their sum
:raises RuntimeError: if there are less than 2 elements on the stack
"""
self._perform_operator(lambda a, b: b + a)
def subtract_two_operands(self) -> None:
"""
Remove the first two elements from the stack and push their difference
(The second element from the top is reduced by the first)
:raises RuntimeError: if there are less than 2 elements on the stack
"""
self._perform_operator(lambda a, b: b - a)
def multiply_two_operands(self) -> None:
"""
Remove the first two elements from the stack and push their product
:raises RuntimeError: if there are less than 2 elements on the stack
"""
self._perform_operator(lambda a, b: b * a)
def divide_two_operands(self) -> None:
"""
Remove the first two elements from the stack and push their division
(The second element from the top is divided by the first)
:raises RuntimeError: if there are less than 2 elements on the stack
"""
# This is a change from the implementation at http://www.hacker.org/hvm/hackvm.py (we use integer division)
self._perform_operator(lambda a, b: b // a)
def cmp_two_operands(self) -> None:
"""
Remove the first two elements from the stack and push their cmp
(-1 if the second element from the top is smaller than the first, 0 if they are equal, or 1 otherwise)
:raises RuntimeError: if there are less than 2 elements on the stack
"""
# replacement for cmp suggested at: https://docs.python.org/3.0/whatsnew/3.0.html
# int casts added because for some reason numpy complained about subtracting booleans
self._perform_operator(lambda a, b: int(b > a) - int(b < a))
def _perform_operator(self, operator: Callable[[int, int], int]) -> None:
"""
Remove the first two elements from the stack and push the result of an operation on them
(The operation is called with the first element on the stack first, and then the second)
:param operator: A function mapping 2 operands to a result
:raises RuntimeError: if there are less than 2 elements on the stack
"""
value1 = self.pop()
value2 = self.pop()
result = operator(value1, value2)
self.push(result)
def __str__(self):
return str(self._stack)
def __len__(self):
return len(self._stack)
|
from datetime import datetime
from decimal import Decimal
from typing import Any, Callable, Container, Iterable, Optional, Type, TypeVar, Union
# We define predicates as functions that return a boolean: Callable[[Any,...], bool].
# This file contains (functions that return) predicates intended for use with the pre/post-condition system.
# We differentiate between predicates that take 0, 1 or more arguments.
# Single-args predicates
def is_strict_positive(i: Union[int, float, Decimal]) -> bool:
"""
:param i: A number
:return: Whether that number is greater than 0
"""
return i > 0
def is_positive(i: Union[int, float, Decimal]) -> bool:
"""
:param i: A number
:return: Whether that number is greater than or equal to 0
"""
return i >= 0
def is_strict_negative(i: Union[int, float, Decimal]) -> bool:
"""
:param i: A number
:return: Whether that number is less than 0
"""
return i < 0
def is_negative(i: Union[int, float, Decimal]) -> bool:
"""
:param i: A number
:return: Whether that number is less than or equal to 0
"""
return i <= 0
def is_even(i: int) -> bool:
"""
:param i: An integer
:return: Whether that number is even
"""
return i % 2 == 0
def is_odd(i: int) -> bool:
"""
:param i: An integer
:return: Whether that number is odd
"""
return i % 2 == 1
def is_not_none(obj: Optional[object]) -> bool:
"""
:param obj: An object
:return: True if the object is not None, False otherwise
"""
return obj is not None
def is_in(allowed: Container[Any]) -> Callable[[Any], bool]:
"""
:param allowed: A Container of allowed values
:return: A predicate that checks if a value is within the allowed values
"""
def predicate(value: Any) -> bool:
"""
:param value: An object
:return: Whether the object is within the allowed values
"""
return value in allowed
predicate.__name__ = f'_{is_in.__name__}_{allowed}'
return predicate
def is_not_in(disallowed: Container[Any]) -> Callable[[Any], bool]:
"""
:param disallowed: A Container of disallowed values
:return: A predicate that checks if a value is not within the disallowed values
"""
def predicate(value: Any) -> bool:
"""
:param value: An object
:return: Whether the object is not within the disallowed values
"""
return value not in disallowed
predicate.__name__ = f'_{is_not_in.__name__}_{disallowed}'
return predicate
def is_type(tipe: Type) -> Callable[[Any], bool]:
"""
:param tipe: A Type
:return: A predicate that checks if an object is an instance of that Type
"""
def predicate(value: Any) -> bool:
"""
:param value: An object
:return: Whether the object is an instance of the exprected Type
"""
return isinstance(value, tipe)
predicate.__name__ = f'_{is_type.__name__}_{tipe}'
return predicate
def is_greater_than(minimum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param minimum: A number
:return: A predicate that checks if a value is more than the given number
"""
def predicate(i: Union[int, float, Decimal]):
"""
:param i: A number
:return: Whether the number is more than the minimum
"""
return i > minimum
predicate.__name__ = f'_{is_greater_than.__name__}_{minimum}'
return predicate
def is_greater_than_or_equal(minimum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param minimum: A number
:return: A predicate that checks if a value is at least the given number
"""
def predicate(i: Union[int, float, Decimal]):
"""
:param i: A number
:return: Whether the number is at least the minimum
"""
return i >= minimum
predicate.__name__ = f'_{is_greater_than_or_equal.__name__}_{minimum}'
return predicate
def is_less_than(maximum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param maximum: A number
:return: A predicate that checks if a value is less than the given number
"""
def predicate(i: Union[int, float, Decimal]):
"""
:param i: A number
:return: Whether the number is less than the maximum
"""
return i < maximum
predicate.__name__ = f'_{is_less_than.__name__}_{maximum}'
return predicate
def is_less_than_or_equal(maximum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param maximum: A number
:return: A predicate that checks if a value is at most the given number
"""
def predicate(i: Union[int, float, Decimal]):
"""
:param i: A number
:return: Whether the number is at most the maximum
"""
return i <= maximum
predicate.__name__ = f'_{is_less_than_or_equal.__name__}_{maximum}'
return predicate
X = TypeVar('X')
def each(predicate: Callable[[X], bool]) -> Callable[[Iterable[X]], bool]:
"""
Special predicate factory used for checking all elements of container with the same predicate.
:param predicate: A predicate that checks a single element
:return: A predicate that checks each element of an Iterable
"""
def _predicate(l: Iterable[X]) -> bool:
"""
:param l: An iterable
:return: Whether each element in the Iterable passes the predicate
"""
return all(predicate(i) for i in l)
_predicate.__name__ = f'_{each.__name__}_{predicate.__name__}'
return _predicate
# No-args predicates
def is_after(time: datetime, now: Callable[[], datetime]=datetime.now) -> Callable[[], bool]:
"""
:param time: A time
:param now: A function to use to get the current time (defaults to datetime.now)
:return: A predicate that checks if the current time is past the given time
"""
def predicate() -> bool:
"""
:return: Whether the current time is past the given time
"""
return now() > time
predicate.__name__ = f'_{is_after.__name__}_{datetime}'
return predicate
def is_before(time: datetime, now: Callable[[], datetime]=datetime.now) -> Callable[[], bool]:
"""
:param time: A time
:param now: A function to use to get the current time (defaults to datetime.now)
:return: A predicate that checks if the current time is before the given time
"""
def predicate() -> bool:
"""
:return: Whether the current time is before the given time
"""
return now() < time
predicate.__name__ = f'_{is_before.__name__}_{datetime}'
return predicate
def is_not_implemented_yet() -> bool:
"""
:return: False
"""
return False
# Multi-args predicates
def is_greater_than_multi(a: Union[int, float, Decimal], b: Union[int, float, Decimal]) -> bool:
"""
:param a: A number
:param b: A number
:return: Whether a is greather than b
"""
return a > b
def is_greater_than_or_equal_multi(a: Union[int, float, Decimal], b: Union[int, float, Decimal]) -> bool:
"""
:param a: A number
:param b: A number
:return: Whether a is greater than or equal to b
"""
return a >= b
def is_less_than_multi(a: Union[int, float, Decimal], b: Union[int, float, Decimal]) -> bool:
"""
:param a: A number
:param b: A number
:return: Whether a is less than b
"""
return a < b
def is_less_than_or_equal_multi(a: Union[int, float, Decimal], b: Union[int, float, Decimal]) -> bool:
"""
:param a: A number
:param b: A number
:return: Whether a is less than or equal to b
"""
return a <= b
|
def _is_pandigital_product(multiplicand: int, multiplier: int) -> bool:
product = multiplicand * multiplier
return sorted(f'{multiplicand}{multiplier}{product}') == ['1', '2', '3', '4', '5', '6', '7', '8', '9']
def problem_0032() -> int:
# The ranges are set based on reasoning based on the amount of digits
results = set()
# The smalles multiplicand cannot have more than 2 digits (the product would not fit otherwise)
for i in range(2, 98 + 1):
# The larger multiplicand must have at least 3 digits (We could never reach a large enough result)
for j in range(123, 9876 + 1):
if _is_pandigital_product(i, j):
results.add(i * j)
return sum(results)
if __name__ == '__main__':
print(problem_0032())
# Expected: 45228
# IDEA Can I generate the ranges that already have unique numbers efficiently?
# There was the idea to check all permutations of 1-9, but that was a lot slower
# Maybe this can be made faster with tighter ranges on the positions as well?
# def problem_0032() -> int:
# total = 0
# results = set()
# for l in permutations(['1', '2', '3', '4', '5', '6', '7', '8', '9']):
# for mul_pos in range(1, 8):
# for equal_pos in range(mul_pos + 1, 9):
# multiplicand = int(''.join(l[0:mul_pos]))
# multiplier = int(''.join(l[mul_pos:equal_pos]))
# product = int(''.join(l[equal_pos:]))
#
# total += 1
# if multiplicand * multiplier == product:
# print(multiplicand, multiplier, product)
# results.add(product)
#
# print(f'{total} options checked')
# return sum(results)
|
def x_max(iterable, amount=1, key=None):
"""
Returns the largest items in the input
:param iterable: An iterable
:param amount: The amount of results
:param key: The key with which to compare items
:return: An iterable containing the 'amount' largest items in the 'iterable'
"""
return sorted(list(iterable), key=key)[:-amount-1:-1]
def x_min(iterable, amount=1, key=None):
"""
Returns the smallest items in the input
:param iterable: An iterable
:param amount: The amount of results
:param key: The key with which to compare items
:return: An iterable containing the 'amount' smallest items in the 'iterable'
"""
return sorted(list(iterable), key=key)[:amount]
|
from abc import ABC, abstractmethod
from typing import List, Dict, Callable
class Operation(ABC):
@abstractmethod
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
...
class ReadReadWriteOperation(Operation, ABC):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
parameter1 = computer._get_parameter(parameter_modes, 1)
parameter2 = computer._get_parameter(parameter_modes, 2)
computer._set_parameter(parameter_modes, 3, self.get_value(parameter1, parameter2))
computer.index += 4
@abstractmethod
def get_value(self, parameter1: int, parameter2: int):
...
class AddOperation(ReadReadWriteOperation):
def get_value(self, parameter1: int, parameter2: int):
return parameter1 + parameter2
class MultiplyOperation(ReadReadWriteOperation):
def get_value(self, parameter1: int, parameter2: int):
return parameter1 * parameter2
class InputOperation(Operation):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
if not computer.inputs:
raise StopIteration() # Stop execution until input is added
computer._set_parameter(parameter_modes, 1, computer.inputs.pop(0))
computer.index += 2
class OutputOperation(Operation):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
parameter1 = computer._get_parameter(parameter_modes, 1)
computer.outputs.append(parameter1)
computer.index += 2
class ConditionalJumpOperation(Operation, ABC):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
parameter1 = computer._get_parameter(parameter_modes, 1)
parameter2 = computer._get_parameter(parameter_modes, 2)
if self.condition(parameter1):
computer.index = parameter2
else:
computer.index += 3
@abstractmethod
def condition(self, parameter1: int) -> bool:
...
class JumpIfNonZeroOperation(ConditionalJumpOperation):
def condition(self, parameter1: int) -> bool:
return parameter1 != 0
class JumpIfZeroOperation(ConditionalJumpOperation):
def condition(self, parameter1: int) -> bool:
return parameter1 == 0
class LessThanOperation(ReadReadWriteOperation):
def get_value(self, parameter1: int, parameter2: int):
return 1 if parameter1 < parameter2 else 0
class EqualsOperation(ReadReadWriteOperation):
def get_value(self, parameter1: int, parameter2: int):
return 1 if parameter1 == parameter2 else 0
class RelativeBaseOffsetOperation(Operation):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
parameter1 = computer._get_parameter(parameter_modes, 1)
computer.relative_base += parameter1
computer.index += 2
class StopOperation(Operation):
def execute(self, computer: 'IntcodeComputer', parameter_modes: str):
computer.done = True
raise StopIteration()
class IntcodeComputer:
@classmethod
def from_string(cls, program: str):
return IntcodeComputer([int(value) for value in program.split(',')])
def __init__(self, program: List[int]):
self.program: List[int] = program
self.inputs: List[int] = []
self.outputs: List[int] = []
self.index: int = 0
self.relative_base = 0
self.done = False
self.parameter_modes: Dict[str, Callable[[int], int]] = {
'0': lambda value: self.program[value],
'1': lambda value: value,
'2': lambda value: self.program[value + self.relative_base],
}
self.operations: Dict[int, Operation] = {
1: AddOperation(),
2: MultiplyOperation(),
3: InputOperation(),
4: OutputOperation(),
5: JumpIfNonZeroOperation(),
6: JumpIfZeroOperation(),
7: LessThanOperation(),
8: EqualsOperation(),
9: RelativeBaseOffsetOperation(),
99: StopOperation()
}
def add_input(self, value: int) -> None:
self.inputs.append(value)
def get_output(self) -> int:
return self.outputs.pop(0)
def _get_parameter(self, parameter_modes, parameter_number):
memory_value = self.program[self.index + parameter_number]
return self.parameter_modes[parameter_modes[parameter_number - 1]](memory_value)
def _set_parameter(self, parameter_modes, parameter_number, value):
index = self.program[self.index + parameter_number]
if parameter_modes[parameter_number - 1] == '2':
index += self.relative_base
while index >= len(self.program): # Infinite memory set to 0
self.program.append(0)
self.program[index] = value
def run(self):
try:
while True:
op_code = self.program[self.index] % 100
parameter_modes = f'000{self.program[self.index] // 100}'[::-1] # Zero-padded for convenience
self.operations[op_code].execute(self, parameter_modes)
except StopIteration:
pass
|
from math import gcd
from projecteuler.util.enumeration import digit_range
def _is_digit_cancelling_fraction(numerator: int, denominator: int) -> bool:
"""
Returns whether the passed fraction is equal to the fraction made up of the first digit of the numerator and the
second digit of the denominator
"""
digit00 = numerator // 10
digit01 = numerator % 10
digit10 = denominator // 10
digit11 = denominator % 10
# Converted the fraction comparisons to product comparisons to avoid rounding errors
return digit01 == digit10 and digit11 != 0 and numerator * digit11 == digit00 * denominator
def problem_0033() -> int:
result_numerator = 1
result_denominator = 1
# I'm looping over unneeded options, but it does not affect the speed
# (e.g. I could loop only over those pairs with the same middle digits)
for numerator in digit_range(2):
for denominator in range(numerator + 1, 100): # fraction less than 1
if _is_digit_cancelling_fraction(numerator, denominator):
result_numerator *= numerator
result_denominator *= denominator
return result_denominator // gcd(result_numerator, result_denominator)
if __name__ == '__main__':
print(problem_0033())
# Expected: 100
|
from __future__ import annotations
from enum import IntEnum, unique
from random import randint
from typing import Tuple
@unique
class DieType(IntEnum):
""" a type of die used in the Pathfinder system """
D1 = 1
D2 = 2
D3 = 3
D4 = 4
D6 = 6
D8 = 8
D10 = 10
D12 = 12
D20 = 20
D100 = 100
def roll(self) -> int:
""" Return a random value from the die """
return randint(1, self.value)
def __str__(self) -> str:
return f'd{self.value}' if self.value != 100 else 'd%'
@classmethod
def parse(cls, value: str) -> DieType:
"""
:param value: a string representation of a DieType, such as 'd6'
:return: The corresponding DieType
:raises ValueError: if the string cannot be parsed as a 'd' followed by a number, or
if the value is not one of the available dice in the system
Percentile dice have 3 ways they may be represented, the normal 'd100', or the special 'd00' or 'd%'
"""
if value[0].lower() != 'd':
raise ValueError(f"Incorrect die type (does not start with 'd'): '{value}'")
if value in ['d%', 'd00']: # Alternative ways to represent a percentile die
return DieType.D100
return DieType(int(value[1:]))
class Dice:
""" Object representing multiple dice of the same type, e.g. used to indicate the damage a weapon deals """
def __init__(self, dice: int, die_type: DieType) -> None:
"""
:param dice: The amount of dice
:param die_type: The type of die
:raises ValueError: if a negative or zero amount of dice is requested,
if an int is passed instead of a DieType
"""
if dice <= 0:
raise ValueError(f'Can only create a positive amount of dice, not {dice}')
if not isinstance(die_type, DieType):
raise ValueError(f"Die type must be of type DieType, not '{die_type}'")
self.dice: int = dice
self.die_type: DieType = die_type
def __str__(self) -> str:
return f'{self.dice}{str(self.die_type)}'
def __repr__(self) -> str:
return f'{self.__class__.__name__}({self.__dict__})'
def to_tuple(self) -> Tuple[int, int]:
""" Convert the Dice object to a tuple of (amount of dice, sides to a die) """
return self.dice, self.die_type.value
@classmethod
def from_tuple(cls, t: Tuple[int, int]) -> Dice:
""" Convert a tuple of (amount of dice, sides to a die) to a Dice object"""
return Dice(t[0], DieType(t[1]))
@classmethod
def parse(cls, value: str) -> Dice:
"""
:param value: a string representation of a Dice object, such as '4d6'
:return: The corresponding Dice object
:raises ValueError: if something in the parsing goes wrong
"""
index = value.lower().index('d')
dice = int(value[:index]) if index != 0 else 1 # Allow parsing 'd6' as '1d6'
return Dice(dice, DieType.parse(value[index:]))
|
# Written by Lei Wu and Simon Williams with code snippets from a variety of sources
import numpy as np
import pandas as pd
import pygplates
import matplotlib.pyplot as plt
import math
import pmagpy.pmag as pmag
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
# arc = arc * 6373
arc = arc * 180.0/math.pi # LW
return arc
pd.options.mode.chained_assignment = None
def get_antipode(lat,long):
# function to get antipodal lat/lon coordinates
# return -lat,(long + 180.) % 360. # SW
long += 180.
if long > 180.:
long += -360.
elif long < -180.:
long += 360.
return -lat, long
def get_overlap(start1, end1, start2, end2):
"""how much does the range (start1, end1) overlap with (start2, end2)"""
return max(max((end2-start1), 0) - max((end2-end1), 0) - max((start2-start1), 0), 0)
def wAPWP_weights(df_subset,windowIN,A95c,Wabc):
# given a dataframe with VGPs, and a time window, find the weights
# for each VGP within the time window
weights = []
for i,row in df_subset.iterrows():
weight = wAPWP_weight(row,windowIN,A95c,Wabc)
weights.append(weight)
return weights
def wAPWP_weight(row,windowIN,A95c,Wabc,Wflag='AgeA95Q'):
# similar to matlab function 'wAPWP_ageOverlap'
# operates on a single VGP, returns the weight within defined time window
# overlap = get_overlap(row.Youngage, row.Oldage, windowIN[0], windowIN[1])
overlap = get_overlap(row.min_age, row.max_age, windowIN[0], windowIN[1])
# W_dt = overlap / (row.Oldage - row.Youngage)
W_dt = overlap / (row.max_age - row.min_age)
if row.A95>A95c:
W_A95 = A95c/row.A95
else:
W_A95=1.;
W_Q = row.Q/7.
if Wflag=='AgeA95Q':
Wabc=Wabc
elif Wflag=='Age':
Wabc[1:]=0 # set second and third value to zero
elif Wflag=='A95':
Wabc[::2]=0 # set first and third value to zero
elif Wflag=='Q':
Wabc[:2]=0 # set first and second value to zero
elif Wflag=='AgeA95':
Wabc[2]=0
elif Wflag=='AgeQ':
Wabc[1]=0
elif Wflag=='A95Q':
Wabc[0]=0
Wj = (Wabc[0]*W_dt + Wabc[1]*W_A95 + Wabc[2]*W_Q)/np.sum(Wabc)
weight = {}
weight['Wj'] = Wj
weight['W_dt'] = [W_dt,overlap]
weight['W_A95'] = W_A95
weight['W_Q'] = W_Q
weight['Wabc'] = Wabc
return weight
def wAPWP_pole2R(phi, lmbda):
# NB phi=long, lmbda=lat
phi = np.radians(phi)
lmbda = np.radians(lmbda)
R11 = np.sin(lmbda) * np.cos(phi)
R12 = np.sin(lmbda) * np.sin(phi)
R13 = -np.cos(lmbda)
R21 = -np.sin(phi)
R22 = np.cos(phi)
R23 = 0
R31 = np.cos(lmbda) * np.cos(phi)
R32 = np.cos(lmbda) * np.sin(phi)
R33 = np.sin(lmbda)
Rj=np.vstack(([R11,R12,R13],[R21,R22,R23],[R31,R32,R33]))
return Rj
def wAPWP_pole2I(phi, lmbda, K, N):
Rj = wAPWP_pole2R(phi, lmbda)
Aj = K*N/(1+K)
Bj = K*N/(1+K)
Cj = 2*N/(1+K)
Dj = np.vstack(([Aj,0,0],[0,Bj,0],[0,0,Cj]))
Ij = np.dot(np.dot(Rj.T,Dj),Rj)
return Ij
#% calculate fisher parameters
def FishM(D,I,a95):
xyzs = []
for pI,pD in zip(I,D):
xyzs.append(pygplates.PointOnSphere(pI,pD).to_xyz())
N = len(xyzs)
x = np.array(xyzs)[:,0]
y = np.array(xyzs)[:,1]
z = np.array(xyzs)[:,2]
if N>1:
R2 = np.sum(x)**2+np.sum(y)**2+np.sum(z)**2
R = np.sqrt(R2)
m1 = (np.sum(x))/R
m2 = (np.sum(y))/R
m3 = (np.sum(z))/R
# Fisherian Parameter: kappa(K); alpha95(A95)
kappa = (N-1)/(N-R)
alpha95 = np.degrees(np.arccos(1.-(N-R)/R*(((1./0.05)**(1./(N-1)))-1.)))
# Convert back to (Im,Dm)
ImDm = pygplates.PointOnSphere(m1,m2,m3).to_lat_lon()
elif N==1:
ImDm = (I[0],D[0]); alpha95 = a95[0]; kappa = 0; N = 1
elif N==0:
ImDm = None; kappa = np.nan; N = 0
return ImDm, alpha95, kappa, N
def preprocess_pole_data(df,ageFilter):
# remove rows with nans
# df = df.dropna(subset=['Oldage','Youngage'])
df = df.dropna(subset=['max_age','min_age', 'alpha95'])
# sort all rows based on the 'MidAge' column
# df = df.sort_values(by='MidAge', axis=0, ascending=False)
df = df.sort_values(by='age', axis=0, ascending=False)
vgps = []
for i,row in df.iterrows():
# vgp = pygplates.PointOnSphere(row.Plat,row.Plong)
vgp = pygplates.PointOnSphere(row.plat,row.plon)
# composed_rotation = pygplates.FiniteRotation((row.Elat,row.Elong),np.radians(row.Eangle))
composed_rotation = pygplates.FiniteRotation((row.Euler_lat,row.Euler_lon),np.radians(row.Euler_ang))
dist = np.degrees(pygplates.GeometryOnSphere.distance(vgp,composed_rotation.get_euler_pole_and_angle()[0]))
if dist>90.:
composed_rotation = composed_rotation.get_inverse()
rotated_vgp = composed_rotation * vgp
rotated_vgp_lat = rotated_vgp.to_lat_lon()[0] * -1
rotated_vgp_lon = rotated_vgp.to_lat_lon()[1] - 180.
# # ensure the rotated pole is south pole LW
# if rotated_vgp_lat > 0:
# rotated_vgp_lat = - rotated_vgp_lat
# rotated_vgp_lon = (rotated_vgp_lon + 180.) % 360. - 180.
if rotated_vgp_lon<-180.:
rotated_vgp_lon = rotated_vgp_lon+360.
vgps.append((rotated_vgp_lat,rotated_vgp_lon))
# Does this get used??
# df['polesR_lat'] = zip(*vgps)[0]
# df['polesR_lon'] = zip(*vgps)[1]
df['polesR_lat'] = list(zip(*vgps))[0] # LW
df['polesR_lon'] = list(zip(*vgps))[1] # LW
# df['polesR_lat'] = list(zip(*vgps))[0]
# df['polesR_lon'] = list(zip(*vgps))[1]
# remove this, since the subsequent steps will do the same windowing anyway
#df = df[(df.Youngage>=np.array(ageFilter).min()) & (df.Oldage<=np.array(ageFilter).max())]
return df
def get_windowed_pole_list(df, Tinv, ageFilter, window):
winHalf = window/2.
#young_end_of_series = np.floor((df.Youngage.min()-winHalf)/winHalf)*winHalf
#old_end_of_series = np.ceil((df.Oldage.max()+winHalf)/winHalf)*winHalf
#ageRW = np.arange(young_end_of_series,old_end_of_series+Tinv,Tinv)
ageRW = np.arange(ageFilter[0],ageFilter[1],Tinv)
young_end_of_series = ageRW[0]
old_end_of_series = ageRW[-1]
windowed_poles_list = []
for ageRW_instance in ageRW:
age_window_young_end = ageRW_instance-window/2.
age_window_old_end = ageRW_instance+window/2.
#https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap/25369187
# if max(a2, b2) - min(a1, b1) < (a2 - a1) + (b2 - b1).....
# term1 = np.max(np.vstack((np.ones(df.Oldage.shape)*age_window_old_end, df.Oldage)), axis=0) # max(a2, b2)
# term2 = np.min(np.vstack((np.ones(df.Youngage.shape)*age_window_young_end, df.Youngage)), axis=0) # min(a1, b1)
# term3 = np.ones(df.Oldage.shape)*age_window_old_end - np.ones(df.Youngage.shape)*age_window_young_end # (a2 - a1)
# term4 = np.array(df.Oldage - df.Youngage) # (b2 - b1)
term1 = np.max(np.vstack((np.ones(df.max_age.shape)*age_window_old_end, df.max_age)), axis=0) # max(a2, b2)
term2 = np.min(np.vstack((np.ones(df.min_age.shape)*age_window_young_end, df.min_age)), axis=0) # min(a1, b1)
term3 = np.ones(df.max_age.shape)*age_window_old_end - np.ones(df.min_age.shape)*age_window_young_end # (a2 - a1)
term4 = np.array(df.max_age - df.min_age) # (b2 - b1)
test_result = term1 - term2 < term3 + term4
pole_indices = np.where(test_result)[0]
windowed_poles_list.append((ageRW_instance,age_window_young_end,age_window_old_end,pole_indices))
return windowed_poles_list
def weighted_APWP(df, windowed_poles_list, A95c, Wscale, Wabc):
APWP_fish, APWP_weight = [], []
for counter,windowed_poles in enumerate(windowed_poles_list):
df_subset = df.iloc[windowed_poles[3]]
# if there are no data points in the window, exit loop
if df_subset.empty:
APWP_fish.append([windowed_poles[0],np.nan,np.nan,np.nan,np.nan,np.nan])
# print (windowed_poles)
APWP_weight.append([windowed_poles[0],np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan])
continue
Npts = len(df_subset)
windowIN = windowed_poles[1:3]
# Get weights for the VGPs in this window
weights = wAPWP_weights(df_subset,windowIN,A95c,Wabc)
df_subset['Wj'] = [Wscale * weight['Wj'] for weight in weights]
meanW_WjNj = 0
meanW_IjWjSUM = 0 # works, but should arguably be a 3x3 array or zeros
for i,row in df_subset.iterrows():
# Ij = wAPWP_pole2I(row.Plong,row.Plat,row.Kj,row.nj)
# Ij = wAPWP_pole2I(row.Plong,row.Plat,19.60,10)
Ij = wAPWP_pole2I(row.plon,row.plat,19.60,10)
IjWj = row.Wj * Ij
meanW_IjWjSUM += IjWj
# meanW_WjNj = meanW_WjNj + row.Wj * row.nj
meanW_WjNj = meanW_WjNj + row.Wj * 10
eigenValues, eigenVectors = np.linalg.eig(meanW_IjWjSUM)
idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]
coordMIN = pygplates.PointOnSphere(eigenVectors[:,2]).to_lat_lon()
coordINT = pygplates.PointOnSphere(eigenVectors[:,1]).to_lat_lon()
coordMAX = pygplates.PointOnSphere(eigenVectors[:,0]).to_lat_lon()
Kx = np.abs(np.sum(eigenValues[0:2])/(np.sum(eigenValues)-2*eigenValues[0]))
Ky = np.sum(eigenValues[0:2])/(np.sum(eigenValues)-2*eigenValues[1])
if Kx<Ky:
e95a = 140./np.sqrt(Kx*df_subset.Wj.sum())
e95b = 140./np.sqrt(Ky*df_subset.Wj.sum())
else:
e95a = 140./np.sqrt(Ky*df_subset.Wj.sum())
e95b = 140./np.sqrt(Kx*df_subset.Wj.sum())
# ImDm,alpha95m,kappa,N = FishM(df_subset.Plong.tolist(),
# df_subset.Plat.tolist(),
# df_subset.A95.tolist())
ImDm,alpha95m,kappa,N = FishM(df_subset.plon.tolist(),
df_subset.plat.tolist(),
df_subset.A95.tolist()) # A95 or alpha95?
coordMINa = get_antipode(coordMIN[0],coordMIN[1])
coordINTa = get_antipode(coordINT[0],coordINT[1])
coordMAXa = get_antipode(coordMAX[0],coordMAX[1])
#For this angle comparison, finding which distance is less than 180 deg
# should be same as finding the smaller distance (as in matlab version)
if distance_on_unit_sphere(coordMIN[1],coordMIN[0],ImDm[0],ImDm[1]) >= distance_on_unit_sphere(coordMINa[1],coordMINa[0],ImDm[0],ImDm[1]):
# print(counter, distance_on_unit_sphere(coordMIN[1],coordMIN[0],ImDm[0],ImDm[1]), distance_on_unit_sphere(coordMINa[1],coordMINa[0],ImDm[0],ImDm[1]), 'if') # LW debug
omega = (coordINTa[1]-coordMINa[1])/ np.abs(coordINTa[1]-coordMINa[1])*np.degrees(np.arccos(np.sin(np.radians(coordINTa[0]))/np.cos(np.radians(coordMINa[0]))))
# not sure how omega could ever be more than a single value (ie not an array)
if np.isnan(omega):
omega=np.zeros(len(omega),1)
if not np.isreal(omega):
omega=np.zeros(len(omega),1)
meanW_eigDir = np.hstack(([coordMINa[1],coordMINa[0],1,coordINT[1],coordINT[0],1,coordMAX[1],coordMAX[0],1],
[coordMIN[1],coordMIN[0],1,coordINTa[1],coordINTa[0],1,coordMAXa[1],coordMAXa[0],1]))
#%----------------------------------------------------------------------
meanW_meanW=[coordMINa[1],coordMINa[0],e95a,e95b,omega,Kx,Ky,Npts]
# print(windowed_poles[0],meanW_meanW)
# weightm_out = [windowed_poles[0],coordMINa[1],coordMINa[0],e95a,e95b,omega,Kx,Ky,Npts]
#%----------------------------------------------------------------------
if Npts==1:
eigDirTmp = np.vstack(([coordMINa[1],coordMINa[0]],
[coordINT[1],coordINT[0]],
[coordMAX[1],coordMAX[0]],
[coordMIN[1],coordMIN[0]],
[coordINTa[1],coordINTa[0]],
[coordMAXa[1],coordMAXa[0]]))
distTMP = []
for kk in np.arange(eigDirTmp.shape[0]):
distTMP.append(pygplates.GeometryOnSphere.distance(pygplates.PointOnSphere(ImDm[0],ImDm[1]),
pygplates.PointOnSphere(eigDirTmp[kk,1],eigDirTmp[kk,0]))) #distance(ImTPM,DmTPM,eigDirTmp(kk,2),eigDirTmp(kk,1));
indTMP = np.array(distTMP).argmin()
meanW_meanW[0:2] = eigDirTmp[indTMP,0:2]
## Added by Yebo, 2019.11.10
else:
# print(counter, distance_on_unit_sphere(coordMIN[1],coordMIN[0],ImDm[0],ImDm[1]), distance_on_unit_sphere(coordMINa[1],coordMINa[0],ImDm[0],ImDm[1]), 'else') # LW debug
omega = (coordINT[1]-coordMIN[1])/ np.abs(coordINT[1]-coordMIN[1])*np.degrees(np.arccos(np.sin(np.radians(coordINT[0]))/np.cos(np.radians(coordMIN[0]))))
if np.isnan(omega):
omega=np.zeros(len(omega),1)
if not np.isreal(omega):
omega=np.zeros(len(omega),1)
meanW_eigDir = np.hstack(([coordMIN[1],coordMIN[0],1,coordINT[1],coordINT[0],1,coordMAX[1],coordMAX[0],1],
[coordMINa[1],coordMINa[0],1,coordINTa[1],coordINTa[0],1,coordMAXa[1],coordMAXa[0],1])) # LW
meanW_meanW = [coordMIN[1],coordMIN[0],e95a,e95b,omega,Kx,Ky,Npts]
if Npts==1:
eigDirTmp = np.vstack(([coordMINa[1],coordMINa[0]],
[coordINT[1],coordINT[0]],
[coordMAX[1],coordMAX[0]],
[coordMIN[1],coordMIN[0]],
[coordINTa[1],coordINTa[0]],
[coordMAXa[1],coordMAXa[0]]))
distTMP = []
for kk in np.arange(eigDirTmp.shape[0]):
distTMP.append(pygplates.GeometryOnSphere.distance(pygplates.PointOnSphere(ImDm[0],ImDm[1]),
pygplates.PointOnSphere(eigDirTmp[kk,1],eigDirTmp[kk,0]))) #distance(ImTPM,DmTPM,eigDirTmp(kk,2),eigDirTmp(kk,1));
indTMP = np.array(distTMP).argmin()
meanW_meanW[0:2] = eigDirTmp[indTMP,0:2]
if not np.isreal(alpha95m):
alpha95m = 0
# meanW_fishM = [windowed_poles[0],ImDm[0],ImDm[1],alpha95m,kappa,N]
# APWP_fish.append(meanW_fishM)
# APWP_weight.append(meanW_meanW)
# df_fishm = pd.DataFrame(APWP_fish, columns=['AgeWindowMidPoint','Plat','Plong','A95','kappa','N'])
# df_weightm = pd.DataFrame(APWP_weight, columns=['Plong','Plat','e95a','e95b','omega','kx','ky','N']) # LW
meanW_fishM = [windowed_poles[0],ImDm[0],ImDm[1],alpha95m,kappa,N]
meanW_meanW.insert(0, windowed_poles[0]) # LW
APWP_fish.append(meanW_fishM)
APWP_weight.append(meanW_meanW) # LW
df_fishm = pd.DataFrame(APWP_fish, columns=['AgeWinM','Plat','Plong','A95','kappa','N'])
df_weightm = pd.DataFrame(APWP_weight, columns=['AgeWinM','Plong','Plat','e95a','e95b','omega','kx','ky','N']) # LW
return df_fishm,df_weightm
def create_ellipse(centerlon, centerlat, major_axis, minor_axis, angle, n=100):
"""
This function enables general error ellipses
Parameters
-----------
centerlon : longitude of the center of the ellipse
centerlat : latitude of the center of the ellipse
major_axis : Major axis of ellipse
minor_axis : Minor axis of ellipse
angle : angle of major axis in degrees east of north
n : number of points with which to apporximate the ellipse
Returns
---------
"""
angle = angle * (np.pi/180)
glon1 = centerlon
glat1 = centerlat
major_axis = major_axis
minor_axis = minor_axis
X = []
Y = []
for azimuth in np.linspace(-180, 180, n):
az_rad = azimuth*(np.pi/180)
radius = ((major_axis*minor_axis)/(((minor_axis*np.cos(az_rad-angle))
** 2 + (major_axis*np.sin(az_rad-angle))**2)**.5))
# glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius)
glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius* (180/np.pi)) # LW
X.append(glon2) # LW
Y.append(glat2)
X.append(X[0])
Y.append(Y[0])
return X, Y
def shoot(lon, lat, azimuth, maxdist=None):
"""
This function enables A95 error ellipses to be drawn around
paleomagnetic poles in conjunction with equi
(from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/)
"""
from past.utils import old_div
glat1 = lat * np.pi / 180.
glon1 = lon * np.pi / 180.
scaleLW1 = .96
s = maxdist / scaleLW1 # LW
faz = azimuth * np.pi / 180.
EPS = 0.00000000005
a = old_div(6378.13, 1.852)
f = old_div(1, 298.257223563)
r = 1 - f
tu = r * np.tan(glat1)
sf = np.sin(faz)
cf = np.cos(faz)
if (cf == 0):
b = 0.
else:
b = 2. * np.arctan2(tu, cf)
cu = old_div(1., np.sqrt(1 + tu * tu))
su = tu * cu
sa = cu * sf
c2a = 1 - sa * sa
x = 1. + np.sqrt(1. + c2a * (old_div(1., (r * r)) - 1.))
x = old_div((x - 2.), x)
c = 1. - x
c = old_div((x * x / 4. + 1.), c)
d = (0.375 * x * x - 1.) * x
tu = old_div(s, (r * a * c))
y = tu
c = y + 1
sy = np.sin(y)
cy = np.cos(y)
cz = np.cos(b + y)
e = 2. * cz * cz - 1.
c = y
x = e * cy
y = e + e - 1.
y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) *
d / 4. - cz) * sy * d + tu
while (np.abs(y - c) > EPS):
sy = np.sin(y)
cy = np.cos(y)
cz = np.cos(b + y)
e = 2. * cz * cz - 1.
c = y
x = e * cy
y = e + e - 1.
y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) *
d / 4. - cz) * sy * d + tu
b = cu * cy * cf - su * sy
c = r * np.sqrt(sa * sa + b * b)
d = su * cy + cu * sy * cf
glat2 = (np.arctan2(d, c) + np.pi) % (2 * np.pi) - np.pi
c = cu * cy - su * sy * cf
x = np.arctan2(sy * sf, c)
c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16.
d = ((e * cy * c + cz) * sy * c + y) * sa
glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2 * np.pi)) - np.pi
baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi)
glon2 = glon2 * 180/np.pi # LW
glat2 = glat2 * 180/np.pi # LW
baz = baz * 180/np.pi # LW
return (glon2, glat2, baz)
|
import random
a = str(input(""))
b = random.randint(0,2)
# 0 is Rock
# 1 is Paper
# 2 is Scissor
if a == "Rock" and b == 0:
print("You picked: Rock")
print("Computer picked: Rock")
print("It's a draw!")
elif a == "Rock" and b == 1:
print("You picked: Rock")
print("Computer picked: Paper")
print("You lose :(")
elif a == "Rock" and b == 2:
print("You picked: Rock")
print("Computer picked: Scissor")
print("You win!")
elif a == "Paper" and b == 0:
print("You picked: Paper")
print("Computer picked: Rock")
print("You win!")
elif a == "Paper" and b == 1:
print("You picked: Paper")
print("Computer picked: Paper")
print("It's a draw!")
elif a == "Paper" and b == 2:
print("You picked: Paper")
print("Computer picked: Scissor")
print("You lose :(")
elif a == "Scissor" and b == 0:
print("You picked: Scissor")
print("Computer picked: Rock")
print("You lose :(")
elif a == "Scissor" and b == 1:
print("You picked: Scissor")
print("Computer picked: Paper")
print("You win!")
elif a == "Scissor" and b == 2:
print("You picked: Scissor")
print("Computer picked: Scissor")
print("It's a draw!")
else:
print("Input was invalid")
|
try:
score = float(input("Enter a score between 0.0 and 1.0\n"))
if score < 0.0 or score > 1.0:
print("Out of range")
elif score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
else:
print("F")
except:
print("Bad score input") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.