text stringlengths 37 1.41M |
|---|
n=int(input())
i=1
while i**2<n:
print (i**2)
i+=1
|
x = input('Введите х: ') # возвращается строка, не число
x=float(x) # преобразуем строку в вещественное число
y=x**5-2*x**3+1
y=str(y)
print('y = ' + y)
|
import DeepLearningModel
import glob
import numpy as np
FREQUENCY = 200 # Frequency the microcontroller collected data
TARGET_FREQUENCY = 50 # Frequency to scale collected data to / Frequency of the TensorFlow model
modelName = 'TensorFlowModel' # The name of the model used for saving / loading
epochs = 30 # Number of cycles the model should run
model = DeepLearningModel.DeepLearningModel(FREQUENCY, TARGET_FREQUENCY)
# load_model loads a saved model created in the CreatingModel example
model.load_model(modelName)
# predict, predicts the output of the array as input
# the function expects an array of dataframes (a dataframe is an array of 100 x, y, z values. shaped as (100, 3, 1))
# using 1 dataframe
predictOutput = model.predict(np.array([np.ones(300).reshape(100, 3, 1)]))
print('Predict output of 1 dataframe')
print(predictOutput)
# using multiple dataframes
predictOutput = model.predict(np.array([np.ones(300).reshape(100, 3, 1) * -2, np.ones(300).reshape(100, 3, 1) * -1, np.zeros(300).reshape(100, 3, 1), np.ones(300).reshape(100, 3, 1), np.ones(300).reshape(100, 3, 1) * 2]))
print('Predict output of multiple dataframes')
print(predictOutput) |
from numpy import *
#from array import *
arr=array([1,2,3,4,5,6])
arr2=arr
print(id(arr))
print(id(arr2))
arr[1]=12
print(arr)
print(arr2)
arr3=arr.view()
#view() uses sghallow copy internally and any modification done on
#one array reflects the changes automatically in the other array
print(arr)
print(id(arr))
print(arr3)
print(id(arr3))
arr[4]=444
print(arr)
print(arr3)
arr4=arr.copy() #uses deep copy internally creates a new array
#independent of the existing arrays
print(arr)
print(arr4)
arr[0]=90
print(arr)
print(arr4) |
"""x=1
while x <= 4:
print("San")
x=x+1
print("Exit_loop")
"""
i = 1
while i<=4:
print("SAndeep " , end="")
j=1
while j<=2:
print("DHONI",end="")
j=j+1
i=i+1
print()
print("EXIT_LOOP") |
from numpy import *
arr=array([1,2,3])
arr2=array([10,20,30])
for i in range(len(arr)):
arr[i]=arr[i]+arr2[i]
print(arr) |
from dictionnaire import villes
from math import *
from time import *
def livraison(depart, arrivee):
vitesse_m = 0
distance_trajet = villes[depart][arrivee] * 1000
distance_parcourue = 0
temps_s = 0
t_avant_pause = 0
pause = False
nb_Pause = 0
distance_restante = 0
while (distance_parcourue < distance_trajet):
if (t_avant_pause == 6660):
pause = True
if (pause == True):
if (vitesse_m > 25/9):
vitesse_m -= 25 / 9
temps_s += 60
distance_parcourue += vitesse_m * 60
elif (vitesse_m < 25/9):
temps_s += 900
t_avant_pause = 0
vitesse_m = 0
pause = False
nb_Pause += 1
else:
temps_s += 60
t_avant_pause += 60
distance_parcourue += vitesse_m * 60
if (t_avant_pause < 600):
if (vitesse_m < 25):
vitesse_m += 25 / 9
distance_parcourue += vitesse_m * 60
distance_restante = (distance_trajet - distance_parcourue)
while ( distance_restante <= 6500 ):
t_avant_pause += 20000
distance_restante = (distance_trajet - distance_parcourue)
if (vitesse_m > 25 / 9):
vitesse_m -= 25 / 9
temps_s += 60
distance_parcourue += vitesse_m * 60
elif (vitesse_m < 25/9):
vitesse_m = 0
return int(distance_parcourue), temps_s
def multipleVille():
villes_demande = None
entry_villes = []
temps_total = 0
distance_total = 0
while villes_demande != "" or len(entry_villes) < 2:
villes_demande = input("\nVeuillez fournir autant de ville que vous le souhaitez, lorsque vous avez fini, veuillez faire entrée: \n").lower().title()
if villes_demande.isalpha():
if villes_demande in villes:
entry_villes.append(villes_demande)
else:
print("\nVeuillez demander une ville présente dans notre base de données, situé dans le fichier dictionnaire.py \n")
elif villes_demande.isalpha() == False and villes_demande != "":
print("\nVeuillez fournir uniquement des lettres lors de votre sélection, merci \n")
if len(entry_villes) < 2 and villes_demande == "":
print("\nVous devez me fournir, au moins 2 villes, merci.\n")
for i in range(len(entry_villes)-1):
distance_parcourue,temps_s = livraison(entry_villes[i], entry_villes[i+1])
print(" ")
print("********************************************************************************************")
print(" ")
print("Trajet {} {} >>>>>>>>>>>>>>>> {}".format(i+1, entry_villes[i], entry_villes[i+1]))
print("---------------------------------------------------------------------------------------------")
print(" Distance: {} kilomètres Durée: {} ".format(distance_parcourue/1000, strftime('%H:%M', gmtime(temps_s))))
distance_total += distance_parcourue
temps_total += temps_s
temps_total += 2700 * (len(entry_villes)-2)
print(" ")
print(" ")
print("¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤")
print(" ")
print("Total {} >>>>>>>>>>>>>>>> {}".format(entry_villes[0], entry_villes[len(entry_villes)-1]))
print("---------------------------------------------------------------------------------------------")
print(" Distance total: {} kilomètres Durée total: {} ".format(distance_total/1000, strftime('%H:%M', gmtime(temps_total))))
multipleVille() |
import heapq
i = 0
arr = []
while True:
i = int(input())
if i == 0:
print(-heapq.heappop(arr))
elif i == -1:
break
else:
heapq.heappush(arr, i)
print(arr)
# while True:
# i = int(input())
# if i == 0:
# arr.sort()
# print(arr.pop(0))
# elif i == -1:
# break
# else:
# arr.append(i)
|
arr = input()
stack=[]
for x in arr:
if x.isdecimal():
stack.append(int(x))
elif x == '(' or x == ')':
continue
else:
n1 = stack.pop()
n2 = stack.pop()
if x == '+':
stack.append(n2 + n1)
elif x == '-':
stack.append(n2 - n1)
elif x == '*':
stack.append(n2 * n1)
elif x == '/':
stack.append(n2 / n1)
print(stack.pop()) |
import pickle
file = open('word_list.txt', 'rb')
# loading the words in a list
dictionary = pickle.load(file)
# code for bi-gram
bi_gram_list = []
word_no = 0 # to position a word in dictionary
for word in dictionary:
word_length = len(word)
if word_length < 2:
bi_gram_list.append(word[:2])
else:
bi_grams = []
letter_no = 0
for bi_gram_no in range(word_length - 1):
bi_grams.append(word[letter_no:letter_no + 2])
letter_no = letter_no+1
bi_gram_list.append(bi_grams)
bi_gram = open('bi-gram_list_.pkl', 'wb')
pickle.dump(bi_gram_list, bi_gram)
bi_gram.close()
# code for tri-gram
tri_gram_list = []
word_no = 0 # to position a word in dictionary
for word in dictionary:
word_length = len(word)
if word_length < 3:
tri_gram_list.append(word[:3])
else:
tri_grams = []
letter_no = 0
for tri_gram_no in range(word_length - 2):
tri_grams.append(word[letter_no:letter_no + 3])
letter_no = letter_no+1
tri_gram_list.append(tri_grams)
tri_gram = open('tri-gram_list_.pkl', 'wb')
pickle.dump(tri_gram_list, tri_gram)
tri_gram.close()
|
#第一题两种方式不换横
'''
a = 1
while a<5001:
if a%5 == 0 and a%7 == 0:
print(a,end =" ")
a+=1
for a in range (1,5001,1):
if a%5 == 0 and a%7 == 0:
print(a,end=" ")
'''
'''
import random
s = random.randint(1,100)
a = 1
while a<11:
c = int(input("请输入数字"))
if c > s:
print("比%d小小小"%c)
elif c < s:
print("比%d大大大"%c)
elif c == s:
print("猜中了哈哈哈")
break
a+=1
'''
'''
a = 1
while a <= 5:
print("*"*a)
a+=1
s = 4
while s > 0:
print("*"*s)
s-=1
'''
a = 10
while a > 0:
print("*"*a)
a-=1
'''
for i in range (1,10,1):
for a in range (1,i+1,1):
print("%d*%d=%d"%(a,i,a*i),end="\t")
print("")
'''
'''
i = 1
while i < 10:
a = 1
while a <= i:
print("%d*%d=%d"%(a,i,a*i),end="\t")
a+=1
print("")
i+=1
'''
|
# 选区类
print("❤"*78)
class Xuanqu(object):
# 类 属性 通过它可以满足条件(不满足条件为假)
is_login = False
def denglu(self):
print("欢迎进入CS游戏选区界面\t 请您选区:\t电信A区 \t网通B区")
print("❤"*78)
A = input("请输入区域(A)或(B)进入游戏:")
if A == A or A == B:
print("欢迎进入登录界面")
print("❤"*78)
def zhang(self):
count = 1
while count <= 3:
print("请登录账号和密码")
D = input("请输入账号:")
M = input("请输入密码:")
if D == "12" and M == "12":
print("登录成功!")
# 满足登录条件 为真 就可以 (进行下一类)
Xuanqu.is_login = True
break
else:
print("账号或密码错误")
count += 1
# 人类
print("❤"*78)
class Person(object):
def people(self):
print("❤"*78)
print("《《开始创建人物》》 ")
print("请选择角色属性:\n <角色① :白狼 性别:男 武器:AK47黑武士 手枪:暗杀者 近身武器:马来剑> \n <角色② :黑锋 性别:男 武器:M4A1死神 手枪:牡丹 近身武器:龙啸>\n<角色③ :夜玫瑰 性别:女 武器:AK47 手枪:修罗 近身武器:尼泊尔>\n <角色④ :潘多拉 性别:女 武器:巴雷特 手枪:牡丹 近身武器:玫瑰手斧>\n(其他角色敬请期待)")
print("❤"*78)
A = input("请(选择)角色:")
if "1" == A:
print("创建角色成功!\t白狼 性别:男 武器:AK47黑武士 手枪:暗者 近身武器:马来剑")
if "2" == A:
print("创建角色成功!\t黑锋 性别:男 武器:M4A1死神 手枪:牡丹 近身武器:龙啸")
if "3" == A:
print("创建角色成功!\t夜玫瑰 性别:女 武器:AK47 手枪:修罗 近身武器:尼泊尔")
if "4" == A:
print("创建角色成功!\t潘多拉 性别:女 武器:巴雷特 手枪:牡丹 近身武器:玫瑰手斧")
print("❤"*78)
def wing(self):
import random
A=input("请选择:按① 可以查看随机您喜欢创建的名字 并查看,按② 继续输入:")
if "1" == A:
for i in range(1,4):
list = ["孤独求败","大鱼小鱼","齐天大圣","令狐者","你的皇帝在此","我爱Python","猫和老鼠","淘气三千问","米老鼠唐老鸭"]
my_random = random.randint(0,len(list))
print("系统为您随机选择:",list[my_random-1],"\t温馨提示:喜欢输入,不喜欢自己想!")
print("❤"*78)
def ming(self):
list = []
dic = {}
name = input("请创建姓名:")
age = int(input("请创建年龄:"))
print("❤"*78)
dic["名称"]=name
dic["年龄"]=age
list.append(dic)
#print(list)
for i in list:
for k,v in i.items():
print("%s:%s"%(k,v))
def shangcheng(self):
print("❤"*78)
k = 1000
print("您现有金额%d;请合理安排您的资金,祝您游戏愉快!"%k)
print("❤"*78)
A = input("《欢迎进入商城》\n【子弹系列】\n请购买您需要的子弹:① 高级子弹:300元,② 中级子弹:200元,③ 低级子弹:100元\n请选择:")
if "1" == A:
a = k - 300
k = a
print("您成功购买高级子弹100发!花掉300元剩余%d元"%k)
if "2" == A:
b = k - 200
k = b
print("您成功购买中级子弹100发!花掉200元剩余%d元"%k)
if "3" == A:
c = k - 100
k = c
print("您成功购买初级子弹100发!花掉100元剩余%d元"%k)
# 枪
print("❤"*78)
A = input("【手枪系列】\n请购买您需要的手枪:① 高级手枪:200元,② 中级手枪:100元,③ 低级手枪:80元\n请选择:")
if "1" == A:
a = k - 200
k = a
print("您成功购买高级手枪!花掉200元剩余%d元"%k)
if "2" == A:
b = k - 100
k = b
print("您成功购买中级手枪!花掉100元剩余%d元"%k)
if "3" == A:
c = k - 80
k = c
print("您成功购买初级手枪!花掉80元剩余%s元"%k)
A = input("【装备系列】\n请购买您需要的手枪:① 高级装备:300元,② 中级装备:200元,③ 低级装备:100元\n请选择:")
if "1" == A:
a = k - 300
k = a
print("您成功购买高级装备!花掉300元剩余%d元"%k)
if "2" == A:
b = k - 200
k = b
print("您成功购买中级装备!花掉200元剩余%d元"%k)
if "3" == A:
c = k - 100
k = c
print("您成功购买初级装备!花掉100元剩余%s元"%k)
print("❤"*78)
# 上战场
class Zhanchang(object):
# 一共大战四回 三回运气 终极大招 猜古诗
def cai(self):
q = input("《欢迎进入游戏》按1 进入 [排位赛]:")
if "1" == q:
print("杀呀!!! 杀呀!!! 敌人来了!! 拿起我们的装备上战场啦! 注意危险!! 危险!!")
print("-"*78)
w = input("我们已经来到了[敌方轰炸区] 装上我们的定时炸药!!《输入炸药密码:111》:")
if "111" == w:
print("咣!!!! 咣!!! ")
print("-"*78)
import random
a = random.randint(1,11)
for i in range(1,4):
R = int(input("请您去 敌区 输入您的幸运(1-10)的数字 并轰炸区域:"))
if R > a:
print("炸死一百人")
t = "****************"
print(t.center(70,"*"))
if R < a:
print("炸死二百人")
t = "****************"
print(t.center(70,"*"))
elif R == a:
print("炸死五百人")
t = "****************"
print(t.center(70,"*"))
print("《敌人说:要吟诗一首》 如果你能接上,我们认输!")
import random
for i in range(1,4):
list = ["春眠不觉晓,","锄禾日当午,","飞流直下三千尺,","唧唧复唧唧","坐车停爱枫林晚"]
sy_random = random.randint(0,len(list))
print("你对吧!:",list[sy_random-1])
if sy_random == 1:
Z = input("请对诗:\nA,一二山四五\nB,上山打老虎\nC,老虎没大招\nD,一枝红杏出墙来\nE,疑是银河落九天\nF,汗滴禾下土\nH,处处闻啼鸟\nI,木兰当户织\nJ,我爱你爱着你就像老鼠爱大米\n请选择诗句的下一句:" )
if Z == "H":
print("您输入的正确")
print("❤"*78)
else:
print("您输入的错误")
print("-"*78)
if sy_random == 2:
Z = input("请对诗:\nA,一二山四五\nB,上山打老虎\nC,老虎没大招\nD,一枝红杏出墙来\nE,疑是银河落九天\nF,汗滴禾下土\nH,处处闻啼鸟\nI,木兰当户织\nJ,我爱你爱着你就像老鼠爱大米\n请选择诗句的下一句:" )
if Z == "F":
print("《您输入的正确》")
print("❤"*78)
else:
print("×您输入的错误×")
print("-"*78)
if sy_random == 3:
Z = input("请对诗:\nA,一二山四五\nB,上山打老虎\nC,老虎没大招\nD,一枝红杏出墙来\nE,疑是银河落九天\nF,汗滴禾下土\nH,处处闻啼鸟\nI,木兰当户织\nJ,我爱你爱着你就像老鼠爱大米\n请选择诗句的下一句:" )
if Z == "E":
print("《您输入的正确》")
print("❤"*78)
else:
print("×您输入的错误×")
print("-"*78)
if sy_random == 4:
Z = input("请对诗:\nA,一二山四五\nB,上山打老虎\nC,老虎没大招\nD,一枝红杏出墙来\nE,疑是银河落九天\nF,汗滴禾下土\nH,处处闻啼鸟\nI,木兰当户织\nJ,我爱你爱着你就像老鼠爱大米\n请选择诗句的下一句:" )
if Z == "I":
print("《您输入的正确》")
print("❤"*78)
else:
print("×您输入的错误×")
print("-"*78)
if sy_random == 5:
Z = input("请对诗:\nA,一二山四五\nB,上山打老虎\nC,老虎没大招\nD,一枝红杏出墙来\nE,疑是银河落九天\nF,汗滴禾下土\nH,处处闻啼鸟\nI,木兰当户织\nJ,我爱你爱着你就像老鼠爱大米\n请选择诗句的下一句:" )
if Z == "D":
print("《您输入的正确》")
print("❤"*78)
else:
print("×您输入的错误×")
print("-"*78)
# 战绩结果
class Zhanji(object):
def jieguo(self):
print("您赢了!!! 我们送您一个大礼")
import random
a=random.randint(1,11)
for i in range(1,2):
r = int(input("请您输入(1~10)选择礼包,谢谢体验!"))
if r > a:
print("让梦想飞在窗外,去迎接那未知的精彩!")
t = "****************"
print(t.center(70,"*"))
if r < a:
print("只有经历过地狱般的磨炼,才能拥有征服天堂的力量,只有流过血的手指,才能弹出世间的绝响!")
t = "****************"
print(t.center(70,"*"))
elif r == a:
print("立志欲坚不欲锐,成功在久不在速.")
t = "****************"
print(t.center(70,"*"))
#实例 选取区类和 人物类
adenglu = Xuanqu()
renwu = Person()
wo = Zhanchang()
me = Zhanji()
adenglu.denglu()
adenglu.zhang()
if Xuanqu.is_login:
renwu.people()
renwu.wing()
renwu.ming()
print("游戏账号:",id(renwu))
renwu.shangcheng()
wo.cai()
me.jieguo()
|
def q():
list = []
for i in range(2,101):
a = True
for a in range(2,i):
if i%a == 0:
a = False
break
if a:
list.append(i)
print(list)
print(result)
|
#author=dipendra ale
def show_menu():
menu = "choose the option below " + "\n\t1: show_all_employees"\
"\n\t2: show_employee" \
"\n\t3: change salary "\
"\n\t4: add_employee"\
"\n\t5: remove_employee"\
"\n\t6: save_bonus info"\
"\n\t7: generate_report" \
"\n\t8: TO exit"\
"\n==> "
while True:
try:
number = int(input(menu))
if 1 <= number <= 8:
break
else:
print("Values 1, 2 , 3, 4, 5, 6 or 7..... please")
except ValueError:
print("Values 1, 2 , 3, 4, 5, 6 or 7 .... please")
if number==1:
show_all_employees()
elif number==2:
show_employee()
elif number==3:
change_salary()
elif number==4:
add_employee()
elif number==5:
remove_employee()
elif number==6:
save_bonus_info()
elif number==7:
generate_report()
else:
exit()
def load_data():
print("load data")
def save_data():
print("save data")
def show_all_employees():
print("show all employee")
def show_employee():
print("show employee")
def change_salary():
print("change salary")
def add_employee():
print("add employee")
def remove_employee():
print("remove employee")
def save_bonus_info():
print("save bonus info")
def generate_report():
print("generate report")
def main():
menu = "choose the option below " + "\n\t1: load_data" \
"\n\t2: Show_menu" \
"\n\t3: Save_data" \
"\n\t4: TO EXIT"\
"\n==> "
while True:
try:
number = int(input(menu))
if 1 <= number <= 4:
break
else:
print("Values 1, 2 or 3 please...")
except ValueError:
print("Values 1, 2 or 3 please...")
if number==2:
show_menu()
elif number==1:
load_data()
elif number==3:
save_data()
else:
exit()
main()
|
with open("input_02.txt", "r") as f:
list = f.read().splitlines()
count = 0
for line in list:
beforeColon = line.split(":")[0]
password = line.split(":")[1].strip()
numbers = beforeColon.split()[0]
lowerBound = numbers.split("-")[0].strip()
upperBound = numbers.split("-")[1].strip()
character = beforeColon.split()[1].strip()
characterCount = password.count(character)
characterAtUpperBound = password[int(upperBound) - 1]
characterAtLowerBound = password[int(lowerBound) - 1]
if (characterAtLowerBound is character) and (characterAtUpperBound is not character):
count += 1
elif (characterAtLowerBound is not character) and (characterAtUpperBound is character):
count += 1
print("The number of valid passwords is: " + str(count))
|
__author__ = 'yan'
# rock-paper-scissors-lizard-Spock
# encode roles with numbers
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
import random
def number2Name(num):
if num == 0 :
return "rock"
elif num == 1 :
return "Spock"
elif num == 2 :
return "paper"
elif num == 3 :
return "lizard"
elif num == 4 :
return "scissors"
else :
print (str(num)+"cannot decode into any role")
def name2Number(name):
if name == "rock" :
return 0
elif name == "Spock" :
return 1
elif name == "paper" :
return 2
elif name == "lizard" :
return 3
elif name == "scissors" :
return 4
def rpsls(name):
num_of_player = name2Number(name)
random.seed()
num_of_computer = random.randrange(0,4,1)
role_of_player = name
role_of_computer = number2Name(num_of_computer)
print("player acts "+role_of_player)
print("computer acts "+ role_of_computer)
if (num_of_player - num_of_computer)%5>0 and (num_of_player - num_of_computer)%5<=2 :
player_win = True
print("player wins")
elif (num_of_player - num_of_computer)%5<=4 and (num_of_player - num_of_computer)%5>2 :
player_win = False
print("computer wins")
elif num_of_player == num_of_computer:
print("even")
player_win = False
else :
print("logical error")
player_win = False
return player_win
# test rpsls(name)
if_players_wins = rpsls("rock")
if_players_wins = rpsls("Spock")
if_players_wins = rpsls("paper")
if_players_wins = rpsls("lizard")
if_players_wins = rpsls("scissors")
|
import threading
import time
def deletrea_palabra(palabra, periodo):
for caracter in palabra:
time.sleep(periodo)
print(caracter.upper())
thread1 = threading.Thread(name='Palabra 1', target=deletrea_palabra, args=('be í', 3))
thread2 = threading.Thread(name='Palabra 2', target=deletrea_palabra, args=('ud cIUes', 5))
thread3 = threading.Thread(name='Palabra 3', target=deletrea_palabra, args=('naHq', 7))
thread1.start()
thread2.start()
thread3.start()
# Instancia 3 threads distintos y ejecútalos con los parametros dados. |
def histogram(items):
for n in items:
output =" "
times = n
while(times>0):
output +='*'
times = times-1
print(output)
histogram ([4,9,7])
|
# 리스트 복사
a = [1, 2, 3]
b = a
# print(id(a)) # id: 변수가 가리키고 있는 객제의 주소 값 리턴
# print(id(b))
# print(a is b) # is: 동일한 객체를 가리키고 있는지 판단
a[1] = 4
# print(a)
# print(b)
# a 변수의 값을 가져오면서 다른 주소를 가리키도록 하는 방법
# 1. [:]이용
a = [1, 2, 3]
b = a[:]
# print(id(a))
# print(id(b))
# 2. copy 모듈 이용
from copy import copy
a = [1, 2, 3]
b = copy(a)
# print(a is b) # False
# 변수를 만드는 여러가지 방법
a, b = ('python', 'life')
print(a) # python (str)
print(b) # life (str)
(a, b) = 'python', 'life'
|
s1 = set([1, 2, 3]) # 리스트
print(s1)
s2 = set('Hello')
print(s2)
# 교집합, 합집합, 차집합 구하기
s1 = set([1, 2, 3, 4, 5, 6])
s2 = set([4, 5, 6, 7, 8, 9])
print(s1 & s2) # 교집합
print(s1.intersection(s2))
print(s1 | s2) # 합집합
print(s1.union(s2))
print(s1 - s2) # 차집합
print(s1.difference(s2))
print(s2 - s1)
print(s2.difference(s1)) |
class Cola:
'''Tipo de dato abstracto donde se representa un manejo tipo FiFO (primero en llegar, primero en salir).
Se implementarán distintos métodos para manejar este TAD a través de listas'''
def __init__(self):
#Constructor de la clase Cola
self.items = []
def estaVacia(self):
#Metodo que permite saber si la Cola está vacía o no
return self.items == []
def agregar(self, item):
#Metodo para agregar items a la Cola. Se agregan siempre al final de la cola como se hace en,
#por ejemplo, una fila (cola) del banco, o del super.-
self.items.insert(0,item)
def avanzar(self):
#Extrae (hace avanzar) la cola. Es decir SACA al primer elemento de la fila.-
return self.items.pop()
def tamano(self):
#Metodo que nos devuelve el tamaño que tenga la Cola (es decir, la cantidad de elementos)
return len(self.items)
def mostrar(self):
#Metodo para dar formato al texto que sale en pantalla.-
return '{}'.format(self.items)
cola = Cola()
print(cola.estaVacia())
cola.agregar('Maca')
cola.agregar('Seba')
print(cola.mostrar())
print(cola.tamano())
cola.avanzar()
cola.agregar('Sergio')
print(cola.mostrar())
cola.avanzar()
print(cola.mostrar())
cola.agregar('Ema')
print(cola.mostrar())
#Vamos a subir a GIT.- |
#!usr/bin/python3.6
import pygame
import random
from colors import Colors
from paddle import Paddle
from ball import Ball
# Initialising the game engine
pygame.init()
# Open a new window
window_width = 1250
window_height = 800
window_size = (window_width,window_height)
window = pygame.display.set_mode(window_size)
pygame.display.set_caption("Pong")
# Global variable that keeps track of the individual scores and the score to win
player1_score = 0
player2_score = 0
score_to_win = 10
# Create the paddles for both players
player1_paddle = Paddle(Colors["red"],20,350)
player2_paddle = Paddle(Colors["indigo"],1220,350)
# Create the ball
ball = Ball(Colors["violet"],window_width / 2,window_height / 2)
ball.reset_displacement()
# Declaring a variable that proceeds the game if there is no outcome
continueGame = True
# Number of pixels the paddles shift by whenever the right key is pressed
paddleShift = 7
# Radius of the ball
ballRadius = 10
# Dimensions of the paddles
paddle_width = 10
paddle_height = 100
# Creating a clock that controls the rate at which the window updates
clock = pygame.time.Clock()
# Main gameplay loop which is only broken when there is some outcome
while continueGame:
# Main event loop
for event in pygame.event.get():
# If the user did something
if event.type == pygame.QUIT:
# The user voluntarily closed the window
continueGame = False
# Game logic
# When the user presses either W and S (player 1) or Up and Down arrow keys,
# The corresponding paddle moves accordingly
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
# If w is pressed, player 1's paddle moves up
player1_paddle.moveUp(paddleShift)
if keys[pygame.K_s]:
# If s is pressed , player 1's paddle moves down
player1_paddle.moveDown(paddleShift)
if keys[pygame.K_UP]:
# If the Up arrow key is pressed, player 2's paddle moves up
player2_paddle.moveUp(paddleShift)
if keys[pygame.K_DOWN]:
# If the Down arrow key is pressed, player 2's paddle moves down
player2_paddle.moveDown(paddleShift)
if keys[pygame.K_x]:
# If the x is pressed, the game closes
continueGame = False
# The ball moves according to the change in its displacement
ball.x += ball.x_change
ball.y += ball.y_change
# Bounce the ball if it hits the sides
if ball.y + ballRadius >= window_height or ball.y - ballRadius <= 0:
ball.y_change *= -1
# Bring the ball back to the center of the screen if it goes past the paddles
if ball.x + ballRadius >= window_width or ball.x - ballRadius <= 0:
if ball.x + ballRadius >= window_width:
# Player 1 scores a point
player1_score += 1
elif ball.x - ballRadius <= 0:
# Player 2 scores a point
player2_score += 1
# Wait for 1 second before bringing back the ball
pygame.time.wait(1000)
ball.x = window_width / 2
ball.y = window_height / 2
ball.reset_displacement()
# If the ball hits either one of the paddles, it should be reflected back
if player1_paddle.y <= ball.y <= player1_paddle.y + paddle_height and ball.x - ballRadius <= player1_paddle.x + paddle_width:
ball.x_change *= -1
ball.x = player1_paddle.x + paddle_width + ballRadius
if player2_paddle.y <= ball.y <= player2_paddle.y + paddle_height and ball.x + ballRadius >= player2_paddle.x:
ball.x_change *= -1
ball.x = player2_paddle.x - ballRadius
# Drawing all the components onto the screen
# Firstly, fill the window with cyan
window.fill(Colors["white"])
# Draws a line in the middle that serves as a half line
line_start_pos = ((window_width / 2),0)
line_end_pos = ((window_width / 2),window_height)
pygame.draw.line(window,Colors["black"],line_start_pos,line_end_pos,3)
# Displays the scores of both players
font = pygame.font.Font("8bitOperatorPlus-Regular.ttf",100)
text = font.render(str(player1_score),1,Colors["gray"])
window.blit(text,((window_width / 4) - 25,(window_height / 2) - 75))
text = font.render(str(player2_score),1,Colors["gray"])
window.blit(text,(((3 * window_width) / 4) - 25,(window_height / 2) - 75))
# Draws the paddles at either ends of the window
pygame.draw.rect(window,player1_paddle.color,(player1_paddle.x,player1_paddle.y,paddle_width,paddle_height))
pygame.draw.rect(window,player2_paddle.color,(player2_paddle.x,player2_paddle.y,paddle_width,paddle_height))
# Draws the ball wherever it is on the window
pygame.draw.circle(window,ball.color,(ball.x,ball.y),ballRadius)
# If there is a winner, display the winner and exit from the game after 5 seconds
if player1_score == score_to_win:
# Player 1 is the winner
font = pygame.font.Font("8bitOperatorPlus-Regular.ttf",50)
text = font.render("Player 1 is the winner!",1,Colors["brown"])
window.blit(text,(window_width / 4,window_height / 4))
pygame.display.flip()
pygame.time.wait(5000)
continueGame = False
if player2_score == score_to_win:
# Player 2 is the winner
font = pygame.font.Font("8bitOperatorPlus-Regular.ttf",50)
text = font.render("Player 2 is the winner!",1,Colors["brown"])
window.blit(text,(window_width / 4,window_height / 4))
pygame.display.flip()
pygame.time.wait(5000)
continueGame = False
# Updating the screen with whatever has been drawn so far
pygame.display.flip()
# Limit the clock to 60 frames per second
clock.tick(60)
# Stops the game engine after the user has exited the main gameplay loop
pygame.quit() |
# -*- coding: utf-8 -*-
import numpy as np
inputs = np.array(input().split(), dtype = 'float')
diff = inputs.max() * 3 - inputs.sum()
if diff % 2 == 0:
print(int(diff / 2.0))
else:
print(int(np.floor(diff / 2.0)) + 2)
|
def update(x):
x=8
print(x) # 10 update to 8
update(10)
def update(x):
x=8
print("x",x)
a=10
update(a) # here pass by value 10 not by reference a
print("a",a)
def update(x):
print(id(x)) # referce to same address because pass by value
x=8
print(id(x)) # after changing value of x get diff address because int , str are imutable
print("x",x)
a=10
print(id(a))
update(a)
print("a",a)
# In python we does't use pass by value or pass by reference none of them.
#mutable
def update(list):
print(id(list))
list[1]=25
print(id(list)) # after updating also address do not change so list is mutable
print("x",list)
list=[10,20,30]
print(id(list))
update(list)
print("list",list)
|
class Student:
def __init__(self,name,rollno):
self.name = name
self.rollno = rollno
self.lap = self.Laptop()
def show(self):
print(self.name ,self.rollno)
self.lap.show()
class Laptop: #inner class
def __init__(self):
self.brand = 'Lenovo'
self.cpu = ' i3'
self.ram = 4
def show(self):
print(self.brand ,self.cpu, self.ram)
s1 = Student("vinay", 2)
s2 = Student("vaibhav" , 3)
s1.show()
lap1 = s1.lap
lap2 = s2.lap
print(id(lap1))
print(id(lap2))
lap1 = Student.Laptop()
|
x=int(input("enter how many times you want to print your name"))
name = input("enter your name")
i=1
j=3
while i<=x:
print(name)
i+=1
while j>=1:
print("thank you")
j-=1 |
class A:
def __init__(self):
print("in init of A")
def feature1(self):
print("feature 1 is working")
def feature2(self):
print("feature 2 is working")
class B: # B is subclass which access all features from superclass but not vise versa
def __init__(self): # if init of B is not present then it print init of A
print("in init of B")
super().__init__() # this function print init of super class A
def feature3(self):
print("feature 3 is working")
def feature4(self):
print("feature 4 is working")
class C(A,B): # now C has two superclass
def __init__(self):
print("in init of C")
super().__init__() # But it print only one because it prefer left one if it not present thrn print right B
def feat(self):
super().feature2()
a1 = A()
c1 = C()
a1.feature1()
c1.feat() |
#def greet():
# print("Hello")
# greet() #recursion means again greet calling greet() and it is infinite
# greet() #give error
# how to increase limit
import sys
sys.setrecursionlimit(200)
print(sys.getrecursionlimit())
i=0
def greet():
global i
i+=1
print("Hello",i)
greet()
greet()
|
class Computer():
def __init__(self):
self.name = "vinay"
self.age = 20
def update(self):
self.age=20
def compair(self,other):
if self.age == other.age:
return True
else:
return False
c1 = Computer() # constructor is allocate memory to object here Computer() is constructor
c2 = Computer()
if c1.compair(c2):
print("They are same") # if age are diff we get they are diff
else:
print("They are diff")
print(id(c1))
print(id(c2))
print(c1.name)
print(c2.name) # print same data
print(c2.age)
c1.name = "vaibhav"
c1.age = 18
print(c1.name)
c1.update() # change age of vaibhav because we write c1.function()
print("updated",c1.age)
|
# a light weight process when you breakdown a beg task into small part that each task called thred
# simple code
class Hello:
def run(self):
for i in range(0,5):
print("hello")
class Hi:
def run(self):
for i in range(5):
print("hi")
t1 = Hello()
t2= Hi()
t1.run()
t2.run()
print("=========using thread=====================")
from threading import *
class Hello(Thread):
def run(self):
for i in range(5):
print("hello")
class Hi(Thread):
def run(self):
for i in range(5):
print("hi")
t1 = Hello()
t2= Hi()
t1.start()
t2.start() #it is very fast or small program so it didn't take gap between hi & hello
print("=========printing alternating=====================")
from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(3):
print("hello")
sleep(1) # it is sleep or stop for 1 sec and then execute next
class Hi(Thread):
def run(self):
for i in range(3):
print("hi")
sleep(1) # it is sleep or stop for 1 sec and then execute next
t1 = Hello()
t2= Hi()
t1.start()
t2.start() # here get hellohi because we get same thread at same time parallel soooo
print("=========printing alternating=====================")
from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(3):
print("hello")
sleep(1) # it is sleep or stop for 1 sec and then execute next
class Hi(Thread):
def run(self):
for i in range(3):
print("hi")
sleep(1) # it is sleep or stop for 1 sec and then execute next
t1 = Hello()
t2= Hi()
t1.start()
sleep(0.2)
t2.start()
t1.join()
t2.join()
print("Bye") |
def fabonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fabonacci(n-1)+fabonacci(n-2)
number=int(input())
print(fabonacci(number))
|
#!/usr/bin/python3
""" checking is an object is an istance of"""
def is_kind_of_class(obj, a_class):
"""Checks if object is an instance of or an instance of a class that
inherited from a specified class"""
if isinstance(obj, a_class):
return True
else:
return False
|
#!/usr/bin/python3
"""
Create empty class BaseGeometry
"""
class BaseGeometry():
"""
Class BaseGeometry with Exception
"""
def area(self):
"""Is the area function"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""This verify value and type"""
if type(value) is not int:
raise TypeError("{:s} must be an integer".format(name))
if value <= 0:
raise ValueError("{:s} must be greater than 0".format(name))
|
# =====================================
# METHODS AND THE PYTHON DOCUMENTATION
# =====================================
# mylist = [1,2,3]
# mylist.append(4)
# mylist.pop()
# mylist.insert
# =====================================
# FUNCTIONS IN PYTHON
# =====================================
# def name_function():
# '''
# DOCSTRING: Information about the function
# INPUT: no input...
# OUTPUT: Hello...
# '''
# print('Hello')
# name_function()
# def say_hello(name):
# print('hello ' +name)
# say_hello('Davin')
# def say_hello(name='NAME'):
# return 'hello ' +name
# say_hello('David')
# result = say_hello('Zach')
# result
# def add(n1, n2):
# return n1 + n2
# result = add(20, 30)
# Find out if the word 'dog' is in a string?
# def dog_check(mystring):
# return 'dog' in mystring.lower()
# dog_check('Dog ran away')
# def pig_latin(word):
# first_letter = word[0]
# # check if vowel
# if first_letter in 'aeiou':
# pig_word = word + 'ay'
# else:
# pig_word = word[1:] + first_letter + 'ay'
# return pig_word
# word = pig_latin('apple')
# ========================================================
# CODING EXERCISE 10: FUNCTIONS #1: print HELLO WORLD
# ========================================================
# def myfunc(name):
# print('Hello World')
# ========================================================
# CODING EXERCISE 11: FUNCTIONS #2: print Hello Name
# ========================================================
# def myfunc(name):
# print(f'Hello {name}')
# ========================================================
# CODING EXERCISE 12: FUNCTIONS #3: simple Boolean
# ========================================================
# def myfunc(x):
# if x:
# return 'Hello'
# else:
# return 'Goodbye'
# ========================================================
# CODING EXERCISE 13: FUNCTIONS #4: using Boolean
# ========================================================
# def myfunc(x, y, z):
# if z:
# return x
# else:
# return y
# ========================================================
# CODING EXERCISE 14: FUNCTIONS #5: simple math
# ========================================================
# def myfunc(x, y):
# return x + y
# ========================================================
# CODING EXERCISE 15: FUNCTIONS #6: is even
# ========================================================
# def is_even(num):
# return num % 2 == 0
# ========================================================
# CODING EXERCISE 16: FUNCTIONS #7: is greater
# ========================================================
# def is_greater(x, y):
# return x > y or y <= x
# ========================================================
# CODING EXERCISE 17: FUNCTIONS #8: *args
# ========================================================
# ========================================================
# CODING EXERCISE 18: FUNCTIONS #9: pick evens
# ========================================================
# ========================================================
# CODING EXERCISE 19: FUNCTIONS #10: skyline
# ========================================================
# def myfunc(a, b):
# # Returns 5% of the sum of a and b
# return sum((a, b)) * 0.05
# result = myfunc(40, 60)
# def myfunc(*args):
# return sum(args) * 0.05
# result = myfunc(40, 60, 100, 1, 34)
# def myfunc(*args):
# for item in args:
# print(item)
# myfunc(40,60,100,1,34)
# def myfunc(**kwargs):
# print(kwargs)
# if 'fruit' in kwargs:
# print('My fruit of choice is {}'.format(kwargs['fruit']))
# else:
# print('I did not find any fruit here')
# myfunc(fruit='apple', veggie='lettuce')
# def myfunc(*args, **kwargs):
# print(args)
# print(kwargs)
# print('I would like {} {}'.format(args[0], kwargs['food']))
# myfunc(10, 20, 30, 'apple', fruit='orange', food='eggs', animal='dogs')
# ========================================================
# FUNCTION #8: *ARGS
# ========================================================
# def myfunc(*args):
# return sum(args)
# ========================================================
# FUNCTION #9: PICK EVENS
# ========================================================
# def myfunc(*args):
# return list(num for num in args if num%2 == 0)
# result = myfunc(1,2,3,4,5,6,7)
# ========================================================
# FUNCTION #10: SKYLINE
# ========================================================
# def myfunc(word):
# new_string = ''
# for index, letter in enumerate(word):
# if index%2 == 0:
# new_string += letter.upper()
# else:
# new_string += letter.lower()
# return new_string
# result = myfunc('haldaserkjealea')
# ========================================================
# FUNCTION PRACTICE EXERCISES
# ========================================================
# def master_yoda(text):
# seperated = text.split()
# reversed = seperated.reverse()
# return reversed.join()
# x = 'I love you'
# result = ' '.join(reversed(x.split()))
# mylist = [1,2,3,4]
# myjoin = ''.join(str(n) for n in mylist)
# def has_33(nums):
# return '33' in ''.join(str(x) for x in nums)
# result = has_33([1, 3, 1, 3,3])
# def paper_doll(text):
# triple = ''
# for letter in text:
# triple += letter*3
# return triple
# result = paper_doll('Mississippi')
# BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
# blackjack(5, 6, 7) - -> 18
# blackjack(9, 9, 9) - -> 'BUST'
# blackjack(9, 9, 11) - -> 19
# def blackjack(a, b, c):
# if sum((a, b, c)) <= 21:
# return sum((a, b, c))
# elif sum((a, b, c)) > 21:
# if a == 11 or b == 11 or c == 11:
# return sum((a, b, c)) - 10
# else:
# return 'BUST'
# result = blackjack(9, 9, 8)
# SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
# summer_69([1, 3, 5]) - -> 9
# summer_69([4, 5, 6, 7, 8, 9]) - -> 9
# summer_69([2, 1, 6, 9, 11]) - -> 14
# def summer_69(arr):
# mysum = 0
# for x in arr:
# if x < 6 or x >9:
# mysum += x
# return mysum
# result = summer_69([4, 5, 6, 7, 8, 9])
# SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order
# spy_game([1, 2, 4, 0, 0, 7, 5]) - -> True
# spy_game([1, 0, 2, 4, 0, 5, 7]) - -> True
# spy_game([1, 7, 2, 0, 4, 5, 0]) - -> False
# def has_33(nums):
# return '33' in ''.join(str(x) for x in nums)
# result = has_33([1, 3, 1, 3,3])
# def spy_game(nums):
# return '007' in ''.join(str(x) for x in nums)
# result = spy_game([1, 2, 4, 0, 0, 7, 5])
# result = list(range(0, 101))
# COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
# count_primes(100) - -> 25
# By convention, 0 and 1 are not prime.
# def count_primes(num):
# myrange = list(range(0, num))
# prime_count = 0
# for x in range(0, num):
# prime_count += 1
# def count_primes(num):
# primelist = [x for x in range(2, num+1) if not [
# t for t in range(2, x) if not x % t]]
# return len(primelist)
# # result = count_primes(100)
# def count_primes(num):
# # Check for 0 or 1 input
# if num < 2:
# return 0
# ###################
# # 2 of greater
# ###################
# # Store our prime numbers
# primes = [2]
# # Counter going up to the input num
# x = 3
# # x is going through every number up to the input num
# while x <= num:
# for y in primes:
# if x % y == 0:
# x += 2
# break
# else:
# primes.append(x)
# x += 2
# print(primes)
# return len(primes)
# result = count_primes(100)
# ========================================================
# LAMBDA EXPRESSIONS, MAP, AND FILTER FUNCTIONS
# ========================================================
# def square(num):
# return num**2
# my_nums = [1, 2, 3, 4, 5]
# for item in map(square, my_nums):
# print(item)
# result = list(map(square, my_nums))
# def splicer(mystring):
# if len(mystring) % 2 == 0:
# return 'EVEN'
# else:
# return mystring[0]
# result2 = list(map(splicer, names))
# def check_even (num):
# return num%2 == 0
# mynums = [1,2,3,4,5,6]
# # result = list(filter(check_even,mynums))
# lambda num: num ** 2
# square(3)
# list(map(lambda num:num**2, mynums))
# result =list(filter(lambda num: num%2 == 0, mynums))
# names = ['Andy', 'Eve', 'Sally']
# list(map(lambda x: x[0], names))
# list(map(lambda x: x[::-1], names))
# ========================================================
# NESTED STATEMENTS AND SCOPE
# ========================================================
# x = 25
# def printer()
# x = 50
# return x
# print(x)
# lambda num: num**2
# GLOBAL
# name = 'THIS IS A GLOBAL STRING'
# def greet():
# # ENCLOSING
# # name = 'Sammy'
# def hello():
# # LOCAL
# # name = 'IM A LOCAL'
# print('Hello ' + name)
# hello()
# greet()
# x = 50
# def func(x):
# print(f'X is {x}')
# # LOCAL REASSIGNMENT ON A GLOBAL VARIABLE!
# x = 'NEW VALUE'
# print(f'I JUST LOCALLY CHANGED X TO {x}')
# return x
# x = func(x)
# print(x)
# ========================================================
# FUNCTIONS AND METHODS - HOMEWORK ASSIGNMENT
# ========================================================
# import math
# def vol(rad):
# # 4/3π * radius
# return 4/3*math.pi*rad**3
# result = vol(2)
# def ran_check(num, low, high):
# if num >= low or num <= high:
# return f'{num} is in the range between {low} and {high}'
# result = ran_check(5, 2, 7)
# def ran_bool(num, low, high):
# return num >= low or num <= high
# result = ran_bool(3, 1, 10)
# def up_low(s):
# uppercase = 0
# lowercase = 0
# for letter in s:
# if letter.isupper():
# uppercase += 1
# elif letter.islower():
# lowercase += 1
# return f'Uppercase Count: {uppercase}\nLowercase Count: {lowercase}'
# s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
# result = up_low(s)
# print(result)
# def unique_list(lst):
# return list(set(lst))
# # result = unique_list([1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5])
# def multiply(numbers):
# result = 1
# for x in numbers:
# result *= x
# return result
# # import functools import reduce
# # def multiply2(numbers):
# # return reduce(lambda x, y: x*y, numbers)
# result = multiply([1,2,3,-4])
# # result2 = multiply2([1,2,3,-4])
# def palindrome(s):
# return s == s[::-1]
# result = palindrome('helleh')
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
abccount = []
for letter in str1.lower():
if letter not in abccount and letter != ' ':
abccount.append(letter)
return len(abccount) == 26
result = ispangram("The quick brown fox jumps over the lazy dog")
|
import pygame
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((1000,500))
red = 255,0,0
white = 255,255,255
black = 0,0,0
color_1 = 100,150,201
screen.fill(white)
while True:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
# screen, color, [x,y,w,h]
pygame.draw.rect(screen,red,[100,100,50,50])
pygame.draw.circle(screen, red, [250,250],80)
pygame.display.update() |
#All Rights Reserved to Ahmed Ezzat -> https://fb.com/ezzat001
import random
print('All Rights Reserved to Ahmed Ezzat -> https://fb.com/ezzat001')
print("[1] Gmail Mail List")
print("[2] Yahoo Mail List")
print("[3] Hotmail List")
type = int(input("Enter The Number : "))
nums = int(input("Do You want it example@email.com or example23@email.com Choose 1 or 2 :"))
amount = int(input("How Many E-Mails you Want : "))
name_listfile = open('name_list.txt','r')
content = name_listfile.readlines()
name_list1 = []
name_list2 = []
last_name_list = []
_last_name_list = []
for i in content:
i = i.replace('\n', '')
name_list1.append(i)
name_list2.append(i)
random.shuffle(name_list1)
random.shuffle(name_list2)
for i in range(len(name_list1)):
first_name = name_list1[i]
last_name = name_list2[i]
name = (first_name+''+last_name).lower()
_name = (first_name+'_'+last_name).lower()
last_name_list.append(name)
_last_name_list.append(_name)
c = 0
if type == 1: #Gmail
x = random.randint(1,2)
if x == 1:
if nums == 1:
for i in last_name_list:
c+=1
i = i+'@gmail.com'
print(i)
if c == amount:
break
elif nums ==2:
for i in last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@gmail.com'
print(i)
if c == amount:
break
else:
if nums == 1:
for i in _last_name_list:
c+=1
i = i+'@gmail.com'
print(i)
if c == amount:
break
if nums == 2:
for i in _last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@gmail.com'
print(i)
if c == amount:
break
elif type == 2: #Yahoo
x = random.randint(1,2)
if x == 1:
if nums == 1:
for i in _last_name_list:
c+=1
i = i+'@yahoo.com'
print(i)
if c == amount:
break
elif nums ==2 :
for i in _last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@yahoo.com'
print(i)
if c == amount:
break
else:
if nums == 1:
for i in last_name_list:
c+=1
i = i+'@yahoo.com'
print(i)
if c == amount:
break
elif nums == 2:
for i in last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@yahoo.com'
print(i)
if c == amount:
break
elif type == 3: #Hotmail
x = random.randint(1,2)
if x == 1:
if nums ==1:
for i in _last_name_list:
c+=1
i = i+'@hotmail.com'
print(i)
if c == amount:
break
elif nums ==2:
for i in _last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@hotmail.com'
print(i)
if c == amount:
break
else:
if nums ==1:
for i in last_name_list:
c+=1
i = i+'@hotmail.com'
print(i)
if c == amount:
break
elif nums ==2:
for i in last_name_list:
c+=1
r = random.randint(0,999)
i = i+str(r)+'@hotmail.com'
print(i)
if c == amount:
break
else:
print("Please Choose Between 1 , 2 and 3")
|
# remove()
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
#pop()
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
# pop() index
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
# delete index del
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
thislist = ["apple", "banana", "cherry"]
# del thislist
print(thislist)
thislist.clear()
print(thislist)
|
# uper and lower
a = "Hello, World"
print(a.upper())
print(a.lower())
# strip white space remove
b = " Hello, Bangladesh "
print(b.strip())
print(b.lstrip())
print(b.rstrip())
# replace string
a = "Hello, Bangladesh"
print(a.replace("Bangladesh", "Dhaka"))
# split separator function
a = "Hello, Bangladesh"
print(a.split(','))
|
# Many Values to Multiple Variables
x, y, z = "Bangladesh", "India", "Pakistan"
print(x)
print(y)
print(z)
# One Value of Multiple Variable
x = y = z = "Hello Bangladesh"
print(x)
print(y)
print(z)
# Unpack a Collection
city = ["Dhaka", "Feni", "Bogura"]
x, y, z = city
print(x)
print(y)
print(z)
a, b, c = ["Dhaka", "Feni", "Bogura"]
print(a)
print(b)
print(c)
|
from abc import ABC, abstractmethod
class Robot(ABC): # Abstract class
@abstractmethod
def show_name(self): # Abstract method
pass
class Human(Robot):
def __init__(self, name, age):
self.name = name
self.age = age
def show_name(self):
return self.name
def show_age(self):
return self.age
human1 = Human("Joy", 20)
print(human1.show_name()) |
"""Implementation of insertion sort algorithm in python
Starting at the beginning of the list find the appropriate position for each
element and reposition it
Space complexity:
n is the size of the list
O(n^3) - creates a new list of size n, n^2 times; not implicit in the algorithm
just this implementation
Time Complexity:
n is the size of the list
O(n^2)"""
def insertion_sort(num_list):
num_list = ["_"] + num_list
for i in range(2, len(num_list)):
insert_val = num_list[i]
for j in range(1, i):
if num_list[j] > insert_val:
num_list = num_list[:j] + [insert_val] + (num_list[j:i] +
num_list[i+1:])
break
return num_list[1:]
|
"""Colas: FIFO"""
#Cola de clientes en un banco
print("Clientes en el banco")
cola = ["Juan","María"]
#Llega nuevo cliente
cola.append("Luis")
#Imprimimos turnos
print("Turnos")
print(cola.index("Juan"),cola.index("María"),cola.index("Luis"))
print (cola)
for nombres in cola:
print(nombres)
#se atiende un cliente
print("Turno numero: ", cola.index("Juan"))
print (cola[0]," fue atendido")
cola.pop(0)
print (cola)
|
class Conta:
"""
Classe do tipo conta, seus atributos e métodos foram elaborados para simular umaconta bancária qualquer
"""
def __init__(self, ID, saldo):
"""
Metodo Construtor da classe Conta
"""
self.ID = ID
self.saldo = saldo
def __str__(self):
return 'ID: %s\nSaldo %.2f'%(self.ID, self.saldo)
def __add__(self,valor): # automatiza operações de soma
self.saldo += valor
def __sub__(self,valor): # automatiza operações de subtração
self.saldo -= valor
def __div__(self,valor): # automatiza operações de divisão
self.saldo /= valor
def __mult__(self,valor): # automatiza operações de multiplicação
self.saldo *= valor
def __call__(self):
return 'ID: %s'%(self.ID)
|
""" """
contato = {'Nome': 'Gabriel Ulisses', 'Celular' '9976-6160': '', 'Email' : 'ga@email.com'}
contato['Nome']
contato['Oficio'] = 'Estudante - Analista estagiário'
'Nome' in contato
'Endereco' in contato
contato_list = {}
contato_list[1] = contato
dic = {'f-acrescimo': lambda x: x+1, 'f-descrescimo': lambda x: x-1,'f-soma': lambda x,y: x+y,'f-subtracao' : lambda x,y: x-y}
dic['f-acrescimo'](5)
dic['f-soma'](5,10)
# ======================================== IMPRIMINDO CHAVES DE UM DICT ======================================== #
for chave in contato:
print(chave)
# ======================================== IMPRIMINDO VALORES DE UM DICT ======================================== #
for chave in contato:
print(contato[chave])
# ======================================== IMPRIMINDO CHAVES E VALORES DE UM DICT ======================================== #
for chave in contato:
print(chave," ", contato[chave])
# ======================================== MÉTODOS ======================================== #
''' GET '''
contato.get('Nome')
contato.get('Nome', 'Valor não encontrado.')
''' ITEMS '''
contato.items() # retorna a chave e valor em formato de tupla dentro de uma lista
''' KEYS '''
contato.keys() # retorna uma lista contendo todas as chaves do dicionário
''' VALUES '''
contato.values() # retorna uma lista contendo todos os valores do dicionário
''' COPY '''
contato_backup = contato.copy() # copia os valores de contato para a variável em questão
''' POP '''
contato.pop('Celular')# retorna o valor indexado e remove ambos(key and value)
''' POPITEM '''
contato.popitem() #retorna a chave e o valor do primeiro elemento do dict em formato de tupla e em seguida os remove
''' CLEAR '''
contato.clear() # limpa os valores do dict
''' SETDEFAULT '''
contato.setdefault('Telefone','(45) 0000-0000') # define um valor padrão para chave, se esta não existir, ela será criada
''' DICT '''
dict() # cria um dicionario vazio
]
|
string = """
interessante,
como o python trabalha com strings
de uma maneira versátil ."""
print(string, end = ' ')
print('Basquete')
lista = ['P','e','d','r','o']
for char in lista:
print(char,end = '')
print('\n')
for char in 'Pedro':
print(char)
"""
Strings e Bytes
"""
string = 'basquete'
byte = b'basquete'
print('%s %s'%(string, type(string)),'%s %s'%(byte, type(byte)))
string = 'se liga'
x = string.encode()
print(string.encode()) # string sendo convertida para string bytes
print(x.decode()) # string sendo convertida para string bytes
"""
Tabela ASCII
"""
ascii_array = []
for i in range(256):
print("%.3i - %s"%(i,chr(i)))
ascii_array.append(chr(i))
#print("%.3i - %c"%(i,i))
for i in ascii_array:
print("%s - %s"%(ord(i),i))
|
import cv2
import numpy as np
def clean_img(img, kernel_size=5, iterations=5):
'''
clean_img :
uses morphological operations to clean the image, in this case uses erosion to remove
extremly small items, and dilation to go back to original shape and closess some holes,
different combination provide diifferent results
docs: https://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html
img: threshhold image
kernel_size: the size of the morph kernel in pixels 5 by default, by default uses rectangle as a shape
iterations: nb of times operations are applied
returns
img: cleaned image
'''
kernel_s = np.ones((2, 2), np.uint8)
img = cv2.erode(img, kernel_s, iterations=iterations)
kernel_1 = np.ones((kernel_size, kernel_size), np.uint8)
img = cv2.erode(img, kernel_1, iterations=iterations)
img = cv2.dilate(img, kernel_1, iterations=iterations)
return img
|
import cv2
def contours_extraction(img):
'''
Basic contour extraction from threshold image
img: img
returns
ctr: list of all extracted contours,
h: containes hierarchical information about every contour,
for every contour [nextCtr_id, prevCtr_id, FirstChildCtr_id, parentCtr_id ]
'''
ctr, h = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return ctr, h[0]
def contour_data(cnt, epsilon=0.001):
'''
Extracts some useful informations from a contour like mass center, area and perimeter, more features can be extracted
using cv2.moments
Also simplifies the contours
cnt: single contour,
epsilon: simplification strength
returns
area: area of contour will be used for filtering
approx: simplified polygon
'''
M = cv2.moments(cnt)
#cx = int(M['m10']/M['m00'])
#cy = int(M['m01']/M['m00'])
area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt, True)
epsilon = epsilon * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
return area, approx
def classify_contour(h, idx, cls_dict):
'''
classifies the contour, on either region of room
for the given contour if there is no parent then the contour is a region, else is room
h: contourss hierarchical features
idx: index of the contour to classify
cls_dict: dictionnary containing classification of the different contours
returns
updated classification dict
'''
p_idx = h[idx][3]
p_p_idx = h[p_idx][3]
if p_idx not in cls_dict:
if p_p_idx == -1:
p_cls = 0
else:
cls_dict = classify_contour(h, idx, cls_dict)
p_cls = cls_dict[p_idx]
else:
p_cls = cls_dict[p_idx]
cls = p_cls + 1
cls_dict[idx] = cls
return cls_dict
# Main function to extract the road mask
def generate_regions(img, epsilon=0.001):
'''
Generate the regions and rooms from an image
img: thresholded image
epsilon :: should be replaced b **kwags
returns
img: cleaned img
ctr: all extracted contours
regions: classified regions
rooms: classified rooms
'''
img_area = img.shape[0] * img.shape[1]
max_area = 0.8*img_area
min_area = 400
ctr, h = contours_extraction(img) # extract contours and hierarchical data
classes_dict = dict()
approxs = [None] * len(ctr)
for i in range(len(ctr)): # classify contours
cnt = ctr[i]
#cnt_area, approx = ctr_data(cnt, epsilon)
cnt_area, approxs[i] = contour_data(cnt, epsilon)
# If area is very small or very big then, thea features are useless...
if cnt_area < max_area and cnt_area > min_area:
classes_dict = classify_contour(h, i, classes_dict)
else:
classes_dict[i] = -1
base_region_idx = 0 if len(list(classes_dict.values())) < 2 else min(
[i for i in list(classes_dict.values()) if i >= 0])
regions = [approxs[i] for i in range(
len(ctr)) if classes_dict[i] == base_region_idx and h[i][2] != -1]
rooms = [approxs[i]
for i in range(len(ctr)) if classes_dict[i] > base_region_idx]
return img, ctr, classes_dict, regions, rooms
|
file1 = "test2DSamcra"
file2 = "2Dres-sorted"
def in_dict(filename):
dict = {}
with open(filename,'r') as f:
for l in f.readlines():
l = l.strip()
if len(l.split(" ")) == 3:
node, delay, cost = l.split(" ")
else:
node, delay, cost, _ = l.split(" ")
cost = int(cost)
if node not in dict:
dict[node] = {}
if delay in dict[node]:
dict[node][delay] = min(dict[node][delay], cost)
else:
dict[node][delay] = cost
return dict
dic1 = in_dict(file1)
dic2 = in_dict(file2)
# check if dic1 is included in dic2
for node in dic1:
for delay in dic1[node]:
if node not in dic2:
print("NODE {} not in {}".format(node, file2))
continue
elif delay not in dic2[node]:
print("DELAY {} not in {} for node {}".format(delay, file2, node))
else:
cost1 = dic1[node][delay]
cost2 = dic2[node][delay]
if cost1 != cost2:
print("{} vs {} for node {} and delay {}".format(cost1,cost2, node, delay))
|
import pandas as pd
import sqlite3
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/00476/buddymove_holidayiq.csv')
df = df.rename(columns={'User Id': 'UserId'})
# CREATING DATA BASE
conn = sqlite3.connect('Reviews.db')
c = conn.cursor()
# Create TABLE
c.execute('CREATE TABLE REVIEWS (UserId text, Sports number,Religious number, Nature number,'
'Theatre number, Shopping number, Picnic number)')
# Saving Created Table into our Data Base
conn.commit()
# Convert DF to SQL
df.to_sql('REVIEWS', conn, if_exists='replace', index=False)
c.execute("""
SELECT * FROM REVIEWS
""")
for row in c.fetchall():
print(row)
|
#This function computes the factorial
#of a number entered by the user
def factor():
n = int(input("Please enter a whole number: "))
fact = 1
for factor in range(1, n+1):
fact = fact * factor
print("The factorial of ",n," is",fact)
factor()
|
# This is opening and reading the .txt file
log_file = open("um-server-01.txt")
# Creating a function
def sales_reports(log_file):
# looping over the txt file
for line in log_file:
# removing any trailing character
line = line.rstrip()
# creating variable to dispay the day
day = line[0:3]
# if the day is tuesday
if day == "Mon":
# print the whole line for tues
print(line)
# calling function witht he txt file
# sales_reports(log_file)
def ten(log_file):
for line in log_file:
line = line.rstrip()
str = line[15:18]
to_num = int(str)
if to_num > 10:
print(line)
ten(log_file)
|
#!/usr/bin/python -tt
import sys
def repeat(s, exclaim):
"""
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s # can also use "s * 3" which is faster (Why?)
if exclaim:
result = result + '!!!'
return result
"""
Python's "repeat" operator, meaning that '-' * 10 gives '----------',
a neat way to create an onscreen "line." In the code comment, we hinted that * works faster than +,
the reason being that * calculates the size of the resulting object once whereas with +,
that calculation is made each time + is called. Both + and * are called "overloaded" operators because they mean
different things for numbers vs. for strings (and other data types).
"""
# Provided simple test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
# +++your code here+++
# LAB(begin solution)
if len(s) < 2:
return ''
first2 = s[0:2]
last2 = s[-2:]
return first2 + last2
# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
# +++your code here+++
# LAB(begin solution)
front = s[0]
back = s[1:]
fixed_back = back.replace(front, '*')
return front + fixed_back
# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
# +++your code here+++
# LAB(begin solution)
a_swapped = b[:2] + a[2:]
b_swapped = a[:2] + b[2:]
return a_swapped + ' ' + b_swapped
def Hello(name):
name = name + '!!!!'
print 'Hello', name
if name == 'Guido':
print repeeeet(name) + '!!!'
else:
print repeat(name, False)
def main():
print 'Strings'
print 'Hi %s well done %d' % ( "raj", 25)
print repeat('Yay', False) ## YayYayYay
print repeat('Woo Hoo', True) ## Woo HooWoo HooWoo Hoo!!!
Hello(sys.argv[1])
print
print 'both_ends'
test(both_ends('spring'), 'spng')
test(both_ends('Hello'), 'Helo')
test(both_ends('a'), '')
test(both_ends('xyz'), 'xyyz')
print
print 'fix_start'
test(fix_start('babble'), 'ba**le')
test(fix_start('aardvark'), 'a*rdv*rk')
test(fix_start('google'), 'goo*le')
test(fix_start('donut'), 'donut')
print
print 'mix_up'
test(mix_up('mix', 'pod'), 'pox mid')
test(mix_up('dog', 'dinner'), 'dig donner')
test(mix_up('gnash', 'sport'), 'spash gnort')
test(mix_up('pezzy', 'firm'), 'fizzy perm')
#Standard boilerplate to call the main() funtion.
if __name__ == '__main__':
main()
|
import tkinter as tk
class LeftFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.l_text = tk.Text(self.parent, width = 40, height = 10)
self.l_text.grid(row=0, column=0)
self.l_text.bind("<Key>", self.return_data)
def return_data(self, event):
data = self.l_text.get(1.0, tk.END)
# uses the variable name "app" assigned to the main window class.
# then calls a method inside that class to append the data from another class text box
app.add_to_right_frame(data)
class RightFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.r_text = tk.Text(self.parent, width = 40, height = 10)
self.r_text.grid(row=0, column=1)
self.r_text.bind("<Key>", self.return_data)
print( self.parent.__str__ )
#print(self.parent.__dict__)
print( self.__str__ )
def return_data(self, event):
data = self.r_text.get(1.0, tk.END)
# uses the variable name "app" assigned to the main window class.
# then calls a method inside that class to append the data from another class text box
app.add_to_left_frame(data)
class MainWindow(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.master = root
self.main_frame = tk.Frame(self.master)
self.main_frame.grid(row=0, column=0, sticky="nsew")
#makes a class attribute of each frame so it can be manipulated later
self.f1 = LeftFrame(self.main_frame)
self.f2 = RightFrame(self.main_frame)
def add_to_left_frame(self, data):
self.f1.l_text.delete(1.0, tk.END)
self.f1.l_text.insert(1.0, data)
def add_to_right_frame(self, data):
self.f2.r_text.delete(1.0, tk.END)
self.f2.r_text.insert(1.0, data)
if __name__ == "__main__":
root = tk.Tk()
app = MainWindow(root)
root.mainloop() |
"""**1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.
* Approach:
* Have two boolean arrays to keep track of row and column that has zero
* Nullify those rows and columns
* Time Complexity O(n^2)(row*column); Space Complexity O(n)
*/
"""
class ZeroMatrix_WithLists(object):
def zeroMatrix(self, matrix):
row_lst = [False]*len(matrix) # have two lists with boolean values
column_lst = [True]*len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0: # track the row and column that has zero
row_lst[i] = True
column_lst[j] = True
for i in range(len(row_lst)):
if(row_lst[i]): self.rowzero(matrix, row_lst[i]) # if zero in row, nullify row
for j in range(len(column_lst)):
if(column_lst[j]): self.columnzero(matrix, column_lst[j]) # if zero in column, nullify column
return matrix
def rowzero(self, matrix, row):
for j in range(len(matrix[0])):
matrix[row][j] = 0 # make row as zero
def columnzero(self, matrix, column):
for i in range(len(matrix)):
matrix[i][column] = 0 # make column as zero
ze = ZeroMatrix_WithLists()
print(ze.zeroMatrix([[1, 1, 1], [1, 0, 1], [1, 1, 1]]))
|
"""*Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the
intersecting node. Note that the intersection is defined based on reference, not value. That is, if the
kth node of the first linked list is the exact same node (by reference) as the jth node of the second
linked list, then they are intersecting.
** Approach: get the length of lists, adjust length to be equal, compare to find intersection
* Time O(n); Space O(1)
*"""
class IntersectionofLinkedList(object):
def __init__(self):
self.head = None
def intersectlist(self, head1, head2):
len1 = self.length(head1)
len2 = self.length(head2)
if len1 > len2:
head1 = head1.next # adjust length of lists
len1 -= 1
if len2 > len1:
head2 = head2.next
len2 -= 1
while head1 != head2:
head1 = head1.next # when they become equal return node
head2 = head2.next
return head1
def length(self, head):
curr = head
count = 0
while curr:
curr = curr.next
count += 1
return count
class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
list1 = IntersectionofLinkedList() # create list 1
list1.head = Node(4)
list1.head.next = Node(1)
list1.head.next.next = Node(8)
list1.head.next.next.next = Node(4)
list1.head.next.next.next.next = Node(5)
list2 = IntersectionofLinkedList() # create list 2
list2.head = Node(5)
list2.head.next = Node(1)
list2.head.next.next = Node(0)
list2.head.next.next.next = list1.head.next.next
print(list1.intersectlist(list1.head, list2.head).data)
|
"""
Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks.
"""
class QueueviaStacks(object):
def __init__(self):
self.newest = []
self.oldest = []
def enqueue(self, item):
self.newest.append(item) # push item into new stack
def dequeue(self):
self.shiftstacks()
print self.oldest
return self.oldest.pop() # get top element, first shift and then pop from oldest
def size(self):
return len(self.oldest)+len(self.newest)
def peek(self):
self.shiftstacks()
return self.oldest[-1] # get top element, first shift and then peek from oldest
def shiftstacks(self):
if len(self.oldest) == 0:
while len(self.newest) != 0:
self.oldest.append(self.newest.pop()) # shift from new to old
questck = QueueviaStacks()
questck.enqueue(1)
questck.enqueue(2)
questck.enqueue(3)
questck.enqueue(4)
questck.enqueue(5)
questck.enqueue(6)
questck.enqueue(7)
questck.enqueue(8)
questck.enqueue(9)
print(questck.dequeue())
print(questck.dequeue())
print(questck.dequeue())
print(questck.size())
print(questck.peek())
print(questck.dequeue())
|
"""* 4.2 Minimal Tree:
* Given a sorted (increasing order) array with unique integer elements,
* write an algorithm to create a binary search tree with minimal height.
* """
from TreeNode import TreeNode
class MinimalTree(object):
def createBSTT(self, sortedlist):
return self.createBST(sortedlist, 0, len(sortedlist)-1)
def createBST(self, sortedlist, start, end):
if start > end:
return None
mid = (start+end)/2
node = TreeNode(sortedlist[mid])
node.left = self.createBST(sortedlist, start, mid-1)
node.right = self.createBST(sortedlist, mid+1, end)
return node
def printNode(self, node):
if node:
self.printNode(node.left)
print(node.data),
self.printNode(node.right)
mt = MinimalTree()
node = mt.createBSTT([1, 2, 3, 4, 5, 6, 7])
mt.printNode(node)
|
"""One Away: There are three types of edits that can be performed on strings: insert a character,
* remove a character, or replace a character. Given two strings, write a function to check if they are
* one edit (or zero edits) away.
* EXAMPLE
* pale, ple -> true
* pales, pale -> true
* pale, bale -> true
* pale, bae -> false
* Approach - increase count if there is a mismatch in character or length
* increase index 1 if string1 length is more and index 2 if string 2 length is more
* Time Complexity O(n); Space Complexity O(1)
"""
class OneEditString(object):
def oneEditString(self, str1, str2):
len1 = len(str1)
len2 = len(str2)
index1 = 0
index2 = 0
count = 0
if(abs(len1-len2) > 1): return False
while((index1 < len1) & (index2 < len2)):
if(str1[index1] != str2[index2]):
if(count == 1):
return False
if(len1 < len2): index2 += 1
elif(len1 > len2): index1 += 1
else:
index1 += 1
index2 += 1
count += 1
else:
index1 += 1
index2 += 1
if((index1 < len1) | (index2 < len2)): count += 1
return count == 1
one = OneEditString()
print(one.oneEditString("pale", "bale"))
print(one.oneEditString("ale", "bale"))
print(one.oneEditString("pale", "balee"))
print(one.oneEditString("ale", "ale"))
print(one.oneEditString("ble", "pale"))
print(one.oneEditString("ble", "paleeeee"))
|
"""Up your Python console game with formatted text!
Requirements:
* Python 3.7+
Works great in JetBrains PyCharm console.
No idea about other consoles!
Try: ``>>> p = FancyPrinter().demo()``
"""
__author__ = "Christopher Couch"
__license__ = "MIT"
__version__ = "2020-06"
class FancyPrinter(object):
def __init__(self):
"""Defines color dictionary."""
# RGB values
dk = 64
med = 128
lt = 192
wash1 = 153 # "wash" means "to wash out a color" and make it lighter
wash2 = 205
# Define the colors
self.rgb_dict = dict(
# GREYSCALE
black=(0, 0, 0),
dark_grey=(dk, dk, dk),
medium_grey=(med, med, med),
light_grey=(lt, lt, lt),
white=(255, 255, 255),
# RED
dark_red=(dk, 0, 0),
medium_red=(med, 0, 0),
red=(255, 0, 0),
light_red=(255, max(wash1 - 50, 0), max(wash1 - 50, 0)), # wash values too light; looks pink; offset 50
# ORANGE
dark_orange=(dk, int(dk / 2), 0),
medium_orange=(med, int(med / 2), 0),
orange=(255, int(255 / 2), 0),
light_orange=(255, wash2, wash1),
# YELLOW
dark_yellow=(dk, dk, 0),
medium_yellow=(med, med, 0),
yellow=(255, 255, 0),
light_yellow=(255, 255, wash1),
# CHARTREUSE
dark_chartreuse=(int(dk / 2), dk, 0),
medium_chartreuse=(int(med / 2), med, 0),
chartreuse=(int(255 / 2), 255, 0),
light_chartreuse=(wash2, 255, wash1),
# GREEN
dark_green=(0, dk, 0),
medium_green=(0, med, 0),
green=(0, 255, 0),
light_green=(wash1, 255, wash1),
# CYAN
dark_cyan=(0, dk, dk),
medium_cyan=(0, med, med),
cyan=(0, 255, 255),
light_cyan=(wash1, 255, 255),
# CERULEAN
dark_cerulean=(0, int(dk / 2), dk),
medium_cerulean=(0, int(med / 2), med),
cerulean=(0, int(255 / 2), 255),
light_cerulean=(wash1, wash2, 255),
# BLUE
dark_blue=(0, 0, dk),
medium_blue=(0, 0, med),
blue=(0, 0, 255),
light_blue=(wash1, wash1, 255),
# PURPLE
dark_purple=(int(dk / 2), 0, dk),
medium_purple=(int(med / 2), 0, med),
purple=(127, 0, 255),
light_purple=(wash2, wash1, 255),
# MAGENTA
dark_magenta=(dk, 0, dk),
medium_magenta=(med, 0, med),
magenta=(255, 0, 255),
light_magenta=(255, wash1, 255),
# PINK
dark_pink=(dk, 0, int(dk / 2)),
medium_pink=(med, 0, int(med / 2)),
pink=(255, 0, int(255 / 2)),
light_pink=(255, wash1, wash2),
# SPECIAL NAMES
normal=(med, med, med), # "Normal" depends on console config. We'll parse this selection separately.
hlink=(0, int(255 / 2), 255), # cerulean
warning=(255, 255, 0), # yellow
error=(255, max(wash1 - 50, 0), max(wash1 - 50, 0)), # light_red
)
return
def __repr__(self):
return 'Console print with style!'
def __call__(self, *args, **kwargs):
self.fancy_print(*args, **kwargs)
def fancy_print(self, string='Default message', **kwargs):
"""Prints text to console using a variety of formatting methods.
Foreground colors, background colors, and format options can be arbitrarily combined.
|
**Foreground and background colors available:**
* black, white, dark_grey, medium_grey, light_grey
* red, orange, yellow, chartreuse, green, cyan, cerulean, blue, purple, magenta, pink
* dark, medium, and light versions of the colors, e.g. 'dark_red', 'medium_green', 'light_blue'
* Special "colors' with automatic formatting: 'hlink', 'warning', 'error', 'normal'
|
**Formats available:**
* bold, dim, underscore, italic, strikethrough, framed
* 'highlight': Black text with yellow background
|
For reference see: https://en.wikipedia.org/wiki/ANSI_escape_code
Arguments:
string (obj): Required. The text to print.
Can also accept objects that convert nicely using str(object).
Keyword Arguments:
fg (str): Optional. Foreground color. If omitted, the standard terminal color will be used.
bg (str): Optional. Background color. If omitted, the standard terminal color will be used.
bold (Boolean): Optional. Default is False.
underscore (Boolean): Optional. Default is False.
italic (Boolean): Optional. Default is False.
strikethrough (Boolean): Optional. Default is False.
framed (Boolean): Optional. Default is False.
highlight (Boolean): Optional. Sets background color to yellow. Default is False.
header (Boolean): Optional. If true, string is printed between two lines of repeated '='. Default is False.
end (str): Optional. If '', a final linebreak will not be included. Default is None.
Returns:
No returns.
"""
# Convert to string if needed.
# This means we can actually accept most objects.
string = str(string) if not isinstance(string, str) else string
# Parse kwargs
f = kwargs.get('fg', 'normal')
b = kwargs.get('bg', 'normal')
bold = kwargs.get('bold', False)
underscore = kwargs.get('underscore', False)
italic = kwargs.get('italic', False)
strikethrough = kwargs.get('strikethrough', False)
framed = kwargs.get('framed', False)
highlight = kwargs.get('highlight', False)
header = kwargs.get('header', False)
end = kwargs.get('end', None)
# Validate kwargs
valid_kwargs = [
'fg',
'bg',
'bold',
'underscore',
'italic',
'strikethrough',
'framed',
'highlight',
'header',
'end',
]
for k in kwargs:
if k not in valid_kwargs:
msg = f'\'{k}\' is not a valid keyword argument. Valid keywords are: {valid_kwargs}'
raise KeyError(msg)
# Validate booleans
for my_bool in [bold, underscore, italic, strikethrough, framed, highlight, header]:
if not isinstance(my_bool, bool):
msg = f'\'b\' must be Boolean but you gave type: {type(my_bool)}'
raise TypeError(msg)
# =========================================================
# Initial boolean options - more follow below
# =========================================================
# Handle highlight option
if highlight:
f = 'black'
b = 'yellow'
# Handle header option
if header:
string = '\n' + '='*80 + '\n' + string + '\n' + '='*80 + '\n'
# =========================================================
# Special foreground "color" options
# =========================================================
special_color_list = ['normal', 'hlink', 'warning', 'error']
# Handle normal option
if f == 'normal':
# Just use the RGB values from dict
pass
# Handle hlink option
if f == 'hlink':
f = 'cerulean'
b = 'normal'
underscore = True
# Handle warning option
if f == 'warning':
f = 'yellow'
b = 'normal'
bold = True
# Handle error option
if f == 'error':
f = 'light_red'
b = 'normal'
bold = True
# =========================================================
# Validate
# =========================================================
# Validate selections
if f not in self.rgb_dict:
raise RuntimeError(f'Foreground color selection \'{f}\' is invalid. '
f'Please choose one of:\n{list(self.rgb_dict.keys())}')
# Validate selections
if b not in self.rgb_dict:
raise RuntimeError(f'Background color selection \'{b}\' is invalid. '
f'Please choose one of:\n{list(self.rgb_dict.keys())}')
# =========================================================
# Process
# =========================================================
# Process color selections
f_tuple = self.rgb_dict[f]
b_tuple = self.rgb_dict[b]
fR, fG, fB = f_tuple[0], f_tuple[1], f_tuple[2]
bR, bG, bB = b_tuple[0], b_tuple[1], b_tuple[2]
# Build list of formatting attributes
attributes = list()
if bold: attributes.append('1')
if underscore: attributes.append('4')
if italic: attributes.append('3')
if strikethrough: attributes.append('9')
if framed: attributes.append('51')
code = ';'.join(attributes)
code = ';' + code if len(code) > 0 else code
# Build final string for console print using 24-bit (True Color)
if f != 'normal' and b != 'normal':
new_str = f'\x1b[38;2;{fR};{fG};{fB}{code};48;2;{bR};{bG};{bB}m{string}\x1b[0m'
elif f == 'normal' and b != 'normal':
new_str = f'\x1b[{code};48;2;{bR};{bG};{bB}m{string}\x1b[0m'
elif f != 'normal' and b == 'normal':
new_str = f'\x1b[38;2;{fR};{fG};{fB}{code}m{string}\x1b[0m'
else:
new_str = f'\x1b[{code}m{string}\x1b[0m'
# Print to console
print(new_str, end=end)
return
def demo(self, string='Foo Fighters Rule'):
"""Prints a demo to console."""
special_fg_colors = ['normal', 'hlink', 'warning', 'error']
self.fancy_print('FOREGROUND COLORS', fg='light_cerulean', header=True)
# Show all colors - foreground
for c in self.rgb_dict:
if c not in special_fg_colors:
print(f'\t> {c}: '.ljust(25, ' '), end='')
self.fancy_print(string, fg=c, bold=True)
self.fancy_print('BACKGROUND COLORS', fg='light_cerulean', header=True)
# Show all colors - background
for c in self.rgb_dict:
if c not in special_fg_colors:
print(f'\t> {c}:'.ljust(25, ' '), end='')
self.fancy_print(string, fg='light_grey', bg=c, bold=False)
# Show special "colors" with additional treatments
self.fancy_print('SPECIAL FOREGROUND COLORS WITH AUTOMATIC TREATMENTS', fg='light_cerulean', header=True)
for c in special_fg_colors:
print(f'\t> {c}:'.ljust(25, ' '), end='')
self.fancy_print(string, fg=c)
self.fancy_print('FORMATTING WITH BOOLEAN FLAGS', fg='light_cerulean', header=True)
# Some formatting
options = ['bold', 'italic', 'underscore', 'strikethrough', 'framed', 'highlight']
for o in options:
kwarg_dict = {'fg': 'light_cerulean', o: True}
print(f'\t> {o}:'.ljust(25, ' '), end='')
self.fancy_print(string, **kwarg_dict)
return
def fancy_print(string=None, **kwargs):
"""Prints text to console using a variety of formatting methods.
Foreground colors, background colors, and format options can be arbitrarily combined.
|
**Foreground and background colors available:**
* black, white, dark_grey, medium_grey, light_grey
* red, orange, yellow, chartreuse, green, cyan, cerulean, blue, purple, magenta, pink
* dark, medium, and light versions of the colors, e.g. 'dark_red', 'medium_green', 'light_blue'
* Special "colors' with automatic formatting: 'hlink', 'warning', 'error', 'normal'
|
**Formats available:**
* bold, dim, underscore, italic, strikethrough, framed
* 'highlight': Black text with yellow background
|
For reference see: https://en.wikipedia.org/wiki/ANSI_escape_code
Arguments:
string (obj): Required. The text to print.
Can also accept objects that convert nicely using str(object).
Keyword Arguments:
fg (str): Optional. Foreground color. If omitted, the standard terminal color will be used.
bg (str): Optional. Background color. If omitted, the standard terminal color will be used.
bold (Boolean): Optional. Default is False.
underscore (Boolean): Optional. Default is False.
italic (Boolean): Optional. Default is False.
strikethrough (Boolean): Optional. Default is False.
framed (Boolean): Optional. Default is False.
highlight (Boolean): Optional. Sets background color to yellow. Default is False.
header (Boolean): Optional. If true, string is printed between two lines of repeated '='. Default is False.
end (str): Optional. If '', a final linebreak will not be included. Default is None.
demo (bool): Optional. If True, a demonstration will be printed to the console.
Returns:
No returns.
"""
demo = kwargs.get('demo', False)
p = FancyPrinter()
if demo:
p.demo(string)
else:
p.fancy_print(string, **kwargs)
return
|
'''
Created on Jan 25, 2018
@author: James
===========================================================
Thanks to http://naelshiab.com/tutorial-send-email-python/
for the short and easy explanation of making an E-mail bot!
===========================================================
'''
import smtplib
# Multipurpose Internet Mail Extensions (MIME)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def Mailer():
file = open("Mechanics/text.txt" , 'r')
whatIsThis = file.readline()
sendingAddress = file.readline()
recievingAddress = file.readline()
file.close
# Breaks Email into multiple parts allowing detailed info such as a subject (Like a descriptor, or property)
message = MIMEMultipart()
message['From'] = sendingAddress
message['To'] = recievingAddress
message['Subject'] = 'Daily Numbers'
# Messages body text
body = 'See attachments'
# Attaches body to message in plain format
message.attach(MIMEText(body, 'plain'))
# Setups Excel file for attachment
workbook = 'Mechanics/Log.xlsx'
attachment = open(workbook, 'rb')
part = MIMEBase('application', 'octet-stream')
'''
=======================================================================================
octet-stream is a binary file
This is the default value for a binary file. As it really means unknown binary file,
browsers usually don't automatically execute it, or even ask if it should be executed.
They treat it as if the Content-Disposition header was set with the value attachment
and propose a 'Save As' file.
=======================================================================================
---------------------------------------------------------------------------------------
THANKS TOO: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
---------------------------------------------------------------------------------------
'''
# Encodes and adds attachment information
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= Log.xlsx")
# Attaches attachment
message.attach(part)
# Makes secure connection to gmail servers
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sendingAddress, whatIsThis)
# Converts message "Object" to string
text = message.as_string()
# Sends mail with actual email address as sender (spoofing is bad!) and disconnect from gmails server.
server.sendmail(sendingAddress, recievingAddress, text)
server.quit()
|
from calculator import Calculator
calc= Calculator()
print(calc.addition(1,2))
print(calc.subtraction(1,2))
print(calc.multiplication(1,2))
print(calc.division(2,1))
print(calc.exponent(1,3))
print(calc.square_root(4))
|
import requests
import random
import re
api_url = 'https://reddit.com'
last_url = ''
class APIError(Exception):
pass
def get(url, no_cache=False):
headers = {
'User-Agent': 'cybits a cute IRC bot',
}
if no_cache:
headers['Cache-Control'] = 'private,max-age=0'
return requests.get(api_url + url, headers=headers)
def normify_url(url):
return api_url + re.sub('\.json.*$','',url)
def get_hot_posts(subreddit):
"""Returns a raw JSON response containing hot posts for the specified
subreddit from the API.
"""
url = '/r/%s/hot.json' % subreddit
r = get(url)
r.raise_for_status()
return r.json()
def extract_random_comment(post, min_length=None):
"""Performs an additional API query in order to extract a random post from
a post. Post parameter should be a data field of a result of a call to
get_hot_posts.
"""
url = '%s.json?sort=random' % post['permalink'].rstrip('/')
r = get(url)
r.raise_for_status()
j = r.json()
comments = [c for c in j[1]['data']['children'] if 'body' in c['data']]
if min_length:
comments = [c for c in comments if len(c['data']['body']) >= min_length]
if len(comments) > 0:
global last_url
last_url = normify_url(url)
return comments[0]
else:
raise APIError('The selected post doesn\'t have any comments')
def get_random_comment(subreddit, min_length=None):
"""Returns a text of a random comment from a specified subreddit (for
a certain value of random).
"""
# Get the hot posts.
p = get_hot_posts(subreddit)
posts = p['data']['children']
if len(posts) == 0:
raise APIError('This subreddit contains no posts')
# Iterate over the random permutation of the hot posts and attempt to
# select a random comment.
random.shuffle(posts)
for post in posts:
if post['data']['num_comments'] > 0:
try:
c = extract_random_comment(post['data'], min_length)
return c['data']['body']
except APIError:
# This will be a predicatable error: no comments (maybe they
# were removed between queries) so we can just carry on
pass
raise APIError('Could not find any comments in the top posts')
|
from random import randint as base_randint
def randint(maximum=100, minimum=0):
"""
Generate a random integer between `minimum` and `maximum`.
Args:
- `maximum` - The maximum integer that can be generated (defaults to 100)
- `minimum` - The minimum integer that can be generated (defaults to 0)
Returns:
A random integer
Usage:
``random()``
``random(300)``
``random(10, 5)``
``random(minimim=20, maximum=40)``
"""
return base_randint(minimum, maximum)
|
# creat function: equal to strip
# the following code not work, how to do that...??
print('请输入您想要从首尾去除的字符或其它参数:')
text = input()
import re
myfun = re.compile(r'text')
print('请输入一行字符串:')
selfString = str(input())
mo = myfun.sub('',selfString)
print(mo)
|
x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s. " % (binary, do_not)
print (x)
print (y)
print ("I said : %r." %x )
print ("I also said : '%s'. " %y)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print (joke_evaluation %hilarious)
w = "This is the left side of ..."
e = "a string with right side."
print (w + e)
|
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print "The animal at 1 is %s." %animals[1]
print "The third animal is at 2 and is a %s." %animals[2]
print "The first animal is at 0 and is a %s." %animals[0]
print "The animal at 3 is %s." %animals[3]
print "The fifth animal is at 4 and is a %s." %animals[4]
print "The animal at 2 is %s." %animals[2]
print "The sixth animal is at 5 and is a %s." %animals[5]
print "The animal at 4 is a %s." %animals[4]
|
def get_fused_sequence_complement(sequence_a, sequence_b):
"""
This function receives two sequences of DNA and combines them, iterating over
the two sequences and alternating between characters from each one. If one
sequence is longer than the other, it will only add characters from both until
the shorter sequence runs out of characters, at which point it will simply add
the characters from the longer string onto the end. After it has completed
this, it passes the combo string to get_complement, which returns a complement
DNA string that this function then returns to its reference in main().
:param sequence_a: the first of the two sequences passed
:param sequence_b: the second of the two sequences passed
:return: the complement of the combo of the two strings received
"""
combo_sequence = ""
if len(sequence_a) >= len(sequence_b):
longer_sequence = sequence_a
else:
longer_sequence = sequence_b
for x in range(len(longer_sequence)):
if len(sequence_a) > x:
if sequence_a[x] in ("A", "T", "C", "G"):
combo_sequence = combo_sequence + sequence_a[x]
if len(sequence_b) > x:
if sequence_b[x] in ("A", "T", "C", "G"):
combo_sequence = combo_sequence + sequence_b[x]
comp_sequence = get_complement(combo_sequence)
return comp_sequence
def get_complement(combo_sequence):
"""
This function receives a combined DNA strand from get_fused_sequence_complement
and iterates over the string, constructing a new string where each character
is the pairing nucleotide to the original character.
:param combo_sequence: the already-combined sequence of the two initial
sequences
:return: the complement sequence to the one passed in
"""
comp_sequence = ""
for x in range(len(combo_sequence)):
char = combo_sequence[x]
if char == "A":
comp_sequence += "T"
elif char == "C":
comp_sequence += "G"
elif char == "T":
comp_sequence += "A"
elif char == "G":
comp_sequence += "C"
return comp_sequence
def main():
"""
Just some sample behavior. Feel free to try your own!
"""
sequence_a = "XXATGTGT"
sequence_b = "ACGTGTATGCTGTGTGTACGTGTGATCG"
fused_sequence_complement = get_fused_sequence_complement(sequence_a, sequence_b)
print(fused_sequence_complement)
# DO NOT WRITE CODE BELOW THIS LINE
if __name__ == '__main__':
main()
|
def string_bits(str):
res = ""
n = len(str)
for x in range(n):
if x % 2 == 0:
res = res + str[x]
return res |
sum = 0
for num in range(1, 101):
a = int(input())
sum += a
print(sum)
|
a = int(input())
b = int(input())
if a > b:
print (a)
else:
print (b)
|
a = int(input())
for num in range(1, a + 1):
if a % num == 0:
print(num)
|
def extra_end(str):
n = len(str)
last = str[n - 2:]
return last + last + last |
N = int(input())
sum = 0
for num in range(N):
a = int(input())
if a == 0:
sum += 1
print(sum)
|
def string_times(str, n):
word = ""
for x in range(n):
word += str
return word
|
# 1. Escribe un programa Python que imprima "Hola Mundo", si a es mayor que b.
a = int(input('Ingrese un valor entero "a": '))
b = int(input('Ingrese un valor entero "b": '))
if a > b:
print('Se imprimirá el saludo: ')
print('Hola Mundo')
else:
print('No se imprimirá el saludo.') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Script to find sentences
which contain both a and b markers.
'''
import sys
reload(sys)
sys.setdefaultencoding('utf8')
final_sents = []
sents_parts = []
i = -1
sents = []
def init(filename):
global sents, i, final_sents, sents_parts
fp = open(filename, 'r')
sents = fp.read().split('\n\n')
sents.pop()
final_sents = []
sents_parts = []
i = -1
breakdown()
def breakdown():
global i, sents, sents_parts
for each in sents:
i += 1
sents_parts.append(each.split('\n'))
parts = []
for every in sents_parts[i]:
parts.append(every.split('\t'))
sents_parts[i] = parts
def separate_a_b_sents(fp, a, b):
global sents_parts
sent_a_b = []
sent_roots = []
init(fp)
#if a=='k1' and b=='k2':
rem = []
for i in xrange(len(sents_parts)):
for j in xrange(len(sents_parts[i])):
part = sents_parts[i][j]
if(part[1] == 'कि'):
rem.append(sents_parts[i])
break
for each in rem:
sents_parts.remove(each)
for i in xrange(len(sents_parts)):
temp = []
for j in xrange(len(sents_parts[i])):
part = sents_parts[i][j]
#print part
if part[7] == a:
temp.append(part[6])
elif part[7] == b and part[6] in temp:
sent_a_b.append(sents_parts[i])
sent_roots.append(part[6])
break
return (sent_a_b, sent_roots)
if __name__ == "__main__":
sent_a_b = separate_a_b_sents(sys.argv[1], 'k1', 'k2')
print sent_a_b
|
v=int(input('Introduceti varsta:'))
print("Greutatea ideala este de", 2*v+8, "kg, Inaltimea ideala este de", 5*v+80, "cm") |
n=int(input('Introduceti numarul:'))
print("Tabla inmultirii cu", n, ':')
print(n, '*1=', n*1)
print(n, '*2=', n*2)
print(n, '*3=', n*3)
print(n, '*4=', n*4)
print(n, '*5=', n*5)
print(n, '*6=', n*6)
print(n, '*7=', n*7)
print(n, '*8=', n*8)
print(n, '*10=', n*10) |
#immutability example
l1= [10,20,'abcdef',30,40]
l2= l1
print(type(l1))
print(l1)
print(l2)
l1[0]= 7777
print(l1)
print(l2)
# slicing operation in list
print(l1[1:3])
# append and remove in list
l1.append(50)
l1.append(60)
print(l1)
l1.remove(50)
print(l1) |
a= int(input('enter first number'))
b= int(input('enter second number'))
c= int(input('enter third number'))
if a<b and a<c:
print('smallest number is ',a)
elif b<c:
print('smallest number is',b)
else:
print('smallest number is', c) |
def alphabet_position(letter):
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if letter in lower:
return lower.index(letter)
else:
return upper.index(letter)
def rotate_character(char, rot):
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if char.isalpha() == False:
return char
position = alphabet_position(char)
position += rot
post_rot = position % 26
if char in lower:
new_character = lower[post_rot]
else:
new_character = upper[post_rot]
return new_character
|
# lambda 변수: 변수를 이용한 표현식
L = [lambda x: x**2, lambda x: x**3, lambda x: x**4]
for f in L: #f는 리스트의 원소인 람다식(무명함수이자, 콜백함수)이 넘어옴
print(f(3)) #3의 제곱, 세제곱, 네제곱을 출력할 것임
min = (lambda x, y: x if x < y else y) #최소값을 반환
# 참일때, 거짓일 때
print(min(100, 200)) |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
image = PhotoImage(file="hello.png")
canvas.create_image(20, 20, anchor=NW, image=image)
# anchor는 이미지의 NW(왼쪽 상단)을 기준점으로 사용하라는 의미
window.mainloop() |
import time
now = time.localtime()
print("현재 시간은", time.asctime())
if now.tm_mon >= 3 and now.tm_mon <= 5:
print("따뜻한 봄이네요~")
elif now.tm_mon >= 6 and now.tm_mon <= 8:
print("더운 여름이네요~")
elif now.tm_mon >= 9 and now.tm_mon <= 11:
print("청명한 가을이네요~")
else:
print("추운 겨울이네요~")
if now.tm_hour < 11 :
print("좋은 아침이에요~")
elif now.tm_hour < 15 :
print("낮이에요~")
elif now.tm_hour < 20 :
print("저녁이에요~")
else:
print("잘 자요~") |
from tkinter import * # TKinter
import random # 난수 발생
answer = random.randint(1, 100) # [1, 100] 난수 발생
def guessing():
guess = int(guessField.get()) # Entry 위젯에서 숫자를 가져옴
# 결과 판단
if guess > answer:
msg = "높음"
elif guess < answer:
msg = "낮음"
else:
msg = "정답"
resultLabel["text"] = msg # 결과를 출력
guessField.delete(0, 5) # Entry 위젯을 초기화
def reset(): # 다시 게임 하기
global answer # 외부 변수
answer = random.randint(1, 100)
resultLabel["text"] = "다시 하기!"
window = Tk()
window.configure(bg="white") # Root Window에 대해 배경색 설정
window.title("숫자 맞추기 게임") # Root Window에 대해 제목 설정
window.geometry("500x80") # Root Window에 대해 크기 설정
Label(window, text="숫자 맞추기 게임에 오신 것을 환영합니다~", bg="white").pack()
guessField = Entry(window)
guessField.pack(side=LEFT)
tryButton = Button(window, text="확인", fg="blue", bg="white", command=guessing)
tryButton.pack(side=LEFT)
resetButton = Button(window, text="초기화", fg="red", bg="white", command=reset)
resetButton.pack(side=LEFT)
resultLabel = Label(window, text="1과 100 사이의 숫자를 입력하세요", bg="white")
resultLabel.pack(side=LEFT)
window.mainloop()
|
def myGederator():
yield 'first'
yield 'second'
yield 'third'
# generator은 yield 문장 사용
for word in myGederator():
print(word)
# chap10_iterator.py와 유사 코드
# Generator는 함수를 이용해 Iterator 객체를 생성하는 것임!
def MyCounterGen(low, high):
while low <= high:
yield low
low += 1
for i in MyCounterGen(1, 10):
print(i, end=' ') |
def postfix_to_infix(expression):
stack = []
postfix = ""
for i in expression:
print(i, "||", len(stack), ">>", stack, "||", postfix)
if i == '(': # 열린 괄호는 스택에 들어감
stack.append(i)
elif i == ')': # 닫힌 괄호는 열린 괄호까지 스택에서 빼냄
while len(stack) > 0 and stack[len(stack) - 1] != '(':
postfix = postfix + stack.pop()
if stack[len(stack) - 1] == '(': # 열린 괄호는 postfix에 집어넣지 않음
stack.pop()
elif i == '*' or i == '/': # 곱하기와 나누기는
while len(stack) > 0 and \
(stack[len(stack) - 1] == '*' or stack[len(stack) - 1] == '/'): # 스택에 연산자 우선순위가 같은 것이 있다면
postfix = postfix + stack.pop()
stack.append(i)
elif i == '+' or i == '-': # 더하기와 빼기는
if len(stack) > 0 and \
(stack[len(stack) - 1] == '*' or stack[len(stack) - 1] == '/'): # 스택에 연산자 우선순위가 높은 것이 들어가 있다면
postfix = postfix + stack.pop()
stack.append(i)
else: # 그 외에는
postfix = postfix + i
for i in range(len(stack)): # 스택에 나머지를 모두 빼냄
postfix = postfix + stack.pop()
return postfix
def main():
#사용자로부터 중위표기식을 입력함
expression = input("Infix Expression >> ")
postfix = postfix_to_infix(expression)
print(postfix)
main()
|
import turtle
polygon = turtle.Turtle()
num_sides = 6 # 육각형의 변의 개수
side_length = 70 # 한 변의 길이
angle = 360.0 / num_sides # 육각형의 내각
for i in range(num_sides):
polygon.forward(side_length) # 한 변의 길이만큼 전진!
polygon.right(angle) # 각도 변경!
turtle.mainloop() |
from tkinter import *
def show():
print("name = %s\n age = %s" % (entryName.get(), entryAge.get()))
# Entry에서 get 함수를 쓰면 입력한 값을 가져옴
window = Tk()
Label(window, text="name").grid(row=0)
# Grid 배치 관리자를 사용함 -> 행 0번째 붙임
Label(window, text="age").grid(row=1)
entryName = Entry(window)
entryName.grid(row=0, column=1)
# Entry를 생성하고 grid를 같이 써서 entryName에 대입하면 안됨!
entryAge = Entry(window)
entryAge.grid(row=1, column=1)
# 0행 1열에 붙이고, 1행 1열에 붙인 Entry
Button(window, text="show", command=show).grid(row=2, column=0, sticky=W, pady=4)
# sticky는 W(왼쪽)에 붙인다는 의미
Button(window, text="quit", command=window.quit).grid(row=2, column=1, sticky=W, pady=4)
# window.quit 콜백함수는 window를 종료한다는 의미
window.mainloop() |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
line = canvas.create_line(0, 0, 300, 200, fill="red")
canvas.coords(line, 0, 0, 300, 100) # line의 좌표를 변경함
canvas.itemconfig(line, fill="blue") # line의 색깔을 변경함
# canvas.delete(line) # line을 삭제함
# canvas.delete(ALL) # 모든 것을 삭제함
window.mainloop() |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=200)
canvas.pack()
canvas.create_text(250, 10, text="Hello World!", fill="blue", font="Courier 20")
# font는 ("Courier", 20)으로 해도 됨
canvas.create_text(250, 100, text="Hello World!", fill="red", font="Helvetica 30")
window.mainloop() |
#이진수 변환기
input_number = input("수를 입력하세요 >> ")
#정수부와 소수부를 나누기
pos = input_number.find('.')
if pos != -1 : #소수점을 찾으면
Z_number, point_number = int(input_number[:pos]), int(input_number[pos+1:])
#print(real_number, point_number)
#정수부는 2로 나눈 나머지에 대한 것
ans_Z = ""
if Z_number > 0 : # 양수이면
while Z_number != 0 :
ans_Z = str(Z_number % 2) + ans_Z
Z_number = Z_number // 2
#else : #음수이면 2의 보수로 바꿔라
print(ans_Z)
#소수부에 대한 것
ans_P = ""
while point_number != 0 :
ans_P = str(point_number * 2) + ans_P
point_number = 1.0 - (point_number * 2) #정수부가 생기면 없애야 함
print(ans_P)
|
def eratosthenes(n):
multiples = set() # 공백의 set을 정의
for i in range(2, n + 1): # 2부터 n까지의 정수에 대해서
if i not in multiples: # set에 없으면
yield i # 함수의 return 값을 i로 출력 (generator) -> 이것이 소수
multiples.update(range(i * 1, n + 1, i)) # i의 배수를 전부 추가함
print(list(eratosthenes(100))) |
print('Введите три числа')
a=int(input())
b=int(input())
c=int(input())
if a%b==c :
print('Условие 3 верно, a даёт остаток c при делении на b')
else:
print ('Условие 3 неверно')
if c==-b/a :
print ('Условие 4 верно, c является решением линейного уравнения ax + b = 0')
else:
print ('Условие 4 неверно')
|
import numpy as np
import matplotlib.pyplot as plt
from danpy.sb import *
from matplotlib.patches import Ellipse
import matplotlib.animation as animation
import matplotlib.patches as patches
from scipy import signal
import argparse
"""
Notes:
X1: angle of pendulum
X2: angular velocity of pendulum
"""
def dx1_dt(X,U):
return(X[1])
def dx2_dt(X,U):
return(-(g/L)*np.sin(X[0]) - b/(m*L**2)*X[1] + (1/(m*L**2))*U)
def forward_integrate_dynamics(
ICs,
UsingDegrees=True,
Animate=False,
U=None,
ReturnX=False,
**kwargs):
"""
ICs must be a list of floats and/or ints of length 2. If ReturnX is True, the this will return an array of shape (2,len(Time)).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**kwargs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UsingDegrees must be a bool. Default is True. If True, then the ICs for pendulum angle and angular velocity can be given in degrees and degrees per second, respectively.
Animate must be a bool. Default is False. If True, the program will run animate_trajectory().
dt must be a number. Default is 0.0001. Used with N_seconds to define the time array (Time).
N_seconds must be a number. Default is 10. Used with dt to define the time array (Time).
U can either be None (default) or can be an array with lenth (len(Time)-1). If None, then U will be chosen to be np.zeros(len(Time)-1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Notes:
X1: angle of pendulum
X2: angular velocity of pendulum
"""
assert type(ICs)==list and len(ICs)==2, "ICs must be a list of length 2."
LocationStrings = ["1st", "2nd"]
for i in range(2):
assert str(type(ICs[i])) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"ICs must be numbers. Check the " + LocationString[i] + " element of IC"
assert type(UsingDegrees)==bool, "UsingDegrees must be either True or False."
assert type(Animate)==bool, "Animate must be either True or False."
dt = kwargs.get("dt",0.0001)
assert str(type(dt)) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"dt must be a number."
N_seconds = kwargs.get("N_seconds",10)
assert str(type(N_seconds)) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"N_seconds must be a number."
Time = np.arange(0,N_seconds+dt,dt)
X = np.zeros((2,len(Time)))
if U is None:
U = np.zeros(len(Time)-1)
else:
assert len(U)==len(Time)-1, "U must have length = (len(Time)-1)."
# ICs
if UsingDegrees:
X[0,0] = ICs[0]*(np.pi/180)
X[1,0] = ICs[1]*(np.pi/180)
else:
X[0,0] = ICs[0]
X[1,0] = ICs[1]
for i in range(len(Time)-1):
X[0,i+1] = X[0,i] + dx1_dt(X[:,i],U[i])*dt
X[1,i+1] = X[1,i] + dx2_dt(X[:,i],U[i])*dt
if ReturnX==True:
return(X)
else:
if Animate:
animate_trajectory(Time,X,U)
else:
plt.figure(figsize=(15,4))
ax1 = plt.subplot(121)
ax1.plot(Time,180*X[0,:]/np.pi,'g')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Pendulum Angle (deg)')
if max(abs(180*X[0,:]/np.pi - 180*X[0,0]/np.pi))<1e-7:
ax1.set_ylim([180*X[0,0]/np.pi - 5,180*X[0,0]/np.pi + 5])
ax2 = plt.subplot(122)
ax2.plot(Time,180*X[1,:]/np.pi,'g--')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Pendulum Angular \n Velocity (deg/s)')
if max(abs(X[1,:]-X[1,0]))<1e-7:
ax2.set_ylim([X[1,0]-1,X[1,0]+1])
plt.show()
def animate_trajectory(Time,X,U,**kwargs):
SaveAsGif = kwargs.get("SaveAsGif",False)
assert type(SaveAsGif)==bool, "SaveAsGif must be either True or False (Default)."
FileName = kwargs.get("FileName","ddp_simple_pendulum")
assert type(FileName)==str,"FileName must be a str."
# Angles must be in degrees for animation
X1d = X[0,:]*(180/np.pi)
X2d = X[1,:]*(180/np.pi)
fig = plt.figure(figsize=(12,10))
ax1 = plt.subplot2grid((2,6),(0,0),colspan=6) # animation
ax2 = plt.subplot2grid((2,6),(1,0),colspan=2) # pendulum angle
ax3 = plt.subplot2grid((2,6),(1,2),colspan=2) # pendulum angular velocity
ax4 = plt.subplot2grid((2,6),(1,4),colspan=2)
plt.suptitle("Simple Pendulum Example",Fontsize=28,y=0.95)
Pendulum_Width = 0.5*L
Pendulum_Length = 2*L
# Model Drawing
Pendulum, = ax1.plot(
[
0,
Pendulum_Length*np.sin(X[0,0])
],
[
0,
-Pendulum_Length*np.cos(X[0,0])
],
Color='0.50',
lw = 10,
solid_capstyle='round'
)
Pendulum_Attachment = plt.Circle((0,0),2*Pendulum_Width/2,Color='#4682b4')
ax1.add_patch(Pendulum_Attachment)
Pendulum_Rivet, = ax1.plot(
[0],
[0],
c='k',
marker='o',
lw=2
)
ax1.get_xaxis().set_ticks([])
ax1.get_yaxis().set_ticks([])
ax1.set_frame_on(True)
ax1.set_xlim(
[
-1.20*Pendulum_Length,
1.20*Pendulum_Length
]
)
ax1.set_ylim(
[
-1.20*Pendulum_Length,
1.20*Pendulum_Length
]
)
ax1.set_aspect('equal')
#Pendulum Angle
# Angle, = ax2.plot([0],[X1d[0]%360],color = 'r')
# ax2.set_xlim(0,Time[-1])
# ax2.set_xticks(list(np.linspace(0,Time[-1],5)))
# ax2.set_xticklabels([str(0),'','','',str(Time[-1])])
# ax2.set_ylim(0,360)
# ax2.spines['right'].set_visible(False)
# ax2.spines['top'].set_visible(False)
# ax2.set_title("Pendulum Angle (deg)",fontsize=16,fontweight = 4,color = 'r',y = 1.05)
Angle, = ax2.plot([0],[X1d[0]],color = 'r')
ax2.set_xlim(0,Time[-1])
ax2.set_xticks(list(np.linspace(0,Time[-1],5)))
ax2.set_xticklabels([str(0),'','','',str(Time[-1])])
if max(abs(X1d-X1d[0]))<1e-7:
ax2.set_ylim([X1d[0]-2,X1d[0]+2])
else:
RangeX1d= max(X1d)-min(X1d)
ax2.set_ylim([min(X1d)-0.15*RangeX1d,max(X1d)+0.15*RangeX1d])
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.set_title("Pendulum Angle (deg)",fontsize=12,fontweight = 4,color = 'r',y = 1.05)
# Angular Velocity
AngularVelocity, = ax3.plot([0],[X2d[0]],color='r',linestyle='--')
ax3.set_xlim(0,Time[-1])
ax3.set_xticks(list(np.linspace(0,Time[-1],5)))
ax3.set_xticklabels([str(0),'','','',str(Time[-1])])
if max(abs(X2d-X2d[0]))<1e-7:
ax3.set_ylim([X2d[0]-2,X2d[0]+2])
else:
RangeX2d= max(X2d)-min(X2d)
ax3.set_ylim([min(X2d)-0.1*RangeX2d,max(X2d)+0.1*RangeX2d])
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.set_title("Pendulum Angular Velocity (deg/s)",fontsize=12,fontweight = 4,color = 'r',y = 1.05)
# Input Torque
Torque, = ax4.plot([0],[U[0]],color='g')
ax4.set_xlim(0,Time[-1])
ax4.set_xticks(list(np.linspace(0,Time[-1],5)))
ax4.set_xticklabels([str(0),'','','',str(Time[-1])])
if max(abs(U-U[0]))<1e-7:
ax4.set_ylim([U[0]-2,U[0]+2])
else:
RangeU= max(U)-min(U)
ax4.set_ylim([min(U)-0.1*RangeU,max(U)+0.1*RangeU])
ax4.spines['right'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax4.set_title("Applied Torque (Nm)",fontsize=12,fontweight = 4,color = 'g',y = 1.05)
def animate(i):
Pendulum.set_xdata([0, Pendulum_Length*np.sin(X[0,i])])
Pendulum.set_ydata([0,-Pendulum_Length*np.cos(X[0,i])])
Angle.set_xdata(Time[:i])
Angle.set_ydata(X1d[:i])
AngularVelocity.set_xdata(Time[:i])
AngularVelocity.set_ydata(X2d[:i])
Torque.set_xdata(Time[:i])
Torque.set_ydata(U[:i])
return Pendulum,Angle,AngularVelocity,Torque,
# Init only required for blitting to give a clean slate.
def init():
Pendulum, = ax1.plot(
[
0,
Pendulum_Length*np.sin(X[0,0])
],
[
0,
-Pendulum_Length*np.cos(X[1,0])
],
Color='0.50',
lw = 10,
solid_capstyle='round'
)
Pendulum_Attachment = plt.Circle((0,0),2*Pendulum_Width/2,Color='#4682b4')
ax1.add_patch(Pendulum_Attachment)
Pendulum_Rivet, = ax1.plot(
[0],
[0],
c='k',
marker='o',
lw=2
)
#Pendulum Angle
Angle, = ax2.plot([0],[X1d[0]],color = 'r')
# Angular Velocity
AngularVelocity, = ax3.plot([0],[X2d[0]],color = 'r')
# Input Torque
Torque, = ax4.plot([0],[U[0]],color='g')
Pendulum.set_visible(False)
Pendulum_Attachment.set_visible(False)
Pendulum_Rivet.set_visible(False)
Angle.set_visible(False)
AngularVelocity.set_visible(False)
Torque.set_visible(False)
return Pendulum,Pendulum_Attachment,Pendulum_Rivet,Angle,AngularVelocity,Torque
dt = Time[1]-Time[0]
ani = animation.FuncAnimation(fig, animate, frames=np.arange(0,len(Time)-1,10), init_func=init, blit=False)
if SaveAsGif==True:
ani.save(FileName+'.gif', writer='imagemagick', fps=10)
plt.show()
def return_Phi(X,U,dt):
"""
Takes in the state vector, X, of shape (2,) and a number U, and outputs a matrix of shape (2,2)
"""
assert np.shape(X)==(2,) and str(type(X))=="<class 'numpy.ndarray'>", \
"X must be an numpy array of shape (2,)"
assert str(type(U)) in ["<class 'int'>",
"<class 'float'>",
"<class 'numpy.float'>",
"<class 'numpy.float64'>"],\
"U must be a number. Not " + str(type(U)) + "."
result = (np.eye(2)
+ np.matrix(
[
[0, dt],
[-(g/L)*np.cos(X[0])*dt, -(b/(m*L**2))*dt]
]
)
)
assert np.shape(result)==(2,2) \
and str(type(result))=="<class 'numpy.matrixlib.defmatrix.matrix'>", \
"result must be a (2,2) numpy matrix. Not " + str(type(result)) + " of shape " + str(np.shape(result)) + "."
return(result)
def return_B(X,U,dt):
"""
Takes in the state vector, X, of shape (2,) and a number U, and outputs a matrix of shape (2,1)
"""
assert np.shape(X)==(2,) and str(type(X))=="<class 'numpy.ndarray'>", \
"X must be an numpy array of shape (2,)"
assert str(type(U)) in ["<class 'int'>",
"<class 'float'>",
"<class 'numpy.float'>",
"<class 'numpy.float64'>"],\
"U must be a number. Not " + str(type(U)) + "."
result = (
np.matrix(
[
[0],
[dt/(m*L**2)]
]
)
)
assert np.shape(result)==(2,1) \
and str(type(result))=="<class 'numpy.matrixlib.defmatrix.matrix'>", \
"result must be a (2,1) numpy matrix. Not " + str(type(result)) + " of shape " + str(np.shape(result)) + "."
return(result)
def return_linearized_dynamics_matrices(X,U,dt):
"""
Takes in the input U and the the corresponding output X, as well as dt and returns two lists that contain the linearized dynamic matrices for each timestep for range(len(Time)-1).
Note that if np.shape(X)[1] = N and len(U) = M, then N = M + 1 (i.e., there is one more timestep for output than input since the initial conditions are assigned to the first state space timestep). Therefore, we only concern ourselves with the linearized dynamics of the (N-1) steps where U drives X to the next timestep (i.e., X will only go up to the N-1 step or index X[:,:-1].)
Phi is a list of length len(Time)-1, each element with shape (n,n), where n is the number of states.
B is a list of length len(Time)-1, each element with shape (n,m), where n is the number of states and m is the number of inputs.
### NEEDS TO BE TESTED ###
np.shape(X)[1] == len(U)+1
len(Phi) == len(U)
type(Phi) == list
len(B) == len(U)
type(B) == list
##########################
"""
Phi = list(
map(
lambda X,U: return_Phi(X,U,dt),
X[:,:-1].T,
U
)
)
B = list(
map(
lambda X,U: return_B(X,U,dt),
X[:,:-1].T,
U
)
)
return(Phi,B)
def return_l_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[(k3/2)*U**2*dt]])
else:
result1 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[k1*(1/2)*(X[0]-TargetAngle)**2*dt]])
else:
result2 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt:\
np.matrix([[k2*(1/2)*(X[1]-TargetAngularVelocity)**2*dt]])
else:
result3 = lambda X,U,dt: np.matrix([[0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_lx_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
result = lambda X,U,dt: np.matrix([[0],[0]])
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[0],[0]])
else:
result1 = lambda X,U,dt: np.matrix([[0],[0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[k1*(X[0]-TargetAngle)*dt],[0]])
else:
result2 = lambda X,U,dt: np.matrix([[0],[0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0],[k2*(X[1]-TargetAngularVelocity)*dt]])
else:
result3 = lambda X,U,dt: np.matrix([[0],[0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_lu_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[k3*U*dt]])
else:
result1 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[0]])
else:
result2 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0]])
else:
result3 = lambda X,U,dt: np.matrix([[0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_lxu_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[0],[0]])
else:
result1 = lambda X,U,dt: np.matrix([[0],[0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[0],[0]])
else:
result2 = lambda X,U,dt: np.matrix([[0],[0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0],[0]])
else:
result3 = lambda X,U,dt: np.matrix([[0],[0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_lux_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[0,0]])
else:
result1 = lambda X,U,dt: np.matrix([[0,0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[0,0]])
else:
result2 = lambda X,U,dt: np.matrix([[0,0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0,0]])
else:
result3 = lambda X,U,dt: np.matrix([[0,0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_luu_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[k3*dt]])
else:
result1 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[0]])
else:
result2 = lambda X,U,dt: np.matrix([[0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0]])
else:
result3 = lambda X,U,dt: np.matrix([[0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_lxx_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.matrix([[0,0],[0,0]])
else:
result1 = lambda X,U,dt: np.matrix([[0,0],[0,0]])
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.matrix([[k1*1*dt,0],[0,0]])
else:
result2 = lambda X,U,dt: np.matrix([[0,0],[0,0]])
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt: np.matrix([[0,0],[0,k2*1*dt]])
else:
result3 = lambda X,U,dt: np.matrix([[0,0],[0,0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_quadratic_cost_function_expansion_variables(
X,U,dt,
RunningCost="Minimize Input Energy"):
"""
Takes in the input U and the the corresponding output X, as well as dt and returns lists that contain the coefficient matrices for the quadratic expansion of the cost function (l(x,u)) for each timestep for range(len(Time)-1).
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
# returns a list of length len(Time)-1, each element with shape (1,1), where n is the number of states.
l_func = return_l_func(RunningCost=RunningCost)
l = list(
map(
lambda X,U: l_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (n,1), where n is the number of states.
lx_func = return_lx_func(RunningCost=RunningCost)
lx = list(
map(
lambda X,U: lx_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (m,1), where n is the number of states.
lu_func = return_lu_func(RunningCost=RunningCost)
lu = list(
map(
lambda X,U: lu_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (m,n), where m is the number of inputs and n is the number of states.
lux_func = return_lux_func(RunningCost=RunningCost)
lux = list(
map(
lambda X,U: lux_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (n,m), where n is the number of states and m is the number of inputs.
lxu_func = return_lxu_func(RunningCost=RunningCost)
lxu = list(
map(
lambda X,U: lxu_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (m,m), where m is the number of inputs.
luu_func = return_luu_func(RunningCost=RunningCost)
luu = list(
map(
lambda X,U: luu_func(X,U,dt),
X[:,1:].T,
U
)
)
# returns a list of length len(Time)-1, each element with shape (n,n), where n is the number of states.
lxx_func = return_lxx_func(RunningCost=RunningCost)
lxx = list(
map(
lambda X,U: lxx_func(X,U,dt),
X[:,1:].T,
U
)
)
return(l,lx,lu,lux,lxu,luu,lxx)
def return_running_cost_func(RunningCost='Minimize Input Energy'):
"""
Should use the current timestep, not the t + dt (or prime notation).
RunningCost should be either 'Minimize Input Energy' (Default), 'Minimize time away from target angle', or 'Minimize time away from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
if "Minimize Input Energy" in RunningCost:
result1 = lambda X,U,dt: np.trapz((k3/2)*U**2,dx=dt)
else:
result1 = lambda X,U,dt: 0
if "Minimize time away from target angle" in RunningCost:
result2 = lambda X,U,dt: np.trapz(k1*(1/2)*(X[0,1:]-TargetAngle)**2,dx=dt)
else:
result2 = lambda X,U,dt: 0
if "Minimize time away from target angular velocity" in RunningCost:
result3 = lambda X,U,dt:\
np.trapz(k2*(1/2)*(X[1,1:]-TargetAngularVelocity)**2,dx=dt)
else:
result3 = lambda X,U,dt: 0
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt) \
+ result3(X,U,dt)
return(result)
def return_terminal_cost_func(TerminalCost='Minimize final angle',
ReturnGradientAndHessian=False):
"""
Should use the current timestep, not the t + dt (or prime notation).
Cost should be either 'Minimize final angle from target angle' (Default), 'Minimize final angular velocity from target angular velocity'. To be set upstream by linearized cost function.
"""
if type(TerminalCost)==str:
assert TerminalCost in ['Minimize final angle from target angle',
'Minimize final angular velocity from target angular velocity'],\
"TerminalCost must be either 'Minimize final angle from target angle' (Default), 'Minimize final angular velocity from target angular velocity'."
else:
assert type(TerminalCost)==list, "TerminalCost must be a list of cost types."
for el in TerminalCost:
assert type(el)==str, "Each element of TerminalCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize final angle from target angle',
'Minimize final angular velocity from target angular velocity'],\
"Each element of TerminalCost must be either 'Minimize final angle from target angle' (Default), 'Minimize final angular velocity from target angular velocity'. '" + el + "' not accepted."
if "Minimize final angle from target angle" in TerminalCost:
result1 = lambda X,U,dt: k4*(1/2)*(X[0,-1]-TargetAngle)**2
result1_grad = lambda X,U,dt:\
np.matrix([[k4*(X[0,-1]-TargetAngle)],[0]])
result1_hess = lambda X,U,dt: np.matrix([[k4*1,0],[0,0]])
else:
result1 = lambda X,U,dt: 0
result1_grad = lambda X,U,dt:\
np.matrix([[0],[0]])
result1_hess = lambda X,U,dt: np.matrix([[0,0],[0,0]])
if "Minimize final angular velocity from target angular velocity" in TerminalCost:
result2 = lambda X,U,dt: k5*(1/2)*(X[1,-1]-TargetAngularVelocity)**2
result2_grad = lambda X,U,dt:\
np.matrix([[0],[k5*(X[1,-1]-TargetAngularVelocity)]])
result2_hess = lambda X,U,dt: np.matrix([[0,0],[0,k5*1]])
else:
result2 = lambda X,U,dt: 0
result2_grad = lambda X,U,dt:\
np.matrix([[0],[0]])
result2_hess = lambda X,U,dt: np.matrix([[0,0],[0,0]])
result = lambda X,U,dt: result1(X,U,dt) \
+ result2(X,U,dt)
if ReturnGradientAndHessian:
result_grad = lambda X,U,dt: result1_grad(X,U,dt) \
+ result2_grad(X,U,dt)
result_hess = lambda X,U,dt: result1_hess(X,U,dt) \
+ result2_hess(X,U,dt)
return(result,result_grad,result_hess)
else:
return(result)
def return_empty_lists_for_quadratic_expansion_of_Q(length):
Qu = [None]*length
Qx = [None]*length
Qux = [None]*length
Qxu = [None]*length
Quu = [None]*length
Qxx = [None]*length
return(Qu,Qx,Qux,Qxu,Quu,Qxx)
def simple_pendulum_ddp(**kwargs):
RunningCost = kwargs.get("RunningCost","Minimize Input Energy")
if type(RunningCost)==str:
assert RunningCost in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'."
else:
assert type(RunningCost)==list, "RunningCost must be a list of cost types."
for el in RunningCost:
assert type(el)==str, "Each element of RunningCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize Input Energy',
'Minimize time away from target angle',
'Minimize time away from target angular velocity'],\
"Each element of RunningCost must be either 'Minimize Input Energy','Minimize time away from target angle', or 'Minimize time away from target angular velocity'. '" + el + "' not accepted."
running_cost_func = return_running_cost_func(RunningCost=RunningCost)
TerminalCost = kwargs.get("TerminalCost","Minimize final angle from target angle")
if type(TerminalCost)==str:
assert TerminalCost in ['Minimize final angle from target angle',
'Minimize final angular velocity from target angular velocity'],\
"TerminalCost must be either 'Minimize final angle from target angle' (Default), 'Minimize final angular velocity from target angular velocity'."
else:
assert type(TerminalCost)==list, "TerminalCost must be a list of cost types."
for el in TerminalCost:
assert type(el)==str, "Each element of TerminalCost must be a string. Not " + str(type(el)) + "."
assert el in ['Minimize final angle from target angle',
'Minimize final angular velocity from target angular velocity'],\
"Each element of TerminalCost must be either 'Minimize final angle from target angle' (Default), 'Minimize final angular velocity from target angular velocity'. '" + el + "' not accepted."
terminal_cost_func,terminal_cost_grad_func,terminal_cost_hess_func = \
return_terminal_cost_func(
TerminalCost=TerminalCost,
ReturnGradientAndHessian=True
)
ICs = kwargs.get("ICs",[0,0]) # in degrees
assert type(ICs)==list and len(ICs)==2, "ICs must be a list of length 2."
LocationStrings = ["1st", "2nd"]
for i in range(2):
assert str(type(ICs[i])) in [
"<class 'numpy.float'>",
"<class 'int'>",
"<class 'float'>"],\
"ICs must be numbers. Check the " + LocationString[i] + " element of IC"
dt = kwargs.get("dt",0.01)
assert str(type(dt)) in [
"<class 'numpy.float'>",
"<class 'int'>",
"<class 'float'>"],\
"dt must be a number."
N_seconds = kwargs.get("N_seconds",10)
assert str(type(N_seconds)) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"N_seconds must be a number."
N_iterations = kwargs.get("N_iterations",10)
assert str(type(N_iterations)) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"N_iterations must be a number."
Animate = kwargs.get("Animate",True)
assert type(Animate)==bool, "Animate must be either True (Default) or False."
PlotCost = kwargs.get("PlotCost",True)
assert type(PlotCost)==bool, "PlotCost must be either True (Default) or False."
thresh = kwargs.get("thresh",1e-2)
assert str(type(thresh)) in ["<class 'numpy.float'>","<class 'int'>","<class 'float'>"],\
"thresh must be a number."
TotalX = []
TotalU = []
Time = np.arange(0,N_seconds + dt,dt)
U = kwargs.get("U",2*np.ones(len(Time)-1)) # initial input
assert len(U)==len(Time)-1, "U must be an array with length len(Time)-1."
TrialCosts = []
IterationNumber = 1
ThresholdNotMet=True
while IterationNumber <= N_iterations and ThresholdNotMet:
print(
"Iteration Number : "
+ str(IterationNumber)
+ "/"
+ str(N_iterations)
) # Does not effect runtime
X = forward_integrate_dynamics(
ICs,
U=U,
dt=dt,
N_seconds=N_seconds,
ReturnX=True)
TotalX.append(X)
TotalU.append(U)
TrialCosts.append(
terminal_cost_func(X,U,dt)
+ running_cost_func(X,U,dt)
)
if IterationNumber>3:
if abs(np.average(TrialCosts[-3:])-TrialCosts[-1]) < thresh:
ThresholdNotMet = False
print("Threshold met after " + str(IterationNumber) + " Trials")
Phi,B = return_linearized_dynamics_matrices(X,U,dt)
l,lx,lu,lux,lxu,luu,lxx = \
return_quadratic_cost_function_expansion_variables(X,U,dt,RunningCost=RunningCost)
# Backward Pass
V = [np.matrix([[terminal_cost_func(X,U,dt)]])]
Vx = [terminal_cost_grad_func(X,U,dt)]
Vxx = [terminal_cost_hess_func(X,U,dt)]
Qu,Qx,Qux,Qxu,Quu,Qxx = \
return_empty_lists_for_quadratic_expansion_of_Q(len(Time)-1)
for i in range(len(Time)-1):
Qx[-(i+1)] = lx[-(i+1)] + Phi[-(i+1)].T*Vx[-1]
Qu[-(i+1)] = lu[-(i+1)] + B[-(i+1)].T*Vx[-1]
Qux[-(i+1)] = lux[-(i+1)] + B[-(i+1)].T*Vxx[-1]*Phi[-(i+1)]
Qxu[-(i+1)] = lxu[-(i+1)] + Phi[-(i+1)].T*Vxx[-1]*B[-(i+1)]
Quu[-(i+1)] = luu[-(i+1)] + B[-(i+1)].T*Vxx[-1]*B[-(i+1)]
Qxx[-(i+1)] = lxx[-(i+1)] + Phi[-(i+1)].T*Vxx[-1]*Phi[-(i+1)]
# It appears that the choice of this does not matter... Ran it for 5 seconds, Target = pi, and the final cost was always 621.50
V.append(
l[-(i+1)]
+ V[-1]
- (1/2)*Qu[-(i+1)].T*(Quu[-(i+1)]**(-1))*Qu[-(i+1)]
)
# V.append(
# V[-1]
# - Qu[-(i+1)].T*(Quu[-(i+1)]**(-1))*Qu[-(i+1)]
# )
Vx.append(
Qx[-(i+1)]
- Qxu[-(i+1)]*(Quu[-(i+1)]**(-1))*Qu[-(i+1)]
)
Vxx.append(
Qxx[-(i+1)]
- Qxu[-(i+1)]*(Quu[-(i+1)]**(-1))*Qux[-(i+1)]
)
V = list(reversed(V))
Vx = list(reversed(Vx))
Vxx = list(reversed(Vxx))
dx = [None]*len(Time)
du = [None]*(len(Time)-1)
dx[0] = np.matrix([[0],[0]])
# Forward Pass
for i in range(len(Time)-1):
du[i] = -Quu[i]**(-1)*(Qux[i]*dx[i] + Qu[i])
dx[i+1] = Phi[i]*dx[i] + B[i]*du[i]
U = np.array(U + np.concatenate(du,axis=0).T)[0]
IterationNumber+=1
X = forward_integrate_dynamics(
ICs,
U=U,
dt=dt,
N_seconds=N_seconds,
ReturnX=True)
TotalX.append(X)
TotalU.append(U)
TrialCosts.append(
terminal_cost_func(X,U,dt)
+ running_cost_func(X,U,dt)
)
if Animate==True:
if "U" in kwargs.keys(): del(kwargs["U"]) # prevents multiple instances of U going into animate_trajectory()
animate_trajectory(Time,X,U,**kwargs)
if PlotCost==True:
plt.figure(figsize=(7,5))
plt.plot(
list(range(1,len(TrialCosts)+1)),
TrialCosts,
marker = 'o')
plt.gca().set_ylabel("Cost")
plt.gca().set_xlabel("Iteration Number")
plt.gca().set_xticks(list(range(1,6*int((len(TrialCosts)+1)/5),int((len(TrialCosts)+1)/5))))
plt.show()
return(Time,TotalX,TotalU,TrialCosts)
m = 1 # kg
L = 0.5 # m
g = 9.8 # m/s²
b = 10 # Nms
k1 = 1000
k2 = 1000
k3 = 1
k4 = 1
k5 = 1
TargetAngle = np.pi #in radians
TargetAngularVelocity = 0 #in radians
RunningCost = ["Minimize Input Energy",
"Minimize time away from target angle",
"Minimize time away from target angular velocity"][:]
TerminalCost = ["Minimize final angle from target angle",
"Minimize final angular velocity from target angular velocity"][:]
if __name__=="__main__":
### Additional Arguments?
parser = argparse.ArgumentParser(
prog = "<filename>",
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
-----------------------------------------------------------------------------
ddp_simple_pendulum.py
-----------------------------------------------------------------------------
Control the position of a simple pendulum by differential dynamic programming.
-----------------------------------------------------------------------------'''),
epilog=textwrap.dedent('''\
-----------------------------------------------------------------------------
Written by Daniel A. Hagen (2018/08/20)
-----------------------------------------------------------------------------'''
)
)
parser.add_argument(
'--animate',
action="store_true",
help='Animate the results.'
)
args = parser.parse_args()
animate = args.animate
simple_pendulum_ddp(Animate=animate)
|
t = int(input())
for i in range(t):
notas = [int(x) for x in input().split()]
nota_min = int(min(notas))
nota_max = int(max(notas))
print(nota_min, nota_max)
if nota_min == nota_max:
print("S", end="" if i == t-1 else "\n")
else:
print("N", end="" if i == t-1 else "\n") |
'''
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Intervals can "touch", such as [0, 1] and [1, 2], but they won't be considered overlapping.
For example, given the intervals (7, 9), (2, 4), (5, 8), return 1 as the last interval can be removed and the first two won't overlap.
The intervals are not necessarily sorted in any order.
'''
import unittest
def min_itvl_remove(intervals):
if not intervals or len(intervals) <= 1:
return 0
intervals.sort(key=lambda tup: tup[1])
min_count = 0
result = [intervals[0]]
for i in range(1, len(intervals)):
ref_itvl = result[-1]
cur_itvl = intervals[i]
if cur_itvl[0] >= ref_itvl[0] and cur_itvl[0] < ref_itvl[1]:
# must remove
min_count += 1
else:
result.append(cur_itvl)
return min_count
class DailyCodingProblemTest(unittest.TestCase):
def test_case_1(self):
test = [(7, 9), (2, 4), (5, 8)]
result = 1
self.assertEqual(min_itvl_remove(test), result)
def test_case_2(self):
test = []
result = 0
self.assertEqual(min_itvl_remove(test), result)
def test_case_3(self):
test = [(7, 9), (2, 4)]
result = 0
self.assertEqual(min_itvl_remove(test), result)
def test_case_4(self):
test = [(1, 4), (0, 3), (5, 9), (3, 7), (8, 10), (11, 12)]
result = 2
self.assertEqual(min_itvl_remove(test), result)
if __name__ == '__main__':
unittest.main()
|
'''
You are given a starting state start, a list of transition probabilities for a Markov chain,
and a number of steps num_steps. Run the Markov chain starting from start for num_steps and
compute the number of times we visited each state.
For example, given the starting state a, number of steps 5000, and the following transition probabilities:
[
('a', 'a', 0.9),
('a', 'b', 0.075),
('a', 'c', 0.025),
('b', 'a', 0.15),
('b', 'b', 0.8),
('b', 'c', 0.05),
('c', 'a', 0.25),
('c', 'b', 0.25),
('c', 'c', 0.5)
]
One instance of running this Markov chain might produce { 'a': 3012, 'b': 1656, 'c': 332 }.
'''
from random import uniform
from bisect import bisect
import unittest
def init_state(state_transitions):
result_state = dict()
for s in state_transitions:
if s[0] not in result_state:
result_state[s[0]] = ([],[])
result_state[s[0]][0].append(s[1])
if not result_state[s[0]][1]:
result_state[s[0]][1].append(s[2])
else:
prev_prob = result_state[s[0]][1][-1]
result_state[s[0]][1].append(prev_prob + s[2])
return result_state
def init_counter(state_transitions):
counter = dict()
for s in state_transitions:
counter[s[0]] = 0
return counter
def next_state(state_mapping, cur_state):
r = uniform(0, 1)
state_tuple = state_mapping[cur_state]
idx = bisect(state_tuple[1], r)
return state_tuple[0][idx]
def markov_chain(state_transitions, steps):
initial_state = init_state(state_transitions)
counter = init_counter(state_transitions)
cur_state = state_transitions[0][0]
for s in range(steps):
counter[cur_state] += 1
cur_state = next_state(initial_state, cur_state)
return counter
class DailyCodingProblemTest(unittest.TestCase):
def test_case_1(self):
states = [
('a', 'a', 0.9),
('a', 'b', 0.075),
('a', 'c', 0.025),
('b', 'a', 0.15),
('b', 'b', 0.8),
('b', 'c', 0.05),
('c', 'a', 0.25),
('c', 'b', 0.25),
('c', 'c', 0.5)
]
steps = 5000
result = markov_chain(states, steps)
print('markov results: ', result)
self.assertTrue(result['a'] > result['b'])
self.assertTrue(result['a'] > result['c'])
self.assertTrue(result['b'] > result['c'])
if __name__ == '__main__':
unittest.main()
|
'''
You have n fair coins and you flip them all at the same time. Any that come up tails you set aside. The ones that come up heads you flip again. How many rounds do you expect to play before only one coin remains?
Write a function that, given n, returns the number of rounds you'd expect to play until one coin remains.
'''
from random import randint
from math import ceil, log
def num_rounds_simulation(n):
if n <= 0:
return 0
rounds = 0
while(n > 1):
i = 0
tails = 0
while(i < n):
tails += randint(0, 1)
i += 1
n -= tails
rounds += 1
return rounds
def expected_rounds(n):
return ceil(log(n, 2))
print('5 coins simulation: {}, expected: {}'.format(num_rounds_simulation(5), expected_rounds(5)))
print('10 coins simulation: {}, expected: {}'.format(num_rounds_simulation(10), expected_rounds(10)))
print('20 coins simulation: {}, expected: {}'.format(num_rounds_simulation(20), expected_rounds(20)))
print('25 coins simulation: {}, expected: {}'.format(num_rounds_simulation(25), expected_rounds(25)))
print('50 coins simulation: {}, expected: {}'.format(num_rounds_simulation(50), expected_rounds(50)))
print('100 coins simulation: {}, expected: {}'.format(num_rounds_simulation(100), expected_rounds(100)))
print('150 coins simulation: {}, expected: {}'.format(num_rounds_simulation(150), expected_rounds(150)))
print('200 coins simulation: {}, expected: {}'.format(num_rounds_simulation(200), expected_rounds(200)))
print('500 coins simulation: {}, expected: {}'.format(num_rounds_simulation(500), expected_rounds(500)))
print('1000 coins simulation: {}, expected: {}'.format(num_rounds_simulation(1000), expected_rounds(1000)))
|
'''
Write an algorithm that computes the reversal of a directed graph. For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
'''
import unittest
def reverse_graph(graph):
reversed_graph = {}
for k, v in graph.items():
reversed_graph[k] = []
for node, connections in graph.items():
for c in connections:
reversed_graph[c].append(node)
return reversed_graph
class DailyCodingProblemTest(unittest.TestCase):
def test_case_1(self):
test = {'A': ['B', 'C'],
'B': ['D'],
'C': [],
'D': []}
expected = {'A': [],
'B': ['A'],
'C': ['A'],
'D': ['B']}
actual = reverse_graph(test)
self.assertEqual(actual, expected)
def test_case_2(self):
test = {'A': ['B'],
'B': ['C'],
'C': []}
expected = {'A': [],
'B': ['A'],
'C': ['B']}
actual = reverse_graph(test)
self.assertEqual(actual, expected)
def test_case_3(self):
test = {'A': ['C'],
'B': ['C'],
'C': []}
expected = {'A': [],
'B': [],
'C': ['A', 'B']}
actual = reverse_graph(test)
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.