text
stringlengths 37
1.41M
|
---|
import math
# --------
# returns the perpendicular distance from point to Line(linaA, lineB)
#
def perpendicularDistance(lineA, lineB, point):
t = lineB[0] - lineA[0], lineB[1] - lineA[1] # Vector ab
dd = math.sqrt(t[0] ** 2 + t[1] ** 2) # Length of ab
t = t[0] / dd, t[1] / dd # unit vector of ab
n = -t[1], t[0] # normal unit vector to ab
ac = point[0] - lineA[0], point[1] - lineA[1] # vector ac
return ac[0] * n[0] + ac[1] * n[1] # Projection of ac to n (the minimum distance)
def addDegree(a, b):
return (a + b) % (2 * math.pi)
def diffDegree(a, b):
return ((a - b + math.pi) % (2 * math.pi)) - math.pi
def pathDistance(path):
distance = 0
for i in range(len(path) - 1):
(aX, aY) = path[i]
(bX, bY) = path[i + 1]
dx = aX - bX
dy = aY - bY
distance += math.sqrt(dx * dx + dy * dy)
return distance
def calculatePosition(direction, distance, position):
absDirection = position[2] + direction
x = math.cos(absDirection) * distance
y = math.sin(absDirection) * distance
return (position[0] + x, position[1] + y)
|
number_input = input("Enter a number: ")
# try the execution inside the try
try:
x = int(number_input)
print(x*10)
# if there is an error, it goes to except
except Exception as error:
print("There is an error. Please try again")
# finally block is always going to be executed
finally:
print("finally block")
print("process ended")
|
# ask user to enter a number save it to variable x
x = input('enter the first number: ')
# ask user to enter a number save it to variable y
y = input('enter the second number: ')
# ask user to enter the operation +, -, *, /
operation = input("enter +, -, *, /: ")
# convert from string to integer / number
x_int = int(x)
y_int = int(y)
# do the math operation based on the operation that user entered
if operation == '+':
print('x + y is {0}'.format(x_int + y_int))
elif operation == '-':
print('x - y is {0}'.format(x_int - y_int))
elif operation == '*':
print('x * y is {0}'.format(x_int * y_int))
elif operation == '/':
print('x / y is {0}'.format(x_int / y_int))
else:
print("we don't know what you want.")
|
options = ('pizza', 'burger')
# you can access tuple by its index
print(options[0])
# example of the use of tuple
genders = ('male', 'female')
classes = (1,2,3,4,5,6)
|
# ask user to enter email address
email = input('Enter your email address: ')
# check if the email has @, if yes print 'your email is valid', else print 'enter the correct email'
if email.count('@') > 0:
# if the email has . after the sign [email protected]
at_position = email.index('@')
dot_position = email.index('.', at_position)
print(dot_position)
if email.count('.') > 0:
print('email is valid')
else:
print('error')
else:
print('Enter the correct email')
|
class BackNForthIterator(object):
ABOVE = 0
BELOW = 1
def __init__(self, list_):
self.list = list_
middle_of_list = len(self.list)//2
self.above = middle_of_list
self.below = middle_of_list
self.previous_iteration = None
def __iter__(self):
return self
def __next__(self):
if self.previous_iteration == None:
self.previous_iteration = BackNForthIterator.BELOW
index = self.below
elif self.previous_iteration == BackNForthIterator.BELOW:
# Return item from above
# Prevent accessing the list in reverse.
if not self.above > 0:
raise StopIteration
self.above -= 1
self.previous_iteration = BackNForthIterator.ABOVE
index = self.above
else:
# Return item from below
self.below += 1
self.previous_iteration = BackNForthIterator.BELOW
index = self.below
try:
return self.list[index]
except IndexError:
raise StopIteration # Done iterating.
|
# HW1
number = int(input('Введите число: '))
print(number + 2)
# HW2
number = int(input('Введите число от 0 до 10: '))
while 10 < number > 0:
print('Введено не верное число')
number = int(input('Введите число от 0 до 10: '))
else:
print(number ** 2)
# HW3
#Пациент в хорошем состоянии, если ему до 30 лет и вес от 50 и до 120 кг,
#Пациенту требуется заняться собой, если ему более 30 и вес меньше 50 или больше 120 кг
#Пациенту требуется врачебный осмотр, если ему более 40 и вес менее 50 или больше 120 кг.
# ДА да да да я это сделал!!!!!! вложенные операторы! 6 часов, и 6 вариантов кода. 21.09.21 21:35
# в условии можно брать в скобки нужные строки чтобы менять приоритет.
name = input('Введите Имя: ')
sur_name = input('Введите Фамилию: ')
age = int(input('Введите Возраст: '))
veight = int(input('Введите Вес: '))
if age < 30 and 50 < veight < 120:
print(name,sur_name, age, 'год,','вес', veight, '- Вы в хорошем состоянии')
elif 40 > age > 30:
if veight < 50 or veight > 120:
print(name,sur_name, age, 'год,','вес', veight, '- Вам следует заняться собой')
elif age > 40:
if veight < 50 or veight > 120:
print(name,sur_name, age, 'год,','вес', veight, '- Вам требуется врачебный осмотр')
|
# card 2 attributes
# rank 2-10 J K Q A
# suit H C S D
import random
def card_generator():
#generate a number between 1 and 13 to correspond to rank
card_num = (random.randint(1,13))
#randomply pair that number with a suit option
suit = ['H', 'C', 'S', 'D']
random_suit = random.randint(0,3)
card_suit = suit[random_suit]
#return number-suit combination
return [card_num, card_suit]
print(card_generator())
def number_of_cards_generator(N):
#how many times we will run the loop
counter = N
#store generated cards in list
hand_of_cards = []
while counter > 0:
new_card = card_generator()
hand_of_cards.append(new_card)
counter -= 1
#return full hand of cards back
return hand_of_cards
# cards = [card_generator() for i in range(1, 5)]
# test by generating 5 cards
print(number_of_cards_generator(5))
# flush [[5, 'S'], [9, 'S'], [10, 'S'], [13, 'S'], [6, 'S']]
# not flush [[5, 'S'], [9, 'D'], [10, 'S'], [13, 'S'], [6, 'S']]
test_of_flush = [[5, 'S'], [9, 'S'], [10, 'S'], [13, 'S'], [6, 'S']]
test_not_flush = [[5, 'S'], [9, 'D'], [10, 'S'], [13, 'S'], [6, 'S']]
# is(has)_flush for functions that return boolean
def check_flush(list_of_cards):
#get all suits in the list of lists
suits_in_hand = []
for elem in list_of_cards:
suit = elem[1]
suits_in_hand.append(suit)
# suits_in_hand = [elem[1] for elem in list_of_cards]
#set it
suits_in_hand_unique = set(suits_in_hand)
# if len(suits_in_hand_unique) == 1:
# return True
# #otherwise: return False
# else:
# return False
return len(suits_in_hand_unique) == 1
print(check_flush(test_of_flush))
print(check_flush(test_not_flush))
def main():
# call all functions here
pass
|
# capitalize
# # You are asked to ensure that the first and last names of
# people begin with a capital letter in their passports.
# For example, alison heck should be capitalised correctly as Alison Heck.
def solve(s):
s_list = s.split()
s_list_cap = []
for elem in s_list:
print(elem)
s_list_cap.append(elem.capitalize())
return s_list_cap
|
# Write a method, overlap(list1, list2), which:
# Accepts two lists, list1 and list2
# Returns a list with the elements in both list1 and list2. The ordering of the returned list is not important.
# Examples
# overlap(['a'], []) should return []
# overlap(['a'], ['a']) should return ['a']
# overlap(['b', 'a', 'n', 'a', 'n', 'a', 's'], ['c', 'a', 'n', 't', 'a', 'l', 'o', 'u', 'p', 'e']) should return ['a', 'n']
#a slower way using loops:
def overlap(list1, list2):
overlapping_char = []
for elem in list1:
if elem in list2:
overlapping_char.append(elem)
return overlapping_char
#there is a faster way to do this, with sets
list(set(list1).intersection(list2))
|
list1 = [1, 2, 5, 4, 4, 3, 6]
list2 = [3, 2, 9, 7, 10, 7, 8]
def ret_diff(x):
return x[1]-x[0]
x = sorted(zip(list1,list2),key=ret_diff)
for i in x:
print(i)
|
# Product Inventory Class
# manages an inventory of products.
# keeps track of various products and can sum up the inventory value.
class Product(object):
def __init__(self, price, ID, quantity):
self.price = price
self.id = ID
self.quantity = quantity
class Inventory(object):
def __init__(self, products): # products arg must be taken as list []
self.products = products
self.value = 0
def print_inv(self):
for i in range(0, len(self.products)):
item = self.products[i]
print (str(i+1)+".", item.id, "$"+str(item.price), "x"+str(item.quantity))
def add_to_inv(self, item):
self.products.append(item)
def inv_sum(self):
sum_ = 0
for product in self.products:
sum_ += product.price * product.quantity
print ("TOTAL INVENTORY VALUE\n", "[$"+str(sum_)+"]")
|
#Use a list comprehension to create a new list first_names
#containing just the first names in names in lowercase.
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names = [name.split()[0].lower() for name in names]
#for name in names:
#name.split()[0].islower
# print(name.split()[0].lower())
print(first_names)
|
""" This module contains functions for reading CSV files containing pressure
and volume data.
"""
import numpy
def read_csv(input_file, delimiter=",", x="p", sigma_x="sigma_p",
y="v", sigma_y="sigma_v"):
"""
Reads a CSV file with x and y data and standard deviation columns.
Parameters
----------
input_file : str
delimiter : str
y : str
x : str
sigma_y : str
sigma_x : str
Returns
-------
x, y, sigma_x, sigma_y : tuple of array_like
"""
data = numpy.genfromtxt(input_file, delimiter=delimiter, names=True)
return (data[x].flatten(), data[sigma_x].flatten(),
data[y].flatten(), data[sigma_y].flatten())
|
import turtle
import random
#people list will store all the people objects
people =[]
#launch window and set up GUI
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Simulator")
#initialize patient0
patient0 = turtle.Turtle()
#method will set up the amount of people objects specified by user
def setPeople(amount):
for _ in range(amount):
people.append(turtle.Turtle())
for person in people:
person.shape("circle")
person.color("green")
person.penup()
person.speed(0)
x = random.randint(-290,290)
y = random.randint(-290,290)
person.goto(x,y)
person.dy = 0
person.dx = 2
#set up patient 0 and spwn in the window
def setPatientZero():
patient0.shape("circle")
patient0.color("red")
patient0.penup()
patient0.speed(0)
x0 = random.randint(-290,290)
y0 = random.randint(-290,290)
patient0.goto(x0,y0)
patient0.dy = 0
patient0.dx = 2
|
#1.
def Biggle(lis):
for x in range(0,len(lis)):
if lis[x]>0:
lis[x]="big"
return lis
#2.
def CountPositives(lis):
count=0
for x in range(0,len(lis)):
if lis[x]>0:
count+=1
lis[len(lis)-1]=count
return lis
#3.
def SumTotal(lis):
sum=0
for x in range(0,len(lis)):
sum+=lis[x]
return sum
#4.
def avg(lis):
sum=0
for x in range(0,len(lis)):
sum+=lis[x]
avg=sum/len(lis)
return avg
#5.
def length(lis):
print(len(lis))
#6.
def min(lis):
min=lis[0]
for x in range(0,len(lis)):
if lis[x]>min:
min=lis[x]
print(min)
return min
#7.
def max(lis):
max=lis[0]
for x in range(0,len(lis)):
if lis[x]>max:
max=lis[x]
return max
#8.
def UltimateAnalysis(lis):
Analysis={'sumTotal':0,'average':0,'minimum':0,'maximum':0,'length':0}
sumtotal = 0
average = 0
minimum = lis[0]
maximum = lis[0]
length = len(lis)
for x in range(len(lis)):
if lis[x] > maximum:
maximum = lis[x]
sumtotal += lis[x]
elif lis[x] < minimum:
minimum = lis[x]
sumtotal += lis[x]
average = sumtotal/len(lis)
Analysis['sumTotal'] = sumtotal
Analysis['average'] = average
Analysis['minimum'] = minimum
Analysis['maximum'] = maximum
Analysis['length'] = length
print (Analysis)
return Analysis
#9.
def ReverseList(lis):
temp=0
for x in range(0,len(lis)//2):
temp=lis[x]
lis[x]=lis[len(lis)-1-x]
lis[len(lis)-1-x]=temp
return lis
|
#import game modules
import sys, pygame
from pygame.sprite import Sprite
from pygame.locals import *
"""class that defines and characterises projectile objects within the game"""
class EnemyProjectile(Sprite):
#initialises projectile object upon invocation
def __init__(self, spawnCoords):
pygame.sprite.Sprite.__init__(self)
self.counter = 0
self.projectileClock = 0
self.bulletImage = None
#load the image for the ship
self.bulletImage = pygame.image.load("enemyPlasmaProjectile.png")
self.bulletImage = pygame.transform.scale(self.bulletImage, (15, 15))
self.image = self.bulletImage
#load the rectangle image behind the sprite
self.rect = self.image.get_rect()
self.rect.center = spawnCoords
#method updates sprite state - moves projectiles along a linear path
def update(self):
self.rect.y += 2
if self.projectileClock == 0 and self.counter == 40:
self.counter = 0
self.projectileClock = 1
elif self.projectileClock == 1 and self.counter == 40:
self.counter = 0
self.projectileClock = 0
else:
self.counter += 1
|
items = [('product-1', 12), ("product-2", 10), ('product-3', 8)]
price = [item[1] for item in items]
# print(price)
fil = [item for item in items if item[1] >= 10]
print(fil)
#list comprehension is a great feature
|
class Point:
default_color = 'Red' # it's a class level attribute
def __init__(self, x, y):
# these are instant level attributes
self.x = x
self.y = y
def drawing(self):
print(f'Point ({self.x}, {self.y})')
# if we change class level attribute value,it is changed for all objects.
Point.default_color = 'Yellow'
point = Point(1, 2)
# calling class level attributes with the object and class name
print(point.default_color)
print(Point.default_color)
point.drawing()
another = Point(3, 4)
another.drawing()
print(another.default_color)
|
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(x=1, y=2)
p2 = Point(x=1, y=2)
print(p1.x)
print(id(p1))
print(id(p2))
print(p1 == p2)
|
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
#a decorator for defining a class method, it's a way to extend the
# behaviour of a method or function
@classmethod
def zero(cls):
return cls(0,0)
# this is an instant level method
def drawing(self):
print(f'Point ({self.x}, {self.y})')
point = Point.zero()
point.drawing()
|
letters = ['a', 'b', 'c', 'd']
letters.append('e') # append at the last
letters.insert(0, '-') # insert at any index
letters.pop() # remove last item
letters.pop(0) # remove at a given index
letters.remove('b') # remove by searching an item
del letters[0:2] # delete a range of object
letters.clear() # clear all the list
print(letters)
|
operand1 = 95
operand2 = 64.5
print operand1, "+", operand2, "=", operand1 + operand2
print operand1, "-", operand2, "=", operand1 - operand2
print operand1, "*", operand2, "=", operand1 * operand2
print operand1, "/", operand2, "=", operand1 / operand2
print operand1, "%", operand2, "=", operand1 % operand2
#I solved this problem by making the numbers equal to operand1 and operand2 in order for the system to respond correctly and solve the math equations
#Writing print was a necesssary step because without it the problems wouldn't show up.
|
# def add(num1, num2):
# return num1 + num2
#
# 1+1
# 2
# 2+2
# 4
# 2-2
# 0
class Calculator():
def __init__(self, expression):
print("Starting calculator.. ")
self.expression = expression
self.operator = self.define_operator()
# function -- split with '+'
def split_by_plus(self):
return self.expression.split("+")
def split_by_minus(self):
return self.expression.split("-")
def convert_list_string_to_int(self, list_string):
return [
int(list_string[0]),
int(list_string[1])
]
# function -- convert to integer
def calculate_list_int(self, list_int):
if self.operator == "+":
return list_int[0] + list_int[1]
elif self.operator == "-":
return list_int[0] - list_int[1]
return None
def define_operator(self):
if "+" in self.expression:
self.operator = "+"
elif "-" in self.expression:
self.operator = "-"
else:
self.operator = None
return self.operator
def calculate(self):
# split_result = self.split_by_plus(string)
# oper = self.define_operator(string)
if self.operator is not None:
if self.operator == '+':
split_result = self.split_by_plus()
elif self.operator == '-':
split_result = self.split_by_minus()
convert_result = self.convert_list_string_to_int(split_result)
return self.calculate_list_int(convert_result)
if __name__ == '__main__':
input_data = input("Enter your expression: ")
print(Calculator(input_data).calculate())
|
nilai = 90
if(nilai > 85):
print("Grade A")
elif(nilai == 70):
print("Grade B")
elif(nilai == 60):
print("Grade C")
elif(nilai == 50):
print("Grade D")
else:
print("Tidak Lulus")
|
string = "Number Guessing Game"
string2 = "Guess a number (1-9)"
print(string)
print(string2)
number = 9
guess = input("Enter Your guess:-")
if(guess < 9):
print("You Lose")
elif(guess == number):
print("YOU WIN")
|
import socket
import time
# start of the application
if __name__ == '__main__':
# checks if the server is connected to a client
isConnected = False
# contains the socket data
mySocket = None
# checks if the Server is currently running
isRunning = True
while isRunning == True:
while isConnected == False:
# if by case the socket was not created
if mySocket is None:
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# check if the server is connected
try:
mySocket.connect(("127.0.0.1", 8222))
isConnected = True
except socket.error:
isConnected = False
print("Socket not made")
# check if the socket is connected
if(isConnected == True):
try:
testString = "Connected to Server"
mySocket.send(testString.encode())
except:
isConnected = False
mySocket = None
if isConnected == False:
print("Server not Found")
time.sleep(1.0)
# when the server is connected to the client
while isConnected == True:
# check if the server has lost connection
try:
key = raw_input('Enter Message: ')
mySocket.send(key.encode())
mySocket.recv(4096)
data = mySocket.recv(4096)
print(data)
except:
isConnected = False
mySocket = False
print("Server Lost")
input()
|
from M0227_Basic_Calculator_II import Solution as Basic_Calculator
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
return Basic_Calculator().calculate(s)
print(7, Solution().calculate("3+2*2"))
print(1, Solution().calculate("3/2"))
print(5, Solution().calculate(" 3+5 / 2 "))
# Given an arithmetic equation consisting of positive integers, +, -, * and / (no parentheses), compute the result.
# The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
# Example 1:
# Input: "3+2*2"
# Output: 7
# Example 2:
# Input: " 3/2 "
# Output: 1
# Example 3:
# Input: " 3+5 / 2 "
# Output: 5
# Note:
# You may assume that the given expression is always valid.
# Do not use the eval built-in library function.
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/calculator-lcci
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
from typing import List
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
if not M or not M[0]: return 0
from collections import deque
result, n = 0, len(M)
for i in range(n):
if M[i][i]:
result += 1
queue = deque()
queue.append(i)
while queue:
j = queue.popleft()
M[j][j] = 0
for k in range(n):
if M[j][k] and M[k][k]:
queue.append(k)
return result
def findCircleNumDisjoint(self, M: List[List[int]]) -> int:
if not M or not M[0]: return 0
from collections import Counter
n = len(M)
disjoint = [-1] * n
def find(x):
if -1 == disjoint[x]:
return x
disjoint[x] = find(disjoint[x])
return disjoint[x]
def union(x, y):
rx = find(x)
ry = find(y)
if ry != rx:
disjoint[ry] = rx
for i in range(n - 1):
for j in range(i + 1, n):
if M[i][j]:
union(i, j)
return Counter(disjoint)[-1]
test = Solution().findCircleNum
print(2, test([[1,1,0], [1,1,0], [0,0,1]]))
print(1, test([[1,1,0], [1,1,1], [0,1,1]]))
print(1, test([[1,0,1], [0,1,1], [1,1,1]]))
print(1, test([[1,1,1], [1,1,1], [1,1,1]]))
# There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
# Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
# Example 1:
# Input:
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
# Output: 2
# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
# The 2nd student himself is in a friend circle. So return 2.
# Example 2:
# Input:
# [[1,1,0],
# [1,1,1],
# [0,1,1]]
# Output: 1
# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
# so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
# Note:
# N is in range [1,200].
# M[i][i] = 1 for all students.
# If M[i][j] = 1, then M[j][i] = 1.
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/friend-circles
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
class DequeNode:
def __init__(self, k = 0, x = 0):
self.key = k
self.val = x
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cnt = 0
self.head = None
self.tail = None
self.pool = {}
def get(self, key: int) -> int:
if key not in self.pool: return -1
node = self.pool[key]
self.__update(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.pool:
node = self.pool[key]
node.val = value
self.__update(node)
return
if self.cnt == self.cap: self.pool.pop(self.__pop().key)
else: self.cnt += 1
self.pool[key] = DequeNode(key, value)
self.__insert(self.pool[key])
def __insert(self, node: DequeNode):
if self.head:
node.next = self.head
self.head.prev = node
self.head = node
if not self.tail: self.tail = node
def __update(self, node: DequeNode):
if node is self.head: return
node.prev.next = node.next
if node is self.tail: self.tail = node.prev
else: node.next.prev = node.prev
node.prev = None
self.__insert(node)
def __pop(self):
node = self.tail
if node is self.head: self.head, self.tail = None, None
else: self.tail, node.prev.next = node.prev, None
return node
class LRUCacheGuard:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.pool = {}
self.head = DequeNode()
self.head.next = self.head
self.head.prev = self.head
def get(self, key: int) -> int:
if key in self.pool:
node = self.pool[key]
self._move_to_head(node)
return node.val
else: return -1
def put(self, key: int, value: int) -> None:
if key in self.pool:
self.pool[key].val = value
self._move_to_head(self.pool[key])
else:
node = DequeNode(key, value)
self.pool[key] = node
self._add_node(node)
if self.size < self.capacity: self.size += 1
else: self.pool.pop(self._pop_tail().key)
def _add_node(self, node):
self.head.next.prev, node.next = node, self.head.next
self.head.next, node.prev = node, self.head
def _remove_node(self, node):
node.next.prev, node.prev.next = node.prev, node.next
return node
def _move_to_head(self, node):
self._remove_node(node)
self._add_node(node)
def _pop_tail(self):
return self._remove_node(self.head.prev)
from collections import OrderedDict
class LRUCacheOrderedDict(OrderedDict):
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self: return -1
self.move_to_end(key)
return self[key]
def put(self, key: int, value: int) -> None:
if key in self: self.move_to_end(key)
self[key] = value
if len(self) > self.capacity: self.popitem(last=False)
cache = LRUCacheOrderedDict(2)
cache.put(1, 1)
cache.put(2, 2)
print(1, cache.get(1))
cache.put(3, 3)
print(-1, cache.get(2))
cache.put(4, 4)
print(-1, cache.get(1))
print(3, cache.get(3))
print(4, cache.get(4))
cache.put(2, 1)
cache.put(2, 2)
print(2, cache.get(2))
cache.put(1, 1)
cache.put(4, 1)
print(-1, cache.get(2))
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
# Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
# get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
# put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
# The cache is initialized with a positive capacity.
# Follow up:
# Could you do both operations in O(1) time complexity?
# Example:
# LRUCache cache = new LRUCache( 2 /* capacity */ );
# cache.put(1, 1);
# cache.put(2, 2);
# cache.get(1); // returns 1
# cache.put(3, 3); // evicts key 2
# cache.get(2); // returns -1 (not found)
# cache.put(4, 4); // evicts key 1
# cache.get(1); // returns -1 (not found)
# cache.get(3); // returns 3
# cache.get(4); // returns 4
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/lru-cache
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
from utils import TreeNode
from typing import List
from M0102_Binary_Tree_Level_Order_Traversal import travel_level
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
return [[node.val for node in (nodes if level % 2 else reversed(nodes))] for level, nodes in travel_level(root)]
test = Solution().zigzagLevelOrder
print(test(TreeNode.create_tree([3,9,20,None,None,15,7])))
print(test(TreeNode.create_tree([3])))
print(test(None))
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
if not word1 or not word2:
if not word1 and not word2: return 0
else: return len(word1) if word1 else len(word2)
n1, n2 = len(word1), len(word2)
memo = [[0] * (n2 + 1) for _ in range(n1 + 1)]
for i in range(n1): memo[i][-1] = i + 1
for j in range(n2): memo[-1][j] = j + 1
for i in range(n1):
for j in range(n2):
if word1[i] == word2[j]:
memo[i][j] = memo[i - 1][j - 1]
else:
memo[i][j] = 1 + min(memo[i - 1][j - 1], memo[i][j - 1], memo[i - 1][j])
return memo[n1 - 1][n2 - 1]
test = Solution().minDistance
print(3, test('horse', 'ros'))
print(5, test('intention', 'execution'))
# Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
# You have the following 3 operations permitted on a word:
# Insert a character
# Delete a character
# Replace a character
# Example 1:
# Input: word1 = "horse", word2 = "ros"
# Output: 3
# Explanation:
# horse -> rorse (replace 'h' with 'r')
# rorse -> rose (remove 'r')
# rose -> ros (remove 'e')
# Example 2:
# Input: word1 = "intention", word2 = "execution"
# Output: 5
# Explanation:
# intention -> inention (remove 't')
# inention -> enention (replace 'i' with 'e')
# enention -> exention (replace 'n' with 'x')
# exention -> exection (replace 'n' with 'c')
# exection -> execution (insert 'u')
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/edit-distance
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1 if x >=0 else -1
x, y = x if sign > 0 else -x, 0
while x > 0:
y = y * 10 + x % 10
x //= 10
y *= sign
return 0 if y < -2**31 or y > 2**31 else y
test = Solution().reverse
print(321, test(123))
print(-321, test(-123))
print(21, test(120))
print(-21, test(-120))
# Given a 32-bit signed integer, reverse digits of an integer.
# Example 1:
# Input: 123
# Output: 321
# Example 2:
# Input: -123
# Output: -321
# Example 3:
# Input: 120
# Output: 21
# Note:
# Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/reverse-integer
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (-n) == n
def isPowerOfTwo2(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
test = Solution().isPowerOfTwo
print(True, test(1))
print(True, test(16))
print(False, test(218))
# Given an integer, write a function to determine if it is a power of two.
# Example 1:
# Input: 1
# Output: true
# Explanation: 2^0 = 1
# Example 2:
# Input: 16
# Output: true
# Explanation: 2^4 = 16
# Example 3:
# Input: 218
# Output: false
|
from utils import TreeNode
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root: return 0
from collections import deque
queue, cur_level, max_width = deque(), 0, 0
start_index, last_index = 0, 0
queue.append((1, 0, root))
while queue:
level, index, node = queue.popleft()
if level > cur_level:
cur_level = level
max_width = max(max_width, last_index - start_index + 1)
start_index = index
last_index = index
if node.left:
queue.append((level + 1, index * 2 + 1, node.left))
if node.right:
queue.append((level + 1, index * 2 + 2, node.right))
max_width = max(max_width, last_index - start_index + 1)
return max_width
test = Solution().widthOfBinaryTree
print(4, test(TreeNode.create_tree([1,3,2,5,3,None,9])))
print(2, test(TreeNode.create_tree([1,3,None,5,3])))
print(2, test(TreeNode.create_tree([1,3,2,5])))
print(8, test(TreeNode.create_tree([1,3,2,5,None,None,9,6,None,None,None,None,None,None,7])))
# Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
# The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
# Example 1:
# Input:
# 1
# / \
# 3 2
# / \ \
# 5 3 9
# Output: 4
# Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
# Example 2:
# Input:
# 1
# /
# 3
# / \
# 5 3
# Output: 2
# Explanation: The maximum width existing in the third level with the length 2 (5,3).
# Example 3:
# Input:
# 1
# / \
# 3 2
# /
# 5
# Output: 2
# Explanation: The maximum width existing in the second level with the length 2 (3,2).
# Example 4:
# Input:
# 1
# / \
# 3 2
# / \
# 5 9
# / \
# 6 7
# Output: 8
# Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
# Note: Answer will in the range of 32-bit signed integer.
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
from sys import argv as arguments
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if len(arguments) != 3:
print("2 arguments required!")
exit()
from_filename = arguments[1]
to_filename = arguments[2]
print("imput " +from_filename)
print("output: " + to_filename)
from_file = open(from_filename, 'r', encoding='utf8')
to_file = open(to_filename, 'w', encoding='utf8')
contents = from_file .read()
contents = [letter if letter.upper() in ALPHABET else '' for letter in contents]
contents = ''.join(contents)
contents = contents.upper()
to_file.write(contents)
from_file.close()
to_file.close()
|
import tempfile
import os
class File(object):
def __init__(self, path):
self.path = path
self.file = open(os.curdir + path, 'a+')
self.file.write('file opened!')
def write(self, text):
self.file.write(text)
def __add__(self, other):
data = self.get_data() + other.get_data()
temp_path = tempfile.gettempdir()
temp_path = temp_path + self.path
try:
file = open(temp_path, 'a+')
except FileNotFoundError:
os.makedirs(temp_path)
file = open(temp_path, 'a+')
file.write(data)
print(f'wrote {data} to {file}')
return file
def get_data(self):
self.file.write('smth')
data = self.file.read()
print(f'file = {self.file}')
return data
obj = File('\\tmp\\file.txt')
obj.write('line\n')
first = File('\\tmp\\first.txt')
second = File('\\tmp\\second.txt')
new_obj = first + second
obj = File('\\tmp\\file.txt')
print(obj.get_data())
|
from random import randrange
def genTen():
for _ in range(10):
grade = 'A'
score = randrange(60,101)
if 80 < score <= 90:
grade = 'B'
elif 70 < score <= 80:
grade = 'C'
elif score <= 70:
grade = 'D'
print("Score: {}; Your grade is {}".format(score, grade))
print("end of the program - bye!")
if __name__ == '__main__':
genTen()
|
#Find and Replace
"""
In this string: words = "It's thanksgiving day. It's my birthday,too!"
print the position of the first instance of the word "day".
Then create a new string where the word "day" is replaced with the word "month".
"""
words = "It's thanksgiving day. It's my birthday,too!"
print(words.find('day'))
print('month'.join(words.split('day')))
#Min and Max
"""
Print the min and max values in a list
like this one: x = [2,54,-2,7,12,98]. Your code should work for any list.
"""
def print_hi_lo(arr):
arr = sorted(arr)
print(arr[0], arr[-1])
x = [2,54,-2,7,12,98]
print_hi_lo(x)
#First and Last
"""Print the first and last values in a list like this one: x = ["hello",2,54,-2,7,12,98,"world"]. Now create a new list containing only the first and last values in the original list. Your code should work for any list.
"""
def first_last(arr):
l = [arr[0], arr[-1]]
print l
return l
x = ["hello",2,54,-2,7,12,98,"world"]
first_last(x)
#New List
"""Start with a list like this one: x = [19,2,54,-2,7,12,98,32,10,-3,6].
Sort your list first. Then, split your list in half.
Push the list created from the first half to position 0 of the list created from the second half.
The output should be: [[-3, -2, 2, 6, 7], 10, 12, 19, 32, 54, 98]. Stick with it, this one is tough!"""
def new_list(arr):
arr = sorted(arr)
halfpoint = len(arr) / 2
a, b = arr[:halfpoint], arr[halfpoint:]
return [a] + b
x = [19,2,54,-2,7,12,98,32,10,-3,6]
new_list(x)
|
# this code is not mine; taken from http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html
def mergeSort(L):
print("Splitting ",L)
if len(L)>1:
mid = len(L)//2
lefthalf = L[:mid]
righthalf = L[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
'''
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
L[k]=lefthalf[i]
i=i+1
else:
L[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
L[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
L[k]=righthalf[j]
j=j+1
k=k+1
'''
while i < len(L)-1:
if lefthalf[j] < righthalf[k]:
L[i] = lefthalf[j]
j += 1
i += 1
if lefthalf[j] >= righthalf[k]:
L[i] = righthalf[k]
k += 1
i += 1
print("Merging ",L)
L = [54,26,93,17,77,31,44,55,20]
mergeSort(L)
print(L)
|
#!/usr/bin/env python3
class CoupleValue:
"""CoupleValue class.
This class implements a couple value used in argument object.
attr:
criterion_name:
value:
"""
def __init__(self, criterion_name, value):
"""Creates a new couple value.
"""
self.__criterion_name = criterion_name
self.__value = value
def __str__(self):
"""Returns Item as a String.
"""
return str(self.__criterion_name) + ": " + str(self.__value)
def __eq__(self, other):
return self.__criterion_name == other.__criterion_name and self.__value == other.__value
def parse(self):
return self.__criterion_name,self.__value
|
# -*- coding: utf-8 -*-
# @Author : JoinApper
# @data : 2019/5/13
"""
栈的实现
"""
from Node import Node
from Empty import Empty
class LinkedStack(object):
def __init__(self):
"""
创造一个空栈
"""
self._head = None
self._size = 0
self.iter_pointer = None
def __len__(self):
"""
返回栈当前长度
:return: 长度
"""
return self._size
def __iter__(self):
self.iter_pointer = self._head
return self
def __next__(self):
if self.iter_pointer is None:
raise StopIteration
else:
now = self.iter_pointer
self.iter_pointer = self.iter_pointer.next
return now.element
def __str__(self):
return "["+",".join(str(i) for i in self)+"]"
def is_empty(self):
"""
判断栈是否为空
:return: Bool
"""
return self._size == 0
def push(self, e):
"""
添加节点到栈顶
:param e: 添加元素
:return: None
"""
self._head = Node(e, self._head)
self._size += 1
def top(self):
"""
返回栈顶元素,如果栈为空,抛出异常
:return: 栈顶元素
"""
if self.is_empty():
raise Empty("Stack is empty")
return self._head.element
def pop(self):
"""
移除并且返回栈顶元素
:return: 栈顶元素
"""
if self.is_empty():
raise Empty("Stack is empty")
answer = self._head.element
self._head = self._head.next
self._size -= 1
return answer
|
# -*- coding: utf-8 -*-
# @Author : JoinApper
# @data : 2019/5/13
"""
队列的实现
"""
from Node import Node
from Empty import Empty
class LinkedQueue(object):
def __init__(self):
"""
创建一个空队列
"""
self._head = None
self._tail = None
self._size = 0
self.iter_pointer = None
def __len__(self):
"""
返回队列长度
:return: 长度
"""
return self._size
def __iter__(self):
self.iter_pointer = self._head
return self
def __next__(self):
if self.iter_pointer is None:
raise StopIteration
else:
now = self.iter_pointer
self.iter_pointer = self.iter_pointer.next
return now.element
def __str__(self):
return "["+",".join(str(i) for i in self)+"]"
def is_empty(self):
"""
判断队列是否为空
:return: Bool
"""
return self._size == 0
def first(self):
"""
取得第一个元素
:return: 第一个元素
"""
if self.is_empty():
raise Empty("Queue is empty")
return self._head.element
def dequeue(self):
"""
移除并且返回第一个元素
:return:第一个元素
"""
if self.is_empty():
raise Empty("Queue is empty")
answer = self._head.element
self._head = self._head.next
self._size -= 1
if self.is_empty():
self._tail = None
return answer
def enqueue(self, e):
"""
添加一个元素到队列
:return: None
"""
newest = Node(e, None)
if self.is_empty():
self._head = newest
else:
self._tail.next = newest
self._tail = newest
self._size += 1
|
import time
import numpy as np
import simpleaudio as sa
# This function generates the audio tone by creating a 650hz SIN wave
def tone(duration, frequency=650, sampling_rate=44100):
"""
Generates a simple audio wave object from a specified frequency and duration.
"""
samples = np.sin(2*np.pi*np.arange(sampling_rate*duration)*frequency/sampling_rate)
samples *= 32767 / np.max(np.abs(samples)) # Normalize to 16 bit range
samples = samples.astype(np.int16)
wave = sa.WaveObject(samples, 1, 2, sampling_rate)
return wave
# <-- Write Your Morse Code Function Here -->
# <-- Complete The Transmit Function -->
def transmit(message):
# time unit (secs)
time_unit = 0.06
# see README.md for use
dot_tone = tone(time_unit)
dash_tone = tone(3 * time_unit)
# <-- Your Code Goes Here -->
# <-- Do Not Modify or Move -->
if __name__ == '__main__':
message = input('Message: ')
transmit(message)
|
#练习6.1 导演为剧本选主角
def out(actor):
print("%s开始参演这个剧本"%actor)
actor=input("导演选定的主角是:")
out(actor)
#练习 6.2 模拟美团外卖商家的套餐
package={"考神套餐":"13元","单人套餐":"9.9元","情侣套餐":"20元"}
def printTest(**para):
for key,value in para.items():
print('{:s}{:s}'.format(key,value))
printTest(**package)
#练习6.3 根据生日判断星座
Horoscope={"白羊座":(3.21,4.19),"金牛座":(4.20,5.20),"双子座":(5.21,6.21),"巨蟹座":(6.22,7.22),"狮子座":(7.23,8.22),
"处女座":(8.23,9.22),"天秤座":(9.23,10.23),"天蝎座":(10.24,11.22),"射手座":(11.23,12.21),"摩羯座":(12.22,1.19),
"水瓶座":(1.20,2.18),"双鱼座":(2.19,3.20)}
def DeterminStart(month,day):
gatevalue=month+day/100
for key,value in Horoscope.items():
if(gatevalue>=value[0] and gatevalue<=value[-1]):
print("%d月%d日星座为:%s"%(month,day,key))
month=int(input("请输入月份:"))
while(month>12 or month==0):
print("无效月份")
month=int(input("请输入月份:"))
day=int(input("请输入日:"))
while(day>30 or day==0) or(month==2 and day>28):
print("无效日")
month=int(input("请输入日:"))
DeterminStart(month,day)
#练习 6.4 将美元转为人民币
RATE=6.28
def Convert(dolar):
return dolar*RATE
Dmoney=input("请输入美元:")
print("转换后人民币金额是:%.2f"%Dmoney)
#6.附加题
def SumValue(value):
if(value==1):
return 1
else:
return value+SumValue(value-1)
print("1-100的求和是:%d"%SumValue(100))
|
# so the least product of 2 3 digit numbers is 10,000 and the largest is 998,001
import math
def largestPalindrome():
for n in range(998001, 10000, -1):
if str(n) == str(n)[::-1] and Factors(n) == True:
return n
def Factors(x):
factors = []
for num in range(2, int(math.sqrt(x)) + 1):
if x % num == 0:
factors.append(num)
factors.append(x // num)
for index in range(1, len(factors), 2):
if len(str(factors[index - 1])) == 3 and len(str(factors[index])) == 3:
return True
return False
print(largestPalindrome())
print(Factors(largestPalindrome()))
|
def part_one(input):
return sum([contains_only_unique_elements(line) for line in input.split('\n')])
def contains_only_unique_elements(line):
words = line.split()
return len(words) == len(set(words))
def part_two(input):
return sum([not contains_anagrams(line) for line in input.split('\n')])
def contains_anagrams(line):
words = line.split()
sorted_words = [''.join(sorted(word)) for word in words]
return len(sorted_words) != len(set(sorted_words))
if __name__ == "__main__":
input = """nyot babgr babgr kqtu kqtu kzshonp ylyk psqk
iix ewj rojvbkk phrij iix zuajnk tadv givslju ewj bda
isjur jppvano vctnpjp ngwzdq pxqfrk mnxxes zqwgnd giqh
ojufqke gpd olzirc jfao cjfh rcivvw pqqpudp
ilgomox extiffg ylbd nqxhk lsi isl nrho yom
feauv scstmie qgbod enpltx jrhlxet qps lejrtxh
wlrxtdo tlwdxor ezg ztp uze xtmw neuga aojrixu zpt
wchrl pzibt nvcae wceb
rdwytj kxuyet bqnzlv nyntjan dyrpsn zhi kbxlj ivo
dab mwiz bapjpz jbzppa
hbcudl tsfvtc zlqgpuk xoxbuh whmo atsxt pzkivuo wsa gjoevr hbcudl
gxhqamx dradmqo gxhqamx gxhqamx
yvwykx uhto ten wkvxyy wdbw
kzc ndzatgb rlxrk hfgorm qwgdky ndzatgb rhvyene qaa wxibe qwmku nmxkjqo
qwx ubca dxudny oxagv wqrv lhzsl qmsgv dxs awbquc akelgma
rrdlfpk ohoszz qiznasf awchv qnvse
ggsyj czcrdn oolj sibjzp ibzjps asp
vbcs ypgzae xcvpsr ptvb leoxqlq zmpt fhawu yfi tvbp
ejkr qlmag nsz jwpurli nhsml asksnug mes
kkgkjml kklmgjk kjgpx iquytbj eccceb mfv iuyqjbt ovv
uoklkco zzey sdfhiyv ytdeg
azr mjv raz arz rdfb
pir dafgsah dafgsah kndjbml estcz yjeoijp kkcws ebq puwno
iqymwc tac vlqc bmnkz xustm leqi
gwdjed cfha axz xjuq
abfjsg pahat qlj zan qsfn iozfys jnvu bis jakggq
afwuejn zrbu zurb hrn lwvjb jnwixla aufejnw
vkqn cuzf humhriz webnf uzfc zfuc
eznxd kgbfy jqyc net vzfege tprzyc
mqnapzn vrgw ilzp vgw
aie zkkih fhpwu bbn fhpwu wvxxgmd
ksoasrn yll mvdjxdo wydymx dmodvjx drnjlm tcjpjhj xzakb wrsbuwl vaygdwf rsasonk
qahbh tfhkl apdqqpm tfhkl nsox
xkelwve mvdmesj xrto tgku gkb bpe
nni nyylpu cyusxe zydeyok yokzdye xiscesy
itwsfr eqwrx igqkvif whklwdb
lpa hwci suwqfln xis sfht lzek ajecd
svpf eulute eya gvmsd app claria tjtk zjt agdyemi bixewo
gmzglxi zlgouy bejg kte xlf giquj mjeq ivjkw ktbhaga hoffyrt
wwjy dtf ftd agei yde xhbfo fyridy
gexcy hetkz ufflrfi frifluf plb kqre etxo elg henqy fspm
khaemn buec ichau wxctsxg
cgmv ujyvcuu jta yux ccx skrafkn cmyc yidqhv ltb ycnajry zitq
ybsahqn pio veeze vdztjz iedou pio sue ijbz gvqncl vpa ijbz
hkfi xzrsyke hikf mxolx xlxmo ungfc tst xjzd
tpx ioprco qixlv ipocro
oahmwrv homvraw vws ntmbdvx
fxlg wnuz ogt bxgtul vmfh nwuz glfx tgxdq bxfv kajuh
vrhqn nrqvh tgogb vya ragbro ulrz uava kexoi yav vkfe
bxxy tyxgxd oabsud bauosd jlch bdmrqq wqhjwb ayblb hclj
sfzsgsc sfzsgsc jbrvh sfzsgsc bdhy
wixleal vhnqbfw qwfnhbv woco oowc
exkkwz wekxzk krxbua nshxqgh
gkn blxgui nkg gnk
otsa isqn otsa isqn
ude xedl ude xedl amkktp
teroe yuvbd inf mpytuvz xiq xqi ovqetn
zyq ybeifwx fvoqp vhoduy bcq wbxl
zymiid vafcqv vjbmekf lgxkma bjti qfavcv iqp fnbu lakmgx
rkaqvd vylkh jfdxh imxxg bbrt imxxg rkaqvd
yajg qnhhs bzmb eyk hijcg tkij iwr jvwp dipzd jvwp
btzhw zttheyo ravsbz bmbba majoe ykrs tbxqf tai cgsvpu srbavz
vsyczfs ymg vsyczfs wxlwaqb oouio owek wxlwaqb azvbqiq
ghrapd ghrapd wisq wisq
znmleu aztnkbs wxc gycxd vqenhh geqyo rpjg
kxbom gzz zzg zgz
dfsesc okwb dfsesc okwb
egpwqbe djlk xpkxa hoo eepbqwg
nxdfror yfhkhn zgea fkspva rjgg bnmq ddsf rjgg gkinm
vdrxfom wbdwu dhkt xtvzc zjobo aqvgrt
svddsgz mhcrbcp wmpd mhcrbcp klim ddlnxv wrdftrc ddow wrdftrc
obxr wscs new brxo wen epns cvjvxts ilnc
rwezl vmbut kgblt xfg vnhlebq nzqdzxm ynh wokrezy zub nzzqxdm
vephajp bzupele mltzglh sbgn vephajp lhve mltzglh
slajp kyaf vlnvy srfietn ayfk inaufex fanuexi
vazwg kjg qanzso ptuu vvlwq uupt kohhql jkg
xmmmpky rbqimi slvxsf tlcwm pbf pks iucx rbmiqi
irkup jvu tkeioz avdu suxamf
tmgih ldca jswka dblzzt rap rgqyy gyrqsk nnnn pok
pdbjhrl gsvxbqr nqfkhtc ngn okbgzd pdbjhrl oostjtm okbgzd
mzqfdat dujh aeplzqh acbguic vlzdt amyszu amyszu jqecky bhl hjqnimq xoy
dszafr bqampg epozj sfrlpe dszafr wfurku sotjpg wagtnxy
jbmo jbmo plbfkvw bkc jbmo
ehelldu vrid unnf vrid xqiu tbibjyi bmbpsmq tpqyefx xqiu
rpgm zzbj cjgfdyb bdjfgcy rzqecd miyvfbu aqlkagf hsuxwgl
gvywzp phvnd ypwypbm yfelxx egbr lcfyz hecdhkj xxfley
tsmebin tbsnmie mkijj ijjmk
cghxrqs vzxle wrfghv skighgt zviteab plcrgv
ezdirp rxkw horcek qcgny inx nikb tigzp
eidk sactjci sre vkapava owvf eyds eyds
vvjdm uye tjixj azklizl pnb
tcrimv xye twii xye twii tad
mtxcg lwjxdj zjudqu ekoujd ysf ajtfta dkj lwjxdj
aowhmvv kkic kjize fnohl ukx remfmii usbp
wkossu limxmhp xnoeocb wkossu lnrlqf kjozfg xeulstx sjncsw ekaimuv xnoeocb sxjegcg
lsfe zpewzlc yhjyiay lou ukhi lpwezzc slef zvtidgg kdeseq enka tfvgudr
ovfsa vuv tbtorv tbtorv gmxn opspw lli mfzvkv zlyhr oznalr
kugrpw sduq rdc ciaxwir ylnzwec kugrpw sduq
obevuau thu jpyfvof rpawwo obevuau gsvoutr quiaei
xpgua pbxa pxgau kdan
ohyzqk abxgg xozgai nib axozig bni fucgykm jpkswt
jrgu dmozts jrug ufpho
qojzue uzeojq txuhj eqjzou
wcvj qwlravl niyxf oiaptlk wlxnnzj jgdzap jgdzap lfgn bdt sfga adrypo
ylah eedu rvwdpmq eedu ylah
quages kmla yjqua dzxcfam srjag wujmcv qujya ssaol uzdwi
gdsppz yqxlish yfkjbbf ecnzu ejvtv cdjwre
slsls pcmrq zax btrc kliv ntho gymkk kkq pcrmq mvnw sjfegpx
ryz jfw eki wvibww qdzylg whbagp ffrfjg wdhnqpm hcrz
tcjqfh tmvzp mpztv vpmzt
xood xutgof teqov fqyyub oakm rzaheiq
axagoq jawbz sexucp sexucp atenr edekcwn edekcwn agl ecj gbje gipivfq
poqv qopv bos flhghs gshlfh
rxd dzphnb bwmna vxd rxd sbk kuor
kqeelq jqbyh xczqzqe jbkmx kelqeq xqcfqn
jdfy qzjyz xvqyo jdfy xvqyo
vyoqyd pwayqag eygmdt smakwc veftikz fzeikvt
aozgkne mpd mktgoew eepp zlwycr eepp hswbxcx nmi ddnfr eepp
dgpfp cfhhqdx vjrb uyimbm byx hfdhxqc
fxq jcouwfy uhuao zsab xjao
noudveu egxyuqw hmnnv vovt wmqkx syatiac whkd
gxyzk opgb kjxp delavq hsnvk kfn irkcfq lvc aadcwy opgb
exuiupk ddiiyvm nsggpj ddiiyvm nsggpj
hhjby rfejzp akxzs nconlt rynivtq voloj qwhhll ubvx yxuacz miuwxh ppe
uspqvx supvxq cekv niddfuw
optzcag sra ajs ozacptg yxkludq jjpvldz mxo mox
dko qyec iuxbrbj dlz jxribub
ywlyz vipfh amsfr fwiozi tahjov tap rsea zwlyy oqdyfbo
xeqml jwy eguc bvzvh
crp mxsihvo wwtg gsypx mxsihvo qpfw looca gewvy zjqki tdkuxo crp
mqlnzm yihsvrl hhtwcv kigymqu yswki hksk vbiujq xeqz irzcq cpnz
zxhfsw uuyhwid nzabem mmfk wszfhx shxzwf hqnrvsq
hfjajdl qwmk hjdalfj mwkq gqbku dsszk
fbiy pujq htgaqqq yro ztpe yiufb fnpi ggchdgz
sixq jsboan eoie msdrwzw sixq njsrc sixq yimqoi
pbxgv kqmi hjuk bbtrlta bqwm bgehofj ainqhm qoypsil manhiq ogebhfj lvmuo
wnax aen fthpcke tcz yadjmva mydavaj rcfkc krfcc
lkatiw zxliii usdj oopxl yylv bkjfy gtlyjv usdj muqazdb
yqonaxv wqnvoo hfpll oyxnlfs fgajc khhtzr hfpll gsvvipz wbjxsnp dcdikt hqw
vvuv kspmnz zvmryqd egvuz eazkhz kspmnz
xgq dziwiym gsl nbzmsta ccbzn yalof dbbugq aar ywmbvk yofla dcwb
qrtyhhw xeyo vlym ulzzbl hrxyb qeyu jqdkewk oxye evaxz kybc bssyt
eqrf cfyy kwhohw ozg jsc egz jsc
vct cet ixxvmz ibhvndq eks dpi jzfwdqv saeh jqzdfwv vwfdqjz
vus vus kitvvgq wpi alfncf gzj oxcy fith oxcy ecbsr
uacculk guwhwdp cankcv yswy bmby sve dvonm nran
ydftm wszgaex rgbw otd dbet lhsxndd jqfyx
vhawg hwagv uagy fveik nrsew zujw hawvg dzfmt agzgw
uqdj talb uqdj aizyuqm
pbbejee szdtohv tycfow xwne qzlqy dxcwejz pqdqrc wfyotc gdqt uxaeug wtldm
hmzmd oyp pyo opy
qwdh kwpll kwpll zsbez uxg klr uxg
myqr zza kqpcos adsql eumunrv qlaeumx
acyye xvdewe nwkhuz bzcmx asw ostiwk mfzu nwkhuz
memq uqadd kfj dses lrxb hxygp dsse bxbr hgpxy uavrar
mjmk lsdttuz qjkg yfthmkn pram
pctfq aly usim shihap uims xkfgp ksrbn ifvsyl
cdma nnnu hdm dhm
kpt upgsm ohvrrqf qwps wjcbve ohvrrqf
wowphgb nteme otizypb eumgvb puoctli opicult wbohwpg
fppz ftkql sbut lkqtf svif viqhlnn buts lljhbd
oqk uinby rqy vbjhf oul hzfo coca glpy brjy yglp qnvhvei
sbbwr dnyrux gpikv nsx aawyeq uhtucwq rhxzy jgx bdgdrl dnyrux lgfgi
agn mljz hgmglem popu jtapub agn
ehfpgr bnobvg bnobvg bnobvg
ozgzedn godezzn art atr
urz rzu xzyc rjhwi kgiodi doiigk layr dwbxu
rkcbav pnp bpsmm ifivfe csouqpw fyswzbd csouqpw bnjt rnnoxed
hpjgtcc ctcpgjh cchjtgp lxn
cinokbx uyaz uyaz uyaz
bphfwad bphfwad bphfwad yml izlhlb dvjvo jeropar
ocgftcl wshjk zbinw fcotlgc xdj nwibz
zbze hllno rmq invd gupoxr gwumc vnzj fcvvhjo dnn sfsxw
oqlhkz hgf yxiahks vhzvl ayshkxi irmwkmq
apeqic ahwu abxjrd tuwrd pynnil eohmlgo lafx ybpofe wbznxv swuafas
cpg jpsfo jposf rer ixeydpz
rhqrwvn wrhqnrv xptms jhc rnqvhwr
zfpl tukxzda lifkqtd ynfuno cttx ctxt tlqdkfi ueswv wbipfbe
eblw bwbjg fuu qqm qtv qtv isbl denfcb
ick yqwcffk pvcchd apkjyc ouu uyfe nplid ick caqscs sddkx
rtzh idn snnw xmlou idn kdhenl rtzh ujwttl pkynkhe
dnwha fpv dnwha iqi xggepo dnwha
yjvk saay enxqhw wigoah dzasyr nnt artl iqwia jpp xmfr hwigao
ryt heenuai ytr gqew hyb byh wdurx kmd adgjz
ypdqeji sfkkfhn stms cdmyh nqllx utiphia gxbx zflhtgo yurztx eni
pwlhlt lhlwpt rfkvlgr tucajej ckujc ntcyae xestygt eshmggk
gtfb codwc vjtli ffmjwx ruoekt cylrm ktroue dfaxzvs kkgejzi ewucgu jyatrum
ersbag cod xssha aqzbe kxu bzghhqk pbs bizvqk bhbbd bps
vhci ypxf bxzor unngl xilpzpk civh nykora vchi
cyb cceu negnld nbcfs pxsjgh xah nbcfs nbcfs jabpxg wtanv qhztvr
cljgzkn lrdeina hrjoz kdgpn vqkmpal nivk scvnu vzuausp
nif fin uxjbip xxztsn yyo opueh zxs qnso paedey hsd fttvqdn
gbnkmpr afo aof ryyudy gbmpnrk
uaa npb dkit npb buadan esv npb hwrj
hws dfgq fcyty qszhu chyxxl ytmpb azxl jrsn boqrx
hkzlnkd fkilvog xbubu fbgbp
fgi inmay uliytc vgkcw qsoe uliytc isjhix oyir ocaq
qrzkpm dpzetbr zommsxo cixg nwjyvp bet wyjpvn cgxi tsncd
uvlf lufv ulfv cigl
uwwf thr kdq fhjmty bvxue vcwwmk kdq nzajq bxkf
qcwduju idxaja qcwduju idxaja
fnarz pstzfne nco qzf kcevoo qwx csvsxga pstzfne
twug xrwy uoctfl bkh yxrw
unpdnbe apf cvm bpullu fyels tjpri jyw unpdnbe xfyekay vhk zpyb
rbv psirdv psirdv mnjrp qpwc vicismd qpwc
zjj zjj kesyhow eqcfqy vqy
zazpd gmea aobl dcs mage hqjdpwc bvxr srw
rhcdb nzsa jgcgc rhcdb wxs vsvvptn zvckqo wxs
unyet prchn fiwter wvgknes dvzbxfs ufet neuyt fczlrx bpocdci vdsfzbx
znfev fwrdarx knqkv ojiv ojiv fwrdarx
tbtlo hdashg kyspxm ypmkxs nmrk
fzr zqxaszt frz xzrre
shueb iraetk uhsv duvah uhsv zstysc nrfllbc emrknka
vzkrmp mgtkjnw njr bwjgp jdwyyhv yudha wbvmx ewu urhiioq
yjq xxr swvm aipdj apjid tfsq gfqg izrvhev
iljuqt fpo fxadit iljuqt iljuqt
zrj poewso vsje bsprbmc vsje yfwf ybu dmkqib ybu hlrpdi ymh
apxaeq bgdm mqty whyay mnuzfgk awm bgdm mwwi ekw bgdm
dpdbfkm crrg mkph kphm grcr ukbk
ilqm wroz mqil qlim
pnlx nwadw uabelu rueamxr wjer uwge jwer ywagrx
akuil nkh oitq werli werli
fkmhcr ieoj xfsa xfacoeb tcg poomcme vck zmpc djcqgkf kft
csyk qni hqfrye zyyxz ggynzad pjpokmu bigqa qie
lkpenw zyllii qtbvdq zqnu ichftg xazped agl irhlbiy snlwfe twliar
acsrba dzz ivylbl rfcdd rfcdd qcg
zbui fomvpx zjhmgl sivtffu xuhswzt fzeid tgj mzok mozk afbhuje tzswxuh
nupjiat fdxkbn tuatp jhdfnub yitdk yghqw nupjiat ibi edfv tuixw auwjm
focht mnprh tljj ayp
pjdnl uaoworh iqm gic dqlu spn heuymio
kvg ferrvhp unvzsd qdcpd rji zpch
nhvay chuzg pyhdd hnmrnq zeidhf pyhdd ohy hnmrnq
boa sau gxh grx
gwo utwpd zcsrx gow bnm
xoqniyd hmithl xoqniyd hmithl
yqqsbzo stca zcsjnqf skbueeu tlbkef mvqbg igzr wujuz yqqsbzo kkfe
wgzuepu wge fkrxuag csenx tkngoz wge azueyxs
get xiryxs xiryxs xiryxs
wammvx edy hahetl xmvawm dye
lscxxgi anmax quo cqprwn imocarq gnbfhe rcnqpw
znpmid yaluvzn ydm ckh uhso rrk wbby lwxsu
atppk byf dzz uift nqejgm njgeqm
dtqmy iog ahub habu
hkthdwt pfxlwsu hkthdwt hkthdwt
tsuiue tsuiue yais tsuiue
swooqmp rqrcs ngr vujrq inuu rqrcs
dhu zxdfiyv xuz xuz mgaty mgaty
kiiiz zco qdv vfgkj rders zco
trszp havbm redpeqk gktp ifvzvwl yfoxnm tzg avzd otiouso eks lqlutwb
cfiru lpdy kpeas mdc lxnjjqz nqyyb xkjsug rcifu dln
jga ijgkjo qhbnupb ofzqn iokjjg gaj lrh pkynrcr jgatk
bexwc tat tat otsngaa
feh mjxbs ehf cyfhlv vvdgdu hef
njlvq ojwaes awsejo ktyvxd qeyeze bpoaj ulgngn zyeqee kqc bsdzzvq
hbfp vnhs vnhs pko pxnxgm
bmy bzpn bzpn bcfep
cju nqjy yjqn bbrj esgzw swgl bjrb
cxvrshm rbglkyv kqwzcyd azqr ckwbbew fhgqv nfk lactzh ssqpwbr wbewbck
ptcb gqkb apcc okl jbbgk qni bqu slydyo qhh dqd osv
zbisefn bmxcljk bmxcljk arkamus vpq uxuwvb
ksik xbzk lahh ctfur sxh rduokr xqou zwbgqsp skik
hwhmfk hwhmfk bjpxzg qqftmu ijyv igvayf bjpxzg
askxqew tibx pqaczy fhzyec echzfy cezfhy
omzyy mbzfvsn kkoff qgqn crnnkn krx oqp jhn anb qte qxt
jypnwn vjbnbsl axf pldxbq pdoy rmxcvig cpad yhah rzqewkg nmzkkr erjo
visidzp bujlfn xuomjj mjnqn wgflg skb
oer oer lfi zyqnem lfi guljz
fannhwu wafma gcje cvcia qwyh ugtbpa geufqg
kwtjib pqwai tdmjj kuxr euzl rxuk
ovi splc hflutgw hflutgw
gvel gelv aeiygth elvg twwr kivxrrj jkmqa
bas ylxbdgn yliv pytkhq haujsyf fggrnbc wsgree rfnppcx key gvdzgfy evdtrrz
oblab wpgm bpyy xuroy qhb adqko
hneb law uzms fhhk yjymdx wjla ixfh yblh
qlvsd bxsq hjaq fuwspzu hyshq idbabc rqcih ilixp wft rglf lmqm
qdskj two ckd qdt hzjvd woo fmmuw
kumc zywzq srafcbb ihfu kfvav
qlkkrq qlkkrq qlkkrq qsc
hob bpecik zqtrfz iqizeu plrer epm zqtrfz xrekeql xrekeql
warszd sxyyorh sxyyorh eztjf warszd kszp
hjbrax liumjue liumjue liumjue
rfnqd folmiu dlicln pdyk uqd rfnqd
mjdu lytfvya xomdujn leaqiyc lgemz lihfnhv zgeml koukz luqda
yqsz zedjmwn aep qwbhd yqsz
etg rmovps abizj yqr kib
yznxec sfqkd ofkzep njr hmeym nsh xdq
ryoyq heoo zuo udvfev ehoo axcnbpu oeho mfenmd shrebzy
uaeh jwllsjp frkhqsy uaeh
giofw hwceb euikqp ldmb kqpkxwv namazcg hqyyzgs cglsqux
qledbd qledbd kbwo wgfmgp
olbsca muxw nxs locsba
gbxxgj xlzm gws pkpwy ofkxb sykhdo nbhrv
najr bfk tbqkm hxabe nvr mdi dmuujr bfil nyripr zcydzy
kiczhcn dfgylw yzkwk nytijj pceu yukj ekaol xpb uep
acyyxn rwczsud acyyxn payiek inusyb rwczsud
mzssokx bshs bshs ocrvlug nzsgvch riejkrd jkj mpmdgsp kvixdfq msmmx
uaxy wpvhf uaaq ranp vfhwp iik kii nvh
shecxef nqpx jly dzm qvmpu kxg hdg
xembm yzevult ljrllc yrlskyk zas wstnz yrlskyk vasra
yoaxppi kzax hvxfezf mek teo cbtlrfa ncxac yee
dzfpbi cynov dje vxypba wcwww cwnu cqtp cnuw wwwcw rkzas
xzwdt jcwv anb xzwdt
fodgjem fmmrsfl eovsneo etzutda paw fmmrsfl jcqql
yfztt alcw nwdmd afgknu njxkj zykz cvv jbnl han iatmruu trqls
yas hpulrmf dzts sltg qsbw fjj rjymnnx dkkv
hwjtgd abmb cfw xoumxn xnoumx cxo xnxmuo alb
hnl zgdiip lrddhl fyw mporhtp waedf dltdfmc lyipoth ubmg hnl
wxard wxard cibp nzquvb muuslvw igvewfh mika wxard
cjqjhva rrhzy qpdc nqnyd enbdee ewrhp cqdp xekgjai
axtmxb axtmxb phl urdqaar urdqaar
umce jult bkart dgdvdwc kqzlzn nqkzlz umlxx cmue xvehqag wxifal
lwsuc ski ubo ksi sik qwcudv
husdv tssr gfp bfzbrp jtmk svvdpb uvshd zbnpdmj svpdvb
nnbvf xbb dobqk xwloqca uxvqti blcwxpu kubwu nognin goywn
xhe dhddftc ggltd dhddftc wspf
jodq cgvnk lpl wkwwlqd prfby bpyfr tbgyqm
bdebxj cuvow jdwdxw kuzh dvxmsyb dyvcxo psf kjnoe odfwgfa
xpfb knzgfsi thmsnbi ymjxn bevohy xpfb
hphcu fjodpdt mfsp jkvvp jvypar nlud lfv uftupcr nul dunl
olz ihyhw qntr lwcbohv qntr wzralwl
kfz pkjhidy msnmwz exox xexo uakipj mmznws zbbji ozispqb
gfi kwdhx qqo kdxwh fig
ehh rfozwr caoisw qntlk pkv zulc kpv hrqz
exmlrj aacc rzb qie rzb
mxyqe cuqz feyd meqyx gdvpu rqyjtvw dmoo vugdp emem
advj xmnad uvh ufnbi xmnad xmnad zzwjksx chbrjas hrbp ruvyg
nasrghk pmol ryko ofgakhd korf vpy nakrsgh
mylyqg aeizp rnk krlwchk aaqg
edxursp sosyv zesgnpx zlo sly alurdc ypmez qib aqtt lmxd
ihm hwzhd jhiw raocjk nlxce yzuzu nhudri tvygl tmclg mdkz
psubdis qrmxebg kdac xvl raxwfx vlx sxme
tci tphdy tggam vqqiyjz sgfvdri sxhztz fhsmxx yaj ncxcxq tic
xkljs cuhrm fdjqwd fuzyzh dzuzgjd lzpye lzpey
jriwl ypkcxd fxrg eit okzzzsc yaykarm qzuv jurgek dzfbbfl
workf rrw absfl gxluw qprdsz absfl qwqbmi amepvz oiqmy workf
dxyyb brnerbx lykd oqmz ursl zqom
cqtuzva aih uhaswd auhwds ktyvc hufogcg
jre fhlgrse svedc prfspaj ghm qcjzfc nsd
fow xyo vlvg sgg jgzvff rjxh eovre xtupnz
pekj pgiecc igxd zbiqoob ovv
xofxmz rdzdiq yruoqkh arfunx yruoqkh ucm bxov
ctogwj lpv ivtoxkf faj ctogwj xfzluad ctogwj vvw
rmc vjxj strgo tykifpp
ulivozu bczond ywnmt shakc yknr psr
bfx alwedh jfomlf pzj tely alwedh vccsoer rgwftcl vccsoer
frkwbv uudwt qsfg onuhiml jrd usu
bgdx deybefo gdj dgbx luu cbuwawd wqqtq dqmwy gin mhtfgy
ohjp ykemg nrs leayrh brtipx jhop phoj
utaep ywsy utaep ywsy
qow dxagjwb qbki bqik
larkpq bdgw mly vvwgv
juar zaerof qekpe hhgd eygru epekq dhgh
xpblz xksc lzue xksc yid nnve trlndn gjczngs cifqoaf
fpv ekz eknldf uqjgeu awwnwxu eknldf eknldf txhxv
mzvk wqtbda ovdbh vnes uiuuc uicuu bpwwtm aaat cygej nio gnl
rkdkzp bjaxqif xuwx bjaxqif hgtz slkqw rkdkzp ztp xfvgk ycvg
zpwr wvxzfcd opgcrfc ytxeboe rcqa ehrga lmgm
brsdnk nqgkjab nbjkaqg gho zqe
szbysu oqrtbp wjpuv oqrtbp oqrtbp gjmqq
uoyi ctscw uoyi ggn ija
fop lxa cgwpw lyvrxbe tit fop fop kfigqnu
ldqmk rxo ajhrbc ahrcjb xqdk kdxq
ith vdrl kvaxktm grkzmon ith ywbz kmnoiz
zdoo omjo fbz dveiipw fbz
ivj mcnu tkijlq xkq lrkyit cumn sfkrk numc ezxeeoi
lcwzdi sbsdgdy olvc olvc bimubzf bimubzf
cdjd umhwh djdc cddj oxheq veazlm
gxszn zsgxn azy yaz
byvmj mjybv jvxkuy akas uxyjvk
whmkttq whgzm gwmzh pkvtljw zgmhw jasudeq
yyjri fxsj xffmna vbal ftff rwq uszym bznil rfuctp ejndv wqr
gnwzjbw dezfvq gzkhzkl ivrdvxx wfah xvivrxd qzdvfe
xnfo zqzn iaod zlcclsd onxf lpskrfk nzqz kqzr kffpwak eky
muc tafbzp nra gvzc xiu gvzc
gfnbnyj nyjbfgn eoosw yjzf
qwwls sqwwl mxph swwql
twor uzjftq twro orwt
qomjuob bqaim zvfqww cvqzm wwipc zsywb bsqkp aoj fus
nlyd gtbgox tajlzgs bgtgxo pqt
pjtmgz ulblj ussh gngagba hhtexq bjbj obe xctciay osriw obe shxri
agc ejjdtak jgq moj agc iua syhxih znavmrc iih qubj
zxwzwhm lipkqhz bbv birxsj gzg iefrjh mprsfs ofpltbl gbo srpmsf hirm
rbpgqoe kymrf uzsut gkbtd xctpg qul hirtfl
wfvg pnqhuv jayjm ftqt mbrotl aydmoc lfwlxk vpvcsi svbn bnsv
jxjxza ysl kls vmt fvgunx hketl oshgie
dfeyxv akx qagwayp qrs lnulrle rqs gbvd bvdg
aac ndptml oke edwrg aac xechxz
mpx yrb oervzb ydvkw avlt oervzb bxdqbo hzwls
dsynfk dsynfk epexzjd epexzjd zofb
vhe zxfolqk lkh fxt flzkxqo lztwkmo khl
izlthi wtokkuz ousbpxp pvr uuxueq lvbeff mfk syjq fwgnfmg yytqesm gdd
kjcg slt khz atzw twpspdx kgyk wgq hjat ntf xvhxol msvdjs
ymm arrggw mmmbvrs ist arrggw nbvvc cwyacp
kuzglex iemp iemp jsko iemp oqs dheqypr
tzztq dsxqbow qgaeo kqn dsxqbow qqzpv
ysr fctpiyn psgb gatavv zsfxoxq nynfoh qaimoj zotjk nxug syr
xvm qvr hdxyhpf cbo xmv lfv wltyjlx
hjq pohc xgqit tducggu zdqmnc xqgit tqxgi srfyzu vdikqx
msiqte ewvp bzrv cmuy gse qqayvb bzrv qehy
watdvu ametrc etlduhh vcc luehdth udavtw
jktj mkq jktj mkq
uekth ufjkmdi qzhge wzwcwk nvrodcc vrcdocn bhcvd
xumywk zwofh kuxmyw acgzsjj hfowz njnz bnklyi
hmm fexu fexu hmm
zeuoarc yoa ggff jazzd mjein yhj qwo qwo
rolkwf fcyat lwm wqqm juwkt wqqm udj tex xgps nyy pdbkkhb
gld ksl gld bnsuhqc gld rwmybj
tvyxk xgmk cri pef epf unsl yktxv
muiql ejq taetjkf ejq xzmo wmv qbtmrh hkfbch taetjkf sut
pqg icvv gpq tufd iixd duft
zekx ybbb gzml vrbwcl opfb fkrv tto cbipr
moh stkkf ynrtdf jlgb kstfk ksktf
nvysvf mdtdoq bqqvr bqqvr
dqyz mzoqtp gzhdgd symsq iwh bpwox
pkqi jgzsrah yfjxx kdp xjaf lbj gkpixnj tyvzzso qmjbo skg nlchzbk
culxfx jarwu eiwriu vwvg gvwv sgnasz
kyfsn dwc sbnoe xwpgjh nbmvec dwc qjdh mpw gefimue fvqjwt kkor
hcdcgxs fof flc hfpjy lii fihcao pxg xywei jwsq yxr
oxrcv pda oxrcv gdvojsz kmlga mixlmp hdcabsn qvoa fwt
poe joylchz humrjy cyxbqfm lyk ybrfmp qmtpqyk vtpr lyk vtpr
ffswqs yxbuj tfzkmc yxbuj giog ckubbfy rtigw rtigw rpitxd
kcvrn eejyftw ejytfew rnckv
lvk lkv cooumh vlk
loypv ukowl loypv nyoyfl vehnm uff
tst sei zovy itdwibj mcbtst wcf rzp xvbtax ffzp xieenuy aegkj
zkhi hvsbgza xbwtdns wypfngy lvabd pybhcd crczm buikdpo vqgon pynfwyg phbcdy
ihy irxrj entmc yxfhbta xsdv xsdv
ezrcv kfgm pjneez puccy gzpxdlf gkfm yucpc mli xezfug
umjppkq idkiri wmnbhi unl nteyw wmnbhi zyv idkiri shhcrau
dzj zveqwae ljnikvb baavr dhsohp zveqwae goq zveqwae
xhc xch bmttdr snd jakd
jmgnvda bdpzfw dfwpzb pimpv blqtbyo lzdzo bgrlfy anmjvdg
lwvu ksg gqbtibd ksg lwvu ohfzlt foajo apyrcwj uaro
vel qksrwp zei ipnvd hdua rkspqw bujf
iozkiu upa knmcug zidypn yswb zswkvx naqsu
tjktoe dqpt pbqi dqpt
lcl tui uoizm xrdpmwi fbsuuqq tgeac hpajm tegac nczlic
ntmm mskzb arem ntmm jayzfe wyurgsh eqwcqt edhska asxhjv jayzfe
jyq juifidx fokzxh cgo xofhzk nhro xyccuq ioa nwk nqaxpfw
cvag bpk cuo ocu buehhq tartafi ifs qwh cveurg
bwut xpfni qzg cmp cid jftawv twiszmo
zgxc sui kypkd vpam ymxicrw jcfbutd fgx jcfbutd
tkxn rjqzljh tkxn mdwcho
qbv zneocv zneocv zneocv
tywf soncr lyepx qzj xdsr pdqv swt
ulu rdk iomqu dgouoba icax
ddsc oxilqpd ddsc atbekg ouzmxf oxilqpd kwtzz yhmyd otvi
vtj llnfrpc vfighju urosrsz vurtse llnfrpc qeuo vfighju nnn smsnp tfom
updfjmz ngtgi zaitq rqqhcyn ladzx zaitq fbaphyz hipe
rii fpos atl tal qhubqdv lat
whxzwdj yznkngr eefbmub wnxitd tnwxid zja ziewilm xylwn ihhsha lrptuyf
fhmzaxv mdn udl gyv pqw qlrz flm rqtji
bgn clnm cnml qyh hhf qqnur sgvigvm
qjtbysc ycbqjts gbgvlz vgzlgb dgxks qbvp grji dcc
wmduuq qayymzo zvh ylbipw sin ybwpli ilypwb
qsvzktt qsvzktt dasmg knh gcgep qai
jxukj qlgr cjssj aavqv
xpxa glsdfxq ngxwon ytuue pizqu
fxl vegoed tct luwm ulwm eeovdg
ntmpe auasx vkwgi cryuiix dmiufo fcb ldl jauncf gyouym asjcryc
lgwdcs eoxm hcrpnuf pcfnhru vlye fpurcnh uquukv vjc
lfns riwpdh phwxvew hhu jfptvv ofxd hkotgfq
qvuwnq wnpvs xdivrfz yaenqr fipwgl
vhcexfd bishqsc gsbruxm yzccyot yjloa aptg vbr gsbruxm ihqhyz yzccyot
knfst zhihi swhhq zhihi
qfto abhjx abhjx bpnijn ogmqxn rclqag dmeb rdogx emfriui hyvp ogmqxn
ivaemm wlsc dvjv aivemm xvf shfonv
vowhosr vptlu ucrut rdynh ttqvhg rdynh abtja pnvdy puxfmf dyhd
uvrenol ycuhvy ygm fjsxiwo oftstid ygm
fix qrqeg dfgvlun fix iraxgtt lhgqdo eqkgshd jwmrm qrsbzba
mxdj icjqzqw fvew gtvlhm mxdj
cyjtkm crb pmg jwo iluc brc ttnd
dasmgp ool ool opc
ubi pmz mtkh ibu hlx ipcvjki sydw zpm eewfdeu oga
avex yjaoghv yjaoghv lwwx
kwkdst iuokd nmpw onayet zlavwnd wwvbr jtrkyku wfxx dumydgh gnd zgi
ahyjnc rjakp bhabq tsmfi ahyjnc tsmfi yitqgi uwnywil shnkbn
krr sbbfjtm yvunas hwppsjf ntuuzw ngyvdmt ynk nfq mfrb pyw hngr
eeecesf phoo ijmx sjp kgmtg sjp wyz
qwixmou oximqwu ixu lsmf
dyrzq lbstdjv ldvowml qjf fqj zpabc dwmvoll jnq
pdtlu hgcfvz mnwjyq ymi cvcp kmx mkx ooffp uiwg opoff uevqt
hflomt fhlmto gutdbyp xyi zpggxc wqe
jpsr wwex yjgdj fqah wrmmw nyrnw hcomcgv teajmu emw zrraid
tvgsca bzgzkga ypsxsk dqz exmu tvgsca dqz qnd
arzn hojpi bznw ejuupe bznw hojpi
rids dule qaefaon sspit mtzgdls cfujw xldhimi igdoy dule
nefsys plea obksngc zxqee avsi obksngc vnsxdrl gspadob avsi owmzpeh tcj
oweq fkr krf rfk ztwjdry shzcmew jhna
hdjizhg dfclic usds luz mcwyj luz qvomls mren otax
pmzzfj pmzzfj wfxyq mqv hyp lhf
dxeaw ckkey ccvawo keaf izlh oacvcw lgcpgeh kdiky
xkwe xekw kwex tzfyx
dmmyt mtdnqw pdw vdav ofrtsk
klz zlk snxnihg snhigxn zkynpd
ijzce xobf uojezxi xiuojez
ztepv zvpet nije aditjlg natkkk dtitg jprgia
fesuh wadrhc bayf kktfaf nxvhq smbdaop gqx ioez fkjufb abyf
hej sta pztkcd pesabzz szp iada iada cdae hej sqst luf
xlnuhn oljaf fljao ascxez fojal
dprclb fzn wgauz rxewtp cjrlgz zfn
fidwoa mvoqy afian ntzokap mkplgy jfukgjv cyfsz
hbvqnnt giinuzq uezugy qooxjc zsxr rnihg ipbels
qroi wtltjq suj tqit bxtc jidzhpe nizp wtltjq nadcdm wwyhjrg
qtr fkbl bpptu baen awjpwsg vvqbxz animt uqbk zvbxvq
nznq fdiul jbv umyrf yufrm hrl duilf
bkvlfuw onkqzeo iwrg rifqzhj mgroul rnor qqqc sbfi hny zosfp kopxb
nvifbx jbowbj fnyskt jbowbj xvun xvun
piyl haajm stwzpp xvjg amjah
gye efwwwiv kyv zmtcgmi ifwvwew
dflx gdtb jyoj jyoj dflx aqhycgi xffnn
inc mpys mzqmcwx vryz ibqrzc pmsy fat rojpxwy rcbqzi gjef"""
print(part_one(input))
print(part_two(input))
|
# -*- coding: utf-8 -*-
"""
Date: 28/08/2015
author: peyoromn
"""
def decimal_to_binary(decimal):
bstring = ""
while decimal > 0:
remainder = decimal % 2
decimal = decimal / 2
bstring = str(remainder) + bstring
return bstring
def main():
decimal = input("Enter a decimal integer: ")
binary = decimal_to_binary(decimal)
print "The binary representation is: {}".format(binary)
if __name__ == '__main__':
main()
|
#! -*- coding: utf-8 -*-
import random
import time
from threading import Thread
class SleepyThread(Thread):
def __init__(self, number, sleep_max):
Thread.__init__(self, name="Thread "+str(number))
self._sleep_interval = random.randint(1, sleep_max)
def run(self):
print "%s, sleep interval: %d seconds\n" % \
(self.getName(), self._sleep_interval)
time.sleep(self._sleep_interval)
print "%s waking up \n" % self.getName()
def main():
num_threads = input("Enter the number of threads: ")
sleep_max = input("Enter the maximum sleep time: ")
thread_list = []
for count in xrange(num_threads):
thread_list.append(SleepyThread(count + 1, sleep_max))
for thread in thread_list:
thread.start()
if __name__ == "__main__":
main()
|
#! -*- coding: utf-8 -*-
"""
Program: filesys.py
Author: Ken
Provides a menu-driven tool for navigating a file system
and gathering information on files.
"""
import os
import os.path
QUIT = '7'
COMMANDS = ('1', '2', '3', '4', '5', '6', '7')
MENU = """1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a filename
7 Quit the program"""
def main():
"""Main Function"""
while True:
print os.getcwd()
print
print MENU
command = accept_command()
run_command(command)
if command == QUIT:
print "Have a nice day!"
break
def accept_command():
"""Inputs and returns a legitimate command number"""
while True:
command = raw_input("Enter a number: ")
if not command in COMMANDS:
print "Error: command not recognized"
else:
return command
def run_command(command):
"""Selects and runs a command"""
if command == '1':
list_current_dir(os.getcwd())
elif command == '2':
move_up()
elif command == '3':
move_down(os.getcwd())
elif command == '4':
print "The total number of files is", \
count_files(os.getcwd())
elif command == '5':
print "The total number of bytes is", \
count_bytes(os.getcwd())
elif command == '6':
target = raw_input("Enter the search string: ")
file_list = find_files(target, os.getcwd())
if not file_list:
print "String not found"
else:
for file_target in file_list:
print "Archivo localizado!" + " -> " + file_target
def list_current_dir(dir_name):
"""Prints a list of the cwd's contents."""
lyst = os.listdir(dir_name)
for element in lyst: print element
def move_up():
"""Moves up to the parent directory"""
os.chdir("..")
def move_down(current_dir):
"""Moves down to the named subdirectory if it exists."""
new_dir = raw_input("Enter the directory name: ")
if os.path.exists(current_dir + os.sep + new_dir) and \
os.path.isdir(new_dir):
os.chdir(new_dir)
else:
print "ERROR: no such name"
def count_files(path):
"""Returns the number of files in the cwd and alls
its subdirectories."""
count = 0
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count += 1
else:
os.chdir(element)
count += count_files(os.getcwd())
os.chdir("..")
return count
def count_bytes(path):
"""Returns the number of bytes in the cwd and all
its subdirectories"""
count = 0
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count += os.path.getsize(element)
else:
os.chdir(element)
count += count_bytes(os.getcwd())
os.chdir("..")
return count
def find_files(target, path):
"""Returns a list of the filenames that contain
the target string int he cwd and all its subdirectories."""
files = []
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
if element == target:
files.append(path + os.sep + element)
else:
os.chdir(element)
files.extend(find_files(target, os.getcwd()))
os.chdir("..")
return files
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 19:14:16 2016
@author: peyo
"""
##
# Remove the outliers from a data set.
#
def remove_outliers(data, num_outliers):
retval = sorted(data)
for i in range(num_outliers):
retval.pop(0)
return retval
def main():
values = []
s = raw_input("Enter a value (blank line to quit): ")
while s != "":
num = float(s)
values.append(num)
s = raw_input("Enter a value (blank line to quit): ")
if len(values) < 4:
print "You didn't enter enough values."
else:
print "With the outliers removed: {ro}".format(ro=remove_outliers(values,2))
print "The original data: ", values
if __name__ == '__main__':
main()
|
#! -*- coding: utf-8 -*-
# Class Employee with static method - pag 322
class Employee(object):
number_employees = 0
max_employee = 10
@staticmethod
def is_crowded():
return Employee.number_employees > Employee.max_employee
# create static method
#is_crowded = staticmethod(is_crowded)
def __init__(self, first, last):
self.first_name = first
self.last_name = last
self.number_employees += 1
def __del__(self):
Employee.number_employees -= 1
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
|
#! -*- coding: utf-8 -*-
# aproximación de la raíz cuadrada de un número
def main():
"""Aproximación de la raíz cuadrada
de un número"""
# Número del cual queremos conocer su raíz cuadrada
objetivo = int(input("Escoge un entero: "))
# Margen de error en la respuesta |respuesta^2 - objetivo| = epsilon
epsilon = 0.01 # qué tan cerca queremos llegar de la respuesta
paso = epsilon**2
respuesta = 0.0
contador_iteraciones = 1
contador_de_respuesta_negativa = 0
while abs(respuesta**2 - objetivo) >= epsilon: #and respuesta <= objetivo:
print(f"contador = {contador_iteraciones} - epsilon = {abs(respuesta**2 - objetivo)} - respuesta = {respuesta}")
if respuesta < 0:
contador_de_respuesta_negativa += 1
respuesta += paso
contador_iteraciones += 1
print(f"Respuestas negativas: {contador_de_respuesta_negativa}")
if abs(respuesta**2 - objetivo) >= epsilon:
print(f"No se encontró la raíz cuadrada de {objetivo}")
else:
print(f"La raíz cuadrada de {objetivo} es {respuesta}")
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""
Input: Three arguments. A grid as a tuple of tuples with integers (1/0),
a row number and column number for a cell as integers.
Output: How many neighbouring cells have chips as an integer.
Example:
count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 1, 2) == 3
count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 0, 0) == 1
Precondition:
3 ≤ len(grid) ≤ 10
all(len(grid[0]) == len(row) for row in grid)
"""
def count_neighbours(grid, row, col):
# if all(len(grid[0]) == len(row) for row in grid):
# for row in grid:
# print row
# print len(grid), len(grid[0])
# else:
# print "break"
# NumeroTotalColumnas => len(grid[0]) -> N
# NumeroTotalFilas => len(grid) -> M
if all(len(grid[0]) == len(rows) for rows in grid):
neighbours = 0
M = len(grid)
N = len(grid[0])
if row == 0 and col == 0:
neighbours = grid[row][col + 1] + grid[row + 1][col] + grid[row + 1][col + 1]
if row == 0 and col == N - 1:
neighbours = grid[row][col - 1] + grid[row + 1][col] + grid[row + 1][col - 1]
if row == M - 1 and col == 0:
neighbours = grid[row - 1][col] + grid[row][col + 1] + grid[row - 1][col + 1]
if row == M - 1 and col == N - 1:
neighbours = grid[row][col - 1] + grid[row - 1][col] + grid[row - 1][col - 1]
if row == 0 and col in range(1, N-1):
neighbours = grid[row + 1][col - 1] + grid[row + 1][col] + grid[row + 1][col + 1] + grid[row][col - 1] + grid[row][col + 1]
if row in range(1, M-1) and col == 0:
neighbours = grid[row - 1][col] + grid[row - 1][col + 1] + grid[row][col + 1] + grid[row + 1][col + 1] + grid[row + 1][col]
if row == M - 1 and col in range(1, N-1):
neighbours = grid[row][col - 1] + grid[row - 1][col - 1] + grid[row - 1][col] + grid[row - 1][col+1] + grid[row][col + 1]
if row in range(1, M-1) and col == N - 1:
neighbours = grid[row - 1][col] + grid[row - 1][col - 1] + grid[row][col - 1] + grid[row + 1][col - 1] + grid[row + 1][col]
if row in range(1, M-1) and col in range(1, N-1):
neighbours = grid[row][col - 1] + grid[row][col + 1] + grid[row - 1][col] + grid[row + 1][col] + grid[row - 1][col - 1] + grid[row - 1][col + 1] + grid[row + 1][col - 1] + grid[row + 1][col + 1]
return neighbours
def main():
grid = ((1,0,0,0,1,0,0,1,1,0),
(0,1,0,1,0,1,1,0,0,1),
(1,1,1,1,0,1,0,0,0,1),
(0,0,1,1,0,1,0,0,0,1),
(1,1,0,1,1,0,1,0,0,1),
(0,1,1,1,0,0,1,1,1,0),
(1,1,1,0,0,0,0,0,1,1),
(0,0,0,1,0,1,0,0,1,1),
(0,0,0,1,0,1,0,1,0,1),
(1,1,0,0,0,1,0,1,1,1),)
print(count_neighbours(grid, 9, 8))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# Converting temperatura from Celsius to Farenheit
from __future__ import division
def main():
C = 21
F = (9/5)*C + 32
print "{} ºC -> {} ºF ".format(C, F)
if __name__ == "__main__":
main()
|
"""ascii table letters mapped to numbers"""
LOWER = 33
UPPER = 127
def main():
users_char = input("Enter a character: ")
print("Tha ASCII code for {} is {}".format(users_char, ord(users_char)))
users_num = get_number(LOWER, UPPER)
print("The character for {} is {}".format(users_num, chr(users_num)))
def get_number(lower, upper):
is_valid = False
while not is_valid:
try:
valid_number = int(input("Enter a number between {} and {}: ".format(lower, upper)))
if not lower <= valid_number <= upper:
print("Invalid number!")
continue
is_valid = True
except ValueError:
print("Invalid input")
return valid_number
if __name__ == '__main__':
main()
# for i in range(LOWER,UPPER+1):
# print("{:3} {:>5}".format(i, chr(i)))
#
#
# num_col = int(input("how many columns: "))
# for i in range(num_col):
# print("{:5}".format(i+1), end="")
# print()
#
# for i in range(LOWER, UPPER):
# for j in range(num_col):
# print("{:5}".format(i), end="")
# print()
|
"""Intermediate exercise with lists of numbers"""
def main():
numbers = []
count = 1
number = get_number(count)
while number > 0:
count += 1
numbers.append(number)
number = get_number(count)
print("The first number is: {}".format(numbers[0]))
print("The last number is: {}".format(numbers[-1]))
print("The smallest number is: {}".format(min(numbers)))
print("The largest number is: {}".format(max(numbers)))
print("The average of the numbers is: {}".format(sum(numbers)/len(numbers)))
def get_number(count):
valid_input = False
while not valid_input:
try:
the_num = int(input("Number {}: ".format(count)))
valid_input = True
except ValueError:
print("Integers please!")
return the_num
if __name__ == '__main__':
main()
|
"""
CP1404/CP5632 Practical (Prac_08)
Let's Drive Program (From Scratch)
"""
from prac_08.taxi import Taxi
from prac_08.silver_service_taxi import SilverServiceTaxi
MENU = """q)uit, c)hoose taxi, d)rive"""
def main():
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2),
SilverServiceTaxi("Hummer", 200, 4)]
current_taxi = 0
bill_to_date = 0
print("Let's Drive!")
print(MENU)
response = input().lower()
while not response == 'q':
if response == 'c':
print("Taxis available:")
for taxi in taxis:
print(str(taxis.index(taxi)) + ' - ' + str(taxi))
current_taxi = int(input("Choose taxi: "))
print("Bill to date: ${:.2f}".format(bill_to_date))
elif response == 'd':
requested_distance = int(input("Drive how far? "))
taxis[current_taxi].drive(requested_distance)
bill_to_date += taxis[current_taxi].get_fare()
print("Your {} trip cost you {:.2f}".format(taxis[current_taxi].name,
taxis[current_taxi].get_fare()))
taxis[current_taxi].start_fare()
print("Bill to date: ${:.2f}".format(bill_to_date))
else:
print("Invalid Choice")
print(MENU)
response = input().lower()
print("Total trip cost: ${:.2f}".format(bill_to_date))
print("Taxis are now:")
for taxi in taxis:
print(str(taxis.index(taxi)) + ' - ' + str(taxi))
if __name__ == '__main__':
main()
|
import math
ABS_TOL = 0.0001
def display_menu():
print(); print()
print('(1) Show the even numbers from x to y')
print('(2) Show the odd numbers from x to y')
print('(3) Show the squares from x to y')
print('(4) Exit the Program')
print()
def main():
display_menu()
response = input()
while response != '4':
x = int(input('x value: '))
y = int(input('y value: '))
if response == '1':
print('Even {} to {}:'.format(x,y))
for i in range(x,y+1):
if i%2 == 0:
print(i, end=' ')
elif response == '2':
print('Odd {} to {}:'.format(x,y))
for i in range(x,y+1):
if i%2 == 1:
print(i, end=' ')
elif response == '3':
print('squares within {} to {}'.format(x,y))
for i in range(x,y+1):
sqrt_i = math.sqrt(i)
if (sqrt_i - math.floor(sqrt_i)) < ABS_TOL:
print(i, end=' ')
elif response == '4':
break
else:
print('bad input. Try again')
display_menu()
response = input()
print('Goodbye')
if __name__ == '__main__': main()
|
nombre = ''
nombres = []
i = 1
while 1:
nombre = input("Entrez le nombre numero {0} : ".format(i))
if nombre.isdigit():
if int(nombre) == 0:
break
nombres.append(int(nombre))
i += 1
plus_grand = nombres[0]
for i in nombres:
if i > plus_grand:
plus_grand = i
print("Le plus grand etait", plus_grand)
|
import numpy as np
"""
CONSTRUIR O MELHOR POLINOMIO P2(X) QUE SE AJUSTE AOS DADOS PELO MÉTODO DOS MINIMOS QUADRADOS
"""
def poli(xData,yData,m):
a = np.zeros((m+1,m+1))
b = np.zeros((m+1,1))
s = np.zeros(2*m+1)
for i in range(len(xData)):
temp = yData[i]
for j in range(m+1):
b[j,] = b[j,] + temp
temp = temp*xData[i]
temp = 1.0
for j in range(2*m+1):
s[j] = s[j] + temp
temp = temp*xData[i]
for i in range(m+1):
for j in range(m+1):
a[i, j] = s[i + j]
a = np.array(a)
b = np.array(b)
print("equações normais:\n")
print(a)
print(b)
E = np.append(a, b, axis=1)
for i in range(1, len(E)):
for j in range(i, len(E)):
E[j, :] = E[j, :] - (E[j, i - 1] / E[i - 1, i - 1]) * E[i - 1, :]
x = np.zeros(3)
x[0] = E[2, 3] / E[2, 2]
x[1] = (E[1, 3] - E[1, 2] * x[0]) / E[1, 1]
x[2] = (E[0, 3] - E[0, 2] * x[0] - E[0, 1] * x[1]) / E[0, 0]
return x
#DADOS
# xData = np.array([1.0,4.0,6.0,7.0], dtype="double")
# yData = np.array([-3.0,-2.0,-1.0,2.0], dtype="double")
xData = np.array([0.0,0.25,0.50,0.75,1.00], dtype="double")
yData = np.array([-153.0,64.0,242.0,284.0,175.0], dtype="double")
m=2
poli = poli(xData,yData,m)
print("\nResultado:")
print("P2(x)={}x² +({}x) + ({})".format(round(poli[0],2),round(poli[1],2),round(poli[2],2)))
|
#-*- coding:utf-8 -*-
import os
def menu():
os.system('cls')
print("¿Qué figura deseas hacer?")
print("Rectángulo --presiona 1")
print("Un triángulo --presiona 2")
optionMenu = raw_input("Selecciona la opción que desees >> ")
if int(optionMenu) == 1:
rbase= raw_input("Medida de la base? >> ")
raltura =raw_input("Medida de la altura? >> ")
print "Lo quieres relleno? ;)"
print "Si --presiona 1"
print "No --presiona 2"
optionFigure = raw_input("Selecciona la opción que desses >> ")
if int(optionFigure)==1:
for i in range (0,int(raltura)):
print ". "*int(rbase)
elif int(optionFigure)==2:
print ". "*int(rbase)
for i in range(0,int(raltura)-1):
print ". "+" "*(int(rbase)-2)+"."
print ". "*int(rbase)
print ""
print "Hacer otra figura --presiona 1"
print "Salir de Programa --presiona 2"
final=raw_input("Selecciona la opción que desees >>")
if int(final)==1:
menu()
elif int(final)==2:
exit()
if int(optionMenu) == 2:
lado= raw_input("Medida del lado? >> ")
print "Lo quieres relleno? ;)"
print "Si --presiona 1"
print "No --presiona 2"
optionFigure = raw_input("Selecciona la opción que desses >> ")
if int(optionFigure)==1:
for i in range (0,int(lado)):
print ". "*(int(lado)-i)
elif int(optionFigure)==2:
print ". "*int(lado)
for i in range(0,int(lado)-2):
print "."+" "*(int(lado)-2-i)+"."
print "."
print ""
print "Hacer otra figura --presiona 1"
print "Salir de Programa --presiona 2"
final=raw_input("Selecciona la opción que desees >>")
if int(final)==1:
menu()
elif int(final)==2:
exit()
menu()
|
from random import*
print("\n\n******** Menu ********")
print("Bienvenue dans le jeu des allumettes!")
print("Instructions: choisissez un nombre d'allumette puis decidez du nombre (entre 1 et 3) a enlever.\n A son tour, l'autre joueur fera de meme et ainsi de suite jusqu'a ce qu'il n'y ait plus d'allumettes.\n Le perdant est celui qui retirera la derniere allumette.")
print("*************************\n")
print("Choisissez le mode de jeu: ")
print("(0) Spectateur ") # IA vs IA
print("(1) Solo: 1 joueur ") #humain VS IA
print("(2) 2 joueurs ") #humain VS humain
n_joueurs_humain=3
#protection nb de joueurs
while n_joueurs_humain>2:
n_joueurs_humain= int(input("Votre choix: "))
#1 joueur humain
def un_joueurs_humain():
#protection difficulté
niveau=5
while niveau>4:
print("Choisissez le niveau de jeu: ")
print("(0) Débutant ") #Random
print("(1) Intermédiaire ") #IA stratégie optimale pour un modulo
print("(2) Master ") #IA stratégie optimale pour deux modulos
print("(3) Pro ") #Stratégie optimal pour trois modulos
print("(4) Expert ") #Stratégie optimal pour tous les modulos
niveau= int(input("Niveau: "))
l_n=[' Débutant', 'Intermédiaire', 'Master', 'Pro', 'Expert']
print('Vous avez choisi le niveau'+l_n[niveau])
n=-1
while n<=0:
n=int(input("Choisissez un nombre total d'allumettes: "))
while n>0:
j=-1
while j<1 or j>3 or j>n:
j= int(input("Combien d'allumettes voulez vous retirez?"))
n-=j
if n==0:
print("Vous avez perdu!")
else:
print("Il reste: ", n)
p=AI_p(niveau, n)
print("J'en prend ", p)
n-=p
print("Il en reste ", n)
if n==0:
print("J'ai perdu!")
return 0
#2 joueurs humains
def deux_joueurs_humain():
n=-1
while n<=0:
n=int(input("Joueur1, choisissez un nombre total d'allumettes: "))
while n>0:
j1=-1
while j1<1 or j1>3 or j1>n:
j1= int(input("Joueur1, combien d'allumettes voulez vous retirez?"))
n-=j1
if n==0:
print("Joueur1, vous avez perdu!")
else:
print("Il reste: ", n)
j2=-1
while j2<1 or j2>3 or j2>n:
j2= int(input("Joueur2, combien d'allumettes voulez vous retirez?"))
n-=j2
print("Il en reste ", n)
if n==0:
print("Joueur2, vous avez perdu!")
return 0
#zero joueurs humain
def zero_joueurs_humain():
#protection difficulté
niveau1=5
niveau2=5
while niveau1>4 or niveau2>4:
niveau1= int(input("Quel niveau de dificultés pour ordi1? "))
niveau2= int(input("Quel niveau de dificultés pour ordi2? "))
n=-1
while n<=0:
n=int(input("Choisissez un nombre total d'allumettes: "))
while n>0:
j=AI_p(niveau1, n)
print('Ordi1 a choisit de retirer {} allumettes'.format(j))
n-=j
if n==0:
print("Ordi1 a perdu!")
else:
print("Il reste: ", n)
p=AI_p(niveau2, n)
print("Ordi2 prend ", p)
n-=p
print("Il en reste ", n)
if n==0:
print("Ordi2 a perdu!")
return 0
#strategie de jeu pour l'ordi selon le niveau de difficulté
def AI_p(level, n):
if level==0:
p= random.randint(1,3)
elif level==1:
if n%4==3:
p=2
else:
p=random.randint(1,3)
elif level==2:
if n%4==3:
p=2
elif n%4==2:
p=1
else:
p=random.randint(1,3)
if level==3:
if n%4==3:
p=2
elif n%4==2:
p=1
elif n%4==0:
p=3
else:
p=random.randint(1,3)
else:
if n%4==3:
p=2
elif n%4==2:
p=1
elif n%4==0:
p=3
else:
p=1
return p
if n_joueurs_humain==1:
print("Vous jouez contre l'ordinateur!")
un_joueurs_humain()
elif n_joueurs_humain==2:
print("Vous jouez contre un autre joueur humain!")
deux_joueurs_humain()
else:
print("Vous etes spectateur!")
zero_joueurs_humain()
|
from PyPDF2 import PdfFileReader, PdfFileWriter
print(''' Welcome to the password protector for pdf
•••by Harinath''' )
pdfwriter=PdfFileWriter()
a=input("Enter pdf location :")
name= input("Enter pdf name without extension : ")
pdf= PdfFileReader(a+name+".pdf")
for pagenum in range(pdf.numPages):
pdfwriter.addPage(pdf.getPage(pagenum))
passw=input("Enter the password you want :")
print('please wait..')
pdfwriter.encrypt(passw)
with open (a+name+" (new).pdf",'wb') as f:
pdfwriter.write(f)
f.close()
print("Check the folder. New pdf has been created and encrypted")
|
" 1 Sum all divisors of an integer"
def sum_of_divisors(n):
m = 0
for x in range( 1, n + 1):
if n % x == 0:
m = m + x
return m
" 2 Check if integer is prime"
def is_prime(n):
return sum_of_divisors(n) == (n + 1)
" 3 Check if a number has a prime number of divisors"
def prime_number_of_divisors(n):
m=0
for x in range( 1, n + 1):
if n % x == 0:
m += 1
return is_prime(m)
" 4 Number containing a single digit?"
def contains_digit( number, digit):
for i in str(number):
if int(i) == digit:
return True
return False
" 5 Number containing all digits?"
def contains_digits( number, digits):
for i in digits:
if not contains_digit( number, i):
return False
return True
" 6 Is number balanced?"
def is_number_balanced(n):
a=[int(x) for x in str(n)]
size = int(len(str(n)) / 2)
b=c=0
for i in a[:size]:
b += i
if not len(str(n)) % 2 == 0:
size+=1
for i in a[size:]:
c += i
return b == c
" 7 Counting substrings"
def count_substrings( haystack, needle):
return haystack.count(needle)
" 8 Zero Insertion"
def zero_insert(n):
a=[int(x) for x in str(n)]
for i in range(len(a)-1):
if a[i] == a[i + 1] or a[i] + a[i + 1] == 10:
a[i]=a[i]*10
n=0
for i in a:
n = n*(10**len(str(i))) + i
return n
" 9 Sum Numbers in Matrix"
def sum_matrix(m):
return sum([sum(a) for a in m])
" 10 Matrix Bombing"
|
print("MASUKKAN LUAS LINGKARAN DENGAN JARI-JARI")
print("========================================")
II = 22/7
r = float(input("Masukkan jari-jari lingkaran: "))
luas = II*(r*r)
print("Luas lingkaran dengan jari-jari {} adalah {:.2f} cm\u00b2".format(r, luas))
|
# Question 10 #
items = 5 # Optional input method: int(input("How many items are there? ")) #
priceList = []
for prices in range(items):
prices = int((input("What is the price of the item? "))[:-1])
priceList.append(prices)
print("The total price is", str(sum(priceList)))
print("The average price is", str(sum(priceList) / items))
print("The highest price is", str(max(priceList)))
print("The lowest price is", str(min(priceList)))
|
import sys
import math
def isPrime(number):
if number == 1:
return False
elif number < 4:
return True
elif number % 2 == 0:
return False
elif number < 9:
return True
elif number % 3 == 0:
return False
else:
r = round(math.sqrt(number))
f = 5
while f <= r:
if number % f == 0:
return False
if number % (f+2) == 0:
return False
f += 6
return True
sum = 0
target = 2000000
seed = 1
while seed < target:
if isPrime(seed) == True:
sum += seed
print("for primes below " + str(seed + 1) + "the sum equals " + str(sum))
seed += 1
|
#QuickSort
#1. choose any element to the pivotList
#2. divide all the other elements into 2 partitions, > pivot and < pivot
#3. use recursion to sort both partitions
#4. finally join the two sorted lists with the pivot
def quickSort(alist):
less = []
pivotList = []
more = []
if len(alist) <= 1:
return alist
else:
pivot = alist[0]
for i in alist:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivotList.append(i)
less = quickSort(less)
more = quickSort(more)
return less + pivotList + more
A = [534, 246, 933, 127, 277, 321, 454, 565, 220]
print(quickSort(A))
|
# define two variables
x = "Python Class"
y = "ABC world of knowing"
print("Welcome to "+ x+" from "+ y)
# instead we can use % operator
print("Welcome to %s from %s" %(x, y))
print("Welcome to %s from %s" %("Python Class", y))
# Now let's use format method which more efficient
print("Welcome to {} from {}".format(x, y))
# now this formatting can be done with indexing too
print("Welcome to {0} from {1}".format(x, y)) # is the most recommended format the string
#we can also use keyword argument as below
print("Welcome to {classname} from {schoolname}".format(classname=x, schoolname=y)) # is the more readable code
print("Welcome to {0} from {1} where we have {studentscount} in our place".format(x, y, studentscount = 100))
|
# list.append(x) -- Add an item to the end of list
# list.insert(i, x) -- Insert an item at a given position
# list.remove(x) ---Remove the first item from the list whose value is equal to x
# list.pop([i]) ---Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes
# and returns the last item in the list
x = 10
y = "training"
z = [10, 20, 30, 40, 50, 60, "school"]
z1 = ['aaa', 'bbb', 'ccc']
print(z == z1)
i = 0
for i in range(len(z)):
print(z[i])
z.append(50) # append adds new index value at the end of list
print(z[-1:])
print(z[::-1])
z.insert(1,"fixme")
print(z)
|
# LIBRARY
from random import randint
# VARIABLE
# Berisi angka secara random dari 0 - 100 sebanyak 100 angka
#arr = [randint(1,100) for i in range(0,100)]
def sort_numbers(s):
for i in range(1, len(s)):
val = s[i]
j = i - 1
while (j >= 0) and (s[j] > val):
s[j+1] = s[j]
j = j - 1
s[j+1] = val
def main():
x = eval(input("Enter numbers to be sorted: "))
x = list(x)
sort_numbers(x)
print(x)
# FUNGSI INSERTION SORT
# Tulis algoritma disini...
|
#!/usr/bin/python
saori= raw_input("ingrese caracter: ")
def caracter(saori):
if ((saori == "a") or (saori == "e") or (saori == "i") or (saori == "o") or (saori == "u")):
return True
else:
return "false"
caracter (saori)
print (caracter(saori))
|
import random
def verify_sort(a):
for i in range(1, len(a)):
if (a[i-1] > a[i]):
raise Exception("Sort is invalid at {0} position ({1} > {2})".format(i, a[i-1], a[i]))
def generate_random_array(length):
return [int(1000 * random.random()) for _ in range(length)]
|
"""
The UnionFind data structure provides an efficient way to respond to queries regarding the connectivity between a set of elements.
Connectivity queries and the linkage of the elements is provided through two operations:
- Find(p) - returns an integer that indicates the connected component in which p belongs
- Union(p, q) - connects the elements p and q
- Connected(p, q) - returns a boolean that indicates whether p and q are within the same component
The connectivity between two elements is supposed to exhibit the following properties:
- Reflexive : p is connected to p.
- Transitive : If p is connected to q and q is connected to r, then p is connected to r.
- Symmetric : If p is connected to q, then q is connected to p.
In the implementation that follows we use an array of integers to represent the elements. Each integer represents
a component or site, into which the respective element belongs. Components are assigned, arbitrarily, an integer
between 0 and N-1, where N is the number of components.For example, array[0] denotes the site or connected component
in which the 0-th element belongs.
For each connected component we maintain a leader or root element. All elements within the same component have an
array entry that equals the root element of their component. If the 1st and 2nd elements belong in the same component
for which the 4th element is the root, then array[0] = array[1] = 3.
The root element has the property that array[root] = root.
However, elements can be linked to their root indirectly through successive union operations. For example an element
could be initially rooted to element 0 but after a union operation between 0 and 1, the new root is 1. Therefore to
safely calculate the root of an arbitrary element p we have to follow all the element references in the array until
we encounter a root element. In the worst case we will need to traverse up to O(N) links to arrive to the root from
another random element. We therefore want to minimise the number of steps required to reach the root from any element.
This particular implementation goes by the name of Union by Rank with Path Compression.
For each root we maintain its rank, the maximum number of links we have to follow from a leaf to reach the root. When
connecting two roots, we aim to link the root with the smallest rank beneath the root with the higher rank in order
to minimize the height of the tree. Using this tactic, the height of the tree increases only when merging two roots
of the same rank. For N elements we can merge two equally-ranked roots up to logN times which places logN as the upper
bound for the tree's height and therefore the cost of the Find operation. This cost can be reduced even further by
applying path compression.
The term path compression refers to the operation of caching the root lookup result for an element whenever the
Find operation is called and updating the components array with that information. This reduces the lookup time for
future Find operations on the same element, in the best case from logN down to 1.
It provides amortized constant time for both find and union operations.
"""
class UnionFind:
def __init__(self, max_elements):
self.N = max_elements
self.num_components = self.N
self.elements = [i for i in range(self.N)]
self.ranks = [1 for _ in range(self.N)]
def find(self, p):
assert 0 <= p < self.N
while self.elements[p] != p:
# path compression by directly caching the lookup result in the component array
self.elements[p] = self.elements[self.elements[p]]
p = self.elements[p]
return p
def union(self, p, q):
assert 0 <= p < self.N
assert 0 <= q < self.N
if p != q:
p_root = self.find(p)
q_root = self.find(q)
if p_root != q_root:
p_rank = self.ranks[p_root]
q_rank = self.ranks[q_root]
if p_rank < q_rank:
self.elements[p_root] = q_root
elif q_rank < p_rank:
self.elements[q_root] = p_root
else:
self.elements[q_root] = p_root
self.ranks[p_root] += 1
self.num_components -= 1
def connected(self, p, q):
return self.find(p) == self.find(q)
def count_components(self):
return self.num_components
if __name__ == "__main__":
N = 100000
uf = UnionFind(N)
for i in range(N):
assert i == uf.find(i)
assert uf.count_components() == N
for even in range(2, N, 2):
uf.union(0, even)
for odd in range(3, N, 2):
uf.union(1, odd)
assert uf.count_components() == 2
for even in range(2, N, 2):
assert uf.connected(0, even)
for odd in range(3, N, 2):
assert uf.connected(1, odd)
uf.union(0, 1)
assert uf.count_components() == 1
with open('../data/mediumUF.txt', 'r') as input_file:
N = int(input_file.readline())
uf = UnionFind(N)
for ln in input_file.readlines():
p, q = [ int(x) for x in ln.split()]
uf.union(p, q)
print uf.count_components(), ' connected components'
|
"""
A minimum priority queue which allows clients to associate an integer with each key.
"""
class IndexedPriorityQueue:
def __init__(self, maxItems):
self.maxItems = maxItems
self.N = 0
# the binary heap, contains indexes
self.heap = [None for _ in range(maxItems)]
# maps from indexes to heap indexes
self.index = [-1 for _ in range(maxItems)]
# maps from indexes to keys
self.keys = [None for _ in range(maxItems)]
def _key_of(self, i):
return self.keys[self.heap[i]]
@staticmethod
def _left_child(i):
return 1 + i * 2
@staticmethod
def _right_child(i):
return 2 + i * 2
@staticmethod
def _parent(i):
return (i - 1) // 2
def _exchange(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
self.index[self.heap[i]] = i
self.index[self.heap[j]] = j
def swim(self, i):
p = self._parent(i)
while i >= 1 and self._key_of(p) > self._key_of(i):
self._exchange(p, i)
i = p
p = self._parent(p)
def sink(self, i):
while self._left_child(i) < self.N:
l, r = self._left_child(i), self._right_child(i)
min_child = l if (l == self.N - 1 or self._key_of(l) < self._key_of(r)) else r
if self._key_of(min_child) < self._key_of(i):
self._exchange(min_child, i)
i = min_child
else:
return
def insert(self, index, key):
assert self.N <= self.maxItems
if self.keys[index] is not None:
if self.keys[index] < key:
self.increase(index, key)
else:
self.decrease(index, key)
return
self.keys[index] = key
self.heap[self.N] = index
self.index[index] = self.N
self.N += 1
self.swim(self.N - 1)
def increase(self, index, key):
self.keys[index] = key
self.sink(self.index[index])
def decrease(self, index, key):
self.keys[index] = key
self.swim(self.index[index])
def del_min(self):
min_index = self.min_index()
k, v = self.keys[min_index], min_index
self._exchange(0, self.N - 1)
self.keys[min_index] = None
self.index[min_index] = -1
# self.heap[self.N] = None
self.heap[self.N - 1] = None
self.N -= 1
self.sink(0)
return (v, k)
def min_index(self):
return self.heap[0]
def min_key(self):
return self.keys[self.heap[0]]
def key_of(self, index):
assert self.contains(index)
return self.keys[index]
def size(self):
return self.N
def is_empty(self):
return self.N == 0
def contains(self, index):
return index in self.heap
class PriorityQueue:
"""
A general binary heap implementation which can handle either plain comparable keys
or key-value pairs.
Using plain keys:
pq = PriorityQueue(10)
for i in range(1, 11):
pq.insert(i)
for i in range(1, 11):
assert pq.del_min() == i
Using key-value pairs:
pq = PriorityQueue(10)
pq.insert(1000.0, "!")
pq.insert(0.0, "Hello ")
pq.insert(12.44, "World")
pq.insert(-5.1, "> ")
s = ""
while not pq.is_empty():
s = s + pq.del_min()
assert s == "> Hello World!"
import random
arr = [x for x in range(1, 11)]
random.shuffle(arr)
pq = PriorityQueue.heapify(arr)
print pq.heap
for i in range(1, 11):
assert pq.del_min() == i
"""
def __init__(self, maxItems):
self.maxItems = maxItems
self.N = 0
# the binary heap, contains indexes
self.heap = [None for _ in range(maxItems)]
# maps from keys to values
self.values = {}
@staticmethod
def heapify(arr):
pq = PriorityQueue(len(arr))
pq.heap = [x for x in arr]
pq.N = len(arr)
for i in range(pq.N / 2, -1, -1):
pq.sink(i)
for x in pq.heap:
pq.values[x] = x
return pq
@staticmethod
def _left_child(i):
return 1 + i * 2
@staticmethod
def _right_child(i):
return 2 + i * 2
@staticmethod
def _parent(i):
return (i - 1) // 2
def _exchange(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
def _is_minpq(self, i):
if i >= self.N:
return True
left = self._left_child(i)
right = self._right_child(i)
if left < self.N and self.heap[i] > self.heap[left]:
return False
if right < self.N and self.heap[i] > self.heap[right]:
return False
val = self._is_minpq(left) and self._is_minpq(right)
if not val:
print val
return val
def swim(self, i):
p = self._parent(i)
while i >= 1 and self.heap[p] > self.heap[i]:
self._exchange(p, i)
i = p
p = self._parent(p)
def sink(self, i):
while self._left_child(i) < self.N:
l, r = self._left_child(i), self._right_child(i)
min_child = l if (l == self.N - 1 or self.heap[l] < self.heap[r]) else r
if self.heap[min_child] is not None and self.heap[min_child] < self.heap[i]:
self._exchange(min_child, i)
i = min_child
else:
return
def insert(self, key, val=None):
assert self.N <= self.maxItems
if val is None:
val = key
if key in self.values:
self.values[key] = val
else:
self.values[key] = val
self.heap[self.N] = key
self.N += 1
self.swim(self.N - 1)
assert self._is_minpq(0)
def del_min(self):
if self.N == 0:
raise Exception("Queue is empty")
k = self.heap[0]
assert k in self.values
v = self.values[k]
self._exchange(0, self.N - 1)
del self.values[k]
self.N -= 1
self.heap[self.N] = None
self.sink(0)
assert self._is_minpq(0)
return v
def min_key(self):
return self.heap[0]
def size(self):
return self.N
def is_empty(self):
return self.N == 0
if __name__ == "__main__":
pq = IndexedPriorityQueue(10)
pq.insert(0, 1.0)
pq.insert(1, 1.5)
pq.insert(2, 0.2)
assert pq.size() == 3
assert not pq.is_empty()
assert pq.key_of(0) == 1.0
assert pq.key_of(1) == 1.5
assert pq.key_of(2) == 0.2
assert pq.contains(0)
assert pq.contains(1)
assert pq.contains(2)
assert not pq.contains(3)
assert pq.min_key() == 0.2
assert pq.min_index() == 2
pq.insert(4, 0.0)
pq.increase(4, 100.0)
i, k = pq.del_min()
assert k == 0.2 and i == 2
pq.insert(3, 10.0)
i, k = pq.del_min()
assert k == 1.0 and i == 0
pq.decrease(3, 1.0)
i, k = pq.del_min()
assert k == 1.0 and i == 3
i, k = pq.del_min()
assert k == 1.5 and i == 1
assert (4, 100.0) == pq.del_min()
assert pq.is_empty()
N = 1000
pq = IndexedPriorityQueue(N)
nums = []
queue = PriorityQueue(N)
for i in range(N):
nums.append(i)
pq.insert(i, i)
import random
random.shuffle(nums)
# for n in nums:
# queue.insert(n)
queue = PriorityQueue.heapify(nums)
def sort_indexed_pairs(p1, p2):
return cmp(p1[1], p2[1])
for i in range(N):
k = pq.del_min()[1]
w = queue.del_min()
cmp1 = i == k
cmp2 = i == w
if not cmp1 or not cmp2:
print "invalid"
assert cmp1
assert cmp2
pq = PriorityQueue(10)
pq.insert(1000.0, "!")
pq.insert(0.0, "Hello ")
pq.insert(12.44, "World")
pq.insert(-5.1, "> ")
s = ""
while not pq.is_empty():
s = s + pq.del_min()
assert s == "> Hello World!"
import random
arr = [x for x in range(1, 11)]
random.shuffle(arr)
pq = PriorityQueue.heapify(arr)
print pq.heap
for i in range(1, 11):
assert pq.del_min() == i
|
"""
Regular expression can be modelled by non-deterministic finite state automata (NFAs). As there are potentially multiple
transitions from each state of the automaton, the next state cannot be computed deterministically . Instead all the
possible transitions must be examined and considered at the same time.
The NFA is represented by a digraph which models the states of the NFA and their transitions. Each character of the
pattern of length M becomes a node in the digraph.
At each step of the NFA simulation we must keep track of all the possible transitions to future states that can take
place from the current state. In graph terms this corresponds to the multiple source reachability problem, i.e. which
nodes are reachable from a starting set S of nodes. This is an application of the DFS algorithm for each starting
node in S.
To implement regular expressions we can built the NFA that corresponds to the regular expression and then feed the
input text to the NFA and follow it until we reach either the end state or the end of the input.
In this simplified version of regular expressions, we only handle parenthesis, the * wildcard and the OR | operator.
We use an operator stack to keep track of the operators. Upon a ( or a | we push the operator on the stack. Upon a
) we pop the operators from the top of the stack until we pop the matching left parenthesis (.
The running time for the construction of the NFA is O(M) since for each of the M characters of the pattern we create
one digraph node and add up to 3 epsilon transitions and execute 1 or 2 stack operations.
The running time of the simulation is O(T*M) as there are T passes for an input text of length T and we perform a DFS
in each pass. The DFS itself takes time proportional to O(M) as there are O(M) nodes and edges.
"""
from graph_utils import Digraph
class SimpleRegEx:
def __init__(self, pattern):
self.pat = pattern
self.end_state = len(pattern)
self.__build_nfa()
# stores a flag per node indicating if the last DFS operation reached the corresponding node
self._marked = [False for _ in range(self.nfa.V())]
def matches(self, text):
# find the epsilon transitions from the origin state
self.__dfs_cycle([0])
current_states = self.__get_reachable_states()
if self.end_state in current_states:
return True
# compute the next set of reachable states for each input character
for i in range(len(text)):
new_states = []
for state in current_states:
if text[i] == self.pat[state] or self.pat[state] == '.':
new_states.append(state+1)
self.__dfs_cycle(new_states)
current_states = self.__get_reachable_states()
if self.end_state in current_states:
return True
if len(current_states) == 0:
return False
return self.end_state in current_states
def __get_reachable_states(self):
return [i for i in range(self.end_state + 1) if self._marked[i]]
def __build_nfa(self):
op_stack = []
self.nfa = Digraph(len(self.pat) + 1)
# tracks the last left parenthesis
leftPar = -1
for i in range(self.end_state):
ch = self.pat[i]
if ch == '(':
# add an epsilon transition to the next character and push the operator for later processing
self.nfa.add_edge(i, i+1)
op_stack.append(i)
leftPar = i
elif ch == '|' and leftPar >= 0:
# add a transition from the left parenthesis node to the first node after the OR (|) operator
self.nfa.add_edge(leftPar, i+1)
op_stack.append(i)
elif ch == ')':
# add a transition from the node right after the | operator to the right parenthesis node
last_op = op_stack.pop()
while self.pat[last_op] == '|':
self.nfa.add_edge(last_op, i)
last_op = op_stack.pop()
leftPar = last_op
self.nfa.add_edge(i, i+1)
# handles the case (...)*
if i < self.end_state - 1 and self.pat[i+1] == '*':
self.nfa.add_edge(leftPar, i+1)
self.nfa.add_edge(i+1, leftPar)
elif ch == '*':
# always add a transition to the next node as the star operator can match a zero input
self.nfa.add_edge(i, i+1)
# handles the case of a star operator after a simple symbol, e.g. ab*
if i > 0 and self.pat[i-1] != ')':
self.nfa.add_edge(i, i-1)
self.nfa.add_edge(i-1, i+1)
assert len(op_stack) == 0
def __dfs_cycle(self, states):
self._marked = [False for _ in range(self.nfa.V())]
for s in states:
self.__dfs(s)
def __dfs(self, v):
self._marked[v] = True
for w in self.nfa.edges(v):
if not self._marked[w]:
self.__dfs(w)
if __name__ == "__main__":
re = SimpleRegEx("abc")
assert re.matches("abc")
re = SimpleRegEx("ab.")
assert re.matches("abd")
re = SimpleRegEx("a*")
assert re.matches("a")
assert re.matches("")
assert re.matches("aaaaaaaaaaaa")
re = SimpleRegEx("(Hello|Hola) G(.)*s")
while True:
text = raw_input('Give a text: ')
print re.matches(text)
|
category = int(input('원하는 음료는 1.커피 2.주스'))
if category == 1:
menu = int(input('번호 선택? 1. 아메리카노 2. 카페라테 3. 카푸치노'))
if menu ==1:
print('1.아메리카노 선택')
elif menu ==2:
print('2.카페라테 선택')
elif menu ==3:
print('3.카푸치노 선택')
else:
menu = int(input('번호 선택? 1. 키위주스 2. 토마토주스 3. 오렌지주스'))
if menu ==1:
print('1.키위주스 선택')
elif menu ==2:
print('2.토마토주스 선택')
elif menu ==3:
print('3.오렌지주스 선택')
|
print('查看什么三角形')
print('请输入三角形的第一条边长')
a=input()
a=int(a)
print('请输入三角形的第二条边长')
b=input()
b=int(b)
print('请输入三角形的第三条边长')
c=input()
c=int(c)
if a+b>c or a+c>b or b+c>a:
if a==b and b==c :
print('这是一个全等三角形')
elif a==b or b==c or c==a :
print('这是一个等腰三角形')
elif a*a+b*b==c*c or a*a+c*c==b*b or b*b+c*c==a*a:
print('这是一个直角三角形')
else:
print('构不成三角形呢')
|
# **********************************************************
# Assignment: Project 16: Password Generator
#
# Description: Write a password generator in Python. Be
# creative with how you generate passwords - strong passwords
# have a mix of lowercase letters, uppercase letters, numbers,
# and symbols. The passwords should be random, generating a
# new password every time the user asks for a new password.
# Include your run-time code in a main method.
#
# Author: Aditya Sharma
#
# Date Start: (2018/08/17)
# Date Completed: (2018/08/17)
#
# Completion time: 2 hours
#
# Honor Code: I pledge that this program represents my own
# program code. I received help from (enter the names of
# others that helped with the assignment; write no one if
# you received no help) in designing and debugging my program.
# *********************************************************
import random
password_list = []
uppercase_set = []
lowercase_set = []
symbols_set = []
choice_selector = []
numbers_set = [0,1,2,3,4,5,6,7,8,9]
uppercase_set.extend("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
lowercase_set.extend("ABCDEFGHIJKLMNOPQRSTUVWXYZ".lower())
symbols_set.extend("~`@#$%^&*()-_+=\|]}[{?/>.<,;:'")
number_of_passwords = int(input("How many passwords do you want generated? "))
length_counter = 0
character_selector = 0
type_selector = 0
password_counter = 1
character_selected = " "
password = " "
while password_counter <= number_of_passwords:
password_length = int(input(f"What is the desired length of Password {password_counter}? "))
lowercase_response = input (f"Would you like lowercase alphabets in Password {password_counter}? ").lower()
uppercase_response = input (f"Would you like uppercase alphabets in Password {password_counter}? ").lower()
numbers_response = input(f"Would you like numbers in Password {password_counter}? ").lower()
symbols_response = input(f"Would you like symbols in Password {password_counter}? ").lower()
if lowercase_response == "yes":
choice_selector.append(1)
# print(choice_selector)
if uppercase_response == "yes":
choice_selector.append(2)
# print(choice_selector)
if numbers_response == "yes":
choice_selector.append(3)
# print(choice_selector)
if symbols_response == "yes":
choice_selector.append(4)
# print(choice_selector)
if lowercase_response == "no" and uppercase_response == "no" and numbers_response == "no" and symbols_response == "no":
print ("Okay, that was a nice try. But, who the hell do you think I am? Go back and retry kid.")
continue
# else:
# print ("checK")'''
while length_counter < password_length:
# print ("1", choice_selector)
# print ("2", type_selector)
type_selector = random.choice(choice_selector)
# print ("3",choice_selector)
# print ("4",type_selector)
# print("\n")
if type_selector == 1:
character_selector = random.randint(0,25)
character_selected = lowercase_set[character_selector]
password_list.append(character_selected)
# print (character_selected)
elif type_selector == 2:
character_selector = random.randint(0,25)
character_selected = uppercase_set[character_selector]
password_list.append(character_selected)
# print (character_selected)
elif type_selector == 3:
character_selector = random.randint(0,9)
character_selected = numbers_set[character_selector]
password_list.append(character_selected)
# print (character_selected)
elif type_selector == 4:
character_selector = random.randint(0,29)
character_selected = symbols_set[character_selector]
password_list.append(character_selected)
# print (character_selected)
else:
print ("Who do you think you are? Do you want a password or not? If not, then leave this program immediately!")
break
length_counter += 1
password = ''.join(map(str, password_list))
print(f"Password {password_counter}: {password} \n")
choice_selector.clear()
length_counter = 0
password_list.clear()
password_counter += 1
'''
choice_selector.clear()
type_selector = 0
password = " "
password_length = 0
lowercase_response = " "
uppercase_response = " "
numbers_response = " "
symbols_response = " "
character_selector = 0
character_selected = " "
password_list.clear() '''
|
import math
import time
def gear_ratio (level1, level2): #Accepts lists as arguements. Lists correspond to series of Pitch Diameters
#12, 18 - Idler, 36
#12, 13, 13, 20
# Thumb: 20, 20
gear_ratio1 = level1[2] / level1[0]
gear_ratio2 = level2[3] / level2[0]
total_gear_ratio = gear_ratio1 * gear_ratio2
return total_gear_ratio
def number_motor_rotations(forefinger_rotation, total_gear_ratio): #FF Rot is in degrees
total_motor_rotation = total_gear_ratio * forefinger_rotation/360
return total_motor_rotation
def finger_position(forefinger_length, angular_position): #AP is in degrees. Tip to base angle
angular_position_radians = angular_position * (math.pi/180)
x = round(math.cos(angular_position_radians) * forefinger_length, 2)
y = round(math.sin(angular_position_radians) * forefinger_length, 2)
coordinate = [x,y]
#print(coordinate)
return coordinate
def elapsed_time (input_speed, number_motor_rotations):
elapsed_time = round(((number_motor_rotations / input_speed) * 60),2)
return elapsed_time
def main():
input_speed = 45
level1 = [12,18,36]
level2 = [12,13,13,20]
forefinger_length = 0.41
time_elapsed = elapsed_time(input_speed, number_motor_rotations (90, gear_ratio(level1, level2)))
angular_position = 0
for i in range (10):
print(finger_position(forefinger_length, angular_position)[0], "\t", finger_position(forefinger_length, angular_position)[1], "\t", "forefinger position at ",angular_position, "degrees rotation")
angular_position += 10 # Starts at 0 --> FF Rotation. Open = 0, closed = FF Rotation
print("\nSTATUS \t ELAPSED TIME")
for i in range (6):
if (i%2 == 0):
print("OPEN \t", time_elapsed * i)
else:
print("CLOSED \t", time_elapsed * i)
print("OPEN \t", time_elapsed * (i+1))
main()
'''
import math
def number_motor_rotation(Forefinger_rot,total_gear_ratio):
number_of_motor_rotations = (total_gear ratio)*((forefinger_rot)/360)
return number_of_motor_rotations
def finger_position(length_forefinger,Angular position):
Angular_position_radians=(Angular_position)*(3.14/180)
x = math.cos(Angular_position_radians)*(length_forefinger)
y = math.sin(Angular_position_radians)*(length_forefinger)
def elapsed_time(input_speed,Number_of_motor_rotations):
elapsed_time = (Number_of_motor_rotations/60)/(input_speed)
return elapsed_time
'''
|
# **********************************************************
# Assignment: Project 15: Reverse Word Order
#
# Description: Write a program (using functions!) that asks
# the user for a long string containing multiple words.
# Print back to the user the same string, except with
# the words in backwards order.
#
# Author: Aditya Sharma
#
# Date Start: (2018/08/17)
# Date Completed: (2018/08/17)
#
# Completion time: 5 minutes hours
#
# Honor Code: I pledge that this program represents my own
# program code. I received help from (enter the names of
# others that helped with the assignment; write no one if
# you received no help) in designing and debugging my program.
# *********************************************************
user_string = input ("Input a phrase containing multiple words: ")
list1 = user_string.split(" ")
print ("\n", list1)
list1.reverse()
print ("\n", list1)
list2 = " ".join(list1)
print (list2)
|
# **********************************************************
# Assignment: Project 18: Cows and Bulls
#
# Description: Write a password generator in Python. Be
# creative with how you generate passwords - strong passwords
# have a mix of lowercase letters, uppercase letters, numbers,
# and symbols. The passwords should be random, generating a
# new password every time the user asks for a new password.
# Include your run-time code in a main method.
#
# Author: Aditya Sharma
#
# Date Start: (2018/08/17)
# Date Completed: (2018/08/17)
#
# Completion time: 5 minutes
#
# Honor Code: I pledge that this program represents my own
# program code. I received help from (enter the names of
# others that helped with the assignment; write no one if
# you received no help) in designing and debugging my program.
# *********************************************************
import random
|
# **********************************************************
# Assignment: Project 12: List Ends
# Description:
#
# Author: Aditya Sharma
#
# Date Start: (2018/08/17)
# Date Completed: (2018/08/17)
#
# Completion time: 5:45 hours
#
# Honor Code: I pledge that this program represents my own
# program code. I received help from (enter the names of
# others that helped with the assignment; write no one if
# you received no help) in designing and debugging my program.
# *********************************************************
list1 = []
number_of_elements = int(input("Input the number of elements in the list."))
counter = 0
while counter <= number_of_elements:
number_added = int(input("Input a number you would like to have in the list."))
list1.append(number_added)
counter += 1
def function ():
list2 = []
list2.append(list1[0])
list2.append(list1[(len(list1) - 1)])
print (list2)
function()
|
#!/usr/bin/env python3
class Node:
def __init__(self, word = None):
self.children = {}; self.word = word
class MultiwayTrie:
def __init__(self):
self.root = Node(); self.size = 0; self.iter_s = [self.root]
def __len__(self):
return self.size
def __iter__(self):
return self
def __next__(self):
if len(self.iter_s) == 0:
self.iter_s.append(self.root); raise StopIteration
else:
curr = Node()
while curr.word is None and len(self.iter_s) != 0:
curr = self.iter_s.pop()
for c in sorted(curr.children.keys()):
self.iter_s.append(curr.children[c])
if curr.word is not None:
return curr.word
else:
self.iter_s.append(self.root); raise StopIteration
def __contains__(self, key):
if not isinstance(key, str) and not isinstance(key, list):
raise TypeError("Keys must be str or list")
curr = self.root
for c in key:
if c not in curr.children:
return False
curr = curr.children[c]
return curr.word is not None
def clear(self):
del self.root; self.root = Node(); self.size = 0; self.iter_s = [self.root]
def empty(self):
return self.size == 0
def add(self, key):
if not isinstance(key, str) and not isinstance(key, list):
raise TypeError("Keys must be str or list")
curr = self.root
for c in key:
if c not in curr.children:
curr.children[c] = Node()
curr = curr.children[c]
if curr.word is None:
curr.word = key; self.size += 1; return True
else:
return False
def remove(self, key):
if not isinstance(key, str) and not isinstance(key, list):
raise TypeError("Keys must be str or list")
curr = self.root
for c in key:
if c not in curr.children:
return False
curr = curr.children[c]
if curr.word is None:
return False
else:
curr.word = None; self.size -= 1; return True
|
"""
Find a package in the Python standard library for dealing with JSON. Import the library module and
inspect the attributes of the module. Use the help function to learn more about how to use the module.
Serialize a dictionary mapping 'name' to your name and 'age' to your age, to a JSON string. Deserialize
the JSON back into Python.
"""
import json
#python
serialize={
'name':"Rochak",
'age':22
}
json_loader=json.dumps(serialize) #converting to json
print (f'Json Object: {json_loader}')
deserialize= json.loads(json_loader)
print(f'Python-Dict: {deserialize}')
|
"""
Write a function to write a comma-separated value (CSV) file. It should accept a filename and a list
of tuples as parameters. The tuples should have a name, address, and age. The file should create a header
row followed by a row for each tuple. If the following list of tuples was passed in:
[('George', '4312 Abbey Road', 22), ('John', '54 Love Ave', 21)] it should write the following in the file:
name,address,age
George,4312 Abbey Road,22
John,54 Love Ave,21
"""
import csv
def write_file(get_profile):
with open('profile.csv','w',newline='') as file:
writer=csv.writer(file)
writer.writerow(['Name','Adress','Age'])
for each in get_profile:
writer.writerow(each)
if __name__ == "__main__":
write_file([('George', '4312 Abbey Road', 22), ('John', '54 Love Ave', 21)])
|
import cmath
a=float(input("Enter first side of triangle: "))
b=float(input("Enter second side of triangle: "))
c=float(input("Enter third side of triangle: "))
s=(a+b+c)/2;
Area=cmath.sqrt(s*(s-a)*(s-b)*(s-c))
print(Area)
|
import numpy as np
import matplotlib.pyplot as plt
def computeCost(X, y, theta):
m = y.size
J = 0.0
h = X.dot(theta)
J = np.sum(np.square(h-y))/(2*m)
return J
def gradientDescent(X, y, theta, alpha, iterations):
m = y.size
J_history = np.zeros((iterations, 1))
for iter in range(iterations): # repeat for all iterations
h = X.dot(theta)
theta = theta - (alpha*X.T.dot(h-y))/m
J_history[iter] = computeCost(X, y, theta)
return theta, J_history
## ======================= Part 2: Plotting =======================
print('Plotting Data ...\n')
data = np.loadtxt('ex1data1.txt', dtype=float, delimiter=',')
X = data[:, [0]]
y = data[:, [1]]
m = data.shape[0] # number of training examples
# Plot Data
plt.plot(X, y, 'rx')
plt.title('MarkerSize')
plt.ylabel('Profit in $10,000s')
plt.xlabel('Population of City in 10,000s')
plt.show()
## =================== Part 3: Gradient descent ===================
print('Running Gradient Descent ...')
X = np.c_[np.ones(m), X] # Add a column of ones to x
theta = np.zeros((2, 1)) # initialize fitting parameters
# Some gradient descent settings
iterations = 1500
alpha = 0.01
# compute and display initial cost
print(computeCost(X, y, theta))
# run gradient descent
theta, J_history = gradientDescent(X, y, theta, alpha, iterations)
# print theta to screen
print('Theta found by gradient descent: ',theta[0], theta[1])
# plot the histrory of J value
plt.plot(J_history)
plt.show()
# plot result
plt.title('MarkerSize')
plt.ylabel('Profit in $10,000s')
plt.xlabel('Population of City in 10,000s')
plt.plot(X[:, 1], y, 'rx')
plt.plot(X[:, 1], X.dot(theta))
plt.show()
# Predict values for population sizes of 35,000 and 70,000
# predict1 = np.array([1,3.5]).dot(theta)
predict1 = theta.T.dot([1,3.5])
print('For population = 35,000, we predict a profit of', predict1*10000)
# predict2 = np.array([1, 7]).dot(theta)
predict2 = theta.T.dot([1,7])
print('For population = 70,000, we predict a profit of ', predict2*10000)
## ============= Part 4: Visualizing J(theta_0, theta_1) =============
print('Visualizing J(theta_0, theta_1) ...')
|
n = input("¿Como te llamas:? ")
print(len(n), "letras")
#OK Otra forma mas fea
a = 0
for i in n:
a = a + 1
print(str(a) + " letras")
|
##OutputSymbols
#def output_symbols():
hours = int(input("hours: "))
total = 21 * hours
print("£{0}".format(total))
|
##Function ?Improvement Exercise
##Times-table Tester
import random
print("Times-table tester")
print()
#Getting the times tables to be tested on
def get_questions():
timesTable = input("Which times-table do you want to be tested on? ")
timesTable = int(timesTable)
return timesTable
#It the inout correct
def verdict(userAnswer, answer):
if UserAnswer == answer:
print('Well done, you got the correct answer!')
print()
else:
print('Sorry, you got the answer wrong. The correct answer is',Ans)
print()
#Generating Questions
def questions(timesTable):
for question in range(1,16):
num1 = get_questions(timesTable)
num2 = random.randrange(2,13)
answer = num1 * num2
userAnswer = input(str(num1) + 'x' + str(num2) + " = ")
userAnswer = int(userAnswer)
verdict(userAnswer,answer)
#Main
timesTable = get_questions(timesTable)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
import math
# Compute the mean.
def findMean(n, arr):
sumNum = 0
for i in arr:
sumNum += i
mean = sumNum/n
return mean
#compute the median
def findMedian(n, arr):
arr.sort()
median = (arr[n//2]*0.5+arr[(n-1)//2]*0.5)
return median
#compute the mode
def findMode(n, arr):
minOcc = 1;
minMode = arr[0];
what = dict(Counter(arr))
#iterate through keys
for i in what:
curVal = i;
#look at value of dict (occurrences) of current key
curOcc = what.get(i)
if(curOcc >= minOcc and curVal < minMode):
minOcc = curOcc
minMode = curVal
return minMode
#compute the standard deviation
def findStandDev(n,arr, mean):
sumDev = 0
for i in arr:
sumDev += (i - mean)**2
stnDev = math.sqrt(sumDev/n)
return stnDev
#compute the confidence intervals to 95%
def findConfInter(n, arr, mean, sdev):
conf1 = mean+1.96*sdev/math.sqrt(n)
conf2 = mean-1.96*sdev/math.sqrt(n)
return (conf1, conf2)
#type cast inputs
input1 = int(input())
input2 = input()
input2 = [int(i) for i in input2.split()]
#invoke functions
mean = findMean(input1, input2)
median = findMedian(input1, input2)
mode = findMode(input1, input2)
sdev = findStandDev(input1,input2,mean)
confs = findConfInter(input1, input2, mean, sdev)
conf1 = confs[1]
conf2 = confs[0]
print(mean)
print(median)
print(mode)
print("{:.1f}".format(sdev))
print("{:.1f}".format(conf2), " ", "{:.1f}".format(conf1))
|
# coding=UTF-8
# 创建文件,并写入文件
import urllib
#
# f = open("t.txt", "w")
# f.write("写入t.txt")
# f.close()
#
# # 读取文件
# f = open("t.txt", "r")
# str = f.read()
# print str
#
# # python 异常处理
# try:
# x = int(input("Please enter a number: "))
# except (NameError, ValueError) as err:
# print("Oops! That was no valid number. Try again ")
#
# # 抛出异常 raise
# raise NameError('HiThere')
#
# class Text:
# publict = ''
# __ss__ = ""
# def text(self):
#
# return
#
# def text2(self):
# # 异常处理
# try:
# print ''
# except:
# print ''
# return
#
#
#
# if __name__ == '__main__':
# # or 表达式使用,以及 and
# if True or True:
# # 除完之后还是整数
# # print 10 // 3
# # hashmap = {'1': '1', '2': '2'}
# # array = ['1', '2', '3']
# # print array
# # print hashmap
# # print 'ok'
# # abs 函数
# print abs(-1)
# # max函数
# print max(1,2)
# # min 函数
# print min(2,3)
# # 转换成字符串
# str(1)
# # 转换成int
# int('2')
# # 转换成bool
# bool(
#
# )
# float()
from Tkinter import Image
from PIL import Image, ImageFilter
with Image.open('aaa.jpg') as image:
w,h = image.size
image.filter(ImageFilter.BLUR).save('aa.jpg', 'jpeg')
|
from graphics import *
from math import sqrt
from random import random
from time import clock
import sys
#Global variables
''' Dictionaries sharing the same key, to make them easily serviceable. '''
#B pls
ACTIVE = {"REFLECT":False,"SPEED":False,"DOUBLE-POINTS":False,"MAGNET":False,"REVERSE":False}
TIMER_DEFAULTS = {"REFLECT":10,"SPEED":15,"DOUBLE-POINTS":20,"MAGNET":10,"REVERSE":10}
ACTIVE_TIMES = {"REFLECT":0,"SPEED":0,"DOUBLE-POINTS":0,"MAGNET":0,"REVERSE":0}
ACTIVE_TEXT_OBJECTS = {"REFLECT":None,"SPEED":None,"DOUBLE-POINTS":None,"MAGNET":None,"REVERSE":None}
HIGH_SCORES_FILE = "hs.txt"
DEBUGGING = False
'''
Apple types:
REFLECT:GREEN
SPEED:ORANGE
DOUBLE_POINTS:BLUE
EXPLOSIVE:BLACK
MAGNET:PURPLE
REVERSE:YELLOW
'''
HIGH_SCORES = []
HIGH_SCORES_NAMES = []
##To do, add one more buff then draw the buff icon 3 on each ide of the screen
def main(win,name=None,menuDone=False):
''' Main program function. '''
#clear array so no values are left when creating a new game
HIGH_SCORES_NAMES.clear()
HIGH_SCORES.clear()
if(name==None):
name = getName(win)
#load scores into memory
loadHighScores()
#main loop
while menuDone == False:
menuDone = drawMenu(win)
else:
Score = 0
numberOfApples = 8
android, apples, scoreDisplay = drawScene(numberOfApples, Score,win)
#playGame returns whether a certain player wishes to play again
again = playGame(win, android, apples, scoreDisplay, name)
#If yes, start again with this name, else start again ith new name(has option to exit)
if(again==True):
main(win,name,True)
elif(again==False):
main(win)
def getName(win):
''' returns the name of the player currently playing, also gives the option to exit game. '''
print("Going to getNameState.")
valid = False
enterName = generateMessage("Enter Name and click the screen once entered",0.5,0.8)
exitButton = generateMessage("EXIT",0.85,0.05,"red")
exitButton.draw(win)
get = Entry(Point(0.5,0.45),10)
get.draw(win)
enterName.draw(win)
while valid ==False:
clicks = win.getMouse()
if(clicks.x >= 0.8 and clicks.x <= 0.9 and clicks.y >= 0 and clicks.y <= 0.1):
win.close()
sys.exit()
else:
name = get.getText()
if(len(name)>0):
break
get.undraw()
enterName.undraw()
exitButton.undraw()
return name
def drawScene(numberOfApples, Score,win):
''' Sets up playState Scene, incluing drawing player, score display and starting apples. '''
android = drawAndroid(win)
apples = drawApples(win, numberOfApples)
string = "Score: "+str(Score)
scoreDisplay = Text(Point(0.5, 0.95), string)
scoreDisplay.setSize(20)
scoreDisplay.setFill("brown")
scoreDisplay.setStyle("bold")
scoreDisplay.setFace("arial")
scoreDisplay.draw(win)
return android, apples, scoreDisplay
def drawAndroid(win):
''' Generates and draws player(android). '''
head = Circle(Point(0.5, 0.50), 0.03)
magnetCircle = Circle(Point(0.50,0.5),0.15)
body = Rectangle(Point(0.47, 0.45), Point(0.53, 0.5))
leg1 = Rectangle(Point(0.48, 0.42), Point(0.49, 0.45))
leg2 = Rectangle(Point(0.52, 0.42), Point(0.51, 0.45))
arm1 = Rectangle(Point(0.53, 0.46), Point(0.54, 0.5))
arm2 = Rectangle(Point(0.46, 0.46), Point(0.47, 0.5))
eye1 = Circle(Point(0.49, 0.51), 0.005)
eye2 = Circle(Point(0.51, 0.51), 0.005)
android = [head, body, leg1, leg2, arm1, arm2, eye1, eye2,magnetCircle]
for part in android:
if part == eye1 or part == eye2:
colour = "white"
else:
colour = "green"
if(part == magnetCircle):
part.setOutline(colour)
continue
part.setFill(colour)
part.setOutline(colour)
part.draw(win)
return android
def drawApples(win, numApples):
''' Generates the starting apples. '''
apples = []
for i in range(numApples):
x = random()
y = random()
apple = Circle(Point(x, y), 0.02)
apple.setFill("red")
apple.setOutline("red")
apple.draw(win)
apples.append(apple)
return apples
def addApple(win,colour):
''' Adds a apple to the scene with a specific colour. '''
x = random()
y = random()
apple = Circle(Point(x, y), 0.02)
apple.setFill(colour)
apple.setOutline(colour)
apple.draw(win)
return apple
def playGame(win, android, apples, scoreDisplay, name):
''' Main game function, handles the game state, including ACTIVE buffs and Scores.
Return boolean base on if the player is playing again. '''
Score = 0
speedX = 0
speedY = 0
speedChange = 0.00003
retardation = 0.00000001
Max_Apples = 8
lost = False
print("Going to playState.")
while not lost:
# move android
for part in android:
part.move(speedX, speedY)
centre = android[0].getCenter()
currentTime = int(clock())
#handles buffs and debuffs
for key in ACTIVE_TIMES:
difference = (currentTime - ACTIVE_TIMES[key])
#Five Seconds left checker
if difference > (TIMER_DEFAULTS[key] - 5) and ACTIVE[key]==True:
#Sanity check
if(ACTIVE_TEXT_OBJECTS[key]!=None):
ACTIVE_TEXT_OBJECTS[key].setFill("red")
#50% left checker
if difference > (TIMER_DEFAULTS[key] - TIMER_DEFAULTS[key]/2) and not difference > (TIMER_DEFAULTS[key] - 5) and ACTIVE[key]==True:
#Sanity check
if(ACTIVE_TEXT_OBJECTS[key]!=None):
ACTIVE_TEXT_OBJECTS[key].setFill("orange")
#Generate and draw Active Text Object
if ACTIVE[key] and ACTIVE_TEXT_OBJECTS[key]==None:
if(key=="REFLECT"):
ACTIVE_TEXT_OBJECTS[key] = generateMessage(key,0.1,0.95)
elif(key=="SPEED"):
ACTIVE_TEXT_OBJECTS[key] = generateMessage(key,0.1,0.9)
elif(key=="DOUBLE-POINTS"):
print("Double Points")
ACTIVE_TEXT_OBJECTS[key] = generateMessage(key,0.15,0.85)
elif(key=="MAGNET"):
ACTIVE_TEXT_OBJECTS[key] = generateMessage(key,0.10,0.80)
elif(key=="REVERSE"):
ACTIVE_TEXT_OBJECTS[key] = generateMessage(key,0.10,0.75)
ACTIVE_TEXT_OBJECTS[key].draw(win)
#Active has finished.
if difference > TIMER_DEFAULTS[key] and ACTIVE[key]==True:
ACTIVE[key] = False
ACTIVE_TEXT_OBJECTS[key].undraw()
ACTIVE_TEXT_OBJECTS[key] = None
if(key=="MAGNET"):
#specific case for efficiency in otherwise we have to try and undraw every time when checking for apples
android[len(android)-1].undraw()
print(key, " bonus has ended!")
# Keep time updated on object that aren't active.
if ACTIVE[key]==False:
ACTIVE_TIMES[key] = currentTime
if(ACTIVE["SPEED"]):
speedChange = 0.00009
retardation = 0.0000001
else:
speedChange = 0.00003
retardation = 0.00000001
if(ACTIVE["DOUBLE-POINTS"]):
multiplyer = 20
else:
multiplyer = 10
# handle speed change
point = win.checkMouse()
if point != None:
if(ACTIVE["REVERSE"]):
if point.getX() < 0.3:
speedX = speedX + speedChange
elif point.getX() > 0.7:
speedX = speedX - speedChange
if point.getY() < 0.3:
speedY = speedY + speedChange
elif point.getY() > 0.7:
speedY = speedY - speedChange
else:
if point.getX() < 0.3:
speedX = speedX - speedChange
elif point.getX() > 0.7:
speedX = speedX + speedChange
if point.getY() < 0.3:
speedY = speedY - speedChange
elif point.getY() > 0.7:
speedY = speedY + speedChange
#handle retardation (drag/slowing down)
if(speedX!=0):
if (speedX > 0):
speedX = speedX - retardation
elif(speedX < 0):
speedX = speedX + retardation
if(speedY!=0):
if(speedY > 0):
speed = speedY - retardation
elif(speedY < 0):
speed = speedY + retardation
if(ACTIVE["REFLECT"]):
#Bounce of the walls (Invincibility)
reflectX = sqrt((speedX*speedX))*1.3
reflectY = sqrt((speedY*speedY))*1.3
if(centre.x > 1):
speedX = speedX - reflectX
elif(centre.x < 0):
speedX = speedX + reflectX
if(centre.y > 1):
speedY = speedY - reflectY
elif(centre.y < 0):
speedY = speedY + reflectY
else:
# have we hit an edge
if centre.getX() < 0 or centre.getX() > 1 or \
centre.getY() < 0 or centre.getY() > 1:
lost = True
# have we hit an apple?
for apple in apples:
appleCentre = apple.getCenter()
if(ACTIVE["MAGNET"]):
grabDistance = 0.15
else:
grabDistance = 0.05
if distanceBetweenPoints(appleCentre, centre) < grabDistance:
#Colour check to see if its bonus apple to add buffs
if(apple.config["fill"]=="green"):
ACTIVE["REFLECT"] = True
print("REFLECT Bonus has Started!")
elif(apple.config["fill"]=="orange"):
ACTIVE["SPEED"] = True
print("SPEED Bonus has Started!")
elif(apple.config["fill"]=="blue"):
ACTIVE["DOUBLE-POINTS"]=True
print("DOUBLE-POINTS Bonus has Started!")
elif(apple.config["fill"]=="purple"):
#draw effect for the android
try:
android[len(android)-1].draw(win)
except Exception:
pass
ACTIVE["MAGNET"] = True
print("MAGNET Bonus has started!")
elif(apple.config["fill"]=="yellow"):
ACTIVE["REVERSE"] = True
print("REVERSE de-buff started!")
elif(apple.config["fill"]=="black"):
#handle explosion
speedX *= -1
speedY *= -1
apple.undraw()
apples.remove(apple)
Score += 5 * multiplyer
# random bonus apples
if len(apples) < Max_Apples:# max apples on screen should be 8
apples.append(spawnBonusApple(win))
scoreDisplay.setText("Score: "+(str(Score)))
message = Text(Point(0.5, 0.5), "")
message.setSize(20)
message.setFace("arial")
message.setFill("brown")
message.setStyle("bold")
message.setText("Game over! Your Score was: "+str(Score))
print("Score : ",Score)
message.draw(win)
#finally save Score.
wasHighScore = saveHighScore(Score,name)
newHS = None
if(wasHighScore):
newHS = generateMessage("New High Score! Well Done!",0.5,0.3,"brown",28)
newHS.draw(win)
win.getMouse()
#clean up for next game.
for part in android:
part.undraw()
for apple in apples:
apple.undraw()
for key in ACTIVE_TEXT_OBJECTS:
if(ACTIVE_TEXT_OBJECTS[key]!=None):
ACTIVE_TEXT_OBJECTS[key].undraw()
ACTIVE_TEXT_OBJECTS[key] = None
#reset buffs
if(ACTIVE[key]):
ACTIVE[key] = False
if(newHS!=None):
newHS.undraw()
scoreDisplay.undraw()
message.undraw()
#Ask player if they want to play again.
playAgain = None
while playAgain == None:
playAgain = retry(win)
if(playAgain==True):
return True
elif(playAgain==False):
return False
def retry(win):
''' Scene for asking player if they want to play again. '''
print("Going to retryState.")
myObjects = []
myObjects.append(generateMessage("Play again?",0.5,0.8,"red",36))
myObjects.append(generateMessage("Yes",0.25,0.5))
myObjects.append(generateMessage("No",0.75,0.5))
for obj in myObjects:
obj.draw(win)
gotAnswer = False
while gotAnswer == False:
#check clicks
clicks = win.getMouse()
if(clicks.x >= 0.2 and clicks.x <= 0.3 and clicks.y >= 0.45 and clicks.y <= 0.55):
#cleanUp
for obj in myObjects:
obj.undraw()
gotAnswer = True
return True
if(clicks.x >= 0.7 and clicks.x <= 0.8 and clicks.y >= 0.45 and clicks.y <= 0.55):
#cleanUp
for obj in myObjects:
obj.undraw()
gotAnswer = True
return False
def spawnBonusApple(win):
''' Randomly generates apples, with a chance to spawn bonus apples. '''
colour = ""
if(DEBUGGING==False):
random1 = random()
if(random1 <= 0.03):
colour = "orange" #Speed Bonus
elif(random1 <= 0.06 and random1 >=0.03):
colour = "green" #Reflect Bonus
elif(random1 <= 0.09 and random1 >=0.06):
colour = "blue" #DOUBLE-POINTS
elif(random1 <= 0.12 and random1 >=0.09):
colour = "black" #Explosive apple
elif(random1 <= 0.15 and random1 >=0.12):
colour = "purple" #Magnet apple
elif(random1 <= 0.18 and random1 >=0.15):
colour = "yellow" #Reverse controls apple
else:
colour="red"
elif(DEBUGGING==True):
random1 = random()
if(random1 <= 0.15):
colour = "orange" #Speed Bonus
elif(random1 <= 0.30 and random1 >=0.15):
colour = "green" #Reflect Bonus
elif(random1 <= 0.45 and random1 >=0.30):
colour = "blue" #DOUBLE-POINTS
elif(random1 <= 0.60 and random1 >=0.45):
colour = "black" #Explosive apple
elif(random1 <= 0.75 and random1 >=0.60):
colour = "purple" #Magnet apple
elif(random1 <= 0.90 and random1 >=0.75):
colour = "yellow" #Reverse controls apple
else:
colour="red"
#print("Adding {0} apple.".format(colour))
return addApple(win,colour)
def distanceBetweenPoints(p1, p2):
''' Returns the distance between two points. '''
return sqrt((p1.getX() - p2.getX()) ** 2 +
(p1.getY() - p2.getY()) ** 2)
def generateMessage(text,x,y,colour="green",size=None):
''' Generates a Text Object, Required parameters are Text, x and y.
Other parameters are optional and have defaults in place '''
message = Text(Point(x,y),text)
if(size!=None):
message.setSize(size)
message.setFace("arial")
message.setStyle("bold")
message.setFill(colour)
return message
def loadHighScores():
''' Loads high scores in from HIGH_SCORES_FILE into memory for viewing and manipulation. '''
try:
highScoreFile = open(HIGH_SCORES_FILE,"r")
except Exception:
print("No Hs file found, creating one now.")
highScoreFile = open(HIGH_SCORES_FILE,"w")
time.sleep(0.2)
highScoreFile = open(HIGH_SCORES_FILE,"r")
lines = highScoreFile.readlines()
if(len(lines) > 0):
for line in lines:
vars = line.strip("\n").split(",")
HIGH_SCORES.append(int(vars[1]))
HIGH_SCORES_NAMES.append(vars[0])
print("Loaded scores from HIGH_SCORES_FILE")
else:
print("No Scores Found")
highScoreFile.close()
#Sorts whilst in the main menu to reduce processing time at the end of the game.
sortScores()
def saveHighScore(Score,Name):
''' Saves the high scores in a csv type format, then returns if the score entered was a high score or not.
Returns high score even if it wasn't the highest score, as long as it made it to the score board.
Each line writing contains a carriage return at the end which must be stripped then loading the file.
Example line in file: 'Joe,150'
'''
newHiScore = False
#check if new HS
try:
#blank the file
open(HIGH_SCORES_FILE, 'w').close()
time.sleep(0.5)
file = open(HIGH_SCORES_FILE,"w")
except Exception:
print("No HS File")
#Sort the scores so we only have to check the lowest score to see if can be added
sortScores()
#Make sure there are high scores to compare, if not just write this new score to the file
if(len(HIGH_SCORES) > 0):
#check if its a high score
#check highest score, or check lowest score?
#I chose lowest high score, as it will get replaced if its not a good enough high score
if(HIGH_SCORES[0] < Score):
#remove last score if max scores is reached
print("New High Score!")
newHiScore = True
if(len(HIGH_SCORES) >= 10):
HIGH_SCORES.pop(0)
HIGH_SCORES_NAMES.pop(0)
#add new score
HIGH_SCORES.append(Score)
HIGH_SCORES_NAMES.append(Name)
else:
# No scores found in file, must write this one proving it is greater than 0
if(Score > 0):
newHiScore = True
file.write(Name+","+str(Score))
#Write the scores in memory, back into the file.
for j in range(len(HIGH_SCORES)):
string = HIGH_SCORES_NAMES[j]+","+str(HIGH_SCORES[j])+"\n"
file.write(string)
file.close()
print("Saved scores to HIGH_SCORES_FILE successfully.")
return newHiScore
def drawMenu(win):
''' Main menu function, return true when the game is ready to play. '''
print("Going to menuState.")
x = 0.5
myObjects = []
myObjects.append(generateMessage("Play!",x,0.55))
myObjects.append(generateMessage("Apples!",x,0.75,"red",28))
myObjects.append(generateMessage("HighScores",x,0.45))
myObjects.append(generateMessage("Exit",x,0.35))
done= False
while done == False:
for text in myObjects:
try:
text.draw(win)
except GraphicsError:
pass
clicks = win.getMouse()
if(clicks.x >= (x - 0.5) and clicks.x < (x + 0.7) and clicks.y >= 0.50 and clicks.y <= 0.6):
done = True
for text in myObjects:
text.undraw()
return True
elif(clicks.x >= (x-0.5) and clicks.x < (x + 0.7) and clicks.y >= 0.40 and clicks.y <= 0.5):
for text in myObjects:
text.undraw()
highScoresDone = False
print("Going to highScoreState.")
while highScoresDone == False:
highScoresDone = showHighScore(win)
elif(clicks.x >= (x-0.5) and clicks.x < (x + 0.7) and clicks.y >= 0.30 and clicks.y <= 0.4):
win.close()
sys.exit()
def sortScores():
''' Simple bubble sort to arrange the scores in ascending order. '''
for passnum in range(len(HIGH_SCORES)-1,0,-1):
for i in range(passnum):
if HIGH_SCORES[i]>HIGH_SCORES[i+1]:
temp = HIGH_SCORES[i]
tempName = HIGH_SCORES_NAMES[i]
HIGH_SCORES[i] = HIGH_SCORES[i+1]
HIGH_SCORES_NAMES[i] = HIGH_SCORES_NAMES[i+1]
HIGH_SCORES[i+1] = temp
HIGH_SCORES_NAMES[i+1] = tempName
def showHighScore(win):
''' Scene to display the scores in a numbered format from high to low, that is easy to read. '''
myObjects = []
gap = 0.05
x = 0.45
y = 0.8
tableName = generateMessage("Name : Score",x,y+0.05,"red")
tableName.draw(win)
for i in range(len(HIGH_SCORES)-1,-1,-1):
y -= gap
string = "{0}. {1} : {2}".format((len(HIGH_SCORES)-i),HIGH_SCORES_NAMES[i],HIGH_SCORES[i])
scorePrint = generateMessage(string,x,y)
scorePrint.draw(win)
myObjects.append(scorePrint)
win.getMouse()
tableName.undraw()
#Clean up scene
for obj in myObjects:
obj.undraw()
return True
if __name__=="__main__":
#Create the graphWin object and pass it into the main function
win = GraphWin("Android Game - Scott Mabin - UP745497", 500, 500)
win.setCoords(0,0,1,1)
main(win)
|
print('hello world')
x = 5
y = 3
if x < y:
print(f"'x' is the winner: {x}")
else:
print(f"'y' is the winner: {y}")
|
import numpy as np
import matplotlib.pyplot as plt
Notes = '''
nth order Taylor method (n = 2, 3, 4, 5):
Function Name: Taylor
Inputs: y0: Initial condition
h = step size
a: starting Time
b: ending Time
plot: Binary input
Default plot = 0: No plotting
plot = 1: plots the solution
F = f (the defining function y' = f(t, y))
Fpr = derivative of f
F2pr = second derivative of f
F3pr = third derivative of f
F4pr = fourth derivative of f
Specify only to requirement.
-------Example 1:
Suppose we want to use 2nd order Taylor. Then define
functions f and f' then call function as follows
def Taylor(y0, h, a, b, plot = 0, F=f, Fpr=f'):
-------Example 2:
Suppose we want to use 3rd order Taylor. Then define
functions f, f' and f'' then call function as follows
def Taylor(y0, h, a, b, plot = 0, F=f, Fpr=f', F2pr = f''):
Output: [t, y] where
y: solution array
t: time array
'''
def temp_func(t, y):
return 0
#Computing T^(n)
def T_n(t, y, h, F, Fpr, F2pr, F3pr, F4pr):
if(F==0):
F = temp_func
if(Fpr==0):
Fpr = temp_func
if(F2pr==0):
F2pr = temp_func
if(F3pr==0):
F3pr = temp_func
if(F4pr==0):
F4pr = temp_func
return F(t, y)+(h/2)*(Fpr(t,y))+(h**2/6)*(F2pr(t,y))+(h**3/24)*(F3pr(t,y)) + (h**4/120)*(F4pr(t, y))
def Taylor(y0, h, a, b, plot = 0, F=0, Fpr=0, F2pr=0, F3pr=0, F4pr=0):
t = [a]
y = [y0]
N = int((b-a)/h)
for i in range(N):
y.append(y[-1] + h*(T_n(t[-1], y[-1], h, F, Fpr, F2pr, F3pr, F4pr)))
t.append(t[-1] + h)
if(plot == 1):
plt.plot(t, y, label = 'solution')
plt.legend()
plt.show()
return [t, y]
|
#Ejercicio 8
num = (int(input('Ingrese numero ')))
if num >= 0:
if str(num) == str(num)[::-1]:
print('%i es capicua' % num)
else:
print('%i no es capicua' % num)
|
#Ejercicio 16 Realizar un programa que cuente los numeros pares entre el 1 y un numero ingresado por el usuario
num = int(input('Intruzca un numero y se le dira cuales son y cuantos numeros pares son los que hay entre 1 y el numero ingresado '))
print (f'Numero ingresado: {num}')
def numPar (lista):
pares =[]
for n in lista:
if n % 2 == 0:
pares.append(n)
return pares
listpar = numPar ((list(range(1+1,num))))
(list(range(1+1, num)))
print (f'Los numeros pares entre 1 y {num} son: {listpar} ')
print ('Total de numeros pares entre estos son: ',(len(listpar)))
|
"""
Graphical version of battleship game
@author: Eetu Karvonen
Game uses 'pyglet' -library to draw game window and to handle mouse clicks
Main game logic is in 'on_mouse_press()' -function. Global variable 'state' holds the state of the game.
'game.py' -library handles boards
"""
import pyglet
import random
import game
import ai
WIN_WITH = 900
WIN_HEIGHT = 500
win = pyglet.window.Window(WIN_WITH, WIN_HEIGHT, resizable=False)
pics = {}
state = {
"state": 0, # 0=place ship horizontally, 1=place ship vertically, 2=player turn, 3=computer turn, 4=game over
"ship": 1, # 1=first ship, 2=second ship ... used to place ships
"ai": None
}
def load_pics(path):
pyglet.resource.path = [path]
pics["miss"] = pyglet.resource.image("square_red.png")
pics["hit"] = pyglet.resource.image("square_green.png")
pics["empty"] = pyglet.resource.image("square_back.png")
pics["ship"] = pyglet.resource.image("square_x.png")
pics["rotate"] = pyglet.resource.image("rotate.png")
pics["new"] = pyglet.resource.image("new_game.png")
def write_text(text, x, y):
label = pyglet.text.Label(text,
font_name='Times New Roman',
font_size=18,
x=x, y=y,)
label.draw()
def draw_squares(boardP, boardC_show):
batch = pyglet.graphics.Batch()
sprites = []
for j, row in enumerate(boardP):
for i, square in enumerate(row):
if square == ' ':
x = i * 40
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["empty"], x, y, batch=batch))
elif square == '$':
x = i * 40
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["hit"], x, y, batch=batch))
elif square == '*':
x = i * 40
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["miss"], x, y, batch=batch))
else:
x = i * 40
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["ship"], x, y, batch=batch))
for j, row in enumerate(boardC_show):
for i, square in enumerate(row):
if square == ' ':
x = i * 40 + 450
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["empty"], x, y, batch=batch))
elif square == '$':
x = i * 40 + 450
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["hit"], x, y, batch=batch))
elif square == '*':
x = i * 40 + 450
y = (WIN_HEIGHT -140) - j * 40
sprites.append(pyglet.sprite.Sprite(pics["miss"], x, y, batch=batch))
batch.draw()
sprites.clear()
def draw_message():
if state["state"] == 1:
text = "Place your ship vertically"
write_text(text, 0, 450)
rotate = pyglet.sprite.Sprite(pics["rotate"], x=280, y=410)
rotate.draw()
elif state["state"] == 0:
text = "Place your ship horizontally"
write_text(text, 0, 450)
rotate = pyglet.sprite.Sprite(pics["rotate"], x=280, y=410)
rotate.draw()
else:
text = game.game["player_last"]
write_text(text, 450, 450)
text2 = game.game["com_last"]
write_text(text2, 0, 450)
if state["state"] == 4:
rotate = pyglet.sprite.Sprite(pics["new"], x=280, y=410)
rotate.draw()
def click_place_ship(x,y):
height = 10
x_fixed = x // 40
y_fixed = height - y // 40 -1
if state["ship"] == 1:
size = 2
orient = state["state"]
if game.validate_placement(x_fixed, y_fixed, orient, size, game.game["boards"]["boardP"]):
game.place_ship(x_fixed, y_fixed, orient, 'a', game.game["boards"]["boardP"])
state["ship"] = 2
elif state["ship"] == 2:
size = 3
orient = state["state"]
if game.validate_placement(x_fixed, y_fixed, orient, size, game.game["boards"]["boardP"]):
game.place_ship(x_fixed, y_fixed, orient, 'b', game.game["boards"]["boardP"])
state["ship"] = 3
elif state["ship"] == 3:
size = 3
orient = state["state"]
if game.validate_placement(x_fixed, y_fixed, orient, size, game.game["boards"]["boardP"]):
game.place_ship(x_fixed, y_fixed, orient, 'c', game.game["boards"]["boardP"])
state["ship"] = 4
elif state["ship"] == 4:
size = 4
orient = state["state"]
if game.validate_placement(x_fixed, y_fixed, orient, size, game.game["boards"]["boardP"]):
game.place_ship(x_fixed, y_fixed, orient, 'd', game.game["boards"]["boardP"])
state["ship"] = 5
elif state["ship"] == 5:
size = 5
orient = state["state"]
if game.validate_placement(x_fixed, y_fixed, orient, size, game.game["boards"]["boardP"]):
game.place_ship(x_fixed, y_fixed, orient, 'e', game.game["boards"]["boardP"])
state["state"] = random.randint(2,3) # Randomly choose player or computer start
def click_fire(x,y,board):
height = 10
x_fixed = (x - 450) // 40
y_fixed = height - y // 40 -1
response = game.make_move(board, x_fixed, y_fixed)
if response == 'miss':
state["state"] = 3
board[y_fixed][x_fixed] = '*'
game.game["boards"]["boardC_show"][y_fixed][x_fixed] = '*'
game.game["player_last"] = "Missed"
elif response == 'hit':
state["state"] = 3
if game.check_sunk(board, x_fixed, y_fixed, "computer_ships"):
game.game["player_last"] = "Hit and sunk"
else:
game.game["player_last"] = "Hit"
board[y_fixed][x_fixed] = '$'
game.game["boards"]["boardC_show"][y_fixed][x_fixed] = '$'
def rotate_click(x,y):
if x > 280 and y > 410 and x < 430 and y < 470:
return True
return False
def board_click(x,y):
if x > 0 and y > 0 and x < 400 and y < 400:
return True
return False
def radar_click(x,y):
if x > 450 and y > 0 and x < 850 and y < 400:
return True
return False
def player_won():
# Returns true or false
sum = 0
for ship in game.game["computer_ships"]:
sum += game.game["computer_ships"][ship]
if sum == 0:
return True
sum = 0
for ship in game.game["player_ships"]:
sum += game.game["player_ships"][ship]
if sum == 0:
return False
def new_game():
game.game["boards"]["boardP"] = game.create_board()
game.game["boards"]["boardC"] = game.create_board()
game.game["boards"]["boardC_show"] = game.create_board()
game.game["player_last"] = "Game on"
game.game["com_last"] = ""
game.game["player_ships"]["a"] = 2
game.game["player_ships"]["b"] = 3
game.game["player_ships"]["c"] = 3
game.game["player_ships"]["d"] = 4
game.game["player_ships"]["e"] = 5
game.game["computer_ships"]["a"] = 2
game.game["computer_ships"]["b"] = 3
game.game["computer_ships"]["c"] = 3
game.game["computer_ships"]["d"] = 4
game.game["computer_ships"]["e"] = 5
game.ai_place_ships()
state["ai"] = ai.Ai()
state["ship"] = 1
state["state"] = 0
@win.event
def on_mouse_press(x, y, btn, modifiers):
if btn == pyglet.window.mouse.LEFT:
#print(x,y)
if state["state"] == 0:
if rotate_click(x, y):
state["state"] = 1
elif board_click(x,y):
click_place_ship(x, y)
elif state["state"] == 1:
if rotate_click(x, y):
state["state"] = 0
elif board_click(x,y):
click_place_ship(x, y)
elif state["state"] == 2:
if radar_click(x, y):
click_fire(x, y, game.game["boards"]["boardC"])
if state["state"] == 3 and game.game_on():
state["ai"] = game.computer_guess(game.game["boards"]["boardP"], state["ai"])
if game.game_on():
state["state"] = 2
if state["state"] == 4 and rotate_click(x, y):
new_game()
if not game.game_on():
state["state"] = 4
if player_won():
game.game["player_last"] = "Game over, player won"
else:
game.game["player_last"] = "Game over, computer won"
@win.event
def on_draw():
win.clear()
write_text("Your board", 0,410)
write_text("Your radar", 450,410)
draw_message()
draw_squares(game.game["boards"]["boardP"], game.game["boards"]["boardC_show"])
if __name__ == "__main__":
load_pics("sprites")
new_game()
pyglet.app.run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.