text stringlengths 37 1.41M |
|---|
'''class user:
def __init__(self,name,mob_no,address=""):
self.name=name
self.mobile_no=mob_no
self.address=address'''
class BankAccount:
def __init__(self,name,ph_no):
self.name=name # accesing by using self .methods
self.phone_no=ph_no
#self.acc_no=acc_no
self.generate_acc_no()
self.balance=0
def generate_acc_no(self):
import uuid
self.account_no=str(uuid.uuid4())
def deposit(self,amount):
self.balance+=amount
def withdraw(self,amount):
if amount > self.balance:
print("Insufficient funds")
else:
self.balance-=amount
ac=BankAccount("jai","9999955555")
print(ac.name,ac.phone_no,ac.balance,ac.account_no)
#print(ac.generate_acc_no())
ac.deposit(100)
print(ac.balance)
ac.deposit(1000)
print(ac.balance)
ac.withdraw(500)
print(ac.balance)
ac.withdraw(800)
print(ac.balance)
|
#---------------------object instantiation-----------------
'''class Person:
pass
jai=Person()#INSTANTIATION
print(type(jai))
s=type(jai) == Person
print(s)'''
#-------------self description---------------------------
'''class Person:
def say_hello(self):
print("Hello")
print(self)
print(jai)
jai=Person()
#jai.say_hello()
jai.say_hello()
#methods are ment to be objects'''
#----------------------keyword arguments and positional arguments------------------------------
'''class Person:
def greet(self,name="ajay"):
return "Hello {}".format(name)
jai=Person()
greets=jai.greet("prakash")
print(greets)
s=jai.greet()
print(s)'''
#---------------special method init-method(no return value)----------------------------------
'''class Person:
def __init__(self):
print("hello")
jai=Person()'''
#-------------------------------------------------
'''class Person:
def __init__(self,name):
print("hello, Im {}!".format(name))
Person("jaiip")
p=Person("jaaa")
print(p)
#print(type(p))'''
#--------attributes of object-------------------------------------
'''class Person:
def __init__(self,full_name,last_name):
self.name=full_name
self.name1=last_name
p=Person("jaip","matam")
s=p.name
h=p.name1
print(s,h)'''
#----------------------any method we can access using self-------------------------
'''class Person:
def __init__(self,full_name):
self.name=full_name
def say_hello(self):
print("hello im {}!".format(self.name))
p=Person("jaip")
p.say_hello()'''
#---------------------------------------------
|
test_cases = int(input('Enter number of test cases : '))
for test_case in range(test_cases):
n = int(input())
answer = []
for i in range(n+1):
decimal = i
binary = '{0:b}'.format(decimal)
count = binary.count('1')
# print(str(i)+' = '+str(count))
answer.append(count)
print(answer)
|
import unittest
def find_repeat(arr):
start = 1
end = len(arr) - 1
while start < end:
mid = start + (end - start)//2
low_start, low_end = start, mid
high_start, high_end = mid + 1, end
actual_num = 0
expected_num = low_end - low_start + 1
for item in arr:
if low_start <= item <= low_end:
actual_num += 1
if actual_num > expected_num:
start, end = low_start, low_end
else:
start, end = high_start, high_end
return start
# Tests
class Test(unittest.TestCase):
def test_just_the_repeated_number(self):
actual = find_repeat([1, 1])
expected = 1
self.assertEqual(actual, expected)
def test_short_list(self):
actual = find_repeat([1, 2, 3, 2])
expected = 2
self.assertEqual(actual, expected)
def test_medium_list(self):
actual = find_repeat([1, 2, 5, 5, 5, 5])
expected = 5
self.assertEqual(actual, expected)
def test_long_list(self):
actual = find_repeat([4, 1, 4, 8, 3, 2, 7, 6, 5])
expected = 4
self.assertEqual(actual, expected)
unittest.main(verbosity=2) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
node = []
i=0
while i < len(l1):
node
print("in while")
i += 1
#print(node[0].val)
#print(node[0].next.val)
#print(node[0].next.next.val)
#print(l1[1])
#print(l1[2])
#print(node1.next)
#print(node2.val)
#print(node2.next)
#print(node3.val)
#print(node3.next)
print(Solution().addTwoNumbers([2,4,3],[5,6,4]))
#l1 = ListNode(0)
#l2 = ListNode(2)
#l3 = ListNode(4)
#l1.next = l2
#l2.next = l3
#
#la = ListNode(0)
#lb = ListNode(2)
#lc = ListNode(4)
#la.next = lb
#lb.next = lc
#print(Solution().addTwoNumbers(l1, la))
|
print("Multiplos de un numero en un rango dado (del 10 al 100)")
x=int(input("Ingrese un numero: "))
print("Los multiplos de " + str(x) + " dentro del rango de 10 al 100 son: ")
for i in range(10, 101):
if i % x == 0:
print(str(i)) |
from tkinter import *
import math
root = Tk()
root.title("Calulator")
root.iconbitmap('F:tutorial\calculator.ico')
root.geometry("315x302+785+301")
display = Text(root, width=40, height=2.5,padx=10, pady=15,background="#f4ffd4", foreground="#000000")
display.place(relx=0.032, rely=0.033, relheight=0.179, relwidth=0.933)
def Clear():
display.delete(0.0, END)
def click(value):
display.insert(END, value)
def Equal():
try:
ans = display.get(0.0, END)
display.delete(0.0, END)
display.insert(END, eval(ans))
except SyntaxError:
pass
def square():
try:
x = display.get(0.0, END)
display.delete(0.0, END)
ans = eval(x)
display.insert(END, ans*ans)
except SyntaxError:
pass
def square_root():
try:
x = display.get(0.0, END)
display.delete(0.0, END)
ans = math.sqrt(eval(x))
display.insert(END, ans)
except SyntaxError:
pass
def Delete():
d = display.get(0.0, END)
display.delete(0.0, END)
display.insert(END, d[:-2])
btn7 = Button(root, text="7", command=lambda: click(7)).place(relx=0.032, rely=0.265, height=34, width=57)
btn8 = Button(root, text="8", command=lambda: click(8)).place(relx=0.222, rely=0.265, height=34, width=57)
btn9 = Button(root, text="9", command=lambda: click(9)).place(relx=0.413, rely=0.265, height=34, width=57)
btn_mul = Button(root, text="x", command=lambda: click("*")).place(relx=0.603, rely=0.265, height=34, width=57)
btn_div = Button(root, text="/", command=lambda: click("/")).place(relx=0.794, rely=0.265, height=34, width=57)
btn4 = Button(root, text="4", command=lambda: click(4)).place(relx=0.032, rely=0.397, height=34, width=57)
btn5 = Button(root, text="5", command=lambda: click(5)).place(relx=0.222, rely=0.397, height=34, width=57)
btn6 = Button(root, text="6", command=lambda: click(6)).place(relx=0.413, rely=0.397, height=34, width=57)
btn_add = Button(root, text="+", command=lambda: click("+")).place(relx=0.603, rely=0.397, height=34, width=57)
btn_sub = Button(root, text="-", command=lambda: click("-")).place(relx=0.794, rely=0.397, height=34, width=57)
btn1 = Button(root, text="1", command=lambda: click(1)).place(relx=0.032, rely=0.53, height=34, width=57)
btn2 = Button(root, text="2", command=lambda: click(2)).place(relx=0.222, rely=0.53, height=34, width=57)
btn3 = Button(root, text="3", command=lambda: click(3)).place(relx=0.413, rely=0.53, height=34, width=57)
btn_root = Button(root, text="√", command=lambda: square_root()).place(relx=0.603, rely=0.53, height=34, width=57)
btn_square = Button(root, text="x²",command=lambda: square()).place(relx=0.794, rely=0.53, height=34, width=57)
btn_dot = Button(root, text=".", command=lambda: click(".")).place(relx=0.032, rely=0.662, height=34, width=57)
btn_zero = Button(root, text="0", command=lambda: click(0)).place(relx=0.222, rely=0.662, height=34, width=57)
btn_equal = Button(root, text="=", command=lambda: Equal()).place(relx=0.413, rely=0.662, height=34, width=57)
btn_Clear = Button(root, text="Clear", command= lambda:Clear()).place(relx=0.603, rely=0.662, height=34, width=57)
btn_delete = Button(root, text="\u232B", command= lambda: Delete()).place(relx=0.794, rely=0.662, height=34, width=57)
btn_Exit = Button(root, text="Exit", command=root.quit).place(relx=0.032, rely=0.820, height=40, width=297)
root.mainloop()
|
num = int(input("Enter the number: "))
def factorial(n):
a = 1
while n >= 1:
a = a * n
n = n - 1
return a
q = factorial(num)
print(q)
range |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 13:01:15 2021
@author: Sahil Patil
"""
def recursive_binary_search(list, target):
if len(list) == 0:
return False
else:
midpoint = (len(list))//2
if list[midpoint] == target:
return True
else:
if list[midpoint] < target:
return recursive_binary_search(list[midpoint + 1:], target)
else:
return recursive_binary_search(list[:midpoint], target)
def verify(result):
print("Target found: ", result)
numbers = [1,2,3,4,5,6,7,8,9,10]
result = recursive_binary_search(numbers, 8)
verify(result)
result = recursive_binary_search(numbers, 12)
verify(result)
|
import os,random
def set_init_cell_position():
for c in range(0,init_cell_number):
x,y=(random.randint(0,grid_rows-1),random.randint(0,grid_cols-1))
grid[x][y]=True
def display_grid():
global generation_counter
print 'Generation counter:',generation_counter
print
for r in range(0,grid_rows):
for c in range(0,grid_cols):
if grid[r][c]:
print 'o',
else:
print '.',
print
def get_neighbours(r,c):
for row in r-1,r,r+1:
if row in range(0,grid_rows):
for col in c-1,c,c+1:
if col in range(0,grid_cols) and not (col==c and row==r):
neighbours.append(grid[row][col])
evolution(r,c,neighbours)
def evolution(x,y,neighbours):
neighbour_counter=0
for i in range(0,len(neighbours)):
if neighbours[i]:
neighbour_counter+=1
if grid[x][y] and (neighbour_counter<2 or neighbour_counter>3):
grid[x][y]=False
elif not grid[x][y] and neighbour_counter==3:
grid[x][y]=True
grid_rows=20
grid_cols=20
grid=[[False] * grid_cols for r in range(0,grid_rows)]
init_cell_number=int(raw_input('Enter initial random cell number: '))
set_init_cell_position()
generation_counter=0
while True:
generation_counter+=1
for i in range(0,grid_rows):
for j in range(0,grid_cols):
neighbours=[]
get_neighbours(i,j)
os.system('clear')
display_grid() |
#Ugyen Dorji, udorji@uci.edu, 83628422
#------NAVIGATION CLASSES------
import MapQuestAPI
MQ=MapQuestAPI
class STEPS:
def calculate(result:dict)->str:
'''
Finds the directions by iterating through a series of nested dictionaries and lists
till it finds the needed information in this case maneuvers then narrative. Once the
values of the narratives are accessed it is printed
'''
x={'y': {}}
print('DIRECTIONS')
result=result['route']['legs']
for x in range(len(result)):
for y in result[x]:
if y=='maneuvers':
for z in range(len(result[x][y])):
for a in result[x][y][z]:
if a=='narrative':
print(result[x][y][z][a])
print()
class TOTALDISTANCE:
def calculate(result:dict)->int:
'''
Accesses the value of distance through the keys route and distance of the result
dictionary,which was created by the MQ.get_url function. Finally turns the value into
an integer, rounds to the nearest whole number and prints the resulting value.
'''
result=result['route']['distance']
result=round(int(result))
print('TOTAL DISTANCE: {} miles'.format(result))
print()
class TOTALTIME:
def calculate(result:dict):
'''
Accesses the value of time through the keys route and time of the result
dictionary. Turns the value into an integer, converts to minutes, rounds to the nearest whole number
and prints the resulting value.
'''
result=result['route']['time']
result=round(int(result)/60)
print('TOTAL TIME: {} minutes'.format(result))
print()
class LATLONG:
def calculate(result:dict):
'''
Accesses the value of locations through the keys route and locations of the result
dictionary. Iterates thorugh the loactions, then iterates through each dictionary within the list
till it finds the key latLng. Finally iterates through the latLng dictionary, turns the
values of of lattitude and longitude into a int, rounds it and prints out the resulting value.
'''
print('LATLONGS')
result=result['route']['locations']
for x in range(len(result)):
for y in (result[x]):
if y=='latLng':
for z in (result[x][y]):
latlng=round(int(result[x][y][z]))
print(latlng)
print()
class ELEVATION:
def calculate(result:dict):
'''
Takes the library returned by the build_elevation_url function and accesses elevationProfile
list, then it iterates through each of the nested dictionaries till it finds the key, height,
finally it rounds the height and prints the value.
'''
print('ELEVATIONS')
elevation_result=MQ.get_result(MQ.build_elevation_url(result))
elevation_result=elevation_result['elevationProfile']
for distHeight in range(len(elevation_result)):
for Height in elevation_result[distHeight]:
if Height=='height':
elevation=round(int(elevation_result[distHeight][Height]))
print(elevation)
print()
def get_latLng(result:dict):
'''
Creates a nested list of latitude and longitude, and then creates a string of the
latitudes and longitudes in the order of longitude then latitude to be used as a parameter
in the build_elevation_url.
'''
latLngs=[]
mini_latLngs=[]
latLngs_str=''
result=result['route']['locations']
for x in range(len(result)):
for y in (result[x]):
if y=='latLng':
for z in (result[x][y]):
latlng=result[x][y][z]
mini_latLngs.append(latlng)
if len(mini_latLngs)==2:
latLngs.append(mini_latLngs)
mini_latLngs=[]
for x in latLngs:
Lng=str(x[0])
lat=str(x[1])
latLngs_str+=lat+','+Lng+','
latLngs_str=latLngs_str[:-1]
return latLngs_str
|
def reverse_concatenate (a, b, c):
new_string = c[::-1] + b[::-1] + a[::-1]
return new_string
string1 = input('Enter first string: ')
string2 = input('Enter second string: ')
string3 = input('Enter third string: ')
print(reverse_concatenate (string1, string2, string3))
|
# TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# We need to set up a base case, which will be the way we exit the function. At what point do we want to exit? Should be simple and we should be moving towards it
if end >= start: # As long the end point is greater than or equal to the starting point, run the code below. Needs to include "=" because the target might be at that point
midpoint = (start + end) // 2 # FInd the value of the midpoint, which is the sum of the start and the end divided by 2
if target == arr[midpoint]: # Base case: If the taget is equal to the value in the array at the midpoint
return midpoint # Target found, return midpoint
elif target > arr[midpoint]: # If the target is greater than the value at the midpoint
return binary_search(arr, target, (midpoint + 1), end) # Recursion! Run the function but change the "start" to the midpoint - 1
elif target < arr[midpoint]: # If the target is less than the value at the midpoint
return binary_search(arr, target, start, (midpoint - 1)) # Recursion! Run the function but change the "end" to the midpoint + 1
return -1 # If the target doesn't exist in the array, return -1 (which is what the tests ask for)
[ 0, 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
# Your code here
pass
|
"""
Clase 2
@SantiagoDGarcia
"""
def suma (a,b):
return a+b
def producto (a,b):
return a*b
def disparador (f,a,b):
print (f(a,b))
disparador (producto, 1, 10) |
friend = ["Rolf", "Bob", "Anne"]
family = ["Jen", "Charlie"]
user_name = input("Enter your name: ")
if user_name == "Anderson":
print("Hello, Master!")
elif user_name in friend:
print("Hello, friend!")
elif user_name in family:
print("Hello, family!")
else:
print("I don't know you!") |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Authors: tongxu01(tongxu01@baidu.com)
Date: 2017/8/20
"""
import os
import sys
import time
from subprocess import PIPE
from subprocess import Popen
"""
Python-Tail - Unix tail follow implementation in Python.
python-tail can be used to monitor changes to a file.
"""
def check_file_validity(file_):
""" Check whether the a given file exists, readable and is a file """
if not os.access(file_, os.F_OK):
raise MonitorError("File '%s' does not exist" % file_)
if not os.access(file_, os.R_OK):
raise MonitorError("File '%s' not readable" % file_)
if os.path.isdir(file_):
raise MonitorError("File '%s' is a directory" % file_)
class Monitor(object):
""" Represents a tail command. """
def __init__(self, tailed_file):
""" Initiate a Tail instance.
Check for file validity, assigns callback function to standard out.
Arguments:
tailed_file - File to be followed. """
check_file_validity(tailed_file)
self.tailed_file = tailed_file
self.callback = sys.stdout.write
def follow(self):
"""Do a tail follow
If file was deleted and recreated , go on following
"""
command = 'tail -F %s' % self.tailed_file
popen = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
while True:
line = popen.stdout.readline()
self.callback(line)
def follow_single_file(self, s=1):
""" Do a tail follow. If a callback function is registered it is called with every new line.
Else printed to standard out.
If file was deleted, stop following.
Arguments:
s - Number of seconds to wait between each iteration; Defaults to 1. """
with open(self.tailed_file) as file_:
# Go to the end of file
file_.seek(0, 2)
while True:
curr_position = file_.tell()
line = file_.readline()
if not line:
file_.seek(curr_position)
time.sleep(s)
else:
self.callback(line)
def register_callback(self, func):
""" Overrides default callback function to provided function. """
self.callback = func
class MonitorError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
|
# coding=utf-8
__author__ = 'xyc'
# The Command Pattern is used to encapsulate commands as objects. This
# makes it possible, for example, to build up a sequence of commands for deferred
# execution or to create undoable commands.
# 讲一个请求封装为一个对象,从而是你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
class Grid:
def __init__(self, width, height):
self.__cells = [["white" for _ in range(height)] for _ in range(width)]
def cell(self, x, y, color=None):
if color is None:
return self.__cells[x][y]
self.__cells[x][y] = color
@property
def rows(self):
return len(self.__cells[0])
@property
def columns(self):
return len(self.__cells)
class UndoableGrid(Grid):
def create_cell_command(self, x, y, color):
def undo():
self.cell(x, y, undo.color)
def do():
undo.color = self.cell(x, y) # Subtle!
self.cell(x, y, color)
return Command(do, undo, "Cell")
def create_rectangle_macro(self, x0, y0, x1, y1, color):
macro = Macro("Rectangle")
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
macro.add(self.create_cell_command(x, y, color))
return macro
class Command:
def __init__(self, do, undo, description=""):
assert callable(do) and callable(undo)
self.do = do
self.undo = undo
self.description = description
def __call__(self):
self.do()
class Macro:
def __init__(self, description=""):
self.description = description
self.__commands = []
def add(self, command):
if not isinstance(command, Command):
raise TypeError("Expected object of type Command, got {}".format(type(command).__name__))
self.__commands.append(command)
def __call__(self):
for command in self.__commands:
command()
do = __call__
def undo(self):
for command in reversed(self.__commands):
command.undo()
grid = UndoableGrid(8, 3) # (1) Empty
redLeft = grid.create_cell_command(2, 1, "red")
redRight = grid.create_cell_command(5, 0, "red")
redLeft() # (2) Do Red Cells
redRight.do() # OR: redRight()
greenLeft = grid.create_cell_command(2, 1, "lightgreen")
greenLeft() # (3) Do Green Cell
rectangleLeft = grid.create_rectangle_macro(1, 1, 2, 2, "lightblue")
rectangleRight = grid.create_rectangle_macro(5, 0, 6, 1, "lightblue")
rectangleLeft() # (4) Do Blue Squares
rectangleRight.do() # OR: rectangleRight()
rectangleLeft.undo() # (5) Undo Left Blue Square
greenLeft.undo() # (6) Undo Left Green Cell
rectangleRight.undo() # (7) Undo Right Blue Square
redLeft.undo() # (8) Undo Red Cells
redRight.undo() |
# if you want to scrape a website :
# 1. using api
# 2. html web scraping using some tool like bs4
# step 0 :
# install these:
# pip install requests
# pip install bs4
# pip install html5lib
import requests
from bs4 import BeautifulSoup
url = "https://codewithharry.com"
# step 1 : get the html
r = requests.get(url)
htmlContent = r.content
# print(htmlContent)
# step 2 : parse the html
soup = BeautifulSoup(htmlContent,'html.parser')
# print(soup.prettify)
# step 3 : html tree traversal
# commonly used type of objects
title = soup.title
# print(type(title))#1 tag
# print(type(title.string))#2 navigablestring
# print(type(soup)) #3 beautifulSoup
# get all the paragraphs from the page
# paras = soup.find_all('p')
# print(paras)
# # get all anchor tags from the page
# anchors = soup.find_all('a')
# print(anchors)
# get first element in the html page
# print(soup.find('p'))
# # get classes of any element in html page
# print(soup.find('p')['class'])
# find all the elements with class lead
# print(soup.find_all('p',class_='lead'))
# get the text from the tags/soup
# print(soup.find('p').get_text())
# get all the links in the page
# all_links = set()
# for link in anchors:
# if(link.get('href')!="#"):
# linkText = "https://codewithharry.com" + link.get('href')
# all_links.add(link)
# print(linkText)
#4 comment
# markup = '<p><!--this is a comment--></p>'
# soup2 = BeautifulSoup(markup)
# print(type(soup2.p.string))
navbarSupportedContent = soup.find(id = 'navbarSupportedContent')
# .contents = a tags children are available as a list
# .children = a tags children are available as a
# for elem in navbarSupportedContent.contents:
# print(elem)
# for item in navbarSupportedContent.strings:
# print(item)
# for item in navbarSupportedContent.stripped_strings:
# print(item)
# for item in navbarSupportedContent.parents:
# print(item)
# print(item.name)
# print(navbarSupportedContent.next_sibling.next_sibling)
# print(navbarSupportedContent.previous_sibling.previous_sibling)
elem = soup.select('.modal-footer')
print(elem)
# print(navbarSupportedContent.previous_sibling.previous_sibling)
# print(title)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy=ListNode(0)
dummy.next=head
slow=fast=dummy
for i in range(n):
fast=fast.next
while fast and fast.next:
slow=slow.next
fast=fast.next
slow.next=slow.next.next
return dummy.next
"""if head.next==None and n==1:
return None
count=0
temp=head
while temp:
count+=1
temp=temp.next
temp=head
i=0
count=count-n
if count==0:
head=head.next
while temp:
i+=1
if i==count:
if temp.next and temp.next.next:
temp.next=temp.next.next
else:
temp.next=None
temp=temp.next
return head
"""
|
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
end=len(nums)-1
i=0
while i<=end:
if nums[i]==0:
nums.insert(0,nums.pop(i))
i+=1
elif nums[i]==2:
nums.append(nums.pop(i))
end-=1
else:
i+=1
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(l,r):
if r is None and l is None:
return True
elif r is None or l is None:
return False
return (r.val==l.val) and check(l.right,r.left) and check(l.left,r.right)
return check(root,root) |
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
res=[]
if len(word1)>len(word2):
length=len(word2)
else:
length=len(word1)
for i in range(0,length):
res.append(word1[i])
res.append(word2[i])
if len(word1)>len(word2):
res=res+list(word1[length:])
else:
res=res+list(word2[length:])
return "".join(res)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def suc(self,root):
root=root.right
while root.left:
root=root.left
return root.val
def pred(self,root):
root=root.left
while root.right:
root=root.right
return root.val
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root:
return None
if key>root.val:
root.right=self.deleteNode(root.right,key)
elif key<root.val:
root.left=self.deleteNode(root.left,key)
else:
if not(root.right) and not root.left:
root=None
elif root.right:
root.val=self.suc(root)
root.right=self.deleteNode(root.right,root.val)
else:
root.val=self.pred(root)
root.left=self.deleteNode(root.left,root.val)
return root
|
#Testing re.split
import re
import unittest
# string = 'hi'
# #newstring = re.split(r'(\d*)$', string2, maxsplit=2)
# newstring = re.search('(\d*)$', string)
#
# end_number = int((newstring.group(1)) + 1 if newstring.group(1) else 1)
# print(re.split('(\d*)$', string)[0] + str(end_number))
# #newstring[1] = int(newstring[1]) + 1
# #finish = newstring[0] + str(newstring[1])
# #print finish
#
# # def my_func(string):
# # return re.split('(\d*)$', string)[0] + str(int(re.search('(\d*)$', string).group(1)) + 1)
# #
# # print my_func('2345this7is.a!string123')
# # print my_func('1234')
# # print my_func('hi')
# newstring = re.search('(\d*)$', string)
# end_number = int((newstring.group(1)) + 1 if newstring.group(1) else 1)
# print(re.split('(\d*)$', string)[0] + str(end_number))
import re
def increment_string(string):
newstring = re.search('(\d*)$', string)
end_number = str(int(newstring.group(1)) + 1 if newstring.group(1) else 1).zfill(len(newstring.group(1)))
rest = str(re.split('(\d*)$', string)[0])
print type(end_number)
print type(rest)
print rest + end_number
#increment_string("foo")
increment_string("foobar001")
# increment_string("foobar1")
# increment_string("foobar00")
# increment_string("foobar99")
increment_string("foobar099")
# increment_string("") |
'''异常处理
def test(x,y):
try:
return x/y
except ZeroDivisionError:
print('0不可除')
except TypeError:
print('类型错误')
finally:
print('结束')
print(test(4,1))
print(test('111','222'))
'''
'''迭代器
from collections.abc import Iterable
print(isinstance('test',Iterable))
strItr=iter('test')
print(next(strItr))
list1 =["1","2",3,4,5]
listItr=iter(list1)
print(next(listItr))
'''
list_1=[x*x for x in range(100000)]
# print(list_1)
list_2=(x*x for x in range(3))
print(list_2)
# print(next(list_2))
# print(next(list_2))
# print(next(list_2))
# for x in list_2:
# print(x)
def print_a(max):
i=0
while(i<max):
i+=1
yield i
a=print_a(10)
print(a)
print(type(a))
print(next(a))
print(a.__next__())
def print_b(max):
i=0
while i<max:
i=i+1
args=yield i
print('测试'+args)
b=print_b(100)
print(b.__next__())
print(b.send('cxe'))
|
# Pandigital prime
# Problem 41
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
# What is the largest n-digit pandigital prime that exists?
from common import is_prime
import itertools
def pandigitals(size):
it = itertools.permutations(range(size, 0, -1))
while True:
number = list(next(it))
if number[0] != 0:
yield number
def list_to_number(ds):
number = 0
for d in ds:
number = number * 10 + d
return number
def solve():
# After checking the forum:
#
# Start with 7 (I used 9) and going down. before 9 and 8 digits are
# divisible by 3 and therefore none of them cannot be prime.
#
for size in range(7, 0, -1):
numbers = pandigitals(size)
try:
while True:
number = list_to_number(next(numbers))
if is_prime(number):
return number
except StopIteration:
pass
return None
if __name__ == '__main__':
print(__file__ + ': ', solve())
|
# coding: utf-8
# Pandigital products
# Problem 32
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
# The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
# Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
# HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
from common import lst_to_int
import itertools
#
# old slow (6s) solution
#
def _find_pandigital_identities():
it = itertools.permutations(range(1, 10))
for digits in it:
for i in range(1, 5):
multiplicand = l_to_i(digits[0:i])
if multiplicand == 1:
continue
for j in range(1, 6 - i):
multiplier = l_to_i(digits[i:i+j])
product = l_to_i(digits[i+j:])
if multiplicand * multiplier == product:
yield (multiplicand, multiplier, product)
#
# inspired by bitchboy's one line solution in the forum:
#
# print(sum(set(sum([[a*b for b in range(a, 10**((9-len(str(a)))//2))if ''.join(sorted(''.join(map(str,(a,b,a*b)))))=="123456789"]for a in range(1,10**5)],[]))))
def find_pandigital_identities():
for multiplicand in range(2, 10**5):
upper = 10**(5 - len(str(multiplicand)))
#
# only care multipliers that are greater than multiplicands
# to avoid duplicates: 39 * 186, and 186 * 39
#
for multiplier in range(multiplicand, upper):
product = multiplicand * multiplier
as_str = ''.join(sorted(''.join(map(str, (multiplicand, multiplier, product)))))
if as_str == '123456789':
yield (multiplicand, multiplier, product)
def solve():
return sum(set(each[2] for each in find_pandigital_identities()))
if __name__ == '__main__':
print(__file__ + ':', solve())
|
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples_of_3_or_5(below):
i = 3
while i < below:
if i % 3 == 0 or i % 5 == 0:
yield i
i += 1
def solve():
return sum(multiples_of_3_or_5(1000))
if __name__ == '__main__':
print(__file__ + ": %d" % solve())
|
# Summation of primes
# Problem 10
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#
# Find the sum of all the primes below two million.
from common import PrimeGenerator
def solve():
g = PrimeGenerator(2_000_000)
return sum(g)
if __name__ == '__main__':
print(__file__ + ": %d" % solve())
|
#P = Loan Principal
#J = Monthly Interest Rate (Annual Rate / 1200)
#N = Number of Months (Years * 12)
#M = Monthly Payment
#V = Value of House
#eightyPercent = 80% of the value of the home
#H = Monthly Interest Payment
#C = Monthly Principal Payment
#Q = New Principal Balance
#PMIPmt = PMI Payment
#T = Monthly Tax
P = 351000;
J = 0.003125;
N = 360;
M = 1647;
V = 370000;
eightyPercent = V * .78;
Q = P;
i = 0;
PMIPmt = 350;
PMIHit = False;
TotalInt = 0;
TotalPMI = 0;
T = 352;
while(Q > 0):
H = P*J;
TotalInt += H;
C = M-H;
Q = P-C;
P = Q;
i += 1;
print("Month: " + str(i));
print("Interest Pmt: " + str(H));
print("Principal Pmt: " + str(C));
print("Balance: " + str(Q));
if(Q < eightyPercent and not PMIHit):
print("****************PMI Ends*****************");
print("Years of PMI: " + str(i/12));
TotalPMI = PMIPmt * i;
print("Total PMI Payments: " + str(TotalPMI));
print("****************PMI Ends*****************");
PMIHit = True;
print("*********Loan Ends*********");
print("Years: " + str(i / 12));
print("Total Interest Paid: " + str(TotalInt));
print("Total PMI: " + str(TotalPMI));
TotalTax = T * i;
print("Total Tax: " + str(TotalTax));
TotalPaid = V + TotalInt + TotalPMI + TotalTax;
print("Total Paid: " + str(TotalPaid));
print("Interest to Value Ratio: " + str(TotalInt / V));
print("Value to Total Paid Ratio: " + str(V / TotalPaid));
|
############################################################################
# Binary classification: Classify movie reviews as positive or negative
# Used IMDB dataset from keras
# This exercise is from the book Deep Learning with Python
# Now we are trying to deal with the overfitting issue by
# reducing the hidden layer's size to 4. We compare the validation loss
# from model with hidden layer's size 4 and 16.
############################################################################
from keras.datasets import imdb
from keras import models
from keras import layers
import numpy as np
import matplotlib.pyplot as plt
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_review = ''.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])
# Encoding the integer sequences into a binary matrix
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
# vectorized training and test data
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
# ------ Setting aside a validation set ------
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
# ----- The model definition: hidden layer's size of 16---------
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
# the final layer uses sigmoid activation to output a probability
model.add(layers.Dense(1, activation='sigmoid'))
# ----- Compiling the model ------
model.compile(optimizer='rmsprop',
loss='binary_crossentropy', # it is the best option with models that outputs probabilities
metrics=['acc'])
history = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data=(x_val, y_val))
results = model.evaluate(x_test, y_test)
print('Result hidden layer\'s size of 16: \n', results)
"""
The model definition:
We are trying to prevent overfitting reducing the model size. Then we are diminishing the model's capacity.
So, the layer's size was decreased to 4
"""
model = models.Sequential()
model.add(layers.Dense(4, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(4, activation='relu'))
# the final layer uses sigmoid activation to output a probability
model.add(layers.Dense(1, activation='sigmoid'))
# ----- Compiling the model ------
model.compile(optimizer='rmsprop',
loss='binary_crossentropy', # it is the best option with models that outputs probabilities
metrics=['acc'])
history_size4 = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data=(x_val, y_val))
results = model.evaluate(x_test, y_test)
print('Result hidden layer\'s size of 4: \n', results)
# ------ Plotting the training and validation loss -------
history_dict = history.history
history_dict_size4 = history_size4.history
val_loss_values = history_dict['val_loss']
val_size4_loss_values = history_dict_size4['val_loss']
acc = history_dict['acc']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, val_size4_loss_values, 'bo', label='Smaller model')
plt.plot(epochs, val_loss_values, 'x', label='Original mdel')
plt.title('Validation loss comparison')
plt.xlabel('Epochs')
plt.ylabel('Validation loss')
plt.legend()
plt.show()
|
def fancy_divide(numbers,index):
try:
denom = numbers[index]
for i in range(len(numbers)):
numbers[i] /= denom
except IndexError:
print("-1")
else:
print("1")
finally:
print("0")
###
def fancy_divide(list_of_numbers, index):
try:
raise Exception("0")
finally:
denom = list_of_numbers[index]
for i in range(len(list_of_numbers)):
list_of_numbers[i] /= denom
return list_of_numbers
##one property of children class will written the values but search for the values from children to parent
##
class SKILL_Set(object):
##x is the list of requirement
##y is the list with the same length which show if I satisfy those requirement
def __init__ (self,x,y):
assert(len(x)==len(y)),"the length of two list didn't match!"
self.r=x
self.s=y
def __str__(self):
return "<"+str(self.r)+"> \n"+ "<"+str(self.s)+">"
class DemandPool(SKILL_Set):
DS_j1_r=['A/B test', 'linear regression', 'Supervise Learning', 'Anomaly detection','predictive modeling']
DS_j1_s=[0,1,1,0,1]
DS_j1=SKILL_Set()
import numpy as np
a = np.arange(24).reshape(4,6)
b = np.ones(24).reshape(4,6)
##concate
c=np.
a = np.array([1,2]) |
# a1.py - Jason Leung
import random
import sys
import time
from search import *
from collections import deque
state = []
# Take command line argument input from user if it exists
if (len(sys.argv) == 10):
for i in range (1, 10):
state.append(int(sys.argv[i]))
else:
state = [1, 2, 3,
4, 5, 6,
7, 8, 0]
puzzle = EightPuzzle(tuple(state))
def make_rand_8puzzle():
global state
global puzzle
actions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
scramble = []
# Randomly chooses 100 actions to make in order to randomize the puzzle
for _ in range(100):
scramble.append(random.choice(actions))
# If the move can be made, then overwrite state with the resulting state given action and create a new EightPuzzle
for move in scramble:
if move in puzzle.actions(state):
state = list(puzzle.result(state, move))
puzzle = EightPuzzle(tuple(state))
def display(state):
# Display current state
for i in range(0, 9, 3):
if (state[i] == 0):
print("*", state[i + 1], state[i + 2])
elif (state[i + 1] == 0):
print(state[i], "*", state[i + 2])
elif (state[i + 2] == 0):
print(state[i], state[i + 1], "*")
else:
print(state[i], state[i + 1], state[i + 2])
def search(h, display):
return astar_search(puzzle, h, display).solution()
def stats(h, display):
# Print stats of astar_search
start = time.time()
solution = search(h, display)
elapsed = time.time() - start
print("Length:", len(solution))
print("Time:", elapsed)
def manhattan(n):
state = n.state
index_goal = {0: [2, 2], 1: [0, 0], 2: [0, 1], 3: [0, 2], 4: [1, 0], 5: [1, 1], 6: [1, 2], 7: [2, 0], 8: [2, 1]}
index_pos = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
distance = 0
# Iterate through each position in the state, and initialize initial as the current position in the state
# Grab the goal position of the state in the current position
# ex. 3 2 1
# state[0] = 3
# initial = [0, 0] (the position it is currently at)
# final = [0, 2] (the goal state position it should be in)
for i in range(len(state)):
if (state[i] != 0):
initial = index_pos[i]
final = index_goal[state[i]]
# Get the x and y distance from initial to goal
x = abs(initial[1] - final[1])
y = abs(initial[0] - final[0])
# Add up all the distances together
distance = x + y + distance
# Returns distance
return distance
def gaschnig(n):
temp_state = list(n.state)
index_goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
index_counter = 0
swaps = 0
while True:
# If the blank is in the 8th position, test if it is in the goal state
if (temp_state.index(0) == 8):
# If goal state has been reached, break out of loop
if (puzzle.goal_test(tuple(temp_state))):
break
else:
# Iterate through the positions checking which values are in the correct position
# Values that are misplaced will swap with blank
if (temp_state[index_counter] != index_goal[index_counter]):
blank_pos = temp_state.index(0)
temp_state[blank_pos], temp_state[index_counter] = temp_state[index_counter], temp_state[blank_pos]
swaps = swaps + 1
index_counter = index_counter + 1
else:
index_counter = index_counter + 1
else:
# Say the blank is in state[5], that means it is in the 6th position
# Therefore it needs to swap with the position of value 6
blank_pos = temp_state.index(0)
value = blank_pos + 1
value_pos = temp_state.index(value)
temp_state[blank_pos], temp_state[value_pos] = temp_state[value_pos], temp_state[blank_pos]
swaps = swaps + 1
# Returns amount of swaps
return swaps
# ----
# Define variables
counter = 0
while True:
# If puzzle is not solvable, keep generating a new random puzzle
make_rand_8puzzle()
solvable = puzzle.check_solvability(state)
if (solvable == True):
break
elif (counter >= 5):
print("Unable to reach goal state")
break
else:
counter = counter + 1
# Only run if puzzle is solvable
if (solvable == True):
node = Node(state)
mdh = manhattan(node)
gh = gaschnig(node)
# Prints initial puzzle state
print()
display(state)
# Prints Misplaced-Tiles Algorithm stats
print()
print("Misplaced-Tiles Algorithm:")
stats(None, True)
# Prints Manhattan Distance Algorithm stats
print()
print("Manhattan Distance Algorithm:")
stats(manhattan, True)
print("Heuristic:", mdh)
# Prints Gaschnig Algorithm stats
print()
print("Gaschnig Algorithm:")
stats(gaschnig, True)
print("Heuristic:", gh)
print() |
#import libraries
import random
import time
#set up global variables
board = ['Go', 'Mediterranean Avenue', 'Baltic Avenue', 'Reading Railroad','Oriental Avenue', 'Jail']
property_info = {'Mediterranean Avenue':{'cost':100,'rent':50,'ownerID':0},'Baltic Avenue':{'cost':150,'rent':60,'ownerID':0}, 'Reading Railroad':{'cost':175,'rent':50,'ownerID':0},'Oriental Avenue':{'cost':200,'rent':75,'ownerID':0}}
player = {'position':0,'money':600,'playerID': 1}
computer = {'position':0,'money':600,'playerID': 2}
game_over = False
#handle players turn
def player_move(player):
global game_over
spaces = random.randint(1,6)
player['position'] = (player['position']+spaces)%len(board)
print("You landed on {}".format(board[player['position']]))
if board[player['position']] in property_info:
if property_info[board[player['position']]]['ownerID'] == 0:
answer = input("Would you like to buy {}? (y or n) ".format(board[player['position']]))
if answer == "y":
property_info[board[player['position']]]['ownerID'] = player['playerID']
player['money'] -= property_info[board[player['position']]]['cost']
print("You bought {}. You now have ${}.".format(board[player['position']], player['money']))
else:
print("You passed up a great opportunity :(")
elif property_info[board[player['position']]]['ownerID'] != player['playerID']:
player['money'] -= property_info[board[player['position']]]['rent']
if player['money'] < 0:
game_over = True
print("You went bankrupt. The computer wins.")
return
print("Rent is ${}. You now have ${}.".format(property_info[board[player['position']]]['rent'], player['money']))
elif board[player['position']] == 'Go':
player['money']+= 200
print("You collected $200. You now have ${}.".format(player['money']))
elif board[player['position']] == 'Jail':
print("You're just visiting though.")
print()
#handle computer's turn
def ai_move(computer):
global game_over
spaces = random.randint(1,6)
computer['position'] = (computer['position']+spaces)%len(board)
print("The computer landed on {}.".format(board[computer['position']]))
if board[computer['position']] in property_info:
if property_info[board[computer['position']]]['ownerID'] == 0:
if computer['money'] > property_info[board[computer['position']]]['cost']:
computer['money'] -= property_info[board[computer['position']]]['cost']
property_info[board[computer['position']]]['ownerID'] = computer['playerID']
print("The computer bought {}".format(board[computer['position']]))
elif property_info[board[computer['position']]]['ownerID'] != computer['playerID']:
player['money'] += property_info[board[computer['position']]]['rent']
computer['money'] -= property_info[board[computer['position']]]['rent']
if computer['money'] < 0:
game_over = True
print("The computer went bankrupt. You win!");
return
print("The computer payed you ${} in rent money and now has ${}. You now have ${}.".format(property_info[board[computer['position']]]['rent'], computer['money'], player['money']))
elif board[computer['position']] == "Go":
computer['money']+= 200
print()
#main method, alternates between player and computer turns
def main():
print("Welcome to Monopoly\n")
while not game_over:
input("press enter to continue:")
print()
player_move(player)
if game_over:
break
time.sleep(.5)
ai_move(computer)
time.sleep(.5)
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
MAX = 1000000
chain_map = {}
def collatz_sequence(n):
return n // 2 if n % 2 == 0 else 3 * n + 1
def get_chain_count(n):
if n == 1:
chain_map[n] = 1
return 1
elif n in chain_map != None:
return chain_map[n]
else:
res = 1 + get_chain_count(collatz_sequence(n))
chain_map[n] = res
return res
max_chain_nb = 1
max_chain_count = 0
for i in range(1, MAX):
res = get_chain_count(i)
if res > max_chain_count:
max_chain_count = res
max_chain_nb = i
print(max_chain_nb, max_chain_count) |
#!/usr/bin/python3
from math import sqrt
def get_prime_factors(nb):
lpf = 0
while nb % 2 == 0:
lpf = 2
nb /= 2
for f in range(3, int(sqrt(nb)) + 1, 2):
while nb % f == 0:
lpf = f
nb /= f
if nb > 2: # nb is prime
lpf = nb
return lpf
print(get_prime_factors(600851475143))
|
#!usr/bin/python3
#"this is basic recursive web crawler that will traverse every url\ link in certain domain "
import urllib.request as r
from bs4 import BeautifulSoup as bs
import sys
import urllib.parse as parse
def scanner (soup): #the function that will scan urls
global unvisited,visited,inp
#if f.closed:
# f=open(sys.argv[1]+".txt",'a')
try :
so = r.urlopen(soup)
except:
print ("there was an error openning the url make sure you enter the url in the following format http://example.com")
return
visited.append(soup)
#f.write(soup+'\n')
s =bs(so)
init =s.findAll('a') #this line will find every <a> tag in a page
for i in init:
st=i['href']
if st[:len(inp)]==inp :
print("correct url")
#print (st)
if st not in visited:
unvisited.append(st) #append the discovered ulr to the unvisited array if it belongs to the same domain
#except :print ("unknown error ")
else:
st=inp+st
print(st)
unvisited.append(st)
print("__\n")
#f.close()
if __name__=="__main__":
if len(sys.argv)<2:
print ("""this is basic recursive web crawler that will traverse every url\ link in certain domain
enter the url you want to scan in the following format example.abc """)
sys.exit()
inp =sys.argv[1]
if inp[:4]!="http" or inp[:5]!="https":
inp="http://"+inp
unvisited=[]
visited=[]
dic={}
count=0
nam=sys.argv[1].replace('.','')
nam=nam.replace('/','')
nam=nam.replace(':','')
#f=open(nam,'w')
scanner(inp)
for each in unvisited : #visit each unvisited url in the unvisited list
if each not in visited:
print ("trying "+ each)
scanner(each)
#except:
# print('error traversing url'+each)
else:
print ("this node was visited already")
print (unvisited,visited)
|
'''
Prove 3 - scene.py
Abi Priebe
5/8/21
'''
'''
During this lesson, you will write code that draws the sky, the ground, and clouds.
During the next lesson, you will write code that completes the scene. The scene that
your program draws may be very different from the example scene above. However, your
scene must be outdoor, the sky must have clouds, and the scene must include repetitive
elements such as blades of grass, trees, leaves on a tree, birds, flowers, insects,
fish, pickets in a fence, dashed lines on a road, buildings, bales of hay, snowmen,
snowflakes, or icicles. Be creative.
Begin your program by copying and pasting the following code into a new file named
scene.py. This beginning code imports the tkinter library and creates a window and a
canvas that your program can draw to.
'''
import tkinter as tk
def main():
# The width and height of the scene window.
width = 800
height = 500
# Create the Tk root object.
root = tk.Tk()
root.geometry(f"{width}x{height}")
# Create a Frame object.
frame = tk.Frame(root)
frame.master.title("Scene")
frame.pack(fill=tk.BOTH, expand=1)
# Create a canvas object that will draw into the frame.
canvas = tk.Canvas(frame)
canvas.pack(fill=tk.BOTH, expand=1)
# Call the draw_scene function.
draw_scene(canvas, 0, 0, width-1, height-1)
root.mainloop()
def draw_scene(canvas, scene_left, scene_top, scene_right, scene_bottom):
"""Draw a scene in the canvas. scene_left, scene_top,
scene_right, and scene_bottom contain the extent in
pixels of the region where the scene should be drawn.
Parameters
scene_left: left side of the region; less than scene_right
scene_top: top of the region; less than scene_bottom
scene_right: right side of the region
scene_bottom: bottom of the region
Return: nothing
If needed, the width and height of the
region can be calculated like this:
"""
scene_width = scene_right - scene_left + 1
scene_height = scene_bottom - scene_top + 1
# Call your functions here
# draw sky
scene_width = scene_right - scene_left + 1
scene_height = scene_bottom - scene_top + 1
draw_sky(canvas, scene_width, scene_height)
# draw clouds
cloud1_center_x = scene_left + 100
cloud1_center_y = scene_bottom - 400
draw_cloud(canvas, cloud1_center_x, cloud1_center_y)
cloud2_center_x = scene_left + 200
cloud2_center_y = scene_bottom - 400
draw_cloud(canvas, cloud2_center_x, cloud2_center_y)
cloud3_center_x = scene_left + 150
cloud3_center_y = scene_bottom - 425
draw_cloud(canvas, cloud3_center_x, cloud3_center_y)
cloud4_center_x = scene_left + 130
cloud4_center_y = scene_bottom - 370
draw_cloud(canvas, cloud4_center_x, cloud4_center_y)
cloud5_center_x = scene_left + 170
cloud5_center_y = scene_bottom - 370
draw_cloud(canvas, cloud5_center_x, cloud5_center_y)
cloud6_center_x = scene_left + 150
cloud6_center_y = scene_bottom - 400
draw_cloud(canvas, cloud6_center_x, cloud6_center_y)
cloud7_center_x = scene_left + 275
cloud7_center_y = scene_bottom - 375
draw_cloud(canvas, cloud7_center_x, cloud7_center_y)
cloud8_center_x = scene_left + 325
cloud8_center_y = scene_bottom - 400
draw_cloud(canvas, cloud8_center_x, cloud8_center_y)
cloud9_center_x = scene_left + 325
cloud9_center_y = scene_bottom - 360
draw_cloud(canvas, cloud9_center_x, cloud9_center_y)
cloud10_center_x = scene_left + 25
cloud10_center_y = scene_bottom - 350
draw_cloud(canvas, cloud10_center_x, cloud10_center_y)
cloud11_center_x = scene_left + 75
cloud11_center_y = scene_bottom - 325
draw_cloud(canvas, cloud11_center_x, cloud11_center_y)
# draw hills
hill_x0 = -scene_width / 4
hill_x1 = 3*scene_width / 4
hill_y0 = scene_height / 2
hill_y1 = 3*scene_height / 2
draw_hill(canvas, hill_x0, hill_x1, hill_y0, hill_y1)
hill_x0 = scene_width / 2
hill_x1 = 5*scene_width / 4
hill_y0 = 2*scene_height / 3
hill_y1 = 3*scene_height / 2
draw_hill(canvas, hill_x0, hill_x1, hill_y0, hill_y1)
# draw trees
tree_center = scene_left + 600
tree_top = scene_top + 100
tree_height = 275
draw_pine_tree(canvas, tree_center, tree_top, tree_height)
tree_center = scene_left + 700
tree_top = scene_top + 100
tree_height = 300
draw_pine_tree(canvas, tree_center, tree_top, tree_height)
tree_center = scene_left + 200
tree_top = scene_top + 100
tree_height = 200
draw_pine_tree(canvas, tree_center, tree_top, tree_height)
# draw house
house_center_x = scene_left + 275
house_center_y = scene_top + 250
house_height = 50
draw_house(canvas, house_center_x, house_center_y, house_height)
# Define functions here
def draw_sky(canvas, width, height):
x0 = 0
x1 = width
y0 = height
y1 = 0
# Draw the sky.
canvas.create_rectangle(x0, y0, x1, y1,
fill="skyblue2")
def draw_cloud(canvas, center_x, center_y):
x0 = center_x - 40
x1 = center_x + 40
y0 = center_y - 25
y1 = center_y + 25
# Draw the cloud.
canvas.create_oval(x0, y0, x1, y1,
fill="aliceBlue", outline="aliceBlue")
def draw_hill(canvas, x0, x1, y0, y1):
# Draw the hill
canvas.create_oval(x0, y0, x1, y1,
fill="green4")
def draw_pine_tree(canvas, peak_x, peak_y, height):
trunk_width = height / 10
trunk_height = height / 8
trunk_left = peak_x - trunk_width / 2
trunk_right = peak_x + trunk_width / 2
trunk_bottom = peak_y + height
skirt_width = height / 2
skirt_height = height - trunk_height
skirt_left = peak_x - skirt_width / 2
skirt_right = peak_x + skirt_width / 2
skirt_bottom = peak_y + skirt_height
# Draw the trunk of the pine tree.
canvas.create_rectangle(trunk_left, skirt_bottom,
trunk_right, trunk_bottom,
outline="gray20", width=1, fill="tan3")
# Draw the crown (also called skirt) of the pine tree.
canvas.create_polygon(peak_x, peak_y,
skirt_right, skirt_bottom,
skirt_left, skirt_bottom,
outline="gray20", width=1, fill="dark green")
def draw_house(canvas, center_x, center_y, height):
# base
x0 = center_x - 50
x1 = center_x + 50
y0 = center_y - 50
y1 = center_y + 50
canvas.create_rectangle(x0, y0, x1, y1,
outline="gray20", fill="PaleVioletRed3")
# roof
x0 = center_x - 60
y0 = center_y - 40
x1 = center_x + 60
y1 = center_y - 40
x2 = center_x
y2 = center_y - 100
canvas.create_polygon(x0, y0, x1, y1, x2, y2,
outline="gray20", fill="IndianRed4")
# windows
x0 = center_x - 40
x1 = center_x - 10
y0 = center_y - 30
y1 = center_y
canvas.create_rectangle(x0, y0, x1, y1,
outline="black", fill="azure")
x0 = center_x + 40
x1 = center_x + 10
y0 = center_y - 30
y1 = center_y
canvas.create_rectangle(x0, y0, x1, y1,
outline="black", fill="azure")
# door
x0 = center_x - 15
x1 = center_x + 15
y0 = center_y + 50
y1 = center_y + 5
canvas.create_rectangle(x0, y0, x1, y1,
outline="black", fill="gray20")
# Call the main function so that
# this program will start executing.
main() |
'''
Checkpoint 1 - heart_rate.py
Abi Priebe
4/22/21
'''
'''
When you physically exercise to strengthen your heart, you should maintain your heart rate within a range for at
least 20 minutes. To find that range, subtract your age from 220. This difference is your maximum heart rate per
minute. Your heart simply will not beat faster than this maximum (220 - age). When exercising to strengthen your
heart, you should keep your heart rate between 65% and 85% of your heart's maximum.
'''
age = int(input("Please enter your age: "))
max = 220 - age
low = max * 0.65
high = max * 0.85
print(f"When you exercise to strengthen your heart, you should keep your heart rate between {low} and {high} beats per minute.")
|
#!/usr/bin/python
from sys import stdin
from keyword import iskeyword
if __name__ == "__main__":
n = input()
n_list = list(n)
n_sum = 0
finished = False
for i in n_list:
n_sum += int(i)
if n_sum % 3 == 0:
finished = True
print(0)
else:
sum_remain = n_sum % 3
# print('sum_remain:', sum_remain)
for i in range(0, len(n_list)):
for j in range(0, len(n_list)-i): # digit
for k in range(0, len(n_list)): # start point
tmp = 0
for l in range(0, j):
# print(i, j, k, l)
tmp += int(n_list[k+l])
# print('tmp', tmp)
if int(tmp) % 3 == sum_remain:
print(j)
finished = True
if finished:
break
if finished:
break
if finished:
break
if finished == False:
print(-1)
|
#!/usr/bin/env python
# coding: utf-8
# In[19]:
import pandas as pd
import numpy as np
df=pd.read_csv('bankdata.csv')
# In[20]:
df.drop('Unnamed: 0',axis=1,inplace=True)
# In[21]:
X=df.drop('default',axis=1)
# In[22]:
y=df['default']
# In[23]:
from sklearn.linear_model import LogisticRegression
lr=LogisticRegression(max_iter=1000)
lr.fit(X,y)
# In[24]:
# it help to get predicted value of hosue by providing features value
def predict_risk(age,ed,employ,address,income,debtinc,creddebt,othdebt):
x =np.zeros(len(X.columns))
x[0]=age
x[1]=ed
x[2]=employ
x[3]=address
x[4]=income
x[5]=debtinc
x[6]=creddebt
x[7]=othdebt
return lr.predict([x])[0]
# In[27]:
print(predict_risk(age=27,ed=1,employ=10,address=6,income=31,debtinc=17.3,creddebt=1.362202,othdebt=4.000798))
# In[ ]:
|
import tkinter
from tkinter import *
from tkinter import messagebox
root=tkinter.Tk()
def btn_is_clicked():
messagebox.showwarning("Warning", "This is info window")
root.geometry('400x500')
Button(
root,
text='Click here',bg='#000000',
fg='#ffffff',width=20,height=2, command=btn_is_clicked).pack()
root.mainloop() |
# READING FROM FILE
employee_file = open("employees.txt", "r") # opens file read mode
print(employee_file.readable()) # checks file is readable
#print(employee_file.read()) # reads entire file to screen
#print(employee_file.readline()) # can be used multiple times to read next line in file
#print(employee_file.readlines()) # reads each line into a list
print(employee_file.readlines()[1]) # reads into a list and displays item at position 1 in the list
#employee_file.close() # closes file
for employee in employee_file.readlines():
print(employee)
employee_file.close()
# WRITING AND APPENDING TO FILE
employee_file = open("employees.txt", "a") # opens file append mode
employee_file.write(
"Toby - HR") # in append mode will append this onto the end of the last line, not after the last line
employee_file.write(
"\nToby - HR") # in append mode will add a newline char to the end of the last line, then write a new line
employee_file = open("employees.txt", "w") # opens file write mode
employee_file.write("Toby - HR") # in write mode, this will overwrite the file entirely
employee_file.close() |
import os
"""os.walk returns the root folder you want to check use in a for loop
returns 3 values; name of folder, its subfolders as a list and list of files in folder"""
for folderName, subfolders, filenames in os.walk('/Users/kj/Desktop/Certificates/Automate the Boring Stuff'):
print('The folder is ' + folderName)
print('The subfolders in ' + folderName + ' are: ' + str(subfolders))
print('The filenames in ' + folderName + ' are: ' + str(filenames))
print()
"""Now we can do stuff to all this"""
for subfolder in subfolders:
if 'fish' in subfolder:
os.rmdir(subfolder)
for file in filenames:
if file.endswith('.py'):
continue # can have it do something here like shutil.copy()
|
# import pretty print to make nicer output
import pprint
# We want to count the number of characters in a string
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
# make a dictionary
count = {}
# We loop over the characters in the string
for character in message.upper():
# initialize each char in the dictionary with 0 using setdefault method
count.setdefault(character, 0)
# increment the occurence found
count[character] += 1
pprint.pprint(count)
|
row=0
while row<5:
c=0
while c<=row:
print("*",end=" ")
c=c+1
print()
row=row+1
|
num=int(input("enter the num"))
num1=int(input("enter the num"))
if num>num1:
a=num
else:
a=num1
while True:
if a%num==0 and a%num1==0:
print(a)
break
a=a+1 |
total = 0
number_items = int(input("Number of items:"))
while number_items < 0:
print("Invalid number of items!")
number_items = int(input("Number of items:"))
for i in range(number_items):
price = float(input("enter price of items:"))
total += price
if total > 100:
total *= 0.9
print("Total price for", number_items, "items is:${:.2f}".format(total))
|
"""Class that contains information on each piece of weather data"""
class WeatherData:
def __init__(self, wban, year_month_day, t_max, t_min, t_avg, station, location):
self.wban = wban
self.year_month_day = year_month_day
self.t_max = t_max
self.t_min = t_min
self.t_avg = t_avg
self.station = station
self.location = location
|
# 15-112: Principles of Programming and Computer Science
# Project: AI based Ludo
# Name : Swapnendu Sanyal
# AndrewID : swapnens
# File Created: November 6, 2017
# Modification History:
# Start End
# 27/10 14:30 27/10 20:00
# 30/10 21:05 19/10 22:08
########################## IMPORTING AND INITIALIZING ALL THE LIBRARIES ###############################
import pygame
pygame.init()
import time
import random
import chalk_path
import os
import copy
#######################################################################################################
############################## CONSTANTS ##############################################################
DISPLAY_HEIGHT = 750 # to set the screnn size
DISPLAY_WIDTH = 700
#setting the color constants
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
WHITE = (255,255,255)
BLACK = (0,0,0)
#size of each square in ludo
SQUARE_SIZE = 705/15 #side of the image by number of boxes
COIN_RADIUS = SQUARE_SIZE/3 # the size of each coin
gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH,DISPLAY_HEIGHT)) # creating the game window
pygame.display.set_caption('LUDO - Main Menu') #setting the caption
image = pygame.image.load('ludo.jpg')
pygame.display.set_icon(image) #setting the icon of the game
clock = pygame.time.Clock() # creating an object of the class Clock
FPS = 7 # FPS means frames per second
no_of_six = 0 # this is to stop players getting more that 2 sixes in a single turn
no_of_tries = 0 # this is to prevent the player from hindering the game by making invalid moves
# creating different font styles
medfont = pygame.font.SysFont("comicsansms",50)
smallfont = pygame.font.SysFont("comicsansms", 40)
PATH = chalk_path.PATH(SQUARE_SIZE) #this stores the location of each block in the game
# this is store the location of each home squares foer each color
RED_HOME = [(PATH[4][0],PATH[10][1]),(PATH[4][0],PATH[8][1]),(PATH[3][0],PATH[9][1]),(PATH[5][0],PATH[9][1])]
BLUE_HOME = [(PATH[23][0],PATH[18][1]),(PATH[23][0],PATH[16][1]),(PATH[22][0],PATH[17][1]),(PATH[24][0],PATH[17][1])]
YELLOW_HOME = [(PATH[23][0],PATH[35][1]),(PATH[23][0],PATH[37][1]),(PATH[22][0],PATH[36][1]),(PATH[24][0],PATH[36][1])]
GREEN_HOME = [(PATH[4][0],PATH[43][1]),(PATH[4][0],PATH[41][1]),(PATH[3][0],PATH[42][1]),(PATH[5][0],PATH[42][1])]
for i in range(1,len(PATH)): # this is to bring the coins to the centre of the squares
PATH[i] = (PATH[i][0] + SQUARE_SIZE/2 , PATH[i][1] + SQUARE_SIZE/2)
spritesheet = [] # to store the images of dice
for i in range(1,7): #this loads the sprites
spritesheet.append(pygame.image.load('dice (' + str(i)+').png'))
print 'done loading'
#######################################################################################################
def roll(i=0): #rolling the dice
global no_of_six
if no_of_six < 3: #only allows 2 conecutive sixes
options = [1,2,3,4,5,6]
else: #if 2 sixes, then choose from all but 6
options = [1,2,3,4,5]
dice = random.choice(options)
if dice==6: no_of_six += 1
else: no_of_six = 0
while i <12: #animation screen - here the dice rolls
pygame.draw.rect(gameDisplay,BLACK,(300,0,DISPLAY_WIDTH-300,50))
temp = random.choice(options)
gameDisplay.blit(spritesheet[temp-1],(300 + (i%6)*45,0))
message_to_screen(color = WHITE, msg = str(temp), where_text = (DISPLAY_WIDTH-100,22) )
i += 1
clock.tick(4*FPS)
pygame.display.update()
#now it displays the actual dice and the number on the screen
pygame.draw.rect(gameDisplay,BLACK,(500,0,DISPLAY_WIDTH-500,50))
gameDisplay.blit(spritesheet[dice-1],(500,0))
message_to_screen(color = WHITE, msg = str(dice), where_text = (DISPLAY_WIDTH-100,22) )
return dice
# this brings back the coins back to the original position
# this function also calls the intro screen
# this function accepts which players are playing from the user and stores it in a list
def game_initialize(gameDisplay):
#intro(gameDisplay)
position = {'red':[None],'blue':[None],'yellow':[None],'green':[None]}
#RED COINS
for i in RED_HOME:
position['red'].append(i)
#BLUE COINS
for i in BLUE_HOME:
position['blue'].append(i)
#YELLOW COINS
for i in YELLOW_HOME:
position['yellow'].append(i)
#GREEN COINS
for i in GREEN_HOME:
position['green'].append(i)
AI_list = intro(gameDisplay)
gameDisplay.fill(BLACK) #crear the screen for the actual game
return (PATH,position,AI_list)
# this function takes care of the intro screen
def intro(gameDisplay):
intro_end = False
AI_list = []
temp = []
#temp = ['yellow']
#Basic instructions to be displayed to the sceen
while not intro_end:
gameDisplay.fill(BLACK)
message_to_screen(WHITE,msg = "Press P to play.",where_text = (350,700))
message_to_screen(WHITE,msg = "You can choose multiple players.",where_text = (350,170),small = True)
message_to_screen(WHITE,msg = "Just press multiple keys.",where_text = (350,240),small = True)
message_to_screen(WHITE,msg = "Press I for instructions.",where_text = (350,100))
# the if conditions are to show the affects of pressing a key
if 'red' not in temp: message_to_screen(RED,msg = "Press R to play as Red",where_text = (350,300))
if "blue" not in temp : message_to_screen(BLUE,msg = "Press B to play as Blue",where_text = (350,400))
if "green" not in temp : message_to_screen(GREEN,msg = "Press G to play as Green",where_text = (350,500))
message_to_screen(YELLOW,msg = "Yellow is a player.",where_text = (350,600))
for event in pygame.event.get():
if event.type == pygame.QUIT: #Quit option
pygame.quit()
exit()
# this is to accept user input nd work accordingly
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
intro_end = True
if event.key == pygame.K_r and 'red' not in temp:
temp.append('red')
if event.key == pygame.K_g and 'green' not in temp:
temp.append('green')
if event.key == pygame.K_b and 'blue' not in temp:
temp.append('blue')
if event.key == pygame.K_i:
os.system("Notepad.exe rules.txt") #to open the file in notepad
pygame.display.update()
clock.tick(FPS) #this controls the frame rate of the screen
#the loop is to invert the player list into a list of players to be controlled by AI
for i in ['blue','green','red','yellow']:
if i not in temp:
AI_list.append(i)
return AI_list
# this function draws the coins on the board at given locations and given colors
def drawcoins(position,PATH): #to draw coints on the board
for i in position:
if i == 'red':
color = RED
elif i == 'blue':
color = BLUE
elif i == 'green':
color = GREEN
else:
color = YELLOW
for j in position[i]:
if j != None and j not in [PATH[58],PATH[64],PATH[70],PATH[76]]:
pygame.draw.circle(gameDisplay,BLACK,j,COIN_RADIUS,5)
#above one gives a black border
#next one fills it with color
#this is because the color may match with hi=ome color when at home
pygame.draw.circle(gameDisplay,color,j,COIN_RADIUS - 5,0)
#this function calculates the distance between two given points
def distance(point1,point2): # to calculate distance between 2 points
x1 = point1[0]
x2 = point2[0]
y1 = point1[1]
y2 = point2[1]
return (x1-x2)**2 + (y1-y2)**2
def detect_coin(click,position): #to detect which coin was selected
coin_selected = []
for i in position:
for j in range(1,len(position[i])):#using basic distance formula
if (distance(click,position[i][j]) <= COIN_RADIUS**2):
coin_selected.append((i,j))
return coin_selected
def detect_square_number(PATH,coin): #this function detects the location as an integer for the selected coin
for i in range(1,len(PATH)):
if PATH[i] == coin:
return i
return False #returns false if the coin selected is not in path
#this function checks if the move is valid
#A move is invalid when a coin is blocking the path of the coin
def is_valid_move(color,start,destination,position,PATH):
for i in range(start+1,destination): #for each position from the starting point to the ending point excluding both
for j in position: #for each color
for k in position[j][1:]: #for each coin
if k == PATH[i]:
return False
return True # returns true if the move is valid
# this function is to capture other people's coins
def capture(color,start,destination,position,PATH):
for k in position[color][1:]: #you cannot capture your own coins
if k == PATH[destination]:
return position
coin_captured = None #this is to make the if statement below to work
for j in position:
if j!=color: #again no suicu=ide allowed
counter = 0
for k in position[j][1:]:
counter += 1 # to record the coin number
if k==PATH[destination]:
coin_captured = (j,counter) #this coin is captured
if coin_captured: # to select the apropriate home for the captured coin
if coin_captured[0] == 'red':
home = RED_HOME
elif coin_captured[0] == 'yellow':
home = YELLOW_HOME
elif coin_captured[0] == "green":
home = GREEN_HOME
elif coin_captured[0] == "blue":
home = BLUE_HOME
for i in home:
isEmpty = True
for j in position[coin_captured[0]]:
if i==j:
isEmpty = False
if isEmpty: #put it in the first location that is available
position[coin_captured[0]][coin_captured[1]] = i
return position #return the positions of the coins
#this is to check if a coin is present at the destination of the current coin selected
def is_coin_present(position,color,destination,coin_number):
for j in position:
is_present = False
for k in position[j][1:]:
if k == PATH[destination]:
is_present = True
if is_present :
return (position,False)
position[color][coin_number] = PATH[destination] #move the coin if the move is valid and then return the updated positions
return (position,True)
#this game is intelligent
#this is a rule based AI
#the strategy implemented is as follows:
#if the player can win, make the move
#if the player cannot win but can capture some coin, bon appetit
#otherwise you can introduce a new coin into the board, please do so
#if you can send one of the coins to its pocket then move it
#otherwise randomly select a coin and move it
def AI(color,position,PATH,move):
print color,move
counter_coins_pocket = 0
which_coins = []
#to determine which coins are on the board
for i in range(1,5):
for j in [58,64,70,76]: #home pocket numbers
if position[color][i] == PATH[j]:
counter_coins_pocket += 1
elif i not in which_coins:
which_coins.append(i) #stores which coins are on the board
#can I win?
#if three coins are already in the pocket
if counter_coins_pocket == 3:
print "about to win"
for j in [58,64,70,76]:
if position[color][which_coins[0]] == PATH[j-move]:
position[color][which_coins[0]] = PATH[j]
return position,1,True
# Can I capture?
temp = position.copy() #to make a temporary copy of the positions
for i in which_coins:
if position[color][i] in PATH:
temp_position = copy.copy(position) # to make a temporary copy of the positions
temp_position , move , move_made = coin_move(temp_position,[(color,i)],move,PATH,check_roll = False) #make the move
for j in temp_position: # to check if any coin was captured in this attempt
if j!=color and temp_position[j]!=position[j]:
print 'capture'
return temp_position,roll(),move_made
position = temp #bringing the position back to its initial state
# can I introduce a new coin?
if move == 6:
for coin_number in which_coins:
print coin_number
if position[color][coin_number] not in PATH:
if color == 'red':
position, move_made = is_coin_present(position,color,2,coin_number)
elif color == 'blue':
position, move_made = is_coin_present(position,color,15,coin_number)
elif color == 'green':
position, move_made = is_coin_present(position,color,41,coin_number)
else:
position, move_made = is_coin_present(position,color,28,coin_number)
if move_made:
return position,roll(),move_made
move_made = False
no_of_trials = 0
temp = []
for i in which_coins:
if position[color][i] in PATH: #only the coins that are on the board
temp.append(i)
which_coins = temp
temp = position.copy()
for i in which_coins:
for j in [58,64,70,76]:
temp_position = copy.copy(position)
if position[color][i] == PATH[j-move]:
_ ,_ , move_made = coin_move(temp_position,[(color,i)],move,PATH,check_roll = False)
if move_made:
return temp_position, roll(), move_made
position = temp
while not move_made and no_of_trials <10 and which_coins: #select a random coin and move it
temp_position = copy.copy(position)
temp_position , _ , move_made = coin_move(temp_position,[(color,random.choice(which_coins))],move,PATH,check_roll = False)
no_of_trials += 1
if move_made:
print "random move made"
return temp_position, roll(), move_made
print "turn passed"
position = temp
return position,roll(),True #skip turn if nothing is possible
#this is the function that makes the coins to move
def coin_move(position,coin_selected,move,PATH, check_roll = True):
color = coin_selected[0][0]
coin_number = coin_selected[0][1]
move_made = True
did_coin_start = detect_square_number(PATH,position[color][coin_number])
#to start the coin movement
if not did_coin_start:
if move == 6:
if color == 'red':
position, move_made = is_coin_present(position,color,2,coin_number)
elif color == 'blue':
position, move_made = is_coin_present(position,color,15,coin_number)
elif color == 'green':
position, move_made = is_coin_present(position,color,41,coin_number)
else:
position, move_made = is_coin_present(position,color,28,coin_number)
else: # if the coin is on the board
# the path modifications to reach home
if color == 'blue' and 8<=did_coin_start<=13 and did_coin_start + move >13:
change = move - (13 - did_coin_start)
if is_valid_move(color,did_coin_start,13,position,PATH):
position['blue'][coin_number] = PATH[58+change]
else: move_made = False
elif color == 'green' and 34<=did_coin_start<=39 and did_coin_start + move >39:
if is_valid_move(color,did_coin_start,39,position,PATH):
change = move - (39 - did_coin_start)
position['green'][coin_number] = PATH[70 +change]
else: move_made = False
elif color == 'yellow' and 21<=did_coin_start<=26 and did_coin_start + move >26:
change = move - (26 - did_coin_start)
if is_valid_move(color,did_coin_start,26,position,PATH):
position['yellow'][coin_number] = PATH[64+change]
else: move_made = False
#you cannot overshoot your pocket
elif color == 'red' and did_coin_start>52 and did_coin_start + move > 58:
move_made = False
elif color == 'green' and did_coin_start>=71 and did_coin_start + move > 76:
move_made = False
elif color == 'blue' and did_coin_start>=59 and did_coin_start + move > 64:
move_made = False
elif color == 'yellow' and did_coin_start>=65 and did_coin_start + move > 76:
move_made = False
elif color in ['green','blue','yellow'] and 58>=did_coin_start + move>52: #to make the list circular
move = did_coin_start+move-52
if is_valid_move(color,did_coin_start,53,position,PATH):
if is_valid_move(color,1,move,position,PATH):
print "True"
position = capture(color,1,move,position,PATH)
position[color][coin_number] = PATH[move]
#if temp == position:
#position[color][coin_number] = PATH[did_coin_start + move]
else: move_made = False
else:
destination = (did_coin_start + move)
temp = copy.copy(position)
if is_valid_move(color,did_coin_start,destination,position,PATH):
position = capture(color,did_coin_start,destination,position,PATH)
if temp == position:
position[color][coin_number] = PATH[did_coin_start + move]
else: move_made = False
if move_made and check_roll:
print color,coin_number,move
return position, roll(),move_made
else: return position, move ,move_made
# to check if any player won
def did_win(gameDisplay,position,PATH):
for i in position:
coin_home = 0
for j in position[i][1:]: #to remove the first element which is None
# I do not need to check for individual colors as I will call this function
# after every move so that once 4 coins of any player is in home, the game ends.
if i == 'red' and j == PATH[58]:
coin_home +=1
elif i == 'yellow' and j == PATH[70]:
coin_home += 1
elif i == 'green' and j == PATH[76]:
coin_home += 1
elif i== 'blue' and j == PATH[64]:
coin_home += 1
if coin_home == 4:
gameDisplay.fill(BLACK)
message_to_screen(color = WHITE, msg = "Player " + i + " won.",where_text = (350,350))
message_to_screen(color = WHITE, msg = "Wait for 10 seconds to restart.",where_text = (350,450),small = True)
message_to_screen(color = RED, msg = "Please do NOT press exit button.",where_text = (350,550),small = True)
print "Hurray"
pygame.display.update()
time.sleep(10)
return i
return -1
def message_to_screen(color,msg = 'PLAYER',where_text = (100,22),small = False):
if not small :textSurface = medfont.render(msg, True, color)
else: textSurface = smallfont.render(msg, True, color)
textRect = textSurface.get_rect()
textRect.center = where_text[0], where_text[1]
gameDisplay.blit(textSurface, textRect)
def playercontrol(player):
if player == 'red':
message_to_screen(color = GREEN)
return 'green'
elif player == 'green':
message_to_screen(color = YELLOW)
return 'yellow'
elif player == 'blue':
message_to_screen(color = RED )
return 'red'
elif player == 'yellow':
message_to_screen(color = BLUE)
return 'blue'
def gameloop():
gameOver = False
gameExit = False
global no_of_tries
while not gameExit:
#if gameOver == True: ##########come back later - replay options
#pass
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = gameExit = True
PATH, coin_position, AI_list = game_initialize(gameDisplay)
player = 'red' #I start with red, always
message_to_screen(color = RED )
move = roll(12) # the 12 is to stop the animation
while not gameOver:
gameDisplay.blit(image,(0,45))
for event in (pygame.event.get() + [1]):
if event != 1 and event.type == pygame.QUIT:
gameOver = gameExit = True
elif event != 1 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
player = playercontrol(player)
move = roll()
elif (event != 1 and event.type == pygame.MOUSEBUTTONUP) or player in AI_list:
is_AI_playing = player in AI_list
if not is_AI_playing:
coin_selected = detect_coin(pygame.mouse.get_pos(),coin_position)
else:
coin_selected = [[player]]
if coin_selected and coin_selected[0][0] == player:
player_change = True
prev_move = move
if not is_AI_playing: #make the move
coin_position, move, move_made = coin_move(coin_position,coin_selected,move,PATH)
else:
coin_position, move, move_made = AI(player,coin_position,PATH,move)
if did_win(gameDisplay,coin_position,PATH) != -1:
gameOver = True
if prev_move == 6: player_change = False #repeat turn if 6
else: player_change = move_made
else:
player_change = False
if player_change or no_of_tries > 4:
player = playercontrol(player) #change players
move = roll()
no_of_tries = 0
else : no_of_tries += 1
if not gameOver: drawcoins(coin_position,PATH)
pygame.display.update()
clock.tick(FPS)
############################# GAME EXIT ###############################################################
gameloop()
pygame.quit()
exit()
################################ CITATIONS ############################################################
|
with open('input.txt', 'r') as f:
data = f.read().split()
def row_num(row):
"""
decodes first 7 chars and returns the row number using bisection search
"""
max_r = 127
min_r = 0
for char in row:
if char == 'F':
min_r = min_r
max_r = (max_r + min_r) // 2
elif char == 'B':
max_r = max_r
min_r = ((max_r + min_r) // 2) + 1
return max_r
def col_num(col):
"""
deodes column number using bisection search
"""
max_c = 7
min_c = 0
for char in col:
if char == 'L':
min_c = min_c
max_c = (max_c + min_c) // 2
elif char == 'R':
max_c = max_c
min_c = ((max_c + min_c) // 2 ) + 1
return max_c
def seat_id(row, col):
"""
returns the formula for calculating seat id
"""
return (row_num(row) * 8) + col_num(col)
def maxSeatID(data):
"""
calculates all seat IDs and returns a list
"""
seat_ids = []
for item in data:
seat_ids.append(seat_id(item[:7], item[7:]))
return seat_ids
def missingSeatID(data):
"""
leverages Set Subtraction to return the only
missing seat between the full list and our calculated
list
"""
seats = maxSeatID(data)
min_id = min(seats)
max_id = max(seats)
check = list(range(min_id, max_id + 1))
return set(check) - set(seats)
# part 1
print(max(maxSeatID(data)))
# part 2
print(missingSeatID(data))
|
from collections import defaultdict
from queue import PriorityQueue
import math
class Node:
def __init__(self, data):
self.data = data
self.visited = False
def __repr__(self):
return f'Node({self.data})'
def __lt__(self, other):
return self.data < other.data
def __eq__(self, other):
return self.data == other.data
def __hash__(self):
return hash(repr(self))
class Edge:
def __init__(self, v: Node, weight: int):
self.v = v
self.weight = weight
def __repr__(self):
return f'Edge({repr(self.v)}, {self.weight})'
def __lt__(self, other):
return self.weight < other.weight
def __eq__(self, other):
return self.weight == other.weight
def __hash__(self):
return hash(repr(self))
class Graph:
def __init__(self, edges: list):
self.edges = edges
self.graph = defaultdict(list)
for u, v, w in self.edges:
self.graph[Node(u)]
self.graph[Node(v)]
for _ in self.edges:
source, dest, weight = _
source = Node(source)
dest = Node(dest)
edge = Edge(dest, weight)
if edge in self.graph[source]:
continue
self.graph[source].append(edge)
def dfs(self, s: Node):
print(f'Source: {s}')
self.source = s
self.reachable = defaultdict(list)
stack = []
stack.append(self.source)
self.source.visited = True
while stack:
u = stack.pop()
print(f'Popped: {u}')
for adjacent in self.graph[u]:
v, v_weight = adjacent.v, adjacent.weight
if not v.visited:
print(v, v_weight)
v.visited = True
stack.append(v)
if v in self.reachable[u]:
continue
self.reachable[u].append(v)
self.__connected()
def bfs(self, s: Node):
print(f'Source: {s}')
self.source = s
self.reachable = defaultdict(list)
queue = PriorityQueue()
queue.put(self.source)
self.source.visited = True
while queue.qsize():
u = queue.get()
print(f'Dequeued: {u}')
for adjacent in self.graph[u]:
v, v_weight = adjacent.v, adjacent.weight
if not v.visited:
print(v, v_weight)
v.visited = True
queue.put(v)
if v in self.reachable[u]:
continue
self.reachable[u].append(v)
self.__connected()
def dijsktra(self, s: Node):
print(f'Source: {s}')
self.source = s
self.dist = {k: math.inf for k in self.graph.keys()}
self.dist[source] = 0
self.previous = {}
queue = PriorityQueue()
queue.put(self.source)
self.source.visited = True
while queue.qsize():
u = queue.get()
# print(f'Dequeued: {u}')
for adjacent in self.graph[u]:
v, v_weight = adjacent.v, adjacent.weight
if not v.visited:
v.visited = True
queue.put(v)
alt = self.dist[u] + v_weight
if alt < self.dist[v]:
self.dist[v] = alt
self.previous[v] = u
def __connected(self):
for k, v in self.reachable.items():
print(f'{k}, {v}')
def is_reachable(self):
pass
def helper(self, node: Node):
try:
# print(self.distances[node])
# path.insert(0, self.previous[node])
print(self.previous[node], self.dist[node])
self.helper(self.previous[node])
except Exception as e:
pass
def print_path(self, destination: Node):
print(f'To: {destination}, cost: {self.dist[destination]}')
self.helper(destination)
def print_costs(self):
for k, v in self.dist.items():
print(repr(k), v)
@property
def nodes(self):
return self.graph.keys()
if __name__ == '__main__':
# edges = [(1,2,100),(1,3,4),(3,4,10),(4,5,20),(4,6,2),(2,3,2)]
# edges = [(1, 3, 4), (1, 2, 100), (3, 4, 10), (4, 5, 20), (4, 6, 2), (10, None, 0)]
# edges = [(1, 3, 4), (1, 2, 100), (3, 4, 10), (4, 5, 20), (4, 6, 2), (2, 3, 2), (3,5,2)]
edges = [
('a', 'b', 15),
('a', 'c', 13),
('a', 'd', 5),
('b', 'h', 12),
('c', 'b', 2),
('c', 'f', 6),
('c', 'd', 18),
('d', 'e', 4),
('d', 'i', 99),
('e', 'c', 3),
('e', 'f', 1),
('e', 'g', 9),
('e', 'i', 14),
('f', 'b', 8),
('f', 'h', 17),
('g', 'f', 16),
('g', 'h', 7),
('g', 'i', 10)
]
source = Node('a')
graph = Graph(edges)
# graph.dfs(source)
# graph.bfs(source)
graph.dijsktra(source)
# graph.print_path(Node('f'))
# graph.print_path(Node('b'))
# graph.print_path(Node('g'))
for _ in graph.nodes:
graph.print_path(_)
print('')
print('')
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class ReverseInK:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next or k == 1:
return head
dummy = ListNode()
dummy.next = head
begin = dummy # which is prev
i = 0
while head:
i += 1
if i % k == 0:
begin = self.reverse(begin, head.next)
head = begin.next
else:
head = head.next
return dummy.next
def reverse(self, begin: ListNode, end: ListNode) -> ListNode:
curr = begin.next
prev = begin
first = curr
curr_next = None
while curr != end:
curr_next = curr.next
curr.next = prev
prev = curr
curr = curr_next
begin.next = prev # prev is the new head after reversing, in the first run, this links dummy to the reversed head
first.next = curr # curr is at end after reversing, first was the first node but is now the last node after reversing
# connect the last node to the end
return first # first is the last node, thus returning it would be the new prev (begin) |
from typing import List
class NextPermutation:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead
"""
i = len(nums) - 2
while i >= 0 and nums[i + 1] <= nums[i]: # find first decreasing element from the end
i -= 1
if i >= 0: # if that first decreasing element is found,
j = len(nums) - 1
while j >= 0 and nums[j] <= nums[i]: # find the element that is just larger that that element
j -= 1
self.swap(nums, i, j) # swap those two elements
self.reverse(nums, i + 1) # reverse the list after the first found element;
# if the first decreasing element is not found (ex: 4321), then still reverse at 0th index.
def reverse(self, nums: List[int], start: int) -> None:
i = start
j = len(nums) - 1
while i < j:
self.swap(nums, i, j)
i += 1
j -= 1
def swap(self, nums: List[int], i: int, j: int) -> None:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
|
import heapq
from typing import List
class KClosestPointsToOrigin:
# We keep a min heap of size K.
# For each item, we insert an item to our heap.
# If inserting an item makes heap size larger than k, then we immediately pop an item after inserting (heappushpop).
# Runtime:
# Inserting an item to a heap of size k take O(logK) time.
# And we do this for each item points.
# So runtime is O(N * logK) where N is the length of points.
# Space: O(K) for our heap.
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
heap = []
for x, y in points:
dist = -(x * x + y * y) # default is min heap, so use negative to create max heap
if len(heap) == K:
heapq.heappushpop(heap, (dist, x, y))
else:
heapq.heappush(heap, (dist, x, y))
return [(x, y) for (dist, x, y) in heap]
|
class LRUCache:
def __init__(self, capacity: int):
self.size = capacity
self.cache = {}
self.next = {}
self.before = {}
self.head, self.tail = '#', '$'
self.connect(self.head, self.tail)
def connect(self, a, b):
self.next[a], self.before[b] = b, a
def delete(self, key):
self.connect(self.before[key], self.next[key])
del self.before[key], self.next[key], self.cache[key] # delete the before pointer to key and next pointer to key by deleting the key-value pair in before dict and next dict;
def append(self, key, val):
self.cache[key] = val
self.connect(self.before[self.tail], key) # append to the end
self.connect(key, self.tail) # order of the argument matters
if len(self.cache) > self.size:
self.delete(self.next[self.head]) # delete the lru at the front
def get(self, key: int) -> int:
if key not in self.cache:
return -1
val = self.cache[key] # get the value
self.delete(key) # delete the previous encounter
self.append(key, val) # add it back
return val
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.delete(key)
self.append(key, value)
|
class LongestPalindrome:
def longestPalindrome(self, s: str) -> str:
res = ""
for i in range(len(s)):
# odd case, like "aba"
temp = self.helper(s, i, i)
if len(temp) > len(res):
res = temp
# even case, like "abba"
temp = self.helper(s, i, i + 1)
if len(temp) > len(res):
res = temp
return res
# get the longest palindrome, l, r are the middle indexes
# from inner to outer
def helper(self, s: str, l: int, r: int) -> str:
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1 # move leftward from the left
r += 1 #move rightward from the right
return s[l+1:r] # return what is before the end of the while loop on both the left and right sides
|
from typing import List
class MergeSortedArray:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead
"""
p1 = m - 1
p2 = n - 1
p = m + n - 1
while p1 >= 0 and p2 >= 0:
if nums1[p1] <= nums2[p2]:
nums1[p] = nums2[p2] # put the larger number towards the back
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
# add the missing elements from nums2
# if nums2 exhausts first, then p2 would equal to -1, and nums2[:-1 + 1] == nums2[:0], which means nums1[:0] = [] (empty list), which does nothing
nums1[:p2 + 1] = nums2[:p2 + 1] |
# The user enters 10 numbers.
# Numbers displayed - odd numbers
list = []
for number in range(10):
number = int(input('Proszę o podanie cyfry:'))
number = round(number)
if number % 2 != 0:
list.append(number)
print(f'Odd numbers: {list}.') |
#Celsjusz → Fahrenheit. The program is done in a loop from 0 to 200 Fahrenheit, every 20.
#C = 5/9 * (F - 32) # formula Celsius → Fahrenheit
#Write a solution using while / for.
print('.' * 84)
for c in range(0, 200, 20):
cz = 5 / 9 * (c - 31)
print(f'Temperature in degrees Fahrenheit: {c} | Temperature in degrees Celsius: {round(cz, 2)}')
fahr = 0
print('.' * 84)
while fahr <= 200:
cel = C = 5/9 * (fahr - 32)
print(f'Temperature in degrees Fahrenheit: {fahr} | Temperature in degrees Celsius: {round(cel, 2)}')
fahr = fahr + 20 |
# Create a list.
# The list has dictionary values without duplicates.
days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}
daysList = days.values()
daysList = list(daysList)
for k in daysList:
daysList.remove(k)
print(daysList) |
# Create a multiplication table as a nested list 10 x 10 list. Table has row x column multiplication results.
width = 50
print('-' * width)
for k in range(1,11):
for m in range(1,11):
print(f'{k * m:^4}', end='|')
print()
print('-' * width) |
# The program asks the user for 4 digits
# then returns the sum of the numbers
print("------------------ SUM OF NUMBERS ------------------")
a, b, c, d = input('Enter 4 digits (separated by spaces): ').split(" ")
print(f'Numbers entered: {a}, {b}, {c}, {d}')
firstNumber = int(a)
secondNumber = int(b)
thirdNumber = int(c)
fourthNumber = int(d)
total = firstNumber + secondNumber + thirdNumber + fourthNumber
print(f'Sum of numbers - {total}.') |
# Make an integer tuple.
# The user gives any number.
# If the number is in the program, the program will display the index..
tuple = (1, 2, 3, 4, 5, 6, 7)
number = int(input('Enter the number: '))
if number in tuple:
print(f'Digit index: tuple.index(l)') |
"""
Advantages of Functional programming:
- Modularity: Writing functionally forces a certain degree of separation in solving your problems
and eases reuse in other contexts.
- Brevity: Functional programming is often less verbose than other paradigms.
- Concurrency: Purely functional functions are thread-safe and can run concurrently.
While it is not yet the case in Python, some functional languages do this automatically,
which can be a big help if you ever need to scale your application.
- Testability: It is a simple matter to test a functional program, in that, all you need is
a set of inputs and an expected set of outputs. They are idempotent.
See https://github.com/Joseph-H/some-py/blob/master/functional_demo.py and
https://github.com/Joseph-H/some-py/blob/master/itertools_demo.py
"""
def butlast(mylist):
"""Like butlast in Lisp; returns the list without the last element."""
return mylist[:-1] # This returns a copy of mylist
def remove_last_item(mylist):
"""Removes the last item from a list"""
mylist.pop(-1) # This modifies mylist
list = ['A', 'B', 'C']
# This function returns the modified copy of the list
new_list = butlast(list)
# Printing the modified copy returned by the function
print(new_list)
print(list) # The original list is not modified
# This function modifies the list passed to it
remove_last_item(list)
# Printing the list after it is modified
print(list)
|
def selection_sort(arr):
for i in range(len(arr)):
max = 0
for j in range(len(arr)-i):
if arr[j] > arr[max]:
max = j
tmp = arr[len(arr)-1-i]
arr[len(arr)-1-i] = arr[max]
arr[max] = tmp
return arr |
def bubble_sort(arr):
count = 0
for i in range(len(arr)-1):
for j in range(len(arr)- i - 1):
count += 1
if arr[j] > arr[j+1]:
tmp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = tmp
return arr, count
def short_bubble_sort(arr):
count = 0
for i in range(len(arr)-1):
change = False
for j in range(len(arr) - i - 1):
count += 1
if arr[j] > arr[j+1]:
change = True
tmp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = tmp
if change == False:
return arr, count
return arr, count
# test = [2,3,4,5,1]
# print bubble_sort(list(test))
# print short_bubble_sort(list(test))
|
def justify(words, K):
begin = 0
res = ""
while begin < len(words):
end = begin + 1
count = len(words[begin])
while end < len(words):
if count + len(words[end]) + 1 > K:
break
count += len(words[end]) + 1
end += 1
if end == len(words):
res += words[begin]
for index in range(begin+1, end):
res += f" {words[index]}"
for space in range(K-count):
res += " "
else:
spaces_to_add = K - count
num_between = end - begin - 1
spaces_between = (spaces_to_add // num_between) if num_between > 0 else 0
extra = spaces_to_add - (num_between * spaces_between)
res += words[begin]
for index in range(begin+1, end):
res += " " * (spaces_between + (1 if extra > 0 else 0))
extra -= 1
res += f" {words[index]}"
res += "\n"
begin = end
return res
print(justify(["a", "large", "fat", "stupid", "dog", "accidentally", "tripped", "over", "the", "skinny", "cat"], 20))
|
import math
# Also return closest if not found
def binary_search(arr, val, begin=None, end=None):
if begin is None:
begin = 0
if end is None:
end = len(arr) - 1
if begin >= end:
return end
mid = math.ceil((end - begin) / 2) + begin
print(begin, mid, end)
if arr[mid] == val:
return mid
elif arr[mid] > val:
return binary_search(arr, val, begin, mid-1)
else:
return binary_search(arr, val, mid+1, end)
test_case = [3,5,7,9,11,13]
print(binary_search(test_case, 12))
|
#a problem I saw where you have a list of values and you want to figure out if a pair of numbers in that list equals a particular sum
#Need a way to track the last move made and not to repeat that once I find a match
def find_pairs(sum, listofnumbers):
left = 0
right = len(listofnumbers) - 1
left_move = False
pairs = []
while(left != right):
if(listofnumbers[left] + listofnumbers[right] > sum):
right-=1
left_move = False
elif(listofnumbers[left] + listofnumbers[right] == sum):
temp = listofnumbers[left],listofnumbers[right]
pairs.append(list(temp))
if(left_move):
right-=1
left_move = False
else:
left+=1
left_move = True
else:
left+=1
left_move = True
return pairs
checking = find_pairs(8, [-1,-1,0,0,1,2,3,4,4,5,7,7,8,8,8,9,9,9])
print(checking)
|
#coding:utf-8
def fence_Crypto(msg,priority="row"):
'''
usage:
fence_Crypto(msg[, priority]) ---> to encrypt or decrypt the msg with fence crypto
args:
msg:
a plaintext which will be crypted or a ciphertext which will be decrypted
priority:
row priority or column priority,default is the former
return:
result:
if msg is plaintext,it contains all of possible ciphertext.
if msg is ciphertext,it contains all of possible plaintext
'''
msg_len = len(msg)
row_num = 1
result = []
if priority == "row":
while row_num<=msg_len:
temp = [msg[block_num::row_num] for block_num in xrange(row_num)]
result.append("".join(temp))
row_num += 1
return result
elif priority == "columns":
pass
else:
print "parameter error!please help(fence_Crypto)" |
import random
play=("rock" , "paper" , "scissor" )
game=random.choice( play )
print(game)
user= input(" enter rock , paper , or scissor " )
#while :
if (game==user) :
print ("tie")
while (user!=game) :
if (user=="rock") :
if game=="paper" :
print (" the computer wins the game " )
break
else :
print ("you have won the game" )
break
if (user=="paper" ) :
if (game=="rock") :
print (" you won the game " )
break
else :
print ("computer won the game " )
break
if ( user=="scissor") :
if (game=="rock") :
print ( "the computer won the game " )
break
else :
print ("you won the game " )
break
|
#!/usr/bin/env python
from timer import Timer
from collections import deque
import matplotlib.pyplot as plt
def test_list(timer, iterations):
"""Appends twice & pops form a list for the given number of iterations"""
timer.start()
a = list()
for i in range(iterations):
a.append(i)
a.append(i)
a.pop(0)
return timer.end()
def test_deque(timer, iterations):
"""Appends twice & pops form a deque for the given number of iterations"""
timer.start()
d = deque()
for i in range(iterations):
d.append(i)
d.append(i)
d.popleft()
return timer.end()
def main():
"""Compares list and deque for a defined number of iterations"""
timer = Timer()
iterations = 100000
time_list = test_list(timer, iterations)
print(u"\u279c Regular list: {}ms".format(time_list*1000))
time_deque = test_deque(timer, iterations)
print(u"\u279c Deque: {}ms".format(time_deque*1000))
print(u"\u279c Deque is {} faster than regular list for {} iterations."
.format(time_list/time_deque, iterations))
def main_with_plot():
"""Generates a plot for altering iteration numbers."""
timer = Timer()
max_iterations = 100000
iterations = []
list_durations = []
deque_durations = []
for i in range(0, max_iterations, 10000):
print("Processing {}/{}...".format(i, max_iterations))
iterations.append(i)
list_duration = test_list(timer, i)
deque_duration = test_deque(timer, i)
list_durations.append(list_duration)
deque_durations.append(deque_duration)
# Plotting
figure, ax = plt.subplots(figsize=(14, 10), facecolor='w')
ax.grid(True)
ax.plot(iterations, list_durations, '-xb', label='list')
ax.plot(iterations, deque_durations, '-xr', label='deque')
ax.set_xlabel("Iterations")
ax.set_ylabel("Time in seconds")
ax.legend(loc='upper left')
plt.show()
if __name__ == '__main__':
main()
main_with_plot()
|
import pandas as pd
import numpy
def load_datagrid(data_as_csv):
return pd.read_csv(data_as_csv)
def sort_dataframe(smaller_dataframe: pd.DataFrame):
#NOTE: Sorts the dataframe's values in ascending order based on all columns
smaller_2darray = smaller_dataframe.to_numpy()
# smaller_2darray = smaller_2darray[smaller_2darray[:,0].argsort()]
smaller_2darray = smaller_2darray [ :, smaller_2darray[1].argsort()]
columns = list(smaller_dataframe.columns)
sorted_dataframe = smaller_dataframe.sort_values(by=columns, ascending=True) # Sort dataframe by all columns
return sorted_dataframe
def dissimilarity(dataframe:pd.DataFrame, row: int, column: int):
smaller_dataframe = dataframe.iloc[0:row, 0:column] #NOTE: given col and row, get smaller 2d grid/ dataframe
sorted_dataframe = sort_dataframe(smaller_dataframe=smaller_dataframe) #NOTE: use pandas to sort_values to sort contens by all columns
return sorted_dataframe
if(__name__ == '__main__'):
this_dataframe = load_datagrid(data_as_csv="datagrid.csv")
# print(this_dataframe)
new_dataframe = dissimilarity(dataframe=this_dataframe, row=10, column=4)
# print(new_dataframe)
pass |
class Node:
def __init__(self,item):
self.item = item
self.proximo = None
def __str__(self):
return str(self.item)
class Stack:
def __init__(self):
self.top = None
self._tamanho = 0
def push(self, item):
novo = Node(item)
novo.proximo = self.top
self._tamanho += 1
self.top = novo
def pop(self):
if self._tamanho == 0:
raise IndexError('Pilha vazia.')
else:
item = self.top.item
self.top = self.top.proximo
self._tamanho -= 1
return item
def peek(self):
if self._tamanho > 0:
return self.top.item
raise IndexError('Pilha vazia.')
def __len__ (self):
return self._tamanho
def __repr__ (self):
r = ''
auxiliar = self.top
while auxiliar:
r += str(auxiliar.item) + '\n'
auxiliar = auxiliar.proximo
return r
#Permite usar a função print() para exibir a pilha
def __str__(self):
return self.__repr__()
|
#Pig latin by Nosa ...
vowel = ['a', 'e', 'i', 'o', 'u', 'y']
total = []
worde = raw_input("Give me a word!").lower().strip()
words = worde.split()
for word in words:
if not word.isalpha():
print(word + " is not a word")
else:
check = [1 if char in vowel else 0 for char in word]
same = (set(check))
print 'This is the check', check, 'This is the same', same
if check[0] == 1:
total.append(word+'yay')
elif len(same) == 1 and same[0] == 0:
total.append(word+'ay')
else:
argot = ''+word[0]
for value in range(1, len(check)):
if check[value] == check[value-1]:
argot += word[value]
else:
answer = word[value:]+argot
total.append(answer+'ay' if check[0] == 0
else answer+'yay')
break
print (" ".join(total)) |
day07回顾:
元组 tuple
元组的运算等于列表的运算
元组是不可变量的序列
字典 dict
可变的容器
键-值对方式进行映射存储
空典的存储是无序容器
添加/修改 字典的元素
字典[键] = 表达式返回值
删除
del 字典[键]
查看:
字典[键]
支持迭代访问
可迭代对象用处:
for 语句
各种推导式: 列表,字典,集合
for x in 字典:
print(x) # x绑定的键
v = 字典[x]
函数:
len,max,min,sum,any,all
字典推导式:
day08 笔记
集合 set
集合是可变的容器
集合内的数据对象都是唯一的(不能重复多次的)
集合是无序的存储结构,集合中的数据没有先后关系
集合内的元素必须是不可变对象
集合是可迭代对象
集合是相当于只有键没有值的字典(键则是集合的数据)
创建空的集合:
set()
创建非空的集合的字面值:
s = {1, 2, 3}
集合的构造函数:
set() 创建一个空的集合(不能用{} 来创建空集合)
set(iterable) 用可迭代对象创建一个新的集合
示例:
s = set()
s = {2,3,5,7}
s = set("ABC") # s = {'A', 'B', 'C'}
s = set("ABCCBA") # s = {'A', 'B', 'C'}
s = set({1:"1", 2:'2', 5:'5'}) # s = {1, 2, 5}
s = set(('ABC', '123', True))
s = {True, None, "ABC", (1, 2, 3)}
python3 中不可变数据类型
bool, int, float, complex, str, tuple, frozenset,bytes(后面才学)
None
可变数据类型
list, dict, set, bytearray(后面才学)
集合的运算:
交集& 并集| 补集- 对称补集^ 子集< 超集 >
& 用于生成两个集合的交集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1 & s2 # {2, 3}
| 生成两个集合的并集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1 | s2 # {1, 2, 3, 4}
- 生成两个集合的补集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1 - s2 # {1} # 生成属于s1, 但属于 s2的所元素的集合
^ 生成两个集合的对称补集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1 ^ s2 # {1, 4}
> 判断一个集合是另一个集合的超集
< 判断一个集合是别一个集合的子集
s1 = {1, 2, 3}
s2 = {2, 3}
s1 > s2 # True
s2 < s1 # True
== != 集合相同/不同
s1 = {1, 2, 3}
s2 = {3, 2, 1}
s1 == s2 # True
in / not in 运算
in 同列表和字典的in运算符规则相同,如果存在于集合中返回 True,否则返回False
示例:
2 in {1, 2, 3} # True
用于集合的函数
len(x) 返回集合的长度
max(x) 返回集合的最大值元素
min(x) 返回集合的最小值元素
sum(x) 返回集合中所有元素的和
any(x) 真值测试,规则与列表相同
all(x) 真值测试,规则与列表相同
集合是可迭代对象,可以用于for语句中
练习:
经理有: 曹操,刘备,孙权
技术员有: 曹操,孙权,张飞,关羽
用集合求:
1. 即是经理也是技术员的有谁?
2. 是经理,但不是技术人员的都有谁?
3. 是技术人员,但不是经理的都有谁?
4. 张飞是经理吗?
5. 身兼一职的人都有谁?
6. 经理和技术员共有几个人?
集合的方法:
详见:
>>> help(set)
文档参见:
python_base_docs_html/set.html
集合推导式:
是用可迭代对象创建集合的表达式
语法:
{表达式 for 变量 in 可迭代对象 [if 真值表达式]}
[] 部分代表可省略
示例:
numbers = [1, 3, 5, 7, 9, 3, 4, 5, 6, 7]
s = {x ** 2 for x in numbers if x % 2 == 1}
print(s)
固定集合 frozenset
固定集合是不可变的,无序的,含有唯一元素的集合
作用:
固定集合可以作为字典的键,也可以作为集合的值
固定集合的构造函数 frozenset
frozenset() 创建一个空的固定集合
frozenset(iterable) 用可迭代对象创建一个新的固定集合
示例:
fz = frozenset()
fz = frozenset("ABCAB")
fz = frozenset([1, 2, 3, 4, 5])
固定集合的运算:
& 交集
| 并集
- 补集
^ 对称补集
in / not in运算
> >= < <= == !=
(以上运算等同于集合的运算)
固定集合的方法:
相当于集合的全部方法去掉修改集合的方法
阶段总结:
数据类型:
不可变数据类型:
bool, int, float, complex, str, tuple, frozenset,bytes(后面才学)
可变的数据类型:
list, dict, set, bytearray(后面才学)
值:
None, False, True, ....
运算符:
+ - * / // % **
< <= > >= == !=
is , is not
in , not in
not and or
& | ^ ~ << >>
+(正号) -(负号)
表达式:
100
100 + 200
max(1,2,3) # 函数调用也是表达式
条件表达式 x if x > y else y
全部的推导式:
列表,字典,集合推导式(只有三种)
语句:
表达式 语句:
print("hello world!")
'''这是字符串'''
赋值语句:
a = 100
b = c = d = 200
x, y = 100, 200
列表[整数表达式] = 表达式
字典[键] = 表达式
if 语句
while语句
for 语句
break 语句
continue语句
pass 语句
del 语句
函数:
len(x),max(x), min(x), sum(x), any(x),all(x)
构造函数:
bool(x) int(x),float(x), complex(x),str(x)
list(x), tuple(x),dict(x),
set(x), frozenset(x)
abs(x) round(x), pow(x,y,z=None)
bin(x), oct(x), hex(x), chr(x), ord(x)
range(start, stop, step)
input(x), print(....)
函数 function
什么是函数
函数是可以重复执行的语句块,可以重复的调用
作用:
用于封装语句块,提高代码的重用性
定义用户级别的函数
def 语句
语法:
def 函数名(形参列表):
语句块(代码块)
作用:
用语句块创建一个函数,并用函数名变量绑定这个函数
语法说明:
1. 函数名是变量,它用于绑定语句块
2. 函数有自己的名字空间,在函数外部不可以访问函数内部的变量,在函数内部可以访问函数外部的变量
(要让函数处理外部的数据需要用参数给函数传入一些数据)
3. 函数不需要传入参数时,形参列表可以为空
4. 语句部分不能为空,如果为空需要填充pass语句
示例见:
def.py
def2.py
函数调用
函数名(实际调用传递参数)
注: 实际调用传递参数 以后称为实参
说明:
函数调用是一个表达式
如果函数内部没有return语句,则函数执行完毕后返回None对象
练习:
写一个函数 myadd,此函数中的参数列表里有两个参数x,y
此函数的功能是打印x+y的和
def myadd(...):
....
myadd(100, 200) # 300
myadd("ABC", '123') # ABC123
2. 写一个函数 print_even, 传入一个参数n代表终止整数
打印 2 4 6 8 ... n之间的所有偶数
函数定义如下:
def print_even(n):
... 此处自己完成
测试调用:
print_even(8)
2
4
6
8
return 语句:
语法:
return [表达式]
注: []代表可以省略其中的内容
作用:
用于函数中结束当前函数的执行,返回到调用该函数的地方,同时返回一个对象的引用关系
return 语句说明:
1. return 语句后跟表达式可以省略,省略后相当于 return None
2. 如果函数内没有 return 语句,则函数执行完最后一条语句后返回None(相当于在最后加了一条return None语句)
示例见:
return.py
练习:
写一个函数myadd2, 实现返回两个数的和:
如:
def myadd(a, b):
.... # 此处自己实现
#测试代码如下:
a = int(input("请输入第一个数: "))
b = int(input("请输入第二个数: "))
print("您输入的两个数之和是: ", myadd(a, b))
练习:
1. 写一个函数mymax, 实现返回两个数的最大值:
如:
def mymax(a, b):
...
print(mymax(100, 200)) # 200
print(mymax("ABCD", "ABC")) # ABCD
2. 写一个函数 input_number:
def input_number():
...
此函数用来获取用户输入的整数,当输入负数时结束输入.
将用户输入的数字以列表的形式返回,再用内建函数max,min,sum求出用户输入的最大值,最小值及和
L = input_number()
print(L) # 打印列表中的数据
print("用户输入的最大数是:", max(L))
print("用户输入的最小数是:", min(L))
print("用户输入的这些数的和是:", sum(L))
练习:
1. 编写函数fun,其功能是: 计算并返回下载多项式的值
Sn = 1 + 1/2 + 1/3 + 1/4 + .... + 1/n
函数如下:
def fun(n):
...
print(fun(3)) # 1.8333333333333
print(fun(10)) # ?????????????
2. 编写函数fun2,计算下列多项式的和
Sn = 1/(1*2) + 1/(2*3) + 1/(3*4) +
... + 1/n*(n+1) 的和
print(fun2(3)) # 0.75
print(fun2(1000))
练习:
1. 写一个函数 get_chinese_char_count,此函数实现的功能是从一个给定的字符串中返回中文字符的个数
def get_chinese_char_count(x):
...
s = input("请输入中英文混合的字符串:") # hello中国
print('您输入的中文的字符个数是:', get_chinese_char_count(s)) # 2
2. 写一个函数isprime(x) 判断x是否为素数,如果为素数,返回True,否则返回False
如:
print(isprime(5)) # True
print(isprime(6)) # False
3. 写一个函数prime_m2n(m, n) 返回从m开始,到n结束范围内的素数,返回这些素数的列表,并打印.
如:
L = prime_m2n(10, 20)
print(L) # [11, 13, 17, 19]
4. 写一个函数 primes(n) 返回指定范围内n(不包含n)的全部素数的列表,并打印这些列表
如:
L = primes(10)
print(L) # [2, 3, 5, 7]
1) 打印100以内全部素数的和
2) 打印200以内全部素数的和
5. 改写之前的学生信息管理程序,将其改为两个函数:
def input_student():
...
def output_student(L):
....
input_student用于从键盘读取学生数据,形成列表并返回列表
output_student(L) 用于将传和的列表L 打印成为表格
测试代码:
L = input_student()
print(L)
output_student(L) # 打印表格
|
#先假设没有'a'这个字符
cnt = 0
s = input("请输入任意字符生成字符串")
for c in s:
if c == 'a':
cnt += 1
print('a的个数是', cnt)
print("此时c变量的值为", c) |
# 2.给出一个数n,打印0+1+2+3+.....+n的值
# 说明:争取用函数来做
n = int(input('输入数字'))
def mysum(n):
y = 0
for x in range(n + 1):
y += x
return y
print(mysum(n)) |
# 2. 输入一个字符串,把输入的字符串中的空格全部去掉.
# 打印出处理后的字符串的长度和字符串内容
def huiwen():
s = input("请输入字符串: ")
r = s.replace(' ', '#')
print(r)
print(r[::-1])
if r == r[::-1]:
return True
return False
print(huiwen())
|
#方法1
d = {}
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for i in range(len(list2)):
d[list1[i]] = list2[i]
print(d)
#引申思考
# list1 和 list2 不等长怎么办
#1
d = {}
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
times = min(len(list1), len(liest2))
for i in range(times):
d[list1[i]] = list2[i]
#2
d = {}
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for i in range(len(list1)):
if i < len(list2):
d[list1[i]] = list2[i]
else:
d[list1[i]] = None |
import time
def alarm(h, m):
while True:
cur_time = time.localtime() # 得到本地时间
print("%02d:%02d:%02d" % cur_time[3:6],
end='\r')
time.sleep(1)
# if h == cur_time[3] and m == cur_time[4]:
if (h, m) == cur_time[3:5]:
print("\n时间到....")
return
if __name__ == '__main__':
hour = int(input("请输入定时的小时: "))
minute = int(input("请输入定时的分钟: "))
alarm(hour, minute)
|
# 4.思考题:
# 有五个朋友在一起,第五位说他比第四位大2岁,第四个人说比第三个人大2岁....第一个人10岁
# 编写程序,算出第五个人几岁
def fn(n):
if n == 1:
return 10
return 2 + fn(n-1)
print('第1个人的年龄是:', fn(1), '岁')
print('第2个人的年龄是:', fn(2), '岁')
print('第3个人的年龄是:', fn(3), '岁')
print('第4个人的年龄是:', fn(4), '岁')
print('第5个人的年龄是:', fn(5), '岁')
|
# 1.用生成器函数,生成质数,给出起始值begin和终止值stop,此生成器函数为
# prime(begin, end)
# 如果[x for x in prime(10, 20)] --> [11,13,17,19]
# 练习使用yield
# 方法1
# def isprime(n):
# for x in range(2, n):
# if n % x == 0:
# return False
# return True
# def prime(begin, end):
# for a in range(begin, end):
# if isprime(a):
# yield a
# L = [x for x in prime(10, 20)]
# print(L)
def primet(begin, end):
if begin < 1:
raise ValueError("begin不允许小于1")
for p in range(begin, end):
for x in range(2, p):
if p % x == 0:
break
else:
yield p
L = [x for x in primet(10, 20)]
print(L)
|
# if.py
# 输入一个数,判断这个数是奇数还是偶数,并打印出来
# x = int(input("请输入一个整数: "))
# if x % 2 == 1:
# print(x, '是奇数')
# else:
# print(x, '是偶数')
def Judge_the_odd_and_even():
x = int(input("请输入一个整数: "))
if x % 2 == 0:
return '偶数'
else:
return '奇数'
print(Judge_the_odd_and_even()) |
# 练习:
# 1. 已知矩形的长边长6cm,短边长4cm,用表达式求周长和面积
# 并打印出来
# print("周长是:", (6 + 4) * 2, 'cm')
# print("面积是:", 6 * 4, '平方厘米')
x = 6
y = 4
print('c=',eval('(x+y)*2'),'cm')
print('s=',eval('(x*y)'),'平方厘米') |
# # global2.py
# v = 100
# def fn():
# v = 200 # 不建议在global之前来创建局部变量
# print(v)
# # global v
# v = 300
# print(v)
# fn()
# print('v=', v) # 200
# static_method.py
#1
class A:
#@staticmethod
def myadd(self,a,b):
return a + b
a = A() # 创建实例
print(a.myadd(100, 200)) # 300
# a = A() # 创建实例
print(a.myadd(300, 400)) # 700
#2
class A:
#@staticmethod
def myadd(a,b):
return a + b
print(A.myadd(100, 200)) # 300
print(a.myadd(300, 400)) # 700
a = A() # 创建实例
print(a.myadd(300, 400)) #报错
#TypeError: myadd() takes 2 positional
#arguments but 3 were given
|
# 制作一个地图
map2048 = [[2, 0, 2, 4],
[2, 2, 4, 4],
[4, 8, 8, 2],
[0, 8, 4, 2]]
def _remove_zero(L):
'''删除列表里的零'''
try:
while True:
i = L.index(0) # index函数为在列表中寻找0,如果没有零则返回一个ValueError
L.pop(i)
except ValueError:
pass
def _left_shift(L):
# 删除所有的零
_remove_zero(L)
# 合并相邻的两个相同的元素将左侧的值做乘二操作,将右侧的值置零
for i in range(len(L) - 1):
if L[i] == L[i+1]:
L[i] *= 2
L[i+1] = 0
# 再次删除零
_remove_zero(L)
while len(L) < 4:
L.append(0)
def test():
for i in map2048:
_left_shift(i)
print(i)
if __name__ == "__main__":
test()
|
from utils import read_from_file, write_to_file
def naive_search(string: str, substring: str, case_insensitive: bool = False) -> list[int]:
occurrences: list[int] = []
if case_insensitive:
string, substring = map(str.lower, (string, substring))
for i in range(len(string) - len(substring) + 1):
for j in range(len(substring)):
if string[i + j] != substring[j]:
break
else:
occurrences.append(i)
return occurrences
if __name__ == '__main__':
text, query = read_from_file('files/file2.in')
result = naive_search(text, query)
print(result)
write_to_file(result)
# Regex implementation
import re
print([match.span()[0] for match in tuple(re.finditer(query, text))])
|
def isFirst_And_Last_Same(numberList):
firstElement = numberList[0]
lastElement = numberList[-1]
if(firstElement == lastElement):
return True
else:
return False
numList = [10, 20, 30, 40, 10]
print("The first and last number of a list is same")
print("result is", isFirst_And_Last_Same(numList))
|
"""
__echoes__
~~~~~~~
Functions of typer.echo() and typer.secho() function
FUNCTIONS
~~~~~~~
echo_file_not_found
echo_file_created
echo_file_exist
echo_file_empty
echo_file_found
echo_file_error
echo_file_valid
echo_cmd_changed
echo_cmd_added
generate_path
echo_fish
"""
import typer
import os
def echo_file_not_found():
typer.secho("FileNotFound: Please make sure "
"that your file name is cmd.yaml",
fg=typer.colors.RED,
bold=True,
err=True)
def echo_file_created():
typer.secho("cmd.yaml created.",
fg=typer.colors.CYAN,
bold=True)
def echo_file_exist():
typer.secho("'cmd.yaml' already exists.",
fg=typer.colors.GREEN,
bold=True)
def echo_file_empty():
typer.secho("\t'cmd.yaml' is empty. Please "
"enter any command into the file.",
fg=typer.colors.YELLOW,
bold=True)
def echo_file_found():
typer.secho("\t'cmd.yaml' file found!\n",
fg=typer.colors.GREEN,
bold=True)
def echo_file_error(e):
typer.secho(f"\tERROR in file : \n{e}",
fg=typer.colors.RED,
bold=True)
def echo_file_valid():
typer.secho("\t'cmd.yaml' is valid!",
fg=typer.colors.GREEN,
bold=True)
def echo_cmd_changed(key):
typer.secho("Command changed for name "
f"'{key}' in cmd.yaml",
fg=typer.colors.CYAN,
bold=True)
def echo_cmd_added():
typer.secho("Command added in cmd.yaml",
fg=typer.colors.CYAN,
bold=True)
# Command specific Echoes
def generate_path():
os.path.join(os.getcwd(), 'cmd.yaml').replace('\\\\', '\\')
def echo_list_header():
typer.secho(f"\t=======PCMD=======\n"
f"Path\t:{generate_path()}\n",
fg=typer.colors.BLUE,
bold=True)
def echo_inspect_header():
typer.secho("PCMD Inspection : ",
fg=typer.colors.BLUE,
bold=True)
# Info echoes
def echo_info_del_init():
typer.secho("INFO : Delete the file and type "
"'pcmd init' to create cmd.yaml file",
fg=typer.colors.CYAN,
bold=True)
def echo_info_init():
typer.secho("INFO : Type 'pcmd init' to "
"create cmd.yaml file",
fg=typer.colors.CYAN,
bold=True)
def echo_fish(string: str):
typer.secho(string,
fg=typer.colors.CYAN,
bold=True)
|
class Cuadruplo():
def __init__(self, numCuadruplo, operador, operandoIzq, operandoDer, resultado):
self.numCuadruplo = numCuadruplo
self.operador = operador
self.operandoIzq = operandoIzq
self.operandoDer = operandoDer
self.resultado = resultado
#Llena el salto para ir a otro cuadruplo
def LlenaResultado(self, numCuadruplo):
self.resultado = numCuadruplo
def __str__(self):
return (str(self.numCuadruplo) + "\t | \t" + str(self.operador) + "\t | \t" + str(self.operandoIzq) + "\t | \t" + str(self.operandoDer) + "\t | \t" + str(self.resultado))
|
####################################################################
# Copyright (C) Rocket Software 1993-2017
# Geocoding example: Calculate coordinates of a street address
# using Google MAPS API and response in JSON format
# Input is a "postal address" in the form of a human-readable address string and
# an indication whether the request comes from a device with a location sensor
# Response in JSON format contains an array of geocoded address information
# and geometry information. We are specifically interested in "lat" and "lng"
# values of the geometry location result.
import io as StringIO
from urllib.request import urlopen
from urllib.parse import urlencode
import json
class Point:
def __init__ (self, lat=0, lng=0):
self.lat = lat
self.lng = lng
def PointValue (self):
lat_str = "%.7f" % self.lat
lng_str = "%.7f" % self.lng
return lat_str + ', ' + lng_str
class decodeAddressException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def decodeAddressToGeocode( address ):
urlParams = {
'address': address,
'sensor': 'false',
}
url = 'http://maps.google.com/maps/api/geocode/json?' + urlencode(urlParams)
response = urlopen( url )
responseBody = str(response.read(), encoding='UTF-8')
body = StringIO.StringIO( responseBody )
result = json.load( body )
if 'status' not in result or result['status'] != 'OK':
if 'status' not in result:
raise decodeAddressException("Unknown error calling decodeAddressToGeocode")
else:
raise decodeAddressException("Error from decodeAddressToGeocode: " + result['status'])
else:
#latitude,longitude
coordinates = Point(result['results'][0]['geometry']['location']['lat'],\
result['results'][0]['geometry']['location']['lng'])
return coordinates
#################################################### |
import sqlite3
import csv
CSV_file = 'db_export_file.csv'
conn = sqlite3.connect('first_db.db')
c = conn.cursor()
export_list = []
headers = ["First Name", "Last Name", "Profession", "Age"]
for row in c.execute('SELECT * FROM people ORDER BY age'):
export_list.append(row)
with open(CSV_file, 'w') as export:
writer = csv.writer(export)
writer.writerow(headers)
writer.writerows(export_list)
|
# general format
##
##a = 0
##b = 5
##while a < b:
## a += 1
## print (a)
##else:
## print("Does the else print?")
## print("Yes. Yes it does, because it never hit a break")
##a = 0
##b = 5
##while a < b:
## a += 1
## print (a)
## break
##else:
## print("Does the else print?")
## print("Yes. Yes it does, because it never hit a break")
##
##print("I am the first piece of code outside the whlle loop. I thought you'd never get to me")
# parse out odd numbers
##x = 10
##count = 0
##odds = []
##while x:
## x = x -1
## count = count + 1
## if x % 2 == 0:
## continue
## odds.append(x)
## print("Which interation? ", count, "Odd Number: ", x)
##
##print("Here are all the odds numbers: ", odds)
# The magic number tp guess is 6
while True:
user_guess = int(input("Guess a number between 1 and 10: "))
if user_guess < 6:
print("Sorry that number is too low, try again.")
elif user_guess > 6:
print("Sorry that number is too high, try again.")
else:
print('You guess right. The magic number is 6!!')
break
print("Game over!")
|
###itertools
####from itertools import *
##
### create a new iterator
###syntax: iterttols.count(start,step)
##
###this would go on forever
####x = count(10)
####for i in x:
#### print(x)
##
### but done this way
### it would start at 2, end at but dont include 10
##
####for num in islice(count(), 2, 10):
#### print(num, end = " ")
##
### cycle
####count = 0
####for x in cycle([1,2,3,4,5]):
#### count += 1
#### if count == 25:
#### break
#### print(x, end = ' ')
##
###repeat
####def my_func(x):
#### return x+x
####my_set = {'a', 'b', 'c'}
####
####for x in repeat (my_func(2), 6):
#### print(x, end = ' ')
##
##### chain()
####list1 = [1,2,3]
####tup1 = (2,3,4)
####set1 = {"a", "b", "c"}
####for x in chain(list1, tup1, set1):
#### print(x, end = ' ')
##
###islice()
##
####list1 = [1,2,3,4,5,6,7,8,9]
####for x in islice(list1, 1, 9, 2):
#### print(x)
##
### accumulate()
####from itertools import *
####from operator import *
#####find the max value
####list1 = [2,1,4,6,8,10,2,4,6,7,9,11,23,4]
####x = list(accumulate(list1, max))
####print(x)
### output: [2, 2, 4, 6, 8, 10, 10, 10, 10, 10, 10, 11, 23, 23]
##
###find the min value
####list1 = [2,1,4,6,8,10,2,4,6,7,9,11,23,4]
####x = list(accumulate(list1, min))
####print(x)
##### output: [2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
####
##### find the running product mul standard for multiply
##### from operator.mul package
####nums = [2.5, 1.75, 4.0, 12.25]
####x = list(accumulate(nums, mul))
####print(x)
##### output: [2.5, 4.375, 17.5, 214.375]
####
##### subtract each number of the list from the one before
##### from operator.sub package
####nums = [1,3,4,5]
####x = list(accumulate(nums, sub))
####print(x)
##### output: [1, -2, -6, -11]
####
##### concatenate each number of the list to one after it
##### from operator.concat package
####ani = ["cat", "-fish", "-frogs", "-clams", "-rooster"]
####x = list(accumulate(ani, concat))
####print(x)
###Output: ['cat', 'cat-fish', 'cat-fish-frogs', 'cat-fish-frogs-clams', 'cat-fish-frogs-clams-rooster']
# can do Amortization
# Amortize a 2.5% loan of 3000 with 12 annual payments of 100\
##from itertools import *
##payments = [10000, -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
## -261, -261, -261]
##amor = list(accumulate(payments, lambda bal, pmt: bal * 1.025 + pmt))
##payment = 0
##for pay in amor:
## print("Payment Number: ", payment, "Loan Amt.: ", pay)
## payment += 1
## # tee
##from itertools import *
##my_list = ["a", "b", "c", "d"]
##screen, file1 = tee(my_list)
##
##for i in screen:
## print( "To the Screen: ", i)
##my_file = open("my_file.txt", "w")
##for i in file1:
## print ( "To The File", i, file =my_file)
##my_file.close()
#startmap
from itertools import *
##
##def fun():
## my_list = ['a', 'b', 'c', 'd']
## return my_list
##
##tup1 = ((1, 2),(2,3),(3,4))
##
##
##for i in starmap(fun(), tup1):
## print(i, end = ' ')
##from itertools import *
##
##values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
##for i in starmap(lambda x,y:(x, y, x*y), values):
## print(i)
##import os
##my_tup = [("/dir_1", "file1"),("/dir_2", "file2"), ("/dir_3", "file3")]
##x = starmap(os.path.join, my_tup)
##
##for i in x:
## print(i)
# filterfalse()
##from itertools import *
##
##def less_than_20(x):
## return x < 20
##
##my_list = [1,3,5,6,10,20,30,40]
##my_filt_false = filterfalse(less_than_20, my_list)
##
##for x in my_filt_false:
## print(x)
##from itertools import *
##
##def less_than_20(x):
## return x < 20
##
##my_filt_false = takewhile(less_than_20, count())
##
##for x in my_filt_false:
## print(x, end = ' ')
##from itertools import *
##
##def less_than_20(x):
## return x < 20
##
##my_list = [1,5,6,7,8,18,19,20,21,22,23]
##my_drop = dropwhile(less_than_20, my_list )
##
##for x in my_drop:
## print(x, end = ' ')
##from itertools import *
##
##list1 = [1,2,3,4,5,6,7]
##list2 = [0,0,0,1,1,1,0]
##
##my_comp = compress(list1, list2)
##for x in my_comp:
## print(x, end = ' ')
##
##from itertools import *
##
##list1 = [1,2,3,4]
##x = combinations(list1, 2)
##
##for i in x:
## print(i, end= ' ')
##
##
##
##from itertools import *
##
##list1 = [1,2,3,4]
##x =permutations(list1)
##
##for i in x:
## print(i, end= ' ')
##from itertools import *
##
##list1 = [1,2,3,4]
##x =combinations_with_replacement(list1, 2)
##
##for i in x:
## print(i, )
## groupby()
from itertools import zip_longest
for i in zip_longest([1,2,3,4], ["a", "b", "c"],'4567', 'hello'):
print (i)
|
# timedelta
from datetime import timedelta, datetime, date
##print(timedelta(days=365))
##print("today is: " + str(datetime.now()))
##print("30 days from day will be:" + str(datetime.now() + timedelta(days=30)))
##print("60 days from day will be:" + str(datetime.now() + timedelta(days=60)))
##print("90 days ago was: " + str(datetime.now() - timedelta(days=90)))
##today = date.today()
##hw = date(2018,10,31)
##diff= (today - hw.days)
##print("How many days between today and last halloween? ", )
#How many days was Halloween (10/31/2018)?
today = date.today()
hw = date(2018,10,31)
print(("Halloween was: {0} days ago".format((today -hw).days)))
# how many seconds are in a year?
year = timedelta(days=365)
print("There are {0} seconds in a year. Use them wisely" \
.format(year.total_seconds()))
# how many days in 5 years?
print( "How many days in 5 years: ", (5 *year).days)
|
"""
Sprites in Point of No Return
"""
from enum import Enum
from math import atan2, pi
import pygame
from pygame.sprite import Sprite
import src.constants as constants
import src.utils as utils
class Direction(Enum):
"""
An enum that represents the four directions. Evaluated to a tuple of two
ints, which is the direction on a -1 to 1 scale in x-y coordinates
"""
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def __repr__(self):
if self == Direction.UP:
return "up"
if self == Direction.DOWN:
return "down"
if self == Direction.LEFT:
return "left"
if self == Direction.RIGHT:
return "right"
return None
class GameSprite(Sprite): # pylint: disable=too-many-instance-attributes
"""
A sprite class to represent any basic objects and characters
Attributes:
surf: a pygame surface, the display image for the sprite
rect: a pygame rectangle, defines the position of the sprite
mask: a pygame mask, defines the hit-box for the sprite from the surf
_spawn_pos: a tuple of two ints, the spawn position of the sprite
_animations: a dictionary with animation sequence names as keys and
dictionaries with the information for each animation sequence
(images, center positions, animation frame rate)
_animation_frame: an int, the current frame of the animation
_layer: an int, the layer to display the sprite on
_last_animation: a tuple, first element is the animation dict from
_animations, second element is the frame of that animation
_game: a Game that contains all the sprites
"""
def __init__(self, game, image_path, spawn_pos=None):
"""
Initializes the character by setting surf and rect, and setting the
given image.
Args:
game: a Game that holds all the sprites
image_path: string giving the path to the character art
spawn_pos: tuple of 2 ints, where to spawn this character, defaults
to the center of the screen
"""
super().__init__()
# Creates animations dictionary and a key for the still images
self._animations = {'stills': utils.get_animation_info(
f'{constants.IMAGE_FOLDER}/{image_path}')}
# Sets current character image to the first still
self.surf = self._animations['stills']['animations'][0]
self._animation_frame = 0
# Default spawn position is the center of the screen
if spawn_pos is None:
self.rect = self.surf.get_rect(center=(constants.SCREEN_WIDTH / 2,
constants.SCREEN_HEIGHT / 2))
self._spawn_pos = (constants.SCREEN_WIDTH / 2,
constants.SCREEN_HEIGHT / 2)
else:
self.rect = self.surf.get_rect(center=spawn_pos)
self._spawn_pos = spawn_pos
self.mask = pygame.mask.from_surface(self.surf)
self._last_animation = (self._animations["stills"], 0)
self._layer = self.rect.bottom
self._game = game
@property
def layer(self):
"""
Returns the display layer for the sprite
"""
return self._layer
@property
def current_animation_name(self):
"""
Returns the name of the current animation
"""
return 'stills'
@property
def current_animation(self):
"""
Returns the current animation type for the sprite
"""
return self._animations[self.current_animation_name]
@property
def last_animation(self):
"""
Returns a dictionary of all the information for the last animation
"""
return self._last_animation[0]
@property
def last_frame(self):
"""
Returns the frame number the last animation was on
"""
return self._last_animation[1]
def reset(self):
"""
Reset the sprite attributes
"""
self.rect.center = self._spawn_pos
def update(self, *args, **kwargs):
"""
Updates the character's current animation and does any other necessary
changes to the character's state.
"""
if self._animation_frame >= len(self.current_animation['animations'])\
* self.current_animation['frame_length']:
self._animation_frame = 0
last_surf = self.surf
frame = int(self._animation_frame
// self.current_animation['frame_length'])
self.surf = self.current_animation['animations'][frame]
if last_surf != self.surf:
self.mask = pygame.mask.from_surface(self.surf)
last_pos = self._last_animation[0]['positions'][self._last_animation[1]]
current_pos = self.current_animation['positions'][frame]
delta = (last_pos[0] - current_pos[0], last_pos[1] - current_pos[1])
self.move(delta)
self._animation_frame += 1
self._last_animation = (self.current_animation, frame)
def move(self, delta_pos):
"""
Moves the sprite's current position a certain number of pixels
Args:
delta_pos: tuple of 2 ints, x/y number of pixels to move
"""
self.rect.move_ip(int(delta_pos[0]), int(delta_pos[1]))
self._layer = self.rect.bottom
class MovingSprite(GameSprite):
"""
A sprite class to represent a basic character/object that can move
Attributes:
_speed: maximum speed in pixels per second
_current_direction: a tuple of two floats, the last direction this
sprite moved, on a -1 to 1 scale relative to _speed and ignoring
motion of the screen
_current_facing: a Direction (Up, Down, Left, Right), which way this
sprite is currently facing
_obstacle_collisions: a boolean, whether to alter direction based on
obstacle collisions
"""
def __init__(self, game, speed, image_path, obstacle_collisions=True,
spawn_pos=None):
"""
Initializes the character by setting surf and rect, and setting the
animation frame images.
Args:
speed: int, the max character speed in pixels/second
spawn_pos: tuple of 2 ints, where to spawn this character, defaults
to top left
image_path: string giving the path to the character art
"""
super().__init__(game, image_path, spawn_pos)
# Add the images for the other animation types to the animations
# dictionary
path = f'{constants.IMAGE_FOLDER}/{image_path}'
for direction in ("up", "down", "left", "right"):
self._animations[direction] = utils.get_animation_info(
f'{path}/{direction}')
still = f'still_{direction}'
self._animations[still] = {}
self._animations[still]['animations'] =\
self._animations[direction]['animations'][0:1]
self._animations[still]['frame_length'] =\
self._animations[direction]['frame_length']
self._animations[still]['positions'] =\
self._animations[direction]['positions'][0:1]
self._speed = speed
self._current_direction = (0, 0)
self._current_facing = Direction.UP
self._obstacle_collisions = obstacle_collisions
@property
def speed(self):
"""
Returns the speed in pixels per second
"""
return self._speed
@property
def frame_speed(self):
"""
Returns the pixels per frame speed
"""
return self._speed / constants.FRAME_RATE
@property
def current_direction(self):
"""
Returns the last direction the sprite faced as a tuple from -1 to 1
"""
return self._current_direction
@property
def current_angle(self):
"""
Returns the angle the player is currently facing in degrees
"""
return atan2(self._current_direction[1], self._current_direction[0])\
* 180 / pi
@property
def current_facing(self):
"""
Returns the current Direction facing of the sprite
"""
if self.current_direction == (0, 0):
return self._current_facing
angle = self.current_angle
if -45 <= angle <= 45:
self._current_facing = Direction.RIGHT
elif 45 < angle < 135:
self._current_facing = Direction.DOWN
elif -135 < angle < -45:
self._current_facing = Direction.UP
elif abs(angle) >= 135:
self._current_facing = Direction.LEFT
return self._current_facing
@property
def current_animation_name(self):
"""
Returns the current animation name of the sprite based on the facing
"""
if self._current_direction == (0, 0):
return f'still_{repr(self.current_facing)}'
return repr(self.current_facing)
def reset(self):
"""
Reset the sprite attributes
"""
super().reset()
self._current_direction = (0, 0)
self._current_facing = Direction.UP
def set_direction(self, direction):
"""
Sets the current direction
Args:
direction: tuple of 2 floats from -1 to 1, x/y coordinates of
target speed as percentage of max
"""
self._current_direction = direction
def update(self, *args, **kwargs):
"""
Updates the character's current position and animation. Also detects
obstacle collisions and sets the direction accordingly.
"""
super().update()
# Detect obstacle collisions and move the sprite accordingly
if self._obstacle_collisions:
collisions = utils.spritecollide(self, self._game.obstacles)
for obstacle in collisions:
threshold = self.rect.height * .25
if (obstacle.rect.bottom <= self.rect.bottom <=
obstacle.rect.bottom + threshold and
self.current_direction[1] < 0) or\
(obstacle.rect.bottom - threshold <= self.rect.bottom <=
obstacle.rect.bottom and self.current_direction[1] >
0):
self.set_direction((self.current_direction[0], 0))
# Move sprite in desired direction
self.move((self.current_direction[0] * self.frame_speed,
self.current_direction[1] * self.frame_speed))
# pylint: disable=too-many-instance-attributes
class AttackingSprite(MovingSprite):
"""
A sprite for a character that can attack
Attributes:
_attacking: a boolean, True if the sprite is currently attacking and
False if not
_max_health: an int representing the maximum health of the sprite
_health: an int representing the sprite's current health
_max_invincibility: an int representing how many frames the sprite has
invincibility after being attacked
_invincibility: an int representing how many more frames this sprite is
invincible for
_max_knockback: an int representing the maximum number of frames this
sprite will be knocked back for
_knockback: an int representing how many more frames this sprite is
being knocked-back for
_knockback_dist: an int representing how many pixels the sprite gets
knocked-back after an attack
_knockback_direction: a tuple of two floats representing which direction
the sprite is getting knocked back in
"""
# pylint: disable=too-many-arguments
def __init__(self, game, speed, image_path, obstacle_collisions=True,
spawn_pos=None, max_health=1,
invincibility_time=constants.DEFAULT_INVINCIBILITY,
knockback_time=constants.DEFAULT_KNOCKBACK_TIME,
knockback_dist=constants.DEFAULT_KNOCKBACK_DIST):
"""
Initializes the character by setting surf and rect, and setting the
animation images and other attributes
Args:
game: a Game that contains all the sprites
speed: int, the max character speed in pixels/second
spawn_pos: tuple of 2 ints, where to spawn this character, defaults
to top left
image_path: string giving the path to the character art. Defaults
to None, which will set a white 50x50 square
obstacle_collisions: whether this sprite will be stopped by
obstacles
max_health: int representing the max health of the sprite
invincibility_time: a float, the time in seconds that this sprite
is invincible for after being attacked.
knockback_time: a float, the time in seconds that this sprite gets
knocked backward for after being attacked
knockback_dist: an int, the number of pixels the sprite gets knocked
back after being attacked
"""
super().__init__(game, speed, image_path,
obstacle_collisions=obstacle_collisions,
spawn_pos=spawn_pos)
# Add attacking animations
path = f'{constants.IMAGE_FOLDER}/{image_path}'
for animation in ("attack_up", "attack_down", "attack_left",
"attack_right"):
self._animations[animation] = utils.get_animation_info(
f'{path}/{animation}')
self._attacking = False
self._max_health = max_health
self._health = self._max_health
self._max_invincibility = invincibility_time * constants.FRAME_RATE
self._invincibility = 0
self._max_knockback = knockback_time * constants.FRAME_RATE
self._knockback = 0
self._knockback_dist = knockback_dist
self._knockback_direction = (0, 0)
@property
def health(self):
"""
Returns the current health of the sprite
"""
return self._health
@property
def is_invincible(self):
"""
Returns whether the sprite is currently invincible
"""
return self._invincibility > 0
@property
def invincibility_time(self):
"""
Returns how much longer the sprite is invincible for in seconds
"""
return self._invincibility / constants.FRAME_RATE
@property
def is_attacking(self):
"""
Returns whether the sprite is currently attacking
"""
return self._attacking
@property
def attack_started(self):
"""
Returns whether the sprite just started an attack
"""
return self.is_attacking and self._animation_frame <= 1
@property
def current_animation_name(self):
"""
Returns the current animation name of the sprite as a string
"""
if self._knockback > 0:
return f'still_{repr(self.current_facing)}'
if self.is_attacking:
return f'attack_{repr(self.current_facing)}'
return super().current_animation_name
@property
def current_facing(self):
"""
Return the sprite's current Direction facing
"""
if self.is_attacking or self._knockback > 0:
return self._current_facing
return super().current_facing
def reset(self):
"""
Resets the sprite attributes
"""
super().reset()
self._attacking = False
self._health = self._max_health
self._invincibility = 0
self._knockback = 0
def damage(self, attack_direction):
"""
Damages the sprite by removing 1 from its health and initiates knockback
Args:
attack_direction: an (x, y) tuple that gives the way the attack was
taken (and the way this sprite will be knocked back)
"""
if self.is_invincible:
return
self._health -= 1
self._invincibility = self._max_invincibility
dist = (attack_direction[0]**2 + attack_direction[1]**2) ** 0.5
self._knockback_direction = (attack_direction[0] / dist,
attack_direction[1] / dist)
self._knockback = self._max_knockback
def attack(self, direction=None):
"""
Initiates an attack
Args:
direction: which way to start the attack. Defaults to the current
way the sprite is facing
"""
if direction is None:
direction = self.current_facing
self._current_facing = direction
self._attacking = True
self._animation_frame = 0
def update(self, *args, **kwargs):
"""
Updates the state of the sprite including animation and movement
"""
# Handle the sprite getting knocked back by an attack
if self._knockback > 0:
step = self._knockback_dist/self._max_knockback / self.frame_speed
self.set_direction((self.current_direction[0] +
self._knockback_direction[0] * step,
self.current_direction[1] +
self._knockback_direction[1] * step))
super().update()
# Handle the sprite attacking
if self._attacking and self._animation_frame == len(
self.current_animation['animations']) * int(
self.current_animation['frame_length']):
self._attacking = False
# Handle if the sprite is invincible and flash the image
if self.is_invincible:
self._invincibility -= 1
if (self.invincibility_time // constants.TRANSPARENT_TIME) \
% 2 == 0:
self.surf.set_alpha(255)
else:
self.surf.set_alpha(constants.INVINCIBILITY_ALPHA)
else:
self.surf.set_alpha(255)
# Change the knockback time left
if self._knockback > 0:
self._knockback -= 1
class Player(AttackingSprite):
"""
A sprite for the player
"""
def __init__(self, game):
"""
Initializes the player
Args:
game: a Game that contains all the sprites
"""
super().__init__(game, constants.PLAYER_SPEED, 'player',
max_health=constants.PLAYER_HEALTH,
invincibility_time=constants.PLAYER_INVINCIBILITY)
def set_direction(self, direction):
"""
Sets the current direction and ensures that it can't go off screen
Args:
direction: tuple of 2 floats from -1 to 1, x/y coordinates of
target speed as percentage of max
"""
delta_pos = (direction[0] * self.frame_speed,
direction[1] * self.frame_speed)
if self.rect.left + delta_pos[0] < 0\
or self.rect.right + delta_pos[0] > constants.SCREEN_WIDTH:
self._current_direction = (0, direction[1])
elif self.rect.top + delta_pos[1] < 0\
or self.rect.bottom + delta_pos[1] > constants.SCREEN_HEIGHT:
self._current_direction = (direction[0], 0)
else:
self._current_direction = direction
class Demon(AttackingSprite):
"""
A sprite for all the enemies
"""
def __init__(self, game, spawn_pos=None):
"""
Initializes the demon
Args:
game: a Game that contains all the sprites
spawn_pos: a tuple of 2 ints, where to spawn the demon, defaults
to the center of the screen
"""
super().__init__(game, constants.DEMON_SPEED, 'demon',
spawn_pos=spawn_pos, max_health=constants.DEMON_HEALTH,
invincibility_time=constants.DEMON_INVINCIBILITY)
class Flashlight(MovingSprite):
"""
A transparent sprite for the flashlight beam
"""
def __init__(self, game):
"""
Initializes the flashlight
Args:
game: a Game that contains all the sprites
"""
super().__init__(game, constants.PLAYER_SPEED, 'flashlight',
obstacle_collisions=False,
spawn_pos=constants.FLASHLIGHT_SPAWN)
@property
def current_animation_name(self):
"""
Returns the current animation name of the flashlight
"""
player_ani = self._game.player.current_animation_name
return player_ani[player_ani.find('_') + 1:]
class Obstacle(GameSprite):
"""
A sprite for game obstacles
"""
def __init__(self, game, spawn_pos=None):
"""
Initializes the obstacle
Args:
game: a Game that contains all the sprites
spawn_pos: a tuple of 2 ints, where to spawn the obstacle, defaults
to the center of the screen
"""
super().__init__(game, 'obstacle', spawn_pos=spawn_pos)
|
"""
Controllers for Point of No Return
"""
from abc import ABC, abstractmethod
import pygame
import src.constants as constants
from src.constants import MOVES
from src.sprites import Direction
class Controller(ABC):
"""
Controls sprites in the game
Attributes:
_game: an instance of Game to update the state of
_sprite: a Sprite or Sprite group to update with the controller
"""
def __init__(self, game, sprite):
"""
Initializes the controller
Args:
game: a Game to update the state of
sprite: a Sprite or a Sprite group to update using the controller
"""
self._game = game
self._sprite = sprite
@property
def game(self):
"""
Returns the game state
"""
return self._game
@property
def sprite(self):
"""
Returns the sprite for the controller
"""
return self._sprite
@abstractmethod
def update(self):
"""
Updates the game model based on player inputs
"""
return
class PlayerController(Controller):
"""
Controls the player with player input
"""
def __init__(self, game):
"""
Creates a Controller for the player
Args:
game: a Game containing the player to update with this controller
and the game state to update
"""
super().__init__(game, game.player)
def update(self):
"""
Updates the player state based on user keyboard input
"""
pressed_keys = pygame.key.get_pressed()
# If the sprite is attacking, lock the player's movement
if self.sprite.is_attacking:
self.sprite.set_direction((0, 0))
else:
if pressed_keys[MOVES['attack']]:
self.sprite.attack()
elif pressed_keys[MOVES['attack_up']]:
self.sprite.attack(Direction.UP)
elif pressed_keys[MOVES['attack_down']]:
self.sprite.attack(Direction.DOWN)
elif pressed_keys[MOVES['attack_left']]:
self.sprite.attack(Direction.LEFT)
elif pressed_keys[MOVES['attack_right']]:
self.sprite.attack(Direction.RIGHT)
else:
direction = [pressed_keys[MOVES['right']]
- pressed_keys[MOVES['left']],
pressed_keys[MOVES['down']]
- pressed_keys[MOVES['up']]]
if (direction[0] > 0 and self.sprite.rect.right >=
constants.SCREEN_WIDTH) or (direction[0] < 0 and
self.sprite.rect.left <= 0):
direction[0] = 0
if (direction[1] > 0 and self.sprite.rect.bottom >=
constants.SCREEN_HEIGHT) or (direction[1] < 0 and
self.sprite.rect.top <= 0):
direction[1] = 0
self.sprite.set_direction((direction[0], direction[1]))
self.sprite.update()
class DemonController(Controller):
"""
Controls the demons
"""
def __init__(self, game):
"""
Creates a Controller for the demons
Args:
game: a Game containing the demon Sprite Group to update with this
controller and the game state to update
"""
super().__init__(game, game.demons)
def update(self):
"""
Updates the demon states to move towards the player
"""
for demon in self.sprite:
player_pos = self.game.player.rect.center
direction = (player_pos[0] - demon.rect.centerx,
player_pos[1] - demon.rect.centery)
dist = (direction[0] ** 2 + direction[1] ** 2) ** 0.5
if dist == 0:
continue
scale = 1 / dist
if self.game.player.is_invincible:
scale *= constants.DEMON_SLOW_SCALE
demon.set_direction((direction[0] * scale, direction[1] * scale))
demon.update()
class ScrollController(Controller):
"""
Controls all sprites to make the game scroll with player
"""
def __init__(self, game):
"""
Creates a Controller for all of the sprites
Args:
game: a Game containing the Sprites to update with this controller
and the game state to update
"""
super().__init__(game, game.all_sprites)
def update(self):
"""
Updates all sprite positions to scroll as the player moves vertically
"""
for entity in self.sprite:
entity.move((0, -self.game.player.current_direction[1]
* self.game.player.frame_speed))
for obs in self.game.obstacles:
obs.update()
|
# MY FIRST ATTEMPT
# import calendar
#
# year_one = 2017
# year_two = 2020
#
# month_one = 5
# month_two = 11
#
# date_one = 9
# date_two = 27
###############################################################################
# MY SECOND ATTEMPT AFTER VIEWING THE SOLUTION
from datetime import date
first_date = date(2020, 3, 5)
second_date = date(2020, 9, 27)
num_of_days = second_date - first_date
print(num_of_days.days) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.