text
stringlengths 37
1.41M
|
---|
#**********Class Decorator**************
print("\n***************Class Decorator***************")
class square:
def __init__(self,side):
self._side=side
@property
def side(self):
return self._side
@side.setter
def side(self, value):
if value>=0:
self._side=value
else:
print("Error")
@property
def area(self):
return self._side**2
@classmethod
def unit_square(cls):
return(1)
s=square(5)
print(s.side)
print(s.area)
|
#Nested loop
print("Welcome to glacticspace Bank ATM")
restart=('y')
chance=3
balance=67000.50
while chance>=0:
pin= int(input('Please Enter your 4 didgit pin:'))
if pin==(1234):
print('You have entered the correct PIN\n')
while restart not in ("n","NO","N","no"):
print('Please prees 1 for your balance\n')
print('Please prees 2 for withdrawl\n')
print('Please prees 3 to Deposite\n')
print('Please prees 4 to return Card\n')
option = int(input('Plese Enter your Choice:'))
if option==1:
print('Your Balance is A$',balance,'\n')
restart =input('Would you like to go back?')
if restart in('n','N','No','no'):
print('Thank You')
break
elif option==2:
option2=('y')
withdrawl=float(input("Enter the Amount to be Withdraw\n"))
if withdrawl in [50,100,500,1000,2000,5000,10000,20000,40000,50000]:
balance=balance-withdrawl
print("\n Your Balance is now A$",balance)
restart = input('Would you like to go Back?')
if restart in('n','N','NO','no'):
print("Thank you")
break
elif withdrawl !=[50,100,500,1000,2000,5000,10000,20000,40000,50000]:
print('Invalid Amount, Re-try again\n')
restart=('y')
elif withdrawl==1:
withdrawl = float(input('Please Enter desired amount:'))
elif option==3:
pay_in= float(input('How much would you like to Deposite?'))
balance = balance+pay_in
print('\nyour Balance is Now A$',balance)
restart=input('Would you like to go back?')
if restart in ('n','NO','no','N'):
print('Thank you')
break
elif option==4:
print("PlEASE WAIT WHILE YOUR CARD IS RETURNED...\n")
print("Thank you, Please visit again!")
break
else:
print('Please Enter a correct number.\n')
restart=('y')
elif pin !=('1234'):
print('Incorrect Password')
chance= chance-1
if chance ==0:
print('\n you reach the maximux level, Plese try after sometime')
break
|
import time
import datetime
def daysUntil(xDay):
today = datetime.date.today()
diff = xDay-today
return diff.days
def main():
print("{} days until freedom, SON!".format(daysUntil(datetime.date(2019,5,1))))
time.sleep(60)
exit(0)
if __name__ == "__main__":
main()
|
'''
链式结构
1、内存不连续
2、不能通过下标访问
3、追加元素很方便
4、遍历操作和查找操作比较复杂
单链表
1、通过指针的方式首尾相连
2、根节点,入口,用来遍历,首节点,尾节点
3、node:包括value,和指针next,指向下一个元素
4、可以定义一个class来体现node对象
5、实现单链表结构
单链表类的属性和方法
1、数据data:root、lenth、
2、method:
init、append、append_left、append_right、
iter_node、remove、find、pop_left(right)、
clear
'''
# 定义实现节点类
# 定义实现单链表类
# 初始化:最大限制,链表长度,根节点,尾节点
# 实现长度获取
# 添加元素
# 添加头部元素
# 实现可迭代
# 查找元素,根据值
# 删除元素,根据值
# 头部弹出,并返回值
# 清空链表,删除所有元素
# (可选)尾部弹出,并返回值
# (可选)去掉重复元素
# (可选)在第一次出现的某个值之前插入一个值 insert(value, newValue)
class Node(object):
# 定义节点类
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class linkedlist(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.tailnode = None
self.length = 0
def __len__(self):
# 获取长度
currNode = self.root.next
count = 0
while currNode is not None:
count += 1
currNode = currNode.next
self.length = count
return self.length
def append(self, value):
# 从尾部添加元素
# 判断容量不为空,同时没有超过最大容量,否则抛出异常
if self.maxsize is not None and len(self) > self.maxsize:
raise Exception('is Full')
# 创建一个新节点
node = Node(value)
tailnode = self.tailnode
# 判断tailnode是否为空,是代表链表只有根节点,将根节点的next指向新节点
# 否则将尾部节点的next指向新节点
if tailnode is None:
self.root.next = node
else:
tailnode.next = node
self.tailnode = node
self.length += 1
def appendleft(self, value):
# 从头部添加元素
headnode = self.root.next
node = Node(value)
self.root.next = node
node.next = headnode
self.length += 1
def iter_node(self):
# 迭代节点
curnode = self.root.next
while curnode is not self.tailnode:
yield curnode
curnode = curnode.next
yield curnode
def __iter__(self):
# self可迭代
for node in self.iter_node():
yield node.value
def find(self, value):
index = 0
for node in self.iter_node():
if node.value == value:
return index
index += 1
return -1
def remove(self, value):
currNode = self.root.next
prevNode = None
while currNode is not None:
if currNode.value == value:
if currNode == self.root.next:
self.root.next = currNode.next
else:
prevNode.next = currNode.next
self.tailnode = prevNode
del currNode
break
else:
prevNode = currNode
currNode = currNode.next
def popleft(self): # o(n) 复杂度
# 从左边弹出一个元素,并返回它
if self.root.next is None: # 判断是否为空
raise Exception('pop from empty linkedList')
headnode = self.root.next
self.root.next = headnode.next
self.length -= 1
value = headnode.value
del headnode
return value
def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.length = 0
# 单测
def test_linked_list():
ll = linkedlist()
ll.append(0)
ll.append(1)
ll.append(2)
assert len(ll) == 3
assert ll.find(2) == 2
assert ll.find(3) == -1
ll.remove(0)
assert len(ll) == 2
# assert ll.find(0) == -1
assert list(ll) == [1,2]
ll.appendleft(100)
assert list(ll) == [100,1,2]
assert len(ll) == 3
headvalue = ll.popleft()
assert headvalue == 100
assert list(ll) == [1,2]
assert len(ll) == 2
# ll.remove(2)
# assert list(ll) == [1]
ll.clear()
assert len(ll) == 0
|
string = list(input())
palavra = list(input())
hasEqual = False
tamanhoVetor = len(string) - len(palavra)
for i in range(0, tamanhoVetor + 1):
trecho = []
for j in range(0, len(palavra)):
trecho.append(string[i+j])
if trecho == palavra:
hasEqual = True
print(i)
if hasEqual == False:
print("NOT FOUND!") |
def lerValores():
x = []
for i in range(0, 10):
x.append(int(input()))
return x
def subValores():
y = lerValores()
for i in range(0, len(y)):
if y[i] <= 0:
y[i] = 1
for i in range(0, len(y)):
print(f"X[{i}] = {y[i]}")
subValores() |
binario = int(input())
decimal = 0
exp = 0
while binario != 0:
divisao = binario // 10
resto = binario % 10
decimal = decimal + resto * (2 ** exp)
exp = exp + 1
binario = divisao
print(decimal) |
"""TCP Client"""
import socket
def Main():
"""127.0.0.1 is the loopback address. Any packets sent to this address will
essentially loop right back to your machine and look for any process
listening in on the port specified."""
host = '127.0.0.1'
port = 5000
#Create a socket and connect to our host and port, this will then connect to our server
s = socket.socket() #by default, the socket constructor creates an TCP/IPv4 socket
s.connect((host,port))
"""Input messages to send to server"""
message = input("-> ")
"""As long as message is not q then we send to the server, and display the feedback from the server"""
while message != 'q':
#Send
s.send(message.encode('utf-8'))
#Receive feedback
#1024 is the receive buffer size. It's enough for us, and it's a nice number.
data = s.recv(1024).decode('utf-8')
print("Received from server: " + data)
#Get ready to send another message
message = input("-> ")
s.close()
"""This if-statement checks if you are running this python file directly. That
is, if you run `python3 tcpClient.py` in terminal, this if-statement will be
true"""
if __name__ == '__main__':
Main() |
# using inheritance importing product
import product
# and checkoutregister classes
import checkoutregister
# adding some products into the supermarket
product.product("123", "Milk", "2 Litres", "2.0")
product.product("789", "Fruits", "2 kgs", "4.0")
product.product("456", "Bread", "", "3.5")
# greeting message generated for the user
print("-----Welcome to FedUni checkout! -----")
while True:
# using the checkoutregister class from checkoutregister file
check_pro_list_items = checkoutregister.checkoutregister()
# while condition is true run the code
while True:
main_class_list = product.product.list_products
print()
# prompt to get the entry of the product from the user
product_code_data = input("Please enter the barcode of your item: ")
# add the entered data and scan the product if it is available or not
check_pro_list_items.scan_items(product_code_data)
print()
# prompt to get the entry from the user to continue or not
user_loop = input("Would you like to scan another product? (Y/N) ").upper()
# if user enter 'N' and then break the loop
if user_loop == 'N':
break
print()
while True:
# show the payment to be paid/payment due to the user
print("Payment due: $" + str(round((check_pro_list_items.price_of_products), 2)))
# get the payment from the user
paying_amount = checkoutregister.checkoutregister.get_float("Please enter an amount to pay: ")
# check if the payment is done or not if yes then break the program
if float(check_pro_list_items.accept_payment(paying_amount)) <= 0:
break
check_pro_list_items.print_receipt()
# give the bag to the items which have low weight then bag
checkoutregister.checkoutregister.bag_products(check_pro_list_items.bucket)
# printing the thankou message to the user
print("Thank you for shopping at FedUni!\n")
# show user to continue to enter the product details of the next customer or he/she wants to quit
enter_new = input("(N)ext customer, or (Q)uit?")
# if user enter 'Q' then exits from the program
if enter_new.upper() == 'Q':
break
|
# print the type of an object - escrevendo o tipo de um objeto
print(type(1))
print(type(1.0))
print(type('a'))
print(type(True))
# use brackets to declare a list - use colchetes para declarar uma lista
print(type([1, 2, 3]))
print(len('Gabriela'))
print(len([10, 11, 12])) |
#!/usr/bin/python3
my_word = "Holberton"
print("{0} is the first letter of the word {1}".format(my_word[0],my_word))
|
import curses
import math
from curses_printable import CursesPrintable
from rectangle import Rectangle
# Vertical scroll list.
class ScrollableList(object):
def __init__(self, aWindowObject, aRectangle, aScrollKeysOrd=(curses.KEY_UP, curses.KEY_DOWN), aTitle=''):
self.title = aTitle
self.scrollKeys = aScrollKeysOrd
self.rectangle = aRectangle
self.viewRectangle = Rectangle(0, 0, aRectangle.width-1, aRectangle.height-1)
# List of NCursesPrintable objects.
self.content = []
self.screen = aWindowObject
def handleInput(self, aInput):
if aInput == self.scrollKeys[0]:
self.scrollUp()
elif aInput == self.scrollKeys[1]:
self.scrollDown()
def scrollUp(self, aNumLines=1):
self.scroll(1*aNumLines)
def scrollDown(self, aNumLines=1):
self.scroll(-1*aNumLines)
# Positive number = up; negative number = down
def scroll(self, aNumLines):
tTempPos = self.viewRectangle.y - aNumLines
# Ensure we can scroll.
if (tTempPos >= 0) and (tTempPos + self.viewRectangle.height) <= len(self.content):
self.viewRectangle.y = tTempPos
def draw(self):
self.drawContent()
self.drawBorder()
# Draw scrollbar on top of border.
if self.shouldShowScrollbar():
self.drawScrollbar()
def shouldShowScrollbar(self):
if len(self.content) > self.viewHeight:
return True
else:
return False
def drawBorder(self):
tUpperLeft = (self.rectangle.y, self.rectangle.x)
tUpperRight = (self.rectangle.y, self.rectangle.x+self.rectangle.width)
tLowerLeft = (self.rectangle.y+self.rectangle.height, self.rectangle.x)
tLowerRight = (self.rectangle.y+self.rectangle.height, self.rectangle.x+self.rectangle.width)
self.screen.vline(tUpperLeft[0], tUpperLeft[1], curses.ACS_VLINE, self.rectangle.height)
self.screen.hline(tUpperLeft[0], tUpperLeft[1], curses.ACS_HLINE, self.rectangle.width)
self.screen.hline(tLowerLeft[0], tLowerLeft[1], curses.ACS_HLINE, self.rectangle.width)
self.screen.vline(tUpperRight[0], tUpperRight[1], curses.ACS_VLINE, self.rectangle.height)
self.screen.addch(tUpperLeft[0], tUpperLeft[1], curses.ACS_ULCORNER)
self.screen.addch(tUpperRight[0], tUpperRight[1], curses.ACS_URCORNER)
self.screen.addch(tLowerRight[0], tLowerRight[1], curses.ACS_LRCORNER)
self.screen.addch(tLowerLeft[0], tLowerLeft[1], curses.ACS_LLCORNER)
def drawScrollbar(self):
self.drawBarOutline()
self.drawBar()
def drawBarOutline(self):
tBarOutlineYMin = self.rectangle.y + 1
tBarOutlineYMax = self.rectangle.y + self.viewHeight + 1
tX = self.rectangle.x + self.barXPos()
for tY in range(tBarOutlineYMin, tBarOutlineYMax):
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE)
self.screen.addstr(tY, tX, ' ', curses.color_pair(1))
def drawBar(self):
tBarSize = self.calculateBarSize()
tBarYMin = self.calculateBarYMin()+1
tX = self.barXPos()
for tY in range(tBarYMin, tBarYMin + tBarSize):
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_RED)
self.screen.addstr(tY, tX, ' ', curses.color_pair(2))
def drawContent(self):
# Only draw viewable content.
tStart = self.viewPos
tEnd = tStart + self.viewHeight
tViewable = self.content[tStart:tEnd]
for tY, tCursesPrintable in enumerate(tViewable, start=1):
tTransformedY = self.rectangle.y + tY
tTransformedX = self.rectangle.x + 1
# Clear line.
self.screen.addstr(tTransformedY, tTransformedX, ' '*self.viewRectangle.width)
tCursesPrintable.printAtLine(self.screen, tTransformedY, tTransformedX)
# Get the view rectangle of the content (the visible rectangle,
# excluding the border).
#def viewRectangle(self):
# pass
def barBounds(self):
return (self.calculateBarSize(), self.calculateBarYMin())
def calculateBarSize(self):
tBarSize = 1
try:
tBarSize = (float(float(self.viewHeight) / len(self.content)) * self.viewHeight)
tBarSize = math.trunc(tBarSize)
except:
# Divide-by-zero
tBarSize = 1
if tBarSize < 1:
tBarSize = 1
return tBarSize
def calculateBarYMin(self):
tPosPercentageOfTotal = 0
try:
# - self.viewHeight()
#print self.calculateBarSize()
tPosPercentageOfTotal = (float(self.viewPos) / (len(self.content) - self.viewHeight))
#tPosPercentageOfTotal = math.trunc(tPosPercentageOfTotal)
#self.screen.addstr(0, 0, str(tPosPercentageOfTotal))
except:
# Divide-by-zero
tPosPercentageOfTotal = 0
if tPosPercentageOfTotal < 0:
tPosPercentageOfTotal = 0
# TODO make some of these calculations solely on the number of buffer lines (self.content) and the current position
# at 100% when len(self.content) - (self.viewPos() + self.viewHeight()) == 0
# equivalently when len(self.content) - self.viewPos() == self.viewHeight()
#
# len(self.content) - self.viewHeight() = whole
# self.viewPos() = part
tBarYMin = tPosPercentageOfTotal * (self.viewHeight - self.calculateBarSize())
tBarYMin = math.trunc(tBarYMin)
return tBarYMin
# 0-based indices.
def setContentLine(self, aLineNum, aCursesPrintable):
# TODO extend content if line not yet given
#self.content[aLineNum] = aCursesPrintable
self.content.append(aCursesPrintable)
#def setRectange(self):
# pass
def barXPos(self):
return self.rectangle.width
# Height of just the content pane (excludes the border).
@property
def viewHeight(self):
return self.viewRectangle.height
@property
def viewPos(self):
return self.viewRectangle.y
|
class Rectangle(object):
def __init__(self, aX, aY, aWidth, aHeight):
self.x = aX
self.y = aY
self.width = aWidth
self.height = aHeight
|
def toplama(sayı1,sayı2):
return sayı1+sayı2
def çıkarma(sayı1,sayı2):
return sayı1-sayı2
def çarpma(sayı1,sayı2):
return sayı1*sayı2
def bölme(sayı1,sayı2):
return sayı1/sayı2
işlem=input("yapmak istediğiniz işlem: ")
if(işlem=="+"):
sayı1=int(input("toplamak istediğiniz sayıları giriniz:"))
sayı2=int(input("toplamak istediğiniz sayıları giriniz:"))
sonuç=toplama(sayı1,sayı2)
elif(işlem=="-"):
sayı1=int(input("çıkarmak istediğiniz sayıları giriniz:"))
sayı2=int(input("çıkarmak istediğiniz sayıları giriniz:"))
sonuç=çıkarma(sayı1,sayı2)
elif(işlem=="*"):
sayı1=int(input("çarpmak istediğiniz sayıları giriniz:"))
sayı2=int(input("çarpmak istediğiniz sayıları giriniz:"))
sonuç=çarpma(sayı1,sayı2)
elif(işlem=="/"):
sayı1=int(input("bölünen sayıyı giriniz:"))
sayı2=int(input("bölen sayıyı giriniz:"))
sonuç=bölme(sayı1,sayı2)
print(f"işleminizin sonucu ...{sonuç}...") |
for i in range(0,11):
if i==0 or i==10:
for j in range(0,11):
print("-",end="")
if i==1 or i==9:
for j in range(0,11):
if j!=5:
print("-",end="")
else:
print("+",end="")
if i==2 or i==8:
for j in range(0,11):
if j<3 or j>7:
print("-",end="")
else:
print("+",end="")
if i==3 or i==7:
for j in range(0,11):
if j<2 or j>8:
print("-",end="")
else:
print("+",end="")
if i==4 or i==6:
for j in range(0,11):
if j<2 or j>8:
print("-",end="")
else:
print("+",end="")
if i==5:
for j in range(0,11):
if j==0 or j==10:
print("-",end="")
else:
print("+",end="")
print("") |
from turtle import*
for i in range(72):
for j in range(6):
forward(70)
right(60)
right(5)
right(30)
forward(150)
for h in range(360):
right(1)
forward(1)
fillcolor("red")
shape("turtle")
stamp()
left(50)
forward(100)
shape("classic")
stamp()
right(90)
forward(170)
for c in range(4):
forward(100)
right(90)
fillcolor("blue")
|
name=None
print("hello world!")
name=input("what's your name?")
#this is a greeting.
print("hello, " +name+ " !")
print("My name is Python.")
pythonFavorites=['read','code','and sleep']
print('I like to ' +str(pythonFavorites[0:4]))
print(' 5 + 3 = 8 ')
#ha ha ha
print( 'OK bye!')
print('I need to code!')
print(str(pythonFavorites[0:4]) + '!')
print('la la la')
#la la la
|
print("게임을 시작합니다")
print("테트리스 시작")
print("1.오른쪽 2.왼쪽 3.블록 바꾸기")
number = input("숫자를 입력하세요: ")
print("당신이 입력한 숫자는?", number)
#만약에 1번을 누르면 오른쪽으로 이동
if int(number) == 1:
print("오른쪽으로 이동")
#만약에 2번을 누르면 왼쪽으로 이동
elif int(number) == 2:
print("왼쪽으로 이동")
#만약에 3번을 누르면 바꾸기 가능
else:
print("바꾸기")
|
import unittest
'''
unittest.skip(reason) 无条件地跳过装饰的测试,说明跳过测试的原因。
unittest.skipIf(condition, reason) 跳过装饰的测试,如果条件为真时。
unittest.skipUnless(condition, reason) 跳过装饰的测试,除非条件为真。
unittest.expectedFailure 测试标记为失败。不管执行结果是否失败,统一标记为失败
'''
class MyTest(unittest.TestCase):
@unittest.skip("直接跳过测试")
def test_skip(self):
print("test aaa")
@unittest.skipIf(3 > 2, "当条件为 True 时跳过测试")
def test_skip_if(self):
print('test bbb')
@unittest.skipUnless(3 > 2, "当条件为 True 时执行测试")
def test_skip_unless(self):
print('test ccc')
@unittest.expectedFailure
def test_expected_failure(self):
assertEqual(2, 3)
if __name__ == '__main__':
unittest.main()
|
def print_menu():
print("="*30)
print("xxx--system---")
print("1.xxx")
print("2.xxx")
def print_string():
print("string")
print_menu()
print_string()
def sum_2_nums(a,b):
result = a + b
print("%d+%d=%d"%(a,b,result))
num1 = int(input("请输入第1数字"))
num2 = int(input("请输入第2个数字"))
#调用函数
sum_2_nums(num1,num2)
#返回值带一值
def get_str():
str = 22
print("当前温度是:%d" %str)
return str
result = get_str()
#一个函数返回多个return
def test():
a = 11
b = 22
c = 33
#第1种,用一个列表来封装3个变量的值
d = [a,b,c]
return d
#第2种
#return [a,b,c]
#第3中
#return (a,b,c)
#return a,b,c
#return b
#return c
num = test()
print(num)
num = test()
print(num)
|
L = [x*2 for x in range(5)]
def creatNum():
a,b =0,1
for i in range(5):
yield b
a,b = b,a+b
a = creatNum()
for num in a:
print(num)
|
def create_room_number_dict():
room_numbers = {'CS101': '3004', 'CS102': '4501', 'CS103': "6755", 'NT110': '1244', 'CM241': '1441'}
return room_numbers
def create_instructor_dict():
instructors = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'}
return instructors
def create_time_dict():
times = {'CS101': '8:00 A.M', 'CS102': '9:00 A.M.', 'CS103': '10:00 A.M.', 'NT110': '11:00 A.M.', 'CM241': '1:00 P.M.'}
return times
def main():
room = create_room_number_dict();
instructor = create_instructor_dict();
time = create_time_dict();
course = input('Enter in a course number: ')
place = room[course]
teacher = instructor[course]
class_time = time[course]
print("The course", course, "is at",class_time, "in room", place, "and is taught by", teacher)
main()
|
"""
Although you have to be careful using recursion it is one of those concepts you want to at least understand. It's also commonly used in coding interviews :)
In this beginner Bite we let you rewrite a simple countdown for loop using recursion. See countdown_for below, it produces the following output:
"""
def countdown_for(start=10):
for i in reversed(range(1, start + 1)):
print(i)
print('time is up')
def countdown_recursive(start=10):
value = start
print(value)
if value > 1:
countdown_recursive(start=value-1)
else:
print('time is up')
countdown_recursive(30)
|
def sum_numbers(numbers=None):
# Check and fix input
if numbers == None:
numbers = range(1,101)
return sum(num for num in numbers) |
"""
Write a simple Promo class. Its constructor receives two variables: name (which must be a string) and expires (which must be a datetime object).
Add a property called expired which returns a boolean value indicating whether the promo has expired or not.
Checkout the tests and datetime module for more info. Have fun!
"""
from datetime import datetime, timedelta
NOW = datetime.now()
class Promo:
def __init__(self, name='', expires=datetime.now()):
self.name = name
self.expires = expires
@property
def expired(self):
return self.expires < datetime.now()
p = Promo('piff', datetime.now() + timedelta(seconds=3))
print(p.name)
print(p.expires)
print(p.expired)
|
#Number guessing game
from tkinter import *
import random
rNumber=random.randint(1,100)
print(rNumber)
window=Tk()
window.title("Number guessing game")
lbl=Label(window,text="Enter your guessing number: ", font=("Arial Bold", 25))
lbl.grid(column=0, row=0)
window.geometry("1000x1000")
textField=Entry(window,width=20)
textField.grid(column=1, row=0)
textField.focus()
def checkBt():
if int(textField.get())>rNumber:
lbl.configure(text="Your guessing number is bigger than the random number")
pass
if int(textField.get())<rNumber:
lbl.configure(text="Your guessing number is smaller than the random number")
pass
if int(textField.get())==rNumber:
lbl.configure(text="You are correct")
check=Button(window,text="check",command=checkBt)
check.grid(column=1,row=1)
|
"""
Classes são utilizadas para criar estruturas definidas.
Estas, definem funções chamadas de métodos.
Os métodos identificam os comportamentos e ações que um
objeto criado a partir da classe pode executar com
seus dados.
Uma classe é uma base de como algo deve ser definido.
Enquanto a classe é uma base, uma instância é um objeto que é
construído a partir de uma classe e contém dados reais.
"""
import random
from typing import List
# Definindo classes
class Carta:
def __init__(self, naipe="♦", valor="10"):
"""
As propriedades que os objetos ``Carta`` devem possuir, são definidos neste método.
Toda vez que uma ``Carta`` é criada, o método ``__init__`` irá definir o estado do
objeto, atribuindo os valores as propriedades.
Ou seja, ``__ init __`` inicializa cada nova instância da classe.
"""
"""
Neste exemplo a classe ``Carta`` possui a propriedade ``naipe`` (♣, v, ♥, ♠),
e a propriedade valor (2,3,4,5,6,7,8,9,10,K,Q,J,A).
"""
self.naipe = naipe
self.valor = valor
# Instanciando um objeto ``Carta`` simulando um dois de ouros.
dois_de_paus = Carta(naipe="♣", valor="2")
print()
dois_de_ouros = Carta(naipe="♦", valor="2")
print(dois_de_ouros.naipe)
print(dois_de_ouros.valor)
print(type(dois_de_ouros))
# Instanciando um novo objeto ``Carta`` simulando um 5 de espadas.
cinco_de_espadas = Carta(naipe="♠", valor="5")
print(cinco_de_espadas.naipe)
print(cinco_de_espadas.valor)
print(type(cinco_de_espadas))
# Objetos criados podem ser comparados
print(dois_de_ouros == cinco_de_espadas)
class Carta:
"""
Classes podem ter atributos associados a classe, como ``tipo``
"""
tipo: str = "cartolina"
def __init__(self, naipe: str, valor: str) -> None:
"""
E tributos de instância, como ``naipe`` e ``valor``.
"""
self.naipe: str = naipe
self.valor: str = valor
dez_de_paus = Carta(naipe="♣", valor="10")
print(dez_de_paus.naipe)
print(dez_de_paus.valor)
print(dez_de_paus.tipo)
print(type(dez_de_paus))
"""
Uma das maiores vantagens de usar classes para organizar dados é que
as instâncias têm a garantia de ter os atributos que você espera.
Todas as instâncias de ``Carta`` têm atributos ``naipe``, ``valor`` e
``tipo``, então você pode usar esses atributos com confiança, sabendo
que eles sempre retornarão um valor.
"""
"""
Os métodos de instância são funções definidas dentro de uma classe e só
podem ser chamados a partir de uma instância dessa classe.
Assim como ``__ init __``, o primeiro parâmetro de um método de instância
é sempre ``self``.
"""
class Baralho:
def __init__(self, cartas: List[Carta] = None) -> None:
self.cartas: List[Carta] = cartas or []
def embaralhar(self) -> None:
random.shuffle(self.cartas)
def tirar_do_topo(self) -> Carta:
return self.cartas.pop(0)
def tirar_de_baixo(self) -> Carta:
return self.cartas.pop(-1)
@property
def numero_de_cartas(self):
return len(self.cartas)
def cortar_no_meio(self):
if self.numero_de_cartas % 2:
meio = self.numero_de_cartas // 2
primeira_metade = self.cartas[:meio]
segunda_metade = self.cartas[:meio]
return Baralho(cartas=primeira_metade), Baralho(cartas=segunda_metade)
cinco_de_espadas = Carta(naipe="♠", valor="5")
dois_de_ouros = Carta(naipe="♦", valor="2")
dez_de_paus = Carta(naipe="♣", valor="10")
cartas_do_baralho = [cinco_de_espadas, dois_de_ouros, dez_de_paus]
baralho = Baralho(cartas=cartas_do_baralho)
print(baralho.cartas)
baralho.embaralhar()
print(baralho.cartas)
#
carta_de_baixo = baralho.tirar_de_baixo()
print(f"A carta de baixo é <Carta valor: {carta_de_baixo.valor}, naipe: {carta_de_baixo.naipe}>")
print(f"O baralho agora tem {baralho.numero_de_cartas} cartas")
carta_do_topo = baralho.tirar_do_topo()
print(f"A carta do topo é <Carta valor: {carta_do_topo.valor}, naipe: {carta_do_topo.naipe}>")
print(f"O baralho agora tem {baralho.numero_de_cartas} cartas")
"""
Quando trabalhamos com classes, podemos utilizar a herança evitando assim duplicação de código.
"""
class FileParser:
def __init__(self, file_path: str) -> None:
self.file_path = file_path
def read_file(self):
print(f"Deve ler o arquivo do caminho: {self.file_path}")
# No caso o CSVParser irá herdar os métodos ``read_file`` do FileParser
class CSVParser(FileParser):
def clean_dot_and_commas(self):
print(f"Deve remover os ; do arquivo: {self.file_path}")
# No caso o JSONParser irá herdar os métodos ``read_file`` do FileParser
class JSONParser(FileParser):
def replace_quotes(self):
print(f"Deve trocar as aspas duplas por aspas simples do arquivo: {self.file_path}")
file_parser = FileParser(file_path="arquivo.txt")
file_parser.read_file()
csv_parser = CSVParser(file_path="arquivo.txt")
csv_parser.read_file()
csv_parser.clean_dot_and_commas()
json_parser = JSONParser(file_path="arquivo.txt")
json_parser.read_file()
json_parser.replace_quotes()
|
class Tabular(object):
def __init__(self, *cols):
self.cols = cols
def show(self, data):
cols = self.cols
titles = [c[0] for c in cols]
vals = [ [str(c[1](d)) if d else "*" for c in cols] for d in data ]
lengths = [ reduce(lambda m, v: max(m, len(v[i])), vals + [ titles], 0) for i,c in enumerate(cols) ]
l = 1 + reduce(lambda l, s: l + s + 3, lengths, 0)
row = lambda r: "| " + " | ".join( ("%"+str(lengths[i])+"s") % v for i,v in enumerate(r)) + " |"
print "-" * l
print row(titles)
print "-" * l
for v in vals:
print row(v)
print "-" * l
|
#Jeremiah Hsieh AI Pac Man Final Project
#basic display and movement of pacman
import math
import pygame as pg
import random
#class for pellet objects using pg sprites to draw
class Pellet(pg.sprite.Sprite):
#initialize default to 255,255,255 which is white,
def __init__(self, x, y, r = 10, rgb = (255, 255, 255)):
pg.sprite.Sprite.__init__(self)
#x is x coordinate of pellet
self.x = x
#y is y coordinate
self.y = y
#r is radius of pellet
self.r = r
#rgb is color although technically python uses BGR (?) although that's may only be for opencv images
self.rgb = rgb
#pacman sprite class
class Pacman(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pacman
self.rect = self.image.get_rect(center=pos)
#ghost sprite class
class Ghost(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = ghost
self.rect = self.image.get_rect(center=pos)
#creates pellet object, sets paremeters
def spawnPellet(x = 100, y = 100):
#create pellet object
pellet = Pellet(x, y)
return pellet
#redraws window and updates values on a clock timer
def redraw(array):
arrayX = len(array)
arrayY = len(array[0])
#refill background first so that previously drawn objects don't stay on screen, 0 0 0 is black
win.fill((0,0,0))
#draw maze bounding box
pg.draw.rect(win, (0, 0, 255), (20, 20, arrayY * 40, arrayX * 40), 2)
#window, color, starting position and size
# pg.draw.rect(win, (255, 255, 255), (paddle.x, paddle.y, paddle.width, paddle.height))
pellet_list.draw(win)
#draw maze features
#loop thorugh maze array
for x in range(arrayX):
for y in range(arrayY):
#draw pellet if 1 is encountered
if array[x][y] == 1:
#remember 0,0 is top left of window not bottom right like on a graph (hence why x and y are reversed?)
pg.draw.circle(win, (255, 255, 255), [(y+1)*40, (x+1)*40], 10)
# pg.draw.rect(win, (255, 0, 0), (((y+1)*40)-20, ((x+1)*40)-20, 40, 40), 2)
#draw wall if 2 is encountered
elif array[x][y] == 2:
pg.draw.rect(win, (0, 0, 255), (((y+1)*40)-20, ((x+1)*40)-20, 40, 40))
#draw pacman sprite where 3 is in array
elif array[x][y] == 3:
# sprites_list.draw(win)
#blit to draw image at coordinates
win.blit(pacman, (((y+1)*40)-15, ((x+1)*40)-15))
# print(pacman.center)
# pg.draw.rect(win, (255, 0, 0), (((y+1)*40)-10, ((x+1)*40)-10, 20, 20), 2)
elif array[x][y] == 4:
win.blit(ghost, (((y+1)*40)-15, ((x+1)*40)-15))
#60 updates per second (equivalent to 5 fps) since it only checks and updates what is seen on screen 5 times per second
clock.tick(6)
pg.display.update()
# pg.display.flip()
def drawWindow():
#initialize pygame module
pg.init()
#draw window
win = pg.display.set_mode((600,600))
#window name
pg.display.set_caption("Pac-man")
return win
#modified version for group partner code
def otherRedraw(win, array, coin_coords, ghost_coords, power_coords, wall_list, score, pacy, pacx):
#load ghost file
ghost = pg.image.load('ghost2.png').convert_alpha()
pacman = pg.image.load('pacman.png').convert_alpha()
arrayX = len(array)
arrayY = len(array[0])
#refill background first so that previously drawn objects don't stay on screen, 0 0 0 is black
win.fill((0,0,0))
#draw maze bounding box
pg.draw.rect(win, (0, 0, 255), (10, 10, arrayY * 20, arrayX * 20), 1)
#window, color, starting position and size
# pg.draw.rect(win, (255, 255, 255), (paddle.x, paddle.y, paddle.width, paddle.height))
# pellet_list.draw(win)
# #draw maze features
# #loop thorugh maze array
# for x in range(arrayX):
# for y in range(arrayY):
# #draw pellet if 1 is encountered
# if array[x][y] == "O":
# #remember 0,0 is top left of window not bottom right like on a graph (hence why x and y are reversed?)
# pg.draw.circle(win, (255, 255, 255), [(y+1)*20, (x+1)*20], 5)
## pg.draw.rect(win, (255, 0, 0), (((y+1)*40)-20, ((x+1)*40)-20, 40, 40), 2)
# #draw wall if 2 is encountered
# elif array[x][y] == "|":
# pg.draw.rect(win, (0, 0, 255), (((y+1)*20)-10, ((x+1)*20)-10, 20, 20))
# #draw pacman sprite where 3 is in array
# elif array[x][y] == ".":
## sprites_list.draw(win)
# #blit to draw image at coordinates
# win.blit(pacman, (((y+1)*20)-7, ((x+1)*20)-7))
## print(pacman.center)
## pg.draw.rect(win, (255, 0, 0), (((y+1)*40)-10, ((x+1)*40)-10, 20, 20), 2)
# elif array[x][y] == "X":
# win.blit(ghost, (((y+1)*20)-7, ((x+1)*20)-7))
#modified rendering
for x in coin_coords:
pg.draw.circle(win, (255, 255, 255), [(x[1]+1)*20, (x[0]+1)*20], 5)
for x in ghost_coords:
win.blit(ghost, (((x[1]+1)*20)-7, ((x[0]+1)*20)-7))
for x in wall_list:
pg.draw.rect(win, (0, 0, 255), (((x[1]+1)*20)-10, ((x[0]+1)*20)-10, 20, 20))
win.blit(pacman, (((pacx+1)*20)-7, ((pacy+1)*20)-7))
#draw score on window
#make font type
font = pg.font.Font('freesansbold.ttf', 32)
#make text and draw on rectangle
text = font.render("Score: " + str(score), True, (0, 255, 0), (0, 0, 0))
#get rectange values
textRect = text.get_rect()
#set location values
textRect.center = ((arrayY * 50) // 2 + 20, (arrayX * 50) // 2 +20)
#draw on window
win.blit(text, textRect)
#60 updates per second (equivalent to 5 fps) since it only checks and updates what is seen on screen 5 times per second
# clock.tick(10)
pg.display.update()
# pg.display.flip()
#print lose text and quit game loop
def loseGame():
#make font type
font = pg.font.Font('freesansbold.ttf', 32)
#make text and draw on rectangle
text = font.render('Game Over', True, (0, 255, 0), (0, 0, 0))
#get rectange values
textRect = text.get_rect()
#set location values
textRect.center = (((mazey * 40) // 2) + 20, ((mazex * 40) // 2)+20)
#draw on window
win.blit(text, textRect)
#update window
pg.display.update()
#return true to pause game
return True
############################program main############################
if __name__ == "__main__":
#initialize pygame module
pg.init()
#window size variables
winx = 600
winy = 600
#fps is frames per second for clock tick speed
fps = 30
#list of all sprites in game
sprites_list = pg.sprite.Group()
#maze is array of numbers which stores the maze state to be rendered
#basic implementation - 0 is nothing, 1 is pellet, 2 is wall (currently only implemented pellets), 3 is pacman, 4 is ghost for now
maze = [[0, 3, 0, 0, 2, 1],
[0, 1, 0, 1, 2, 0],
[1, 1, 2, 0, 2, 1],
[2, 2, 2, 0, 2, 4],
[1, 0, 0, 1, 1, 0]]
#maze x y sizes
mazex = len(maze)
mazey = len(maze[0])
#pacman x y coordinate, maybe automate it to read from maze array?
pacx = 0
pacy = 1
#gamestate timer
clock = pg.time.Clock()
#set window parameters
win = pg.display.set_mode((winx,winy))
#window name
pg.display.set_caption("Pac-man")
#load pacman image sprite
pacman = pg.image.load('pacman2.png').convert_alpha()
ghost = pg.image.load('ghost.png').convert_alpha()
#make pacman class object for player
player = Pacman([200, 200])
enemy = Ghost([200, 200])
#add to list of sprites to render
sprites_list.add(player)
#initialize pygame object storage
pellet_list = pg.sprite.Group()
#game loop variable, loops until condition is false which stops game
run = True
pause = False
#window loop to render objects
while run == True:
#check for user input
#unlike key.getpressed it won't repeat automatically
for event in pg.event.get():
#exit program by clicking x
if event.type == pg.QUIT:
#stop loop
run = False
elif event.type == pg.KEYDOWN and event.key == pg.K_w:
#check if pacman is against edge of maze (or wall but not implemented yet)
if pacx > 0 and maze[pacx-1][pacy] != 2:
#lazy ghost check
if maze[pacx-1][pacy] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "up" one
pacx -= 1
maze[pacx][pacy] = 3
elif event.type == pg.KEYDOWN and event.key == pg.K_s:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacx < mazex - 1 and maze[pacx+1][pacy] != 2:
if maze[pacx+1][pacy] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "down" one
pacx += 1
maze[pacx][pacy] = 3
elif event.type == pg.KEYDOWN and event.key == pg.K_a:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacy > 0 and maze[pacx][pacy-1] != 2:
if maze[pacx][pacy-1] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "left" one
pacy -= 1
maze[pacx][pacy] = 3
elif event.type == pg.KEYDOWN and event.key == pg.K_d:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacy < mazey - 1 and maze[pacx][pacy+1] != 2:
if maze[pacx][pacy+1] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "right" one
pacy += 1
maze[pacx][pacy] = 3
#check for keypresses (continuous)
keys = pg.key.get_pressed()
#keyboard presses to move pacman
if keys[pg.K_UP]:
#check if pacman is against edge of maze (or wall but not implemented yet)
if pacx > 0 and maze[pacx-1][pacy] != 2:
if maze[pacx-1][pacy] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "up" one
pacx -= 1
maze[pacx][pacy] = 3
if keys[pg.K_DOWN]:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacx < mazex - 1 and maze[pacx+1][pacy] != 2:
if maze[pacx+1][pacy] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "down" one
pacx += 1
maze[pacx][pacy] = 3
if keys[pg.K_LEFT]:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacy > 0 and maze[pacx][pacy-1] != 2:
if maze[pacx][pacy-1] == 4:
pause =loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "left" one
pacy -= 1
maze[pacx][pacy] = 3
if keys[pg.K_RIGHT]:
#check if pacman is against edge of maze (or wall but not implekented yet)
if pacy < mazey - 1 and maze[pacx][pacy+1] != 2:
if maze[pacx][pacy+1] == 4:
pause = loseGame()
#move location of pacman in array
#make original space empty
maze[pacx][pacy] = 0
#move "right" one
pacy += 1
maze[pacx][pacy] = 3
#clock tick controls how many time the game is updated per second, higher = more frames
# clock.tick (fps)
if pause == False:
#draw sprites onto window
redraw(maze)
#stop pygame
pg.quit() |
#!/usr/bin/env python3
# Сумма трёх чисел
print(int(input('num1 '))+int(input('num2 '))+int(input('num3 '))) |
from .settings import DEBUG, debug_logs, debug_read1_file, NOT_UTF_8
# -------------------------------
# ----- character functions -----
# -------------------------------
def ischar(c:str) -> bool:
return len(c) == 1
def isalpha(c:str) -> bool:
if not ischar(c):
return False
elif ord('A') <= ord(c) <= ord('Z') or ord('a') <= ord(c) <= ord('z') or c == '_':
return True
else:
return False
def isnum(c:str) -> bool:
if not ischar(c):
return False
elif ord('0') <= ord(c) <= ord('9'):
return True
else:
return False
def isalnum(c:str) -> bool:
if isalpha(c) or isnum(c):
return True
else:
return False
def iswhitespace(c:str) -> bool:
if not ischar(c):
return False
elif c == ' ' or c == '\t' or c == '\n':
return True
else:
return False
# ----------------------------------
# ----- file related functions -----
# ----------------------------------
import re
from typing import List, IO, Any
def getcurpos(fin:IO) -> int:
return fin.tell()
def setcurpos(fin:IO, pos:int) -> None:
fin.seek(pos)
def read1(fin:IO, debug:bool=DEBUG) -> str:
try:
c = fin.read(1)
except:
print('Warning: character unsupported by \'utf-8\' codec encountered.')
c = NOT_UTF_8
if debug:
with open(debug_read1_file, 'a+') as debug:
debug.write(c)
return c
def debug(fin:IO, message:Any, execute:bool=DEBUG) -> None:
if not execute:
return
curpos = getcurpos(fin)
with open(debug_logs, 'a+') as debug:
debug.write('[' + str(curpos) + '] : ' + str(message) + '\n')
def clear_file(filepath:str) -> None:
with open(filepath, 'w+'):
pass
def peek1(fin:IO) -> str:
curpos = getcurpos(fin)
c = read1(fin)
setcurpos(fin, curpos)
return c
def skip1(fin:IO) -> None:
fin.read(1)
return
def skipwhitespaces(fin:IO) -> str:
whitespaces = ''
c = peek1(fin)
while iswhitespace(c):
whitespaces += c
read1(fin)
c = peek1(fin)
return whitespaces
def skip1until(fin:IO, char:str) -> None:
c = peek1(fin)
while c != char:
skip1(fin)
c = peek1(fin)
def extract_word(fin:IO) -> str:
word = ''
c = peek1(fin)
while isalnum(c):
word += c
read1(fin)
c = peek1(fin)
return word
def write(fout:IO, to_write:str) -> None:
fout.write(to_write)
def mysplit(string:str) -> List[str]:
return re.split(r'[/\\]', string)
def get_filename_from_path(filepath:str) -> str:
return mysplit(filepath)[-1]
|
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep
import datetime
today = datetime.date.today()
#Aks the user for how many days to scout ahead
while True:
try:
start_scout = int(input("How many days until you can leave? (0 to leave today)"))
daysahead = int(input("How many days ahead from today ("+ str(today)+ ") do you wanna scout?"))
if isinstance(daysahead, int) and isinstance(start_scout, int):
break
except ValueError:
print("Please insert a number")
my_url_cph_to_sthlm="https://www.sj.se/#/tidtabell/K%25C3%25B6benhavn%2520H/Stockholm%2520Central/enkel/avgang/20200101-0001/avgang/20200101-0001/BO-22--false///0//"
my_url_sthlm_to_cph="https://www.sj.se/#/tidtabell/Stockholm%2520Central/K%25C3%25B6benhavn%2520H/enkel/avgang/20200101-0001/avgang/20200101-0001/BO-22--false///0//"
my_url_goteborg_to_sthlm="https://www.sj.se/#/tidtabell/G%25C3%25B6teborg%2520C/Stockholm%2520Central/enkel/avgang/20200929-0500/avgang/20200929-1500/BO-22--false///0//"
my_url_sthlm_to_goteborg="https://www.sj.se/#/tidtabell/Stockholm%2520Central/G%25C3%25B6teborg%2520C/enkel/avgang/20200929-0500/avgang/20200929-1500/BO-22--false///0//"
def main(my_url):
today = datetime.date.today()
today += datetime.timedelta(days=int(start_scout))
#Here goes the path to your chromedriver.exe file:
path_to_chromedriver = 'C:\Program Files\chromedriver\chromedriver.exe'
dates=[] #List to store exact date
prices=[] #List to store price of the tickets
driver = webdriver.Chrome(executable_path=path_to_chromedriver)
waiting = 3
for i in range(daysahead):
prices_today = []
dates.append(str(today))
my_url = my_url.replace(my_url[90:98],str(today).replace("-", ""),2)
driver.get(my_url)
sleep(waiting)
for i in range(2):
try:
button = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/div[2]/div/main/div[1]/div/div/div/div[1]/div[3]/div[2]/div/div/div[5]/div[4]/div/button")
except:
pass
try:
button = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/div[2]/div/main/div[1]/div/div/div/div[1]/div[3]/div[1]/div/div/div[5]/div[4]/div/button")
except:
pass
if button.get_attribute("class")!="timetable__navigation-container timetable__link-hover-state timetable__navigation-button outline ng-scope":
continue
button.click()
sleep(waiting)
content = driver.page_source
soup = BeautifulSoup(content, features="html.parser")
for a in soup.findAll(lambda tag: tag.name == 'div' and tag.get('class') == ["timetable-unexpanded-price"]):
not_available = a.find("span", attrs={"class":"timetable-unexpanded-price--unavailable"})
if not_available:
continue
else:
try:
price=a.find(lambda tag: tag.name == 'span' and tag.get('class') == ['ng-binding']).get_text()
price = price.replace(" ", "")
price = int(price)
prices_today.append(price)
except AttributeError:
pass
if prices_today: prices.append(prices_today)
today += datetime.timedelta(days=1)
driver.quit()
#Time to sort these prices and print the cheapest days to travel.
cheapest=1338
all_time_cheapest=1337
dates_with_all_time_cheapest=[]
for prices_today,date in enumerate(dates):
try:
cheapest=min(prices[prices_today])
except:
continue
if cheapest<all_time_cheapest:
dates_with_all_time_cheapest=[date]
all_time_cheapest=cheapest
elif cheapest == all_time_cheapest:
dates_with_all_time_cheapest.append(date)
else:
continue
return(dates_with_all_time_cheapest, all_time_cheapest)
print("for STHLM to CPH:", str(main(my_url_sthlm_to_cph)))
print("for CPH to STHLM:", str(main(my_url_cph_to_sthlm)))
|
import numpy as np
import itertools
import time
# easy sudoku board
grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]
# supposed hardest sudoku board ever!
'''grid = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0]
]'''
print(np.matrix(grid))
def possible(y, x, n):
global grid
for i in range(0,9):
if grid[y][i] == n :
return False
for j in range(0,9):
if grid[j][x] == n :
return False
x0 = (x//3) * 3
y0 = (y//3) * 3
for i, j in itertools.product(range(3),range(3)):
if grid[y0+i][x0+j] == n :
return False
return True
def solve():
global grid
for x, y in itertools.product(range(9),range(9)):
if grid[y][x] == 0:
for n in range(1,10):
if possible(y,x,n):
grid[y][x] = n
solve()
grid[y][x] = 0
return
print(np.matrix(grid))
input('More?')
begin = time.time()
solve()
end = time.time()
print(end-begin)
|
"""
9. 점수 구간에 해당하는 학점이 아래와 같이 정의되어 있다.
점수를 입력했을 때 해당 학점이 출력되도록 하시오.
81~100 : A
61~80 : B
41~60 : C
21~40 : D
0~20 : F
예시
<입력>
score : 88
<출력>
A
"""
print('<입력>')
scr = input('score : ')
print('<출력>')
if int(scr) < 21:
grade = 'F'
elif int(scr) < 41:
grade = 'D'
elif int(scr) < 61:
grade = 'C'
elif int(scr) < 81:
grade = 'B'
else:
grade = 'A'
print(grade) |
#Polymorphism in inheritance lets us define methods in the child class that have the same name as the methods in the parent class
#Polymorphism means having many forms.
#Same function name(different parameters)being used for different implementations
class Bird:
def intro(self):
print("There are many type of birds")
def fly(self):
print("Many birds fly but some cannot")
class sparrow(Bird):
def fly(self):
print("Sparrows can fly")
class ostritch(Bird):
def fly(self):
print("Ostritches cannot fly")
if __name__ == "__main__":
obbird = Bird()
obsparrow = sparrow()
obsotritch = ostritch()
for bird in (obsparrow, obsotritch):
bird.intro()
bird.fly()
print()
|
"""Program to generate preprocessed N-gram vocabulary for contextual embeddings
To do this, we need to collect all of the N-gram vocab from a corpus, and then
run each N-gram chunk through the embedder. The vocabulary for the embedder is
going to be 1-grams and it will process an array. For example, if we have a sample
sentence: "The dog crossed the road", and we are collecting trigrams, our vocab will
include entries like: `["<PAD> The dog", "The dog crossed", "dog crossed the",...]` etc.
To prepare the output file (which will be in `word2vec` binary format, we evaluate N-gram
and we populate a single word2vec entry with delimiters:
`"The@@dog@@crossed <vector>`
The `<vector>` is found by running, e.g. ELMo with the entry "The dog crossed", which yields
a `Time x Word` output, and we select a pooled representation and send it back
"""
import argparse
import baseline
import sys
sys.path.append('../python/addons')
import embed_elmo
import embed_bert
from baseline.tf.embeddings import *
from baseline.embeddings import *
from baseline.vectorizers import create_vectorizer, TextNGramVectorizer
from baseline.reader import CONLLSeqReader, TSVSeqLabelReader
from baseline.w2v import write_word2vec_file
from baseline.utils import ngrams
import tensorflow as tf
import numpy as np
import codecs
import re
from collections import Counter
BATCHSZ = 32
def pool_op(embedding, name):
if len(embedding.shape) == 3:
assert embedding.shape[0] == 1
embedding = embedding.squeeze()
T = embedding.shape[0]
if T == 1:
return embedding.squeeze()
if name == 'mean':
return np.mean(embedding, axis=0)
if name == 'sum':
return np.sum(embedding, axis=0)
if name == 'max':
return np.max(embedding, axis=0)
if name == 'last':
return embedding[-1]
elif name == 'first':
embedding[0]
center = T//2 + 1
return embedding[center]
def get_unigram_vectorizer(s, vf, mxlen, lower=True):
"""Get a vectorizer object by name from `BASELINE_VECTORIZERS` registry
:param s: The name of the vectorizer
:param vf: A vocabulary file (which might be ``None``)
:param mxlen: The vector length to use
:param lower: (``bool``) should we lower case? Defaults to ``True``
:return: A ``baseline.Vectorizer`` subclass
"""
vec_type = 'token1d'
transform_fn = baseline.lowercase if lower else None
if s == 'bert':
vec_type = 'wordpiece1d'
if s == 'elmo':
vec_type = 'elmo'
return create_vectorizer(type=vec_type, transform_fn=transform_fn, vocab_file=vf, mxlen=mxlen)
def get_embedder(embed_type, embed_file):
"""Get an embedding object by type so we can evaluate one hot vectors
:param embed_type: (``str``) The name of the embedding in the `BASELINE_EMBEDDINGS`
:param embed_file: (``str``) Either the file or a URL to a hub location for the model
:return: An embeddings dict containing vocab and graph
"""
if embed_type == 'bert' or embed_type == 'elmo':
embed_type += '-embed'
embed = baseline.load_embeddings('word', embed_type=embed_type,
embed_file=embed_file, keep_unused=True, trainable=False, known_vocab={})
return embed
parser = argparse.ArgumentParser(description='Encode a sentence as an embedding')
parser.add_argument('--input_embed', help='Input embedding model. This will typically be a serialized contextual model')
parser.add_argument('--type', default='default', choices=['elmo', 'default'])
parser.add_argument('--files', required=True, nargs='+')
parser.add_argument('--output_embed', default='elmo.bin', help='Output embedding model in word2vec binary format')
parser.add_argument('--lower', type=baseline.str2bool, default=False)
parser.add_argument('--vocab_file', required=False, help='Vocab file (required only for BERT)')
parser.add_argument('--max_length', type=int, default=100)
parser.add_argument('--ngrams', type=int, default=3)
parser.add_argument('--reader', default='conll', help='Supports CONLL or TSV')
parser.add_argument('--column', default='0', help='Default column to read features from')
parser.add_argument('--op', type=str, default='mean')
args = parser.parse_args()
# Create our vectorizer according to CL
uni_vec = get_unigram_vectorizer(args.type, args.vocab_file, args.ngrams)
def read_tsv_features(files, column, filtsz, lower):
"""Read features from CONLL file, yield a Counter of words
:param files: Which files to read to form the vocab
:param column: What column to read from (defaults to '0')
:param filtsz: An integer value for the ngram length, e.g. 3 for trigram
:param lower: Use lower case
:return: A Counter of words
"""
words = Counter()
text_column = int(column)
transform_fn = lambda z: z.lower() if lower else z
for file_name in files:
if file_name is None:
continue
with codecs.open(file_name, encoding='utf-8', mode='r') as f:
for il, line in enumerate(f):
columns = line.split('\t')
text = columns[text_column]
sentence = text.split()
if len(text) == 0:
print('Warning, invalid text at {}'.format(il))
continue
pad = ['<UNK>'] * (filtsz//2)
words.update(ngrams(pad + [transform_fn(x) for x in sentence] + pad, filtsz=filtsz))
return words
def read_conll_features(files, column, filtsz, lower):
"""Read features from CONLL file, yield a Counter of words
:param files: Which files to read to form the vocab
:param column: What column to read from (defaults to '0')
:param filtsz: An integer value for the ngram length, e.g. 3 for trigram
:param lower: Use lower-case
:return: A Counter of words
"""
words = Counter()
conll = CONLLSeqReader(None)
text_column = str(column)
# This tabulates all of the ngrams
for file in files:
print('Adding vocab from {}'.format(file))
examples = conll.read_examples(file)
transform_fn = lambda z: z.lower() if lower else z
for sentence in examples:
pad = ['<UNK>'] * (filtsz//2)
words.update(ngrams(pad + [transform_fn(x[text_column]) for x in sentence] + pad, filtsz=filtsz))
return words
reader_fn = read_conll_features if args.reader == 'conll' else read_tsv_features
words = reader_fn(args.files, args.column, args.ngrams, args.lower)
# print them too
print(words.most_common(25))
# build a vocab for the output file comprised of the ngram words
output_vocab = list(words)
# Make a session
with tf.Session() as sess:
# Get embeddings
embed = get_embedder(args.type, args.input_embed)
# This is our decoder graph object
embedder = embed['embeddings']
# This is the vocab
vocab = embed['vocab']
# Declare a tf graph operation
y = embedder.encode()
init_op = tf.global_variables_initializer()
sess.run(init_op)
vecs = []
one_hot_batch = []
for i, token in enumerate(output_vocab):
tokens = token.split('@@')
# Run vectorizer to get ints and length of vector
if i % BATCHSZ == 0 and i > 0:
# This resets the session, which is needed for ELMo to get same results when batching
sess.run(init_op)
vecs += [pool_op(emb, args.op) for emb in sess.run(y, feed_dict={embedder.x: one_hot_batch})]
one_hot_batch = []
one_hot, sentence_len = uni_vec.run(tokens, vocab)
one_hot_batch.append(one_hot)
if one_hot_batch:
sess.run(init_op)
vecs += [pool_op(emb, args.op) for emb in sess.run(y, feed_dict={embedder.x: one_hot_batch})]
write_word2vec_file(args.output_embed, output_vocab, vecs)
|
"""
Search and recognize the name, category and
brand of a product from its description.
"""
from typing import Optional, List, Union, Dict
from itertools import combinations
import pandas as pd # type: ignore
from pymystem3 import Mystem # type: ignore
try:
from cat_model import PredictCategory # type: ignore
except ImportError:
from receipt_parser.cat_model import PredictCategory # type: ignore
# pylint: disable=C1801
def df_apply(data: pd.DataFrame, func, axis: int = 1) -> pd.DataFrame:
"""
User define the `apply` function from pd.DataFrame.
Use only for 2-column and 3-column data.
Parameters
----------
data : pd.DataFrame
The data on which the `func` function will be applied.
func : function
Function to apply to each column or row.
axis : {0 or 'index', 1 or 'columns'}, default=1
Axis along which the function is applied.
Returns
-------
pd.DataFrame
Result of applying ``func`` along the given axis of the
DataFrame.
Examples
--------
>>> from pandas import DataFrame
>>> DataFrame.my_apply = df_apply
>>> df[['name', 'brand']].my_apply(foo)
"""
_cols = data.columns
_len = len(_cols)
if _len == 2:
return data.apply(lambda x: func(x[_cols[0]], x[_cols[1]]), axis=axis)
return data.apply(lambda x: func(x[_cols[0]], x[_cols[1]], x[_cols[2]]), axis=axis)
class Finder:
"""
Search and recognize the name, category and brand of a product
from its description.
Search is carried out in the collected datasets: `brands_ru.csv`,
`products.csv`, `all_clean.csv`.
Parameters
----------
pathes: Optional[Dict[str, str]], (default=None)
Dictionary with paths to required files.
Attributes
----------
mystem : Mystem
A Python wrapper of the Yandex Mystem 3.1 morphological
analyzer (http://api.yandex.ru/mystem).
See aslo `https://github.com/nlpub/pymystem3`.
cat_model: PredictCategory
Class for predicting a category by product description
using a neural network written in PyTorch.
brands_ru : np.ndarray
List of Russian brands.
products : pd.DataFrame
DataFrame of product names and categories.
all_clean : pd.DataFrame
General dataset with all product information.
data: pd.DataFrame
Text column with a description of the products to parse.
Products description should be normalized by Normalizer.
See `receipt_parser.normalize.Normalizer`.
Examples
--------
>>> product = 'Майонез MR.RICCO Провансаль 67% д/п 400'
>>> finder = Finder()
>>> finder.find_all(product)
Notes
-----
You may be comfortable with the following resource:
'https://receiptnlp.tinkoff.ru/'.
See also `receipt_parser.parsers.tinkoff`.
"""
def __init__(self, pathes: Optional[Dict[str, str]] = None):
pathes = pathes or {}
self.mystem = Mystem()
pd.DataFrame.appl = df_apply
# Init model:
model_params = {"num_class": 21, "embed_dim": 50, "vocab_size": 500}
bpe_model = pathes.get("cat_bpe_model", "models/cat_bpe_model.yttm")
cat_model = pathes.get("cat_model", "models/cat_model.pth")
self.cat_model = PredictCategory(bpe_model, cat_model, model_params)
# Read DataFrames:
brands = pathes.get("brands_ru", "data/cleaned/brands_ru.csv")
products = pathes.get("products", "data/cleaned/products.csv")
all_clean = pathes.get("all_clean", "data/cleaned/all_clean.csv")
self.brands_ru = pd.read_csv(brands)["brand"].values
self.products = pd.read_csv(products)
self.all_clean = pd.read_csv(all_clean)
self.data = pd.DataFrame()
def find_brands(self, name: str, brand: Optional[str] = None) -> pd.Series:
"""
Find Russian brands using the dataset `brands_ru.csv`.
For more accurate recognition, a combination of words in a
different order is used.
Parameters
----------
name : str
Product name.
brand : str, optional (default=None)
Product category.
Returns
-------
pd.Series
pd.Series([name, brand])
"""
if name and not brand:
names = set(
[f"{comb[0]} {comb[1]}" for comb in combinations(name.split(), 2)]
+ name.split()
)
for rus_brand in self.brands_ru:
if rus_brand in names:
name = name.replace(rus_brand, "").replace(" ", " ").strip()
return pd.Series([name, rus_brand])
return pd.Series([name, brand])
@staticmethod
def __remove_duplicate_word(arr: List[str]) -> List[str]:
"""
Remove duplicates in words when one name is a continuation
of another: ['вода', 'вода питьевая'] --> ['вода питьевая'].
Parameters
----------
arr : List[str]
List description of products in different variants.
Returns
-------
arr : List[str]
List description of products without duplicates.
"""
if max([len(x.split()) for x in arr]) > 1:
arr = sorted(arr, key=lambda x: len(x.split()))
one_words = []
for product in arr.copy():
if len(product.split()) == 1:
one_words.append(product)
else:
for word in one_words:
if word in product and word in arr:
arr.remove(word)
return arr
# pylint: disable=bad-continuation
def find_product(
self, name: str, product: str, category: Optional[str] = None
) -> pd.Series:
"""
Find products name using the dataset `products.csv`.
For more accurate recognition, a combination of words in a
different order is used.
Parameters
----------
name : str
Product name.
product : str
Product description.
category : str, optional (default=None)
Product category.
Returns
-------
pd.Series
pd.Series([name, product, category])
"""
if name and not product:
names = pd.DataFrame(
set(
[f"{comb[0]} {comb[1]}" for comb in combinations(name.split(), 2)]
+ name.split()
),
columns=["product"],
)
merge = self.products.merge(names)
if len(merge):
product = ", ".join(
self.__remove_duplicate_word(merge["product"].values)
)
if len(merge) == 1:
category = merge["category"].values[0]
else:
category = self.cat_model.predict(name)
return pd.Series([name, product, category])
def _use_mystem(self, name: str, product: str) -> str:
"""
Use Yandex pymystem3 library to lemmatize words in product descriptions.
I tried to use pymorphy, but the recognition quality got worse.
Parameters
----------
name : str
Product name.
product : str
Product description.
Returns
-------
str
Product description after lemmatization.
Notes
-----
See also `https://github.com/nlpub/pymystem3`.
"""
if name and not product:
name = "".join(self.mystem.lemmatize(name)[:-1])
return name
def find_category(self, name: str, product: str, category: str) -> pd.Series:
"""
Find a product category using the dataset `products.csv`.
Parameters
----------
name : str
Product name.
product : str
Product description.
category : str
Product category.
Returns
-------
pd.Series
pd.Series([product, category])
"""
if product and not category:
tmp = self.products[self.products["product"] == product]
if len(tmp):
category = tmp["category"].values[0]
else:
category = self.cat_model.predict(name)
return pd.Series([product, category])
def find_product_by_brand(
self, product: str, brand: str, category: str
) -> pd.Series:
"""
If we were able to recognize the product brand,
but could not recongize the product name,
we can assign the most common product name for this brand.
Parameters
----------
product : str
Product description.
brand : str
Product brand.
category : str
Product category.
Returns
-------
pd.Series
pd.Series([product, brand, category])
"""
if brand and not product:
single_brand_goods = self.all_clean[self.all_clean["Бренд"] == brand]
if len(single_brand_goods):
product = single_brand_goods["Продукт"].value_counts().index[0]
category = single_brand_goods["Категория"].value_counts().index[0]
return pd.Series([product, brand, category])
def __print_logs(self, message: str, verbose: int) -> None:
"""
Print the number of recognized brands,
categories and names of goods.
"""
if verbose:
_len = len(self.data)
print(message)
print(
"Recognized brands: "
f"{len(self.data['brand_norm'].dropna())}/{_len}, "
f"products: {len(self.data['product_norm'].dropna())}/{_len}, "
f"categories: {len(self.data['cat_norm'].dropna())}/{_len}",
"-" * 80,
sep="\n",
end="\n\n",
)
@staticmethod
def __transform_data(data: Union[pd.DataFrame, str]) -> pd.DataFrame:
"""Transform pd.Series or str to pd.DataFrame."""
columns = ["product_norm", "brand_norm", "cat_norm"]
if isinstance(data, str):
data = pd.DataFrame([data], columns=["name_norm"])
else:
if "name_norm" not in data.columns:
raise ValueError(
"Столбец с описанием товара должен иметь название `name_norm`."
)
for col in columns:
if col not in data.columns:
data[col] = None
return data
def __find_all(self, verbose: int) -> None:
self.__print_logs("Before:", verbose)
# Find brands:
self.data[["name_norm", "brand_norm"]] = self.data[
["name_norm", "brand_norm"]
].appl(self.find_brands)
self.__print_logs("Find brands:", verbose)
# Find product and category:
self.data[["name_norm", "product_norm", "cat_norm"]] = self.data[
["name_norm", "product_norm"]
].appl(self.find_product)
self.__print_logs("Find product and category:", verbose)
# Remove `-`:
self.data["name_norm"] = self.data["name_norm"].str.replace("-", " ")
self.data[["name_norm", "product_norm", "cat_norm"]] = self.data[
["name_norm", "product_norm", "cat_norm"]
].appl(self.find_product)
self.__print_logs(
"Remove `-` and the second attempt to find a product:", verbose
)
# Use Mystem:
self.data["name_norm"] = self.data[["name_norm", "product_norm"]].appl(
self._use_mystem
)
self.data[["name_norm", "product_norm", "cat_norm"]] = self.data[
["name_norm", "product_norm", "cat_norm"]
].appl(self.find_product)
self.__print_logs(
"Use Mystem for lemmatization and the third attempt to find a product:",
verbose,
)
# Find category:
self.data[["product_norm", "cat_norm"]] = self.data[
["name_norm", "product_norm", "cat_norm"]
].appl(self.find_category)
self.__print_logs("Find the remaining categories:", verbose)
# Find product by brand:
self.data[["product_norm", "brand_norm", "cat_norm"]] = self.data[
["product_norm", "brand_norm", "cat_norm"]
].appl(self.find_product_by_brand)
self.__print_logs("Find product by brand:", verbose)
def find_all(
self, data: Union[pd.DataFrame, str], verbose: int = 0
) -> pd.DataFrame:
"""
Start search and recognition search processes in `data`.
Parameters
----------
data : Union[pd.DataFrame, str]
Text column with a description of the products to parse.
Products description should be normalized by Normalizer.
See `receipt_parser.normalize.Normalizer`.
verbose: int (default=0)
Set verbose to any positive number for verbosity.
Returns
-------
pd.DataFrame
Recognized product names, brands and product categories.
"""
self.data = self.__transform_data(data)
self.__find_all(verbose)
return self.data
|
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
""" Study Drills
1. Write English comments for each line to understand what that line does.
2. Each time print_a_line is run, you are passing a variable current_line.
Write out what current_line is equal to on each function call, and trace
how it becomes line_count in print_a_line.
current_line is equal to 1, 2, and 3 in the three function calls. As it
gets passed to the function it is "renamed" to line_count.
3. Find each place a function is used, and check its def to make sure that
you are giving it the right arguments.
4. Research online what the seek function for file does. Try pydoc file and
see if you can figure it out from there.
seek(offset[, whence]) -> None. Move to new file position.
|
| Argument offset is a byte count. Optional argument whence defaults to
| 0 (offset from start of file, offset should be >= 0); other values are 1
| (move relative to current position, positive or negative), and 2 (move
| relative to end of file, usually negative, although many platforms allow
| seeking beyond the end of a file). If the file is opened in text mode,
| only offsets returned by tell() are legal. Use of other offsets causes
| undefined behavior.
| Note that not all file objects are seekable.
5. Research the shorthand notation += and rewrite the script to use +=
instead.
"""
|
import hashmap
# create a mapping of state to abbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities in them
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set(cities, 'FL', 'Jacksonville')
# add some more cities
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')
# print out some cities
print '-' * 10
print "NY State has: %s" % hashmap.get(cities, 'NY')
print "OR State has: %s" % hashmap.get(cities, 'OR')
# print some states
print '-' * 10
print "Michigan's abbreviation is: %s" % hashmap.get(states, 'Michigan')
print "Florida's abbreviation is: %s" % hashmap.get(states, 'Florida')
# do it by using the state then cities dict
print '-' * 10
print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan'))
print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida'))
# print every state abbreviation
print '-' * 10
hashmap.list(states)
# print every city in state
print '-' * 10
hashmap.list(cities)
print '-' * 10
state = hashmap.get(states, 'Texas')
if not state:
print "Sorry, no Texas."
# default values using ||= with the nil result
# can you do this on one line?
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
"""
When to Use Dictionaries or Lists
1. You have to retrieve things based on some identifier, like names,
addresses, or anything that can be a key.
2. You don't need things to be in order. Dictionaries do not normally
have any notion of order, so you have to use a list for that.
3. You are going to be adding and removing elements and their keys.
Study Drills
1. Do this same kind of mapping with cities and states/regions in your
country or some other country.
TODO
2. Find the Python documentation for dictionaries and try to do even
more things to them.
TODO
3. Find out what you can't do with dictionaries. A big one is that
they do not have order, so try playing with that.
TODO
4. Read about Python's assert feature and then take the hashmap code
and add assertions for each of the tests I've done instead of
print. For example, you can assert that the first get operation
returns "New York" instead of just printing that out.
TODO
5. Did you notice that the list function listed the items I added in a
different order than they were added? This is an example of how
dictionaries don't maintain order, and if you analyze the code
you'll understand why.
TODO
6. Create a dump function that is like list but which dumps the full
contents of every bucket so you can debug it.
TODO
7. Make sure you know what the hash function does in that code. It's a
special function that converts strings to a consistent integer.
Find the documentation for it online. Read about what a "hash
function" is in programming.
TODO
""" |
from Deck import Deck
from Card import Card
from Player import Player
def display_cards(cards):
for card in cards:
print(card)
def cards_sum(cards):
total = 0
for card in cards:
total += card.card_value()
return total
def contains_ace(cards, person):
for card in cards:
if card.rank == 'Ace':
if cards_sum(cards) >= 21:
card.value = 1
else:
if person == 'p':
while True:
try:
value = int(input('Choose either 1 or 11 for your ace card: '))
except:
print('You can only enter a number')
continue
else:
if value == 1 or value == 11:
break
else:
print('You must choose 1 or 11 only')
continue
else:
card.value = 11
if __name__ == '__main__':
print('$$$$$$$$$$$$$$$$$$$$ WELCOME TO BLACKJACK $$$$$$$$$$$$$$$$$$$$\n')
# Create a 52 card deck
deck = Deck()
# Shuffle the deck
deck.shuffle()
# print(deck) #to check
print('Each player will have $2500 initially \n')
# take name and bet from player
playerName = input('Please enter your name: ')
gameOver = False
player = Player(playerName, 2500)
while not gameOver:
while True:
try:
playerBet = int(input('Please place your bet: '))
except:
print('You must enter a number')
else:
if playerBet > player.balance or playerBet < 1:
print('You must enter a number between 1 and 2500')
continue
else:
player.bet_placed(playerBet)
break
print('\n' * 100)
print(f'{player.name}\'s cards: ')
playerCards = [deck.pick_card(), deck.pick_card()]
display_cards(playerCards)
print(f'{player.name}\'s Sum: {cards_sum(playerCards)}')
print('\nDealer Cards: ')
dealerCards = [deck.pick_card(), deck.pick_card()]
dealerDisplayCards = [dealerCards[1]]
display_cards(dealerDisplayCards)
print(f'Dealer Sum: {cards_sum(dealerDisplayCards)}\n')
contains_ace(playerCards, 'p')
contains_ace(dealerCards, 'd')
# handle all naturals
if cards_sum(dealerCards) == 21 and cards_sum(playerCards) == 21:
print('Game is tied. You will get your bet back')
player.bet_win(playerBet)
elif cards_sum(playerCards) == 21 and cards_sum(dealerCards) < 21:
print(f"This is a natural. {player.name} will get 1.5 times their bet back")
player.bet_win(playerBet*1.5)
elif cards_sum(dealerCards) == 21 and cards_sum(playerCards) < 21:
print(f'Dealer has a natural. {player.name} loses their bet')
bust = False
playerTurn = False
while not bust:
while not playerTurn:
playerAction = input('\nDo you wanna hit or stand? h = hit, s = stand: ')
if playerAction == 'h':
playerCards.append(deck.pick_card())
print(f'\n{player.name}\'s Cards:')
display_cards(playerCards)
print(f'{player.name}\'s Sum: {cards_sum(playerCards)}')
if cards_sum(playerCards) >= 21:
bust = True
playerTurn = True
print('You have busted. You lost your bet')
else:
playerTurn = True
if not bust:
while cards_sum(dealerCards) <= 17:
print('\nDealer hits')
pickedCard = deck.pick_card()
dealerCards.append(pickedCard)
dealerDisplayCards.append(pickedCard)
print(f'Dealer Cards:')
display_cards(dealerDisplayCards)
if cards_sum(dealerCards) >= 21:
bust = True
print('\nRevealing all dealer cards..... ')
display_cards(dealerCards)
print('Dealer has been busted. You win 1.5 times your bet')
player.bet_win(playerBet*1.5)
if not bust:
print(f'\nRevealing all dealer cards.....')
print(f'Dealer Cards:')
display_cards(dealerCards)
print(f'Dealer Sum: {cards_sum(dealerCards)}')
print(f'\n{player.name}\'s Cards:')
display_cards(playerCards)
print(f'{player.name}\'s Sum: {cards_sum(playerCards)}')
if cards_sum(playerCards) > cards_sum(dealerCards):
print('Congratulations! You have won!')
player.bet_win(playerBet * 1.5)
elif cards_sum(playerCards) < cards_sum(dealerCards):
print('Sorry! You lost your bet')
else:
print('Its a draw!!')
player.bet_win(playerBet)
print(f'\n{player.name}\'s Balance: {player.balance}')
while True:
playAgain = input('Do you wanna play again? (y/n): ')
if playAgain == 'y' or playAgain == 'n':
break
else:
print('Please enter y(yes) or n(no): ')
continue
print('\n'*100)
if playAgain == 'y':
gameOver = False
else:
gameOver = True
print('*********************************THANKS FOR PLAYING*********************************')
break
|
def letterCasePermutation(self, S: str) -> List[str]:
ls = [] # list store stirng
def UpperCaseInCharacter(S: str, index: int) -> str:
s = list(S)
s[index] = s[index].upper()
return "".join(s)
def LowerCaseInCharacter(S: str, index: int) -> str:
s = list(S)
s[index] = s[index].lower()
return "".join(s)
def CasePer(S: str, index: int, n: int):
if index >= n:
ls.append(S)
else:
CasePer(S, index + 1, n)
if S[index].isalpha():
if S[index].islower():
S = UpperCaseInCharacter(S, index)
CasePer(S, index + 1, n)
else:
S = LowerCaseInCharacter(S, index)
CasePer(S, index + 1, n)
CasePer(S, 0, len(S))
return ls |
def oddEvenList(self, head: ListNode) -> ListNode:
odds = ListNode(0)
evens = ListNode(0)
index = 1
oddsHead = head
evensHead = evens
while head: # using while head to avoid NoneType error
if (index % 2 != 0):
odds.next = head
odds = odds.next
# use next in stead of val to advoid NoneType error
else:
evens.next = head
evens = evens.next
head = head.next
index += 1
evens.next = None
odds.next = evensHead.next
return oddsHead # zero at start |
def subsets(self, nums: List[int]) -> List[List[int]]:
ls, leng = [], len(nums)
def subsets(origin_set: List[int], subset: List[int], index: int, n: int):
if index >= n:
new_set = []
new_set.extend(subset)
ls.append(new_set)
else:
new_set = []
new_set.extend(subset)
subsets(origin_set, new_set, index + 1, n)
# print(subset)
new_set.append(origin_set[index])
# print(subset)
subsets(origin_set, new_set, index + 1, n)
subsets(nums, [], 0, leng)
return ls
|
def cipher(word):
s=""
for w in word:
if(w.islower()):
s=s+chr(219-ord(w))
else:
s=s+w
return s
def main():
cip=cipher("Sample Sentence だよ")
print(cip)
rev_chip=cipher(cip)
print(rev_chip)
if __name__ == "__main__":
main()
|
b={1:'Entry',2:'Details',3:'Exit'}
for i in b:
print(b[i])
b1=int(input('Enter Command:'))
if b1==1:
import entry
elif b1==2:
import details
elif b1==3:
print('Exit')
else:
print('Please Enter Right One:')
|
# GUI 연습
import tkinter as tk # 창 생성
Window = tk.Tk()
# window 창 설정
Window.title( "제목" )
Window.geometry( "500x500+200+100" ) # ("너비 x 높이 + x좌표 + y좌표")
# 배치 (위젯)
label = tk.Label( Window, text= "입력하세요" )
label.pack()
display = tk.Entry( Window, width=30 )
display.pack()
# Window.resizeable(False, False) # 윈도우 창 크기 조절 여부 조절 -> 상수도 입력가능 ( 상하, 좌우 )
# 함수
def func(event):
print(tk.Entry.get(display)) # 입력창에 들어있는 값을 출력 해준다.
# print('enter pressed ~') # 임시 // 문자열만 출력
Window.bind('<Return>',func) # 엔터키 이벤트를 함수에 연결
Window.mainloop()
|
import pygame
import random
pygame.init()
#Creating window for game
screen_width = 900
screen_height = 500
gamewindow = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("My Game")
pygame.display.update()
clock = pygame.time.Clock()
#colors
white = (255,255,255)
red = (255, 0, 0)
black = (0, 0, 0)
random_color = (200, 154, 20)
#To update score on gamewindow
font = pygame.font.SysFont(None, 55)
def text_screen(text, color, x, y):
screen_text = font.render(text, True, color)
gamewindow.blit(screen_text, [x,y])
#For increasing lenth of snake upon eating each time
def plotsnake(gamewindow, color, snake_list, snake_size):
for x,y in snake_list:
pygame.draw.rect(gamewindow,color,[x, y, snake_size, snake_size])
#Welcome Screen
def welcome():
exit_game = False
while not exit_game:
gamewindow.fill(white)
text_screen("Welcome To Snakes", red, 260, 150)
text_screen("Press Space Bar To Start Game", red, 170, 200)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
gameloop()
pygame.display.update()
clock.tick(40)
#Creating Gameloop
def gameloop():
# Game specific variables
game_over = False
exit_game = False
snake_x = 65
snake_y = 75
veloc_x = 0
veloc_y = 0
init_velocity = 5
food_x = random.randint(45, screen_width // 1.5)
food_y = random.randint(45, screen_height // 1.5)
snake_size = 15
score = 0
fps = 40
snake_lst = []
snake_length = 1
clock = pygame.time.Clock()
with open("highscore.txt","r") as f:
highscore = f.read()
while not exit_game:
# pass
if game_over:
with open("highscore.txt", "w") as f:
f.write(str(highscore))
gamewindow.fill(white)
text_screen("Game Over! Press Enter to continue", red, 100, 200)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN: #K_RETURN means Enter key is pressed
welcome()
else:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
veloc_x = init_velocity
veloc_y = 0
if event.key == pygame.K_LEFT:
veloc_x = -init_velocity
veloc_y = 0
if event.key == pygame.K_UP:
veloc_y = -init_velocity
veloc_x = 0
if event.key == pygame.K_DOWN:
veloc_y = init_velocity
veloc_x = 0
snake_x += veloc_x
snake_y += veloc_y
if abs(snake_x - food_x) < 10 and abs(snake_y - food_y) < 10:
score += 10
food_x = random.randint(45, screen_height // 1.5)
food_y = random.randint(45, screen_height // 1.5)
snake_length += 5
if score>int(highscore):
highscore = score
gamewindow.fill(white)
text_screen("Score: " + str(score), red, 5, 5)
text_screen("HighScore: " + str(highscore), red, 600, 5)
pygame.draw.rect(gamewindow, red, [food_x, food_y, snake_size, snake_size])
head = []
head.append(snake_x)
head.append(snake_y)
snake_lst.append(head)
if len(snake_lst) > snake_length:
del snake_lst[0]
if snake_x > screen_width or snake_x < 0 or snake_y > screen_height or snake_y < 0:
game_over = True
if head in snake_lst[:-1]:
game_over = True
plotsnake(gamewindow, black, snake_lst, snake_size)
# pygame.draw.rect(gamewindow, black, [snake_x, snake_y, snake_size, snake_size])
pygame.display.update()
clock.tick(fps)
pygame.quit()
quit()
welcome() |
import re
count = int(input("input data:"))
results = ''
for i in range(count):
val = input()
# Use regular expression to remove all non-alphanumerical characters
val = re.sub('[^A-Za-z0-9]', '', val)
# Replace all letters with lowercase to avoid case sensitive
val = val.lower()
if (val == val[::-1]):
results = results + "Y "
else:
results = results + "N "
print(results)
|
# -*- coding: utf-8 -*-
# Exercício 1
# valor1= float(input("digite o valor 1: "))
# valor2= float(input ("digite o valor 2: "))
# soma = valor1 + valor2
# subtracao = valor1 - valor2
# multiplicacao= valor1*valor2
# divisao = valor1/valor2
# resto = valor1%valor2
# media = (valor1+valor2)/2
# print (soma)
# print (subtracao)
# print (multiplicacao)
# print (divisao)
# print (resto)
# print (media)
#Exercício 2
nome = input('Escreva seu nome: ')
idade = int(input('Qual é a sua idade: '))
if idade >= 18:
print ('seja bem vindo(a) ' + nome)
if idade <= 11:
print ('Você é jovem demais para acessar o site.')
else:
print ('Menor de idade.')
|
# Step 1. 필요한 모듈과 라이브러리를 로딩하고 검색어를 입력 받습니다
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import datetime
import sys
import numpy
import pandas as pd
import xlwt
import random
import urllib.request
import urllib
import re
import math
import os
import MySQLdb
s_time = time.time()
connection = MySQLdb.connect(
user='root',
passwd='lfochino',
host='127.0.0.1',
db='scrapingdata',
charset='utf8'
)
#db 연결 확인
print(type(connection))
# <class 'MySQLdb.connections.Connection'>
#커서 연결
cursor = connection.cursor()
#커서 연결 확인
print(type(cursor))
cursor.execute("DROP TABLE IF EXISTS match_lists")
# sql = """CREATE TABLE match_lists (index int,event_day varchar(10),league_name varchar(45), event_time TIME, hometeam varchar(45), hometeam_score varchar(8),match_result varchar(16),awayteam_score varchar(8),awayteam varchar(45))"""
cursor.execute("CREATE TABLE match_lists (id INT AUTO_INCREMENT PRIMARY KEY,event_day varchar(10),league_name varchar(45), event_time varchar(20), hometeam varchar(45), hometeam_score varchar(8),match_result varchar(16),awayteam_score varchar(8),awayteam varchar(45))")
for month in range(1,13):
#Step 2. 크롬 드라이버를 사용해서 웹 브라우저를 실행합니다.
options = webdriver.ChromeOptions()
options.add_argument('headless')
# options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")
options.page_load_strategy = 'normal'
# 혹은 options.add_argument("--disable-gpu")
driver = webdriver.Chrome('chromedriver', chrome_options=options)
# driver = webdriver.Chrome('chromedriver')
# time.sleep(2)
if (month <10):
driver.get('https://sports.daum.net/schedule/worldsoccer?date=20210%d' %month)
else:
driver.get('https://sports.daum.net/schedule/worldsoccer?date=2021%d' %month)
# driver.maximize_window() #윈도우 최대창크기
# time.sleep(2)
#element.send_keys("\n") #엔터키 작동
#목표 1. 리그별 리스트 만들기
html = driver.page_source ## 페이지의 elements모두 가져오기
soup = BeautifulSoup(html, 'html.parser')
scheduleList = soup.find(id="scheduleList")
for day in range(1,32):
if (day <10):
scheduleList2 = scheduleList.find_all("div",{"data-term":"0%s"%day})
print("2월 0%s일\n" %day)
else:
scheduleList2 = scheduleList.find_all("div",{"data-term":"%s"%day})
print("2월 %s일\n" %day)
for x in scheduleList2:
tbody = x.find("tbody")
tr = tbody.find_all("tr")
tit_league = x.find("strong","tit_league").get_text() #리그 종류
# league_img = x.find("img")
# league_img =league_img.get('src') # 리그 로고
event_day = x.find('span','num_date').get_text()
event_day = event_day.replace(".","/")
print(tit_league) #리그 종류
# print(league_img)
for y in tr:
hometeam = y.find('div','info_team team_home').find('span','txt_team').get_text()
hometeam_score = y.find('div','info_team team_home').select_one("span:nth-of-type(3)").text
hometeam_img = y.find('div','info_team team_home').find("img").get("src")
awayteam = y.find('div','info_team team_away').find('span','txt_team').get_text()
awayteam_score = y.find('div','info_team team_away').find("em").get_text()
awayteam_img = y.find('div','info_team team_away').find("img").get("src")
event_time = y.find('td','td_time').get_text()
match_result = y.find('span','state_game').get_text()
# if(hometeam_score === "-"):
# hometeam_score = -1
# else if
#cursor.execute(f"INSERT INTO match_list VALUES(\"{num}\",\"{event_day}\",\"{tit_league}\",\"{event_time}\",\"{hometeam}\",\"{hometeam_score}\",\"{match_result}\",\"{awayteam_score}\",\"{awayteam}\")"%day) #,\"{league_img}\",\"{hometeam_img}\",\"{awayteam_img}\"
sql = "insert into match_lists (event_day,league_name,event_time,hometeam,hometeam_score,match_result,awayteam_score,awayteam) VALUES (%s, %s,%s,%s,%s,%s,%s,%s)"
val = (event_day,tit_league,event_time,hometeam,hometeam_score,match_result,awayteam_score,awayteam)
cursor.execute(sql,val)
print(event_day,tit_league,event_time, hometeam, hometeam_score ,match_result, awayteam_score,awayteam) #league_img,hometeam_img,awayteam_img
print("\n")
connection.commit()
driver.close()
e_time = time.time()
t_time = e_time - s_time
print("소요시간은 %s 초 입니다" %round(t_time,1))
#쿼리문 작성 부분
#테이블 생성 |
__author__ = 'skye2017-11-18'
# coding=utf-8
# 在Python中没有switch – case语句。
a = 100
if a:
print('1 - if 表达式条件为 true')
print(a)
b = 0
if b: # 布尔值除了 0 都是 true
print('2 - if 表达式条件为 true')
print(b)
print('再见')
age = int(input('请输入你家狗狗的年龄: '))
print('回答:', end='')
if age < 0:
print('你是在逗我吧!')
elif age == 1:
print('相当于 14 岁的人。')
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5
print('对应人类年龄: ', human)
input('点击 enter 键退出')
# 该实例演示了数字猜谜游戏
num = 7
guess = -1
print('数字猜谜游戏!')
while guess != num:
guess = int(input('请输入你猜的数字:'))
if guess == num:
print('恭喜,你猜对了!')
elif guess < num:
print('猜的数字小了...')
elif guess > num:
print('猜的数字大了...')
# 以下实例 x 为 0-99 取一个数,y 为 0-199 取一个数,
# 如果 x>y 则输出 x, 如果 x 等于 y 则输出 x+y,否则输出y。
import random
x = random.choice(range(100))
y = random.choice(range(200))
if x > y:
print('x:',x)
elif x == y:
print('x+y:', x+y)
else:
print('y:',y)
"""对上面例子的一个扩展"""
print("=======欢迎进入狗狗年龄对比系统========")
while True:
try:
age = int(input("请输入您家狗的年龄:"))
print("回答:", end='')
age = float(age)
if age < 0:
print("您在逗我?")
elif age == 1:
print("相当于人类14岁")
break
elif age == 2:
print("相当于人类22岁")
break
else:
human = 22 + (age - 2)*5
print("相当于人类:",human)
break
except ValueError:
print("输入不合法,请输入有效年龄")
###退出提示
input("点击 enter 键退出")
|
p1 = input("Player 1, choose rock, paper, or scissors: ")
p2 = input("Player 2, choose rock, paper, or scissors: ")
def play(player1, player2):
if player1 == player2:
print("play again")
elif player1 == 'rock':
if player2 == 'scissors':
print("Rock hits scissors. Player 1 win!")
elif player1 == 'paper':
if player2 == 'scissors':
print("Scissors cut paper. Player 2 wins")
elif player1 == 'scissors':
if player2 == 'rock':
print("Rock hits scissors. Player 2 wins!")
elif player1 == 'rock':
if player2 == 'paper':
print("Paper covers rock. Player 2 wins!")
elif player1 == 'scissors':
if player2 == 'paper':
print("Scissors cut paper. Player 1 wins!")
elif player1 == 'paper':
if player2 == 'rock':
print("Paper covers rock. Player 1 wins!")
else:
return "Paper wins"
else:
print("Invalid choice")
return play(p1, p2)
print(play(p1, p2)) |
moves = [1,5,3,5,1,2,1,4]
board = [[0,0,0,0,0], # 0
[0,0,1,0,3], # 1
[0,2,5,0,1], # 2
[4,2,4,4,2], # 3
[3,5,1,3,1]] # 4
result = [] # 4 3 1 1 3 2 0 4
total = 0
second_num = 0
# len(board) = 5
for i in moves:
print(i-1) # 0 4 2 4 0 1 0 3
second_num = i-1
for first_num in range(len(board)):
if (board[first_num][i-1] != 0):
print("자판기 : " + str(board[first_num][i-1]))
result.append(board[first_num][i-1])
board[first_num][i-1] = 0
if len(result) >= 2:
if result[-1] == result[-2]:
result.pop()
result.pop()
total += 2
break
elif (board[4][i-1] == 0):
print("자판기 : 0 " )
break
print(result)
print(total)
# 0 0 -> 0
# 1 0 -> 0
# 2 0 -> 0
# 3 0 -> 4 --> result
# 0 4 -> 0
# 1 4 -> 3
|
from pyfirmata import Arduino
from tkinter import *
#Especifique a Porta do Arduino
PORTA = "COM3"
arduino = Arduino(PORTA)
led = arduino.get_pin('d:13:o')
# d= Digital
#Pinno 13
#o = OUTPUT
def acender():
led.write(1)
def apagar():
led.write(2)
janela = Tk()
janela.title("Acender e Apagar LED com botão")
janela.geometry("350x60")
frame = Frame(master=janela)
frame.pack()
btacende = Button(master=frame, text="Acender", command=acender)
btacende.grid(row=0, column=0)
btapaga = Button(master=frame, text="Apagar", command=apagar)
btapaga.grid(row=0, column=1)
janela.mainloop()
|
from typing import List
def checkio(game_result):
rPattern = createPattern(game_result)
for i in rPattern:
for s in "XO":
if i.count(s) == 3 :
return s
return "D"
def createPattern(game_result):
list =[]
#horizontal pattern
list.extend(game_result)
#vertical pattern
for i in range(0,3):
pat = ""
for res in game_result:
pat +=res[i]
list.append(pat)
#cross pattern
list.append(game_result[0][0]+game_result[1][1]+game_result[2][2])
list.append(game_result[0][2]+game_result[1][1]+game_result[2][0])
return list
if __name__ == '__main__':
print("Example:")
print(checkio(["X.O",
"XX.",
"XOO"]))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio([
"O.X",
"XX.",
"XOO"]) == "X", "Xs wins again"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
def sort_positive(arr):
pos = []
for i in range(0, len(arr)):
if arr[i] > 0:
pos.append(arr[i])
pos.sort()
j=0
for i in range(0, len(arr)):
if arr[i]>=0:
arr[i] = pos[j]
j +=1
return arr
def main():
arr = [28, -6, -3, 8, 4, 1, -5, -8, 23, 2]
pos = sort_positive(arr)
print(pos)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 19:51:53 2020
@author: Chennakesava Reddy
"""
#5)write a python program to create alist and access the elements in the list
my_list = ['u', 'l', 't', 'i', 'm','a','t','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ["Happy", [2, 0, 1, 5]]
print(n_list[0][1])
print(n_list[1][3])
|
class Movies:
'''
initializing tht class and objects
'''
def __init__(self):
'''
stroing the movies for view.movies and find.movies
'''
self.movies = [{'name': 'sherlock', 'year': '2009', 'genre': 'thriller'},
{'name': 'titanic', 'year': '1997', 'genre': 'drama'},
{'name': 'andhadhun', 'year': '2018', 'genre': 'crime'}]
def find_movie(self):
'''
function to find the movie
'''
try:
choice = input(
"\nPlease type 'name' to find by name/ 'year' to find by year/ 'genre' to find by genre\nHow do you want to find your movie:")
if choice == 'name' or choice == 'year' or choice == 'genre':
user_input = input("\nWhat are you looking for? ")
movie_list = list(
filter(lambda movie: movie[choice] == user_input, self.movies))
except Exception:
print("Invalid option, Please try again with valid input.")
choice = input(
"Please type 'name' to find by name or 'year' to find by year or 'genre' to find by genre\nHow do you want to find your movie:")
user_input = input("\nWhat are you looking for? ")
movie_list = list(
filter(lambda movie: movie[choice] == user_input, self.movies))
for movie in movie_list:
print(f"\nMovie Name : {movie['name']}",
f" Movie Year : {movie['year']}", f" Movie Genre : {movie['genre']}")
def add_movie(self):
'''
function to add the movie
'''
self.movies.append({'name': input("Please input name:"), 'year': input(
"Please input year:"), 'genre': input("Please input genre:")})
print(f"\nThe movie you said is been added to your collection: \n",
self.movies)
def view_movie(self):
'''
function to view the movie
'''
for movie in self.movies:
print(f"Movie Name : {movie['name']}",
f" Movie Year : {movie['year']}",
f" Movie Genre : {movie['genre']}")
new_movie = Movies()
running = True
while running:
inp = input("Please type 'find' to find any movie/ 'add' to add new movie/ 'view' to view your collection/ 'end' to end program\nWhat would you like to do: ")
if inp == "find":
new_movie.find_movie()
elif inp == "add":
new_movie.add_movie()
elif inp == "view":
new_movie.view_movie()
elif inp == "end":
print("\nThank you!")
running = False
else:
print("\nPlease try again\nThank you!")
running = False
|
# CRYPTOGRAPHIC TOOL BASED ON AES-256 (OFB MODE) - A Symmetric Cryptographic Encryption and Decryption in Python
# Submitted by - Abhay Chaudhary
# Submitted to - Dr. Garima Singh
# CSE1007 Introduction to Cryptography (SLOT-A+TA)
# Python v3.9.0
# imports
import os
import sys
from tqdm import tqdm
from termcolor import colored,cprint
class Encryption:
def __init__(self,filename): # Constructor
self.filename = filename
def encryption(self): # Allows us to perfrom file operation
try:
original_information = open(self.filename,'rb')
except (IOError, FileNotFoundError):
cprint('File with name {} is not found.'.format(self.filename), color='red',attrs=['bold','blink'])
sys.exit(0)
try:
encrypted_file_name = 'cipher_' + self.filename
encrypted_file_object = open(encrypted_file_name,'wb')
content = original_information.read()
content = bytearray(content)
key = 192
cprint('Encryption Process is in progress...!',color='green',attrs=['bold'])
for i,val in tqdm(enumerate(content)):
content[i] = val ^ key
encrypted_file_object.write(content)
except Exception:
cprint('Something went wrong with {}'.format(self.filename),color='red',attrs=['bold','blink'])
finally:
encrypted_file_object.close()
original_information.close()
class Decryption:
def __init__(self,filename):
self.filename = filename
def decryption(self): # produces the original result
try:
encrypted_file_object = open(self.filename,'rb')
except (FileNotFoundError,IOError):
cprint('File with name {} is not found'.format(self.filename),color='red',attrs=['bold','blink'])
sys.exit(0)
try:
decrypted_file = input('Enter the filename for the Decryption file with extension:') # Decrypted file as output
decrypted_file_object = open(decrypted_file,'wb')
cipher_text = encrypted_file_object.read()
key = 192
cipher_text = bytearray(cipher_text)
cprint('Decryption Process is in progress...!',color='green',attrs=['bold'])
for i,val in tqdm(enumerate(cipher_text)):
cipher_text[i] = val^key
decrypted_file_object.write(cipher_text)
except Exception:
cprint('Some problem with Ciphertext unable to handle.',color='red',attrs=['bold','blink'])
finally:
encrypted_file_object.close()
decrypted_file_object.close()
space_count = 30 * ' '
cprint('{} Encription and Decription of Files in AES-256 (OFB MODE). {}'.format(space_count, space_count), 'red')
cprint('{} {}'.format(space_count + 3 * ' ','Programmed by Abhay Chaudhary 19BCE7290.'),'green')
while True:
cprint('1. Encryption',color='magenta')
cprint('2. Decryption',color='magenta')
cprint('3. Exit', color='red')
# cprint('Enter your choice:',color='cyan',attrs=["bold"])
cprint('~Python3:',end=' ', color='green')
choice = int(input())
if choice == 1:
logo = ''' ___ _ _
| __|_ _ __ _ _ _ _ _ __| |_(_)___ _ _
| _|| ' \/ _| '_| || | '_ \ _| / _ \ ' \
|___|_||_\__|_| \_, | .__/\__|_\___/_||_|
|__/|_| '''
cprint(logo,color='red',attrs=['bold'])
cprint('Enter the filename for Encryption with proper extension:',end=' ',color='yellow',attrs=['bold'])
file = input()
E1 = Encryption(file)
E1.encryption()
cprint('{} Encryption is done Sucessfully...!'.format(file), color='green',attrs=['bold'])
cprint('Do you want to do it again (y/n):',end = ' ', color='red',attrs=['bold','blink'])
again_choice = input()
if (again_choice.lower() == 'y'):
continue
else:
break
elif choice == 2:
logo = ''' ___ _ _
| \ ___ __ _ _ _ _ _ __| |_(_)___ _ _
| |) / -_) _| '_| || | '_ \ _| / _ \ ' \
|___/\___\__|_| \_, | .__/\__|_\___/_||_|
|__/|_| '''
cprint(logo,color='red',attrs=['bold'])
cprint('Enter the Encrypted filename with proper extension:',end=' ',color='yellow',attrs=['bold'])
file = input()
D1 = Decryption(file)
D1.decryption()
cprint('{} Decryption is done Sucessfully...!'.format(file),color='green',attrs=['bold'])
cprint('Do you want to do it again (y/n):',end = ' ', color='red',attrs=['bold','blink'])
again_choice = input()
if (again_choice.lower() == 'y'):
continue
else:
break
elif choice == 3:
sys.exit(0)
else:
print('Your choice of selection is not available. Sorry to see you again.')
|
"""Example file containing the main executable for an app."""
from logging import DEBUG
from Logger import logging_config
# Create a Logger for main_app
MAIN_LOG = logging_config.get_simple_logger("main_logger", DEBUG)
# Main program
def __main__():
MAIN_LOG.info("Running Main Program inside main_app.py")
MAIN_LOG.info("Using simple_function to add 1 to 1")
simple_function(1)
# Simple function to be tested
def simple_function(real_number):
""":returns: real_number + 1"""
MAIN_LOG.debug("Adding 1 to %d", real_number)
return real_number + 1
|
from tkinter import *
import sys
class Main(Frame):
def __init__(self, root):
super(Main, self).__init__(root)
self.build()
def build(self):
self.formula = "0"
self.lbl = Label(text=self.formula, bg="#000", foreground="#FFF", font=("Times New Roman", 21, "bold"))
self.lbl.place(x=10, y=50)
button = [
"x^2", "x^3", "x^4", "DEL", "C",
"7", "8", "9", "*", "/",
"4", "5", "6", "+", "-",
"1", "2", "3", "%", "=",
"(", "0", ")", "Exit"
]
x = 10
y = 90
for b in button:
com = lambda x = b: self.logicalc(x)
Button(text=b, command= com, bg="#000",
foreground="#FFF", font=("Times New Roman", 21)).place(x=x, y=y, width=90, height=90)
x += 92
if x > 460:
y += 92
x = 10
def logicalc(self, operation: str):
if self.formula == "ERROR":
self.formula = "0"
if operation == "DEL":
operation = ""
self.formula = self.formula[:-1]
if operation == "C":
operation = ""
self.formula = operation
if operation == "Exit":
sys.exit()
elif operation == "%":
operation = "/100"
elif operation == "x^2":
operation = "**2"
elif operation == "x^3":
operation = "**3"
elif operation == "x^4":
operation = "**4"
elif operation == "=":
operation = ""
if self.formula[-1].isdigit() or self.formula[-2].isdigit():
try:
self.formula = str(eval(self.formula))
except ZeroDivisionError:
self.formula = "ERROR"
else:
if operation.isdigit() and self.formula == "0":
self.formula = ""
if not operation.isdigit():
if self.formula != "" and not self.formula[-1].isdigit() and operation == "(" or operation == ")":
if operation == "(":
operation = "("
if operation == ")":
operation = ")"
elif self.formula != "" and not self.formula[-1].isdigit():
self.formula = self.formula[:-1]
self.formula += operation
self.update()
def update(self):
if self.formula == "":
self.formula = "0"
self.lbl.configure(text=self.formula)
|
class user():
def __init__(self,first,last,age):
self.first=first
self.last=last
self.age=age
harry=user("harry","rajput",22)
raju=user("raju","rajput","23")
print(harry.first,harry.last,harry.age)
|
i=int(input("enter the no.:"))
n=6
while i<=10:
print(i,"*",n,"=",i*n)
i=i+1 |
def banka(p,t,tax):
amount1=p+(p*t)/100+(tax*p)/100
return amount1
print("total amount","=",amount1)
p=int(input("principle:"))
t=int(input("tenur:"))
tax=int(input("tax:"))
banka(p,t,tax)
def bankb(p1,t2,tax2):
amount=p1+(p1*t2)/100+(tax2*p1)/100
return amount
print("total amount","=",amount)
p1=int(input("principle:"))
t2=int(input("tenure:"))
tax2=int(input("tax:"))
bankb(p1,t2,tax2)
bankaa=banka(p,t,tax)
bankbb=bankb(p1,t2,tax2)
if bankaa>bankbb:
print("bank a is baest")
else:
print("bankb is beat")
|
from collections import OrderedDict
my_order = OrderedDict()
for i in range(int(input())):
name,space,price = input().rpartition(' ')
if name not in my_order:
my_order[name] = int(price)
else:
my_order[name] += int(price)
for item_name, net_price in my_order.items():
print (item_name,net_price)
|
#setting the global constant for the RETAIL_PRICE
RETAIL_PRICE = 99.00
MIN_QUANTITY = 10
#othe variables delclared for the function
quantity = 0
fullPrice = 0
discountRate = 0
discountAmount = 0
totalAmount = 0
def main():
#getting quanity from user
quantity= int(input('Enter quantity: '))
if quantity >= MIN_QUANTITY and quantity <= 19:
print('The discount rate is:', '20%')
discountRate=(.20)
elif quantity >= 20 and quantity <= 49:
print('The discount rate is:', '30%')
discountRate=(.30)
elif quantity >= 50 and quantity <= 99:
print('The discount rate is:', '40%')
elif quantity >= 100:
print ('The discount rate is:', '50%')
discountRate=(.50)
# this will calculate the discount totalAmount
fullPrice = (quantity * RETAIL_PRICE)
print(' Full price:', fullPrice)
#Calculates the discounted totalAmount
discountAmount = (fullPrice * discountRate)
print(' Discount amount: $', discountAmount)
#Calulates the total after the discount amount
totalAmount = (fullPrice - discountAmount)
print(' Total Amount: $', totalAmount)
# This is calling the main function
main()
|
#!/usr/bin/env python3
#
# DESCRIPTION
#
# Prints terminal colours.
#
def print_color_table():
for style in range(8):
for fg in range(30, 38):
s = ''
for bg in range(40, 48):
cc = ';'.join([str(style), str(fg), str(bg)])
s += '\x1b[{}m {} \x1b[0m'.format(cc, cc)
print(s)
print('\n')
if __name__ == "__main__":
print_color_table()
|
class PlayerCharacter:
# Class Object Attribute. does not change
membership = True
# __init__ constructor
# self is class PlayerCharacter same as "this" in Java
def __init__(self, name, age):
if self.membership: # same as PlayerCharacter.membership
self.name = name # attributes that is dynamic (changes)
self.age = age # attributes
def shout(self):
return f'my name is {self.name}'
def run(self, hello):
return f'{hello} my name is {self.name}'
player1 = PlayerCharacter('Cindy', 54)
player2 = PlayerCharacter('Tom', 22)
print(player1.name)
print(player2.age, player2.shout())
print("RUN METHOD: ", player2.run("Hi"))
print(player2.membership)
print("\n**********\n")
# to see blueprint of PlayerCharacter
# help(PlayerCharacter)
class MustBe18:
def __init__(self, name="anonymous", age=0):
if age > 18:
self.name = name
self.age = age
def shout(self):
return f'my name is {self.name}'
user = MustBe18("Ziko", 23)
print(user.shout())
|
from CustomError import NotNumberException
age = ""
while True:
try:
age = input("What is your age? ")
if age == "0":
raise ZeroDivisionError("Numerator cannot be zero-based")
10/int(age)
except ValueError:
print(f"inputted data: '{age}' is not a valid number")
raise NotNumberException("This is not a valid number").message()
except ZeroDivisionError as e:
print(f"{age} >>> {e}")
else: # todo place code here that should run if no errors occurred
print("Thank you")
break
finally: # todo place code here that should run regardless if there are errors or not
print("Ok, i am finally done") |
def my_function(*students):
print("The tallest student is " + students[2])
my_function("James", "Ella", "Jackson")
print("\n**********\n")
def my_function(*argv):
print(argv)
my_function('Hello', 'World!')
def multi_func(num1, num2):
return num1 * num2
print(multi_func(5, num2=67))
print("\n**********\n")
def is_true(a):
return a
result = is_true(6 < 3)
print("The result is", result)
print("\n**********\n")
def get_odd_func(numbers):
odd_numbers = [num for num in numbers if num % 2]
return odd_numbers
print(get_odd_func([1, 2, 3, 4, 5, 6]))
print("\n**********\n")
def get_even_func(numbers):
odd_numbers = [num for num in numbers if not num % 2]
return odd_numbers
print(get_even_func([1, 2, 3, 4, 5, 6]))
print("\n**********\n")
def double_list(numbers):
return 2 * numbers
numbers = [1, 2, 3]
print(double_list(numbers))
print("\n****GLOBAL SCOPE FROM METHOD******\n")
num = 100
own_num = 15
def input_number():
global own_num
own_num = 50
result = int(input("Enter a number: ")) * own_num
return result
print(input_number())
for num in range(5, 9):
for i in range(2, num):
if num%i == 1:
print(num)
break |
# list, set, dictionary
# var = [param for param in iterable]
# var = [expression for param in iterable conditional]
print("\n****** LIST COMPREHENSION *******\n")
my_list = [*'hello']
my_list2 = [char for char in 'hello']
print(my_list)
print(my_list2)
my_list3 = [num for num in range(0, 100)]
print(my_list3)
# doubling my_list3
my_list4 = list(map(lambda x: x * 2, [num for num in range(0, 100)]))
# doubling my_list3 simpler way
my_list5 = [num ** 2 for num in range(0, 100)]
# only even numbers
# todo info var = [expression for param in iterable conditional]
my_list6 = [num ** 2 for num in range(0, 100) if num % 2 == 0]
print("DOUBLING =", my_list4)
print("SQUARING =", my_list5)
print("EVEN NUMBERS =", my_list6)
print("\n****** SET COMPREHENSION *******\n")
#
#
# todo ==> Set Dictionary Comprehension
# doubling my_list3 simpler way
my_set2 = {num ** 2 for num in range(0, 100)}
# only even numbers
# todo info var = [expression for param in iterable conditional]
my_set3 = {num ** 2 for num in range(0, 100) if num % 2 == 0}
print("SQUARING =", my_set2)
print("EVEN NUMBERS =", my_set3)
print("\n****** DICT COMPREHENSION *******\n")
simple_dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 4
}
# var = [expression for param in iterable conditional]
my_dict = {key: value ** 2 for key, value in simple_dict.items() if value % 2 == 0}
some_dict = {num: num * 2 for num in [1, 2, 3]}
print("DICTOO",my_dict)
print(some_dict)
student_attendance = {"Rold": 96, "Box": 85}
for t in student_attendance.items():
print(t)
i, x = t
print(f"{i} : {x}")
sequence = [1, 2, 3, 4, 5, 6]
print(list(x * 2 for x in sequence))
users = [
(0, "Bob", "Password"),
(1, "Bobs", "Password"),
(2, "Bobd", "Password")
]
# making username as key
user_dict = {user[1]: user for user in users}
print(user_dict.values())
print(user_dict) |
# generator is a subset of an iterable
from time import time
def generator_fn(num):
for i in range(num):
yield i # yield only keeps only value in memeory per time
g = generator_fn(10)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#
#
#
print("\n******** GENERATOR PERFORMANCE ********\n")
def performance(func):
def wrap_func(*args, **kwargs):
start = time()
result = func(*args, **kwargs)
end = time()
print(f"time taken: {end - start} s")
return result
return wrap_func # notice we are not calling it i.e ()
@performance
def long_time():
for i in range(1000000):
i * 5
@performance
def long_time2():
for i in list(range(1000000)):
i * 5
long_time()
long_time2()
|
counter = 0
while counter < 4:
print("yoga")
counter += 1
print("**********************\n\n", 0o7)
i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2
print("**********************\n\n", 0o7)
i = 5
while True:
if i % 0o11 == 0:
break
print(i)
i += 1
print("**********************\n\n", 0o7, "\n\n")
someList = [5, 10, 15, 30]
for i in range(len(someList)):
print(someList[i])
print("**********************\n\n")
for num in range(0, 11):
if(num % 2 == 0):continue
print(num)
print("**********************\n\n")
x = 'abcd'
for i in range(len(x)):
print("hello")
print("**********************\n\n")
x = 'zikozee'
for i in x:
print(i.upper())
|
def find_root(parent, n):
if parent[n] != n:
parent[n] = find_root(parent, parent[n])
return parent[n]
def check_connection(network, first, second):
parent = dict()
for conn in network:
a, b = conn.split('-')
parent.setdefault(a, a)
parent.setdefault(b, b)
ra = find_root(parent, a)
rb = find_root(parent, b)
parent[ra] = rb
return find_root(parent, first) == find_root(parent, second)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"scout2", "scout3") == True, "Scout Brotherhood"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"super", "scout2") == True, "Super Scout"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"dr101", "sscout") == False, "I don't know any scouts."
|
def clock_angle(time):
h, m = map(int, time.split(':'))
h %= 12
h = (h + m / 60.) * 30
m *= 6
angle = abs(h - m)
if angle > 180:
angle = 360 - angle
return round(angle, 1)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert clock_angle("02:30") == 105, "02:30"
assert clock_angle("13:42") == 159, "13:42"
assert clock_angle("01:42") == 159, "01:42"
assert clock_angle("01:43") == 153.5, "01:43"
assert clock_angle("00:00") == 0, "Zero"
assert clock_angle("12:01") == 5.5, "Little later"
assert clock_angle("18:00") == 180, "Opposite"
|
VOWELS = "aeiouy"
def translate(phrase):
ans = []
it = iter(phrase)
while True:
try:
c = it.next()
ans.append(c)
if c in VOWELS:
it.next()
it.next()
elif c.isalpha():
it.next()
except StopIteration:
break
return ''.join(ans)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert translate(u"hieeelalaooo") == "hello", "Hi!"
assert translate(u"hoooowe yyyooouuu duoooiiine") == "how you doin", "Joey?"
assert translate(u"aaa bo cy da eee fe") == "a b c d e f", "Alphabet"
assert translate(u"sooooso aaaaaaaaa") == "sos aaa", "Mayday, mayday"
|
import heapq
class Node(object):
def __init__(self, idx, dis):
self.idx = idx
self.dis = dis
def __lt__(self, other):
return self.dis < other.dis
def checkio(land_map):
w, h = len(land_map[0]), len(land_map)
dijkstra = [Node((0, i), land_map[0][i]) for i in xrange(w)]
heapq.heapify(dijkstra)
visited = set()
while True:
cur = heapq.heappop(dijkstra)
if cur.idx[0] == h - 1:
return cur.dis
if cur.idx not in visited:
visited.add(cur.idx)
for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
nx, ny = cur.idx[0] + dx, cur.idx[1] + dy
if 0 <= nx < h and 0 <= ny < w:
md = cur.dis + land_map[nx][ny]
heapq.heappush(dijkstra, Node((nx, ny), md))
return 'Not gonna happen'
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[1, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 0, 1],
[1, 1, 0, 1, 1, 0, 1],
[1, 1, 0, 1, 1, 1, 1],
[1, 0, 0, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1, 1]]) == 2, "1st example"
assert checkio([[0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0]]) == 3, "2nd example"
assert checkio([[1, 1, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 1]]) == 2, "3rd example"
|
def on_edge(point, edge):
p0, p1 = edge
if (p0[0] - point[0]) * (p1[1] - point[1]) == (p1[0] - point[0]) * (p0[1] - point[1]):
# same slope
if p0[0] <= point[0] <= p1[0] or p1[0] <= point[0] <= p0[0]:
if p0[1] <= point[1] <= p1[1] or p1[1] <= point[0] <= p0[1]:
return True
return False
def ray_casting(edges, point):
# https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm
cross_x = []
for edge in edges:
# ignore horizontal line where y = the y value of point since on_edge() will cover this case
if edge[0][1] > edge[1][1] and edge[1][1] == point[1]:
cross_x.append((edge[1][0], 1))
elif edge[0][1] < edge[1][1] and edge[0][1] == point[1]:
cross_x.append((edge[0][0], 1))
elif (edge[0][1] - point[1]) * (edge[1][1] - point[1]) < 0:
# calculate the cross x value as (num, den) format, and ensure den > 0
x = (edge[0][0] * (edge[0][1] - edge[1][1]) - (edge[0][0] - edge[1][0]) * (edge[0][1] - point[1]), edge[0][1] - edge[1][1])
if x[1] < 0:
x = (-x[0], -x[1])
cross_x.append(x)
cross_x.append((point[0], 1))
cross_x.sort(cmp=lambda a, b: cmp(a[0] * b[1], b[0] * a[1]))
return cross_x.index((point[0], 1)) % 2 == 1
def is_inside(polygon, point):
edges = []
n = len(polygon)
for i in xrange(n - 1, -1, -1):
edges.append([polygon[i], polygon[i - 1]])
for edge in edges:
if on_edge(point, edge):
return True
return ray_casting(edges, point)
if __name__ == '__main__':
assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),
(2, 2)) == True, "First"
assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),
(4, 2)) == False, "Second"
assert is_inside(((1, 1), (4, 1), (2, 3)),
(3, 2)) == True, "Third"
assert is_inside(((1, 1), (4, 1), (1, 3)),
(3, 3)) == False, "Fourth"
assert is_inside(((2, 1), (4, 1), (5, 3), (3, 4), (1, 3)),
(4, 3)) == True, "Fifth"
assert is_inside(((2, 1), (4, 1), (3, 2), (3, 4), (1, 3)),
(4, 3)) == False, "Sixth"
assert is_inside(((1, 1), (3, 2), (5, 1), (4, 3), (5, 5), (3, 4), (1, 5), (2, 3)),
(3, 3)) == True, "Seventh"
assert is_inside(((1, 1), (1, 5), (5, 5), (5, 4), (2, 4), (2, 2), (5, 2), (5, 1)),
(4, 3)) == False, "Eighth"
|
import math
print('-'*30)
print(' TINTA EM CORES')
print('-'*30)
metros = float(input('area a ser pintada:'))
litros = metros/6
galao = math.ceil(litros/18)
latas = math.ceil(litros/3.6)
vgalao = galao*80
vlatas = latas*25
#MISTURANDO LATAS E GALOES
pgalao = math.trunc(litros/18)
platas = (litros%18)/3.6
vpgalao = pgalao*80
vplatas = platas*25
vmista = vpgalao+vplatas
print('você vai precisar de {:.2f} litros'.format(litros))
print('1. voce pode usar {} latas de 3.6litros de tinta e pagar R$ {:.2f} reais '.format(latas,vlatas))
print('2. voce pode usar {} galao de 18 litros e pagar R$ {:.2f} reais'.format(galao,vgalao))
print('3. voce pode usar {} galao de 18 litros e {:.2f} latas de 3.6 litros, pagando R${:.2f} reais'.format(pgalao,platas,vmista))
print('-'*20)
if vgalao<vlatas and vgalao<vmista:
print('escolha opçao 2 e pague apenas R${:.2f} reais'.format(vgalao))
elif vlatas<vgalao and vlatas<vmista:
print('escolha opção 1 e paque apenas R${:.2f} reais'.format(vlatas))
else:
print('escolha opçao 3 e pague apenas R${:.2f} reais'.format(vmista))
|
c = float(input('informe a temperatura em Celsius que deseja converter:'))
f = (((9*c)/5)+32)
print('a temperatura informada em Farenheit é',f)
input('.') |
def segs(h,m,s):
total=h*3600+m*60+s
return total
horas=int(input('informe a quantidade de horas: '))
minutos=int(input('informe a quantidade de minutos: '))
segundos=int(input('informe a quantidade de segundos: '))
print('o tempo total é de {} segundos'.format(segs(horas,minutos,segundos)))
|
def hipotenusa (b,c):
a=(b**2+c**2)**0.5
return a
b=int(input('informe o valor de um dos catetos: '))
c=int(input('informe o valor do outro cateto: '))
print('o valor da hipotenusa é {:.2f}'.format(hipotenusa(b,c)))
|
def inversos(n):
s=0
divisor=1
while divisor<=n:
s+=1/divisor
divisor+=1
return s
print('o valor da soma dos inversos de 1 a n é : ',
inversos(int(input('informe um numero: ')))) |
from tkinter import *
def bt_tipo_click():
a=float(et_lado01.get())
b=float(et_lado02.get())
c=float(et_lado03.get())
if a<b+c and b<a+c and c<b+a:
if a==b==c:
tipo.configure(text='Triângulo Equilátero')
else:
if a==b or a==c or b==c:
tipo.configure(text='Triangulo Isoceles')
else:
tipo.configure(text='Triangulo Escaleno')
else:
tipo.configure(text='Não forma um Triangulo')
tela=Tk()
tela.title('Triangulos')
tela.geometry('350x150')
lb_lado01=Label(tela,text='lado 1:')
lb_lado02=Label(tela,text='lado 2:')
lb_lado03=Label(tela,text='lado 3:')
et_lado01=Entry(tela)
et_lado02=Entry(tela)
et_lado03=Entry(tela)
tipo=Label(tela)
lb_lado01.place(x=10, y=10)
lb_lado02.place(x=10, y=40)
lb_lado03.place(x=10, y=70)
et_lado01.place(x=50, y=10)
et_lado02.place(x=50, y=40)
et_lado03.place(x=50, y=70)
tipo.place(x=200, y =50)
bt_tipo=Button(tela,text='Verificar Tipo')
bt_tipo.place(x=10,y=120, width=165)
bt_tipo['command']=bt_tipo_click
tela.mainloop() |
def media(n):
if n<5:
return 'D'
if n<7:
return 'C'
if n<9:
return 'B'
if n<10:
return 'A'
n= int(input('informe a media do aluno: '))
print('a nota informada tem conceito',media(n)) |
from tkinter import *
font=('Arial','10')
def bt_calc():
global v
terra=float(et_peso.get())
if v.get()==1:
planeta = (terra / 10) * 0.37
nome='Mercúrio'
if v.get()==2:
planeta = (terra / 10) * 0.88
nome = 'Vênus'
if v.get()==3:
planeta = (terra / 10) * 0.38
nome = 'Marte'
if v.get()==4:
planeta = (terra / 10) * 2.64
nome = 'Jupiter'
if v.get()==5:
planeta = (terra / 10) * 1.15
nome = 'Saturno'
if v.get()==6:
planeta = (terra / 10) * 1.17
nome = 'urano'
lb_res.configure(text='em {} o peso seria de {}kg'.format(nome,planeta),bg='yellow',font=font)
tela=Tk()
tela.title('peso nos planetas')
tela.geometry('250x200')
lb_peso=Label(tela,text='Peso na Terra (kg):')
et_peso=Entry(tela)
bt_calcular=Button(tela,text='Calcular Peso')
lb_planeta=Label(tela,text='selecione o Planeta:')
lb_res=Label(tela)
v=IntVar()
Radiobutton(tela,text='Mércurio',variable=v,command=bt_calc, value=1).place(x=10,y=90)
Radiobutton(tela,text='Vênus',variable=v,command=bt_calc, value=2).place(x=90,y=110)
Radiobutton(tela,text='Marte',variable=v,command=bt_calc, value=3).place(x=170,y=90)
Radiobutton(tela,text='Jupiter',variable=v,command=bt_calc, value=4).place(x=10,y=110)
Radiobutton(tela,text='Saturno',variable=v,command=bt_calc, value=5).place(x=90,y=90)
Radiobutton(tela,text='Urano',variable=v,command=bt_calc, value=6).place(x=170,y=110)
lb_peso.place(x=10,y=10)
et_peso.place(x=10,y=40)
bt_calcular.place(x=150,y=40)
lb_planeta.place(x=10,y=70)
lb_res.place(x=10,y=130)
bt_calcular['command']=bt_calc
tela.mainloop() |
#Funções definidas pela linguagem
'''
print(parametro)
input(parametro)
int(parametro)
float(parametro)
list(parametro)
len(parametro)
range(parametro)
min,sum,max
'''
#funções que só podem ser usados com LISTA
'''
lista.append(parametro)
lista.index(parametro)
'''
#funçoes que só podem ser usadas com dicionarios
'''
dic.items
dic.values
dic.keys
'''
#FUNÇÕES DEFINIDAS PELO USUÁRIO
'''
-->MODULOS
-->SUBALGORITMOS
-->ROTINAS
-->SUBROTINAS
-->METODOS
'''
#CRIANDO UMA FUNÇÃO
def hello_world():
print('Hello World!')
#CRIANDO UMA FUNÇÃO COM PARAMETRO/ARGUMENTO
def hello_world_nome(nome):
print('Hello World para {}'.format(nome))
def soma(n1,n2):
print(n1+n2)
#USANDO A FUNÇÃO
hello_world()
#USANDO FUNÇÃO COM PARAMETRO - SOMENTE COM PARAMETROS
hello_world_nome('Evaldo Junior')
nome=input('digite um nome: ')
hello_world_nome(nome)
hello_world_nome(input('digite um nome: '))
soma(1,2)
soma(5,5)
soma(int(input('digite o primeiro valor: ')),int(input('digite o segundo valor: ')))
|
def e_primo(num):
divisores = 0
i = 1
while i <= num:
if num % i == 0 :
divisores = divisores + 1
i = i + 1
if divisores == 2:
return True
else:
return False
n=int(input('informe o numero: '))
if e_primo(n)==False:
print('{} não é primo'.format(n))
if e_primo(n)==True:
print('{} é primo'.format(n)) |
prods=[]
quants=[]
dic={}
while True:
prod=str(input('informe o nome do produto: '))
prod=prod.upper()
if prod=='FIM':
break
else:
quant = int(input('informe a quantidade de {} a comprar: '.format(prod)))
prods.append(prod)
quants.append(quant)
dic=dict(zip(prods,quants))
print(dic)
soma=0
for x in dic.values():
soma=soma+x
print('o total dos itens é ',soma) |
lista = [] #lista vazia
print('tamanho:',len(lista))#tamanho da lista
lista.append(10) #adicionar um elemento a lista
print('tamanho:',len(lista))#tamanho da lista
print(lista)
lista.append(20)
lista.append(30)
lista.append(20)
print('tamanho:',len(lista))
print(lista)
del lista[0] #apagar item da posição informada
print(lista)
lista.remove(20)
print(lista)
|
def divisivel (x,y):
if x%y==0:
return 'é divisível'
else:
return 'não é divisível'
x=int(input('informe o valor: '))
y=int(input('informe o divisor: '))
print('{} {} por {}'.format(x,divisivel(x,y),y)) |
raio = float(input('informeo raio do circulo desejado:'))
area = 3.14*raio**2
print('a area do circulo é ',area)
input('.') |
import math
print('-----------------')
print('TINTAS EM CORES')
print('-----------------')
metros = float(input('informe quantos metros quadrados deseja pintar:'))
litros = metros/3
galao = math.ceil(litros/18)
print('você vai precisar de',galao,'galão(ões) de tinta')
print('cada galão custa R$ 80,00 reais')
print('o valor total será de R$', float(galao*80),'reais')
input('.')
|
# heap sort
# Utility Function to get parent node by index
# i is the index of array member
def getParent(i):
idx = (i-1)//2
if idx >= 0:
return idx
else:
return None
# Utility Function to get left child node by index
def getLeftChild(i, arr):
idx = 2*i + 1
if idx < len(arr):
return idx
else:
return None
# Utility Function to get right child node by index
def getRightChild(i, arr):
idx = 2*i + 2
if idx < len(arr):
return idx
else:
return None
# Given an array A and an index i
# assume left tree of i and right tree of i are max heaps
# make tree with root i to be a max heap
# heapsize is used to control how much elements to be processed
def maxHeapify(A, i, heapsize):
largest = i
leftIdx = getLeftChild(i, A)
if leftIdx is not None and leftIdx < heapsize and A[leftIdx] > A[i]:
largest = leftIdx
rightIdx = getRightChild(i, A)
if rightIdx is not None and rightIdx < heapsize and \
A[rightIdx] > A[largest]:
largest = rightIdx
# notice that the process need to be continued
# only if larest is not i
# otherwise, the process stops
if largest is not i:
tmp = A[i]
A[i] = A[largest]
A[largest] = tmp
maxHeapify(A, largest, heapsize)
# for every node which is not leaf node
# adjust it to a max heap
def buildMaxHeap(A):
for i in range(len(A)//2, -1, -1):
maxHeapify(A, i, len(A))
# final function for heapsort
def heapSort(A):
# firstly, reconstruct A to be a max heap
buildMaxHeap(A)
heapsize = len(A)
# find max element for every step
for i in range(len(A) - 1, 0, -1):
tmp = A[0]
A[0] = A[i]
A[i] = tmp
heapsize = heapsize - 1
maxHeapify(A, 0, heapsize)
if __name__ == '__main__':
print("--->Test utility functions...")
A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
print("original A is: ", str(A))
for idx, val in enumerate(A):
print("<-------index: % d, value:: %d------->" % (idx, val))
parentIdx = getParent(idx)
if parentIdx is not None:
print("parent node of %d: %d" % (A[idx], A[parentIdx]))
else:
print("This is Root Node")
leftChildIdx = getLeftChild(idx, A)
if leftChildIdx is not None:
print("left node of %d: %d" % (A[idx], A[leftChildIdx]))
else:
print('\n')
continue
rightChildIdx = getRightChild(idx, A)
if rightChildIdx is not None:
print("right node of %d: %d" % (A[idx], A[rightChildIdx]))
print('\n')
print("--->Test maxHeapify...")
A = [16, 4, 10, 14, 7, 9, 3, 2, 8, 1]
print("original A is: ", str(A))
print("lfet and right tree of index 1 are both max heap befor process")
maxHeapify(A, 1, len(A))
print("after call maxHeapify to process index 1:")
print(A)
print('\n')
print("--->Test buildMaxHeap...")
A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
print("original A is: ", str(A))
buildMaxHeap(A)
print("processed A is: ", str(A))
print('\n')
print("--->Test heapSort...")
A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
print("original A: ", str(A))
heapSort(A)
print("sorted A: ", str(A))
|
import math
import typing
import kinematics2d as k2d
__all__ = ["Pose"]
class Pose:
"""A 2-dimensional pose.
Attributes:
- position: k2d.Vector
- orientation: float (in radians)
"""
def __init__(self, position: k2d.Vector, orientation: float) -> None:
self._position: k2d.Vector = k2d.Vector.from_copy(position)
self._orientation: float = orientation
@classmethod
def from_copy(cls, source: "Pose") -> "Pose":
return cls(k2d.Vector.from_copy(source.position), source.orientation)
@classmethod
def zeros(cls) -> "Pose":
return cls(k2d.Vector.zeros(), 0.0)
@property
def position(self) -> k2d.Vector:
return self._position
@position.setter
def position(self, value: k2d.Vector) -> None:
self._position.x = value.x
self._position.y = value.y
@property
def orientation(self) -> float:
return self._orientation
@orientation.setter
def orientation(self, value: float) -> None:
self._orientation = value
def __repr__(self) -> str:
return "Pose(pos: {}, ort: {})".format(self.position, self.orientation)
def __add__(self, other: "Pose") -> "Pose":
"""Calculate the transformation of other to the coordinate frame of self."""
return Pose(
self.position + other.position.rotated(self.orientation),
self.orientation + other.orientation,
)
def __iadd__(self, other: "Pose") -> "Pose":
return self + other
def __sub__(self, other: "Pose") -> "Pose":
"""Calculate the transformation of self to the coordinate frame of other."""
return Pose(
(self.position - other.position).rotated(-other.orientation),
self.orientation - other.orientation,
)
def __isub__(self, other: "Pose") -> "Pose":
return self - other
def is_at_position(
self, target: k2d.Vector, tolerance: typing.Optional[float] = None
) -> bool:
if tolerance is None:
tolerance = k2d.EPSILON
return abs(target - self.position) <= tolerance
def is_at_orientation(
self, target: float, tolerance: typing.Optional[float] = None
) -> bool:
if tolerance is None:
tolerance = k2d.EPSILON
return abs(k2d.angle_diff(self.orientation, target)) <= tolerance
def is_at(
self,
target: "Pose",
pos_tolerance: typing.Optional[float] = None,
ort_tolerance: typing.Optional[float] = None,
) -> bool:
return self.is_at_position(
target.position, pos_tolerance
) and self.is_at_orientation(target.orientation, ort_tolerance)
|
'''
Sample input : hello
sample output: {h: 1, e: 1, l: 2, 0: 1}
'''
# first solve
inp = input()
spis = {}
new_spis = []
for i in range(len(inp)):
count=1
if inp[i] not in new_spis:
new_spis.append(inp[i])
spis.update({inp[i]: count})
count = 1
else:
count += 1
spis.update({inp[i]: count})
print(spis)
# second solve
def char_frequency(inp): # inp:str --> input('hello')
dict = {} # create new empty dict
for el in arr:
keys = dict.keys()
if el in keys:
dict[el] += 1 # dict[el] = for example it is 'h' if 'h' in key of our dict --> {'h': +=1}
else:
dict[el] = 1 # if dict[el] not in dict yet, for example 'e' --> {'e': 1}
return dict
# arr = hello
inp = input()
print(char_frequency(inp))
|
def swap(i, j):
sqc[i], sqc[j] = sqc[j], sqc[i]
def heapify(end,i):
l=2 * i + 1
r=2 * (i + 1)
max=i
if l < end and sqc[i] < sqc[l]:
max = l
if r < end and sqc[max] < sqc[r]:
max = r
if max != i:
swap(i, max)
heapify(end, max)
def heap_sort():
end = len(sqc)
start = end // 2 - 1 # use // instead of /
for i in range(start, -1, -1):
heapify(end, i)
for i in range(end-1, 0, -1):
swap(i, 0)
heapify(i, 0)
sqc = [2, 7, 1, -2, 56, 5, 3]
heap_sort()
print(sqc) |
from Stack import Stack
def check_line(input_line):
st = Stack([])
key_dict = {
')': '(',
'}': '{',
']': '['
}
inx = 0
for elem in input_line:
inx += 1
if elem not in key_dict.keys():
st.push(elem)
elif st.is_empty():
return 'Неупорядоченный. Ошибка первого элемента'
elif key_dict[elem] == st.peek():
st.pop()
else:
return f'Неупорядоченный. Ошибка элемента {elem} позиция {inx}'
return 'Список упорядоченный'
if __name__ == '__main__':
print(check_line('[([])((([[[]]])))]{()}[((([{}])))]'))
|
"""exdictionary = {"hi":2, "hola":4}
print(exdictionary["ahi"])
if "hi" in exdictionary:
print("hola")"""
""".clear() - deletes all contents of a dictionary
.items() - returns all key, value pairs
.get(key) - returns the value for the passed key
.keys() - returns a list of all keys
.values() - returns a list of all values
**len() also works with Dictionaries**
"""
"""for x in exdictionary:
print(x) #This only prints key
if "a" in x:
print("hi")"""
list = [9,10,12]
dictionary = {1:2,2:list,3:6,5:8}
for x in dictionary.items():
print(x)
print(list)
#2
dictionary2 = {1:"hi",2:"ho",3:"ha"}
def function(dictionary,value):
for x in dictionary:
if value == dictionary[x]:
print(x)
function(dictionary2,"hi")
#3
list2 = [1,2,3,4]
dic = {0:1,1:2,2:3,3:4}
#4
acdictionary = {}
j = input("How many words u wanna input")
for t in range(1,int(j)+1):
k = input("What is you word")
i = input("What is you Definition")
acdictionary[k] = i
print(acdictionary)
#5
list = [0,1,2,3,4,5,6,7]
listdic = {list}
|
# Rosette.py
import turtle
t = turtle.Pen()
colors = ["red", "pink", "blue", "purple", "yellow", "green"]
for x in range (6):
t.pencolor(colors[x%6])
t.circle(100)
t.left(60)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.