text
stringlengths 37
1.41M
|
---|
"""
Write a program that takes an integer and sets the nth bit in binary representation of that integer
"""
def setBit(n,k):
print(bin(n))
#We simply shift one by K bits
a = 1 << k
print(a)
#Now, all we have to do is or the n and the a, this will give the new integer obtained after setting that bit
print(bin(n|a))
return (n | a)
n = int(input("Enter the number:\t"))
k = int(input("Enter the bit number:\t"))
print("The result is ",setBit(n,k))
|
str1 = input("Enter the string:\t")
map1 = {}
list1 = []
for i in str1:
if i in map1:
list1.append(i)
else:
map1[i] = 1
print("THe duplicate characters are:\t",list1)
|
class TrieNode:
def __init__(self):
## Initialize this node in the Trie
self.children = {}
self.is_word = False
pass
def insert(self, char):
if char not in self.children:
self.children[char] = TrieNode()
pass
def suffixes(self, suffix = ''):
## Recursive function that collects the suffix for
## all complete words below this point
results = []
for char, node in self.children.items():
if node.is_word:
results.append(suffix + char)
results.extend(node.suffixes(suffix + char))
return results
class Trie(object):
""" The Trie itself containing the root node and insert/find functions """
def __init__(self):
""" Initialize this Trie (add a root node) """
self.root = TrieNode()
def insert(self, word):
""" Add a word to the Trie """
trieNode = self.root
for char in word:
if char not in trieNode.children:
trieNode.insert(char)
trieNode = trieNode.children[char]
trieNode.is_word = True
def find(self, prefix):
if prefix == "":
print("No results!")
#This simply returns the node of the end character of the prefix,
#And if no such prefix is present it simply returns False.
findNode = self.root
for char in prefix:
if char not in findNode.children:
return False
findNode = findNode.children[char]
return findNode
MyTrie = Trie()
wordList = [
"ant", "anthology", "antagonist", "antonym",
"fun", "function", "factory",
"trie", "trigger", "trigonometry", "tripod"
]
for word in wordList:
MyTrie.insert(word)
from ipywidgets import widgets
from IPython.display import display
from ipywidgets import interact
def f(prefix):
if prefix != '':
prefixNode = MyTrie.find(prefix)
if prefixNode:
print('\n'.join(prefixNode.suffixes()))
else:
print(prefix + " not found")
else:
print("No matches")
print('')
#Input 1
print("Input 1: ")
prefix = "tr"
f(prefix)
print()
#Input 2
print("Input 2")
prefix = "an"
f(prefix)
print()
#Input 3
print("Input 3")
prefix = "f"
f(prefix)
#Input 4
print("Input 4")
prefix = "ant"
f(prefix)
#Input 5 (Edge case)
print("Input 5")
prefix = ""
f(prefix)
#Outputs
# Input 1:
# ie
# igger
# igonometry
# ipod
# Input 2
# t
# thology
# tagonist
# tonym
# Input 3
# un
# unction
# actory
# Input 4
# hology
# agonist
# onym
# Input 5
# No matches
|
str1 = input("Enter the string:\t")
print("The string is "+str1)
|
def stock(list1):
max1 = 0
buy_day = 0
sell_day = 0
for i in range(0,len(list1)):
for j in range(i+1,len(list1)):
temp = list1[j] - list1[i]
if temp > max1:
max1 = temp
buy_day = i
sell_day = j
print("Buy Date:\t",buy_day)
print("Sell Date:\t",sell_day)
print("Profit:\t",max1)
list1 = [310,315,275,295,260,270,290,230,255,250]
stock(list1)
|
"""break statement will break out of the loop"""
x=int(input('how many candies do you want:'))
av=10
i=1
while i <=x:
if i>av:
break
print ('candy')
i+=1
print("bye")
"""continue statement is to skip the next comment line but stays with in the loop"""
x=int(input("print till with number:"))
for i in range (1,x):
if i%3==0 or i%5==0:
continue
print(i)
"""pass statement is used to give a empty fun body"""
for i in range (1,30):
if i%2 !=0:
pass
else:
print(i)
|
#output using print statement
print("hello")
#we also use end= to create a format for our output
print("greek",end=" ")
print("kevin")
#sep is used to seperate the values
print("10","9","8",sep='-')
|
# -*- coding: UTF-8 -*-
"""PyRamen Homework Starter."""
# Import libraries
import csv
from pathlib import Path
# Set file paths for menu_data.csv and sales_data.csv
menu_filepath = Path("Resources/menu_data.csv")
sales_filepath = Path("Resources/sales_data.csv")
report_filepath = Path("Resources/sales_report.txt")
# @Initialize list objects to hold our menu and sales data
menu = []
sales = []
# Read in the menu data into the menu list
with open(menu_filepath, mode="r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
header = next(csv_reader)
for row in csv_reader:
menu.append(row)
# Read in the sales data into the sales list
with open(sales_filepath, mode="r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
header = next(csv_reader)
for row in csv_reader:
sales.append(row)
# Initialize dict object to hold our key-value pairs of items and metrics
report = {}
# Loop over every row in the sales list object
for sale in sales:
# Initialize sales data variables
quantity = float(sale[3])
menu_item = sale[4]
# If the item value not in the report, add it as a new entry with initialized metrics
if menu_item not in report.keys():
report[menu_item] = {
"01-count": 0,
"02-revenue": 0,
"03-cogs": 0,
"04-profit": 0
}
# For every row in our sales data, loop over the menu records to determine a match
for record in menu:
# Initialize menu data variables
item = record[0]
price = float(record[3])
cost = float(record[4])
if item == menu_item:
# print(f"matched data: item = {item}, price = {price}, cost = {cost}")
report[menu_item]["01-count"] += quantity
report[menu_item]["02-revenue"] += price * quantity
report[menu_item]["03-cogs"] += cost * quantity
report[menu_item]["04-profit"] += (price - cost) * quantity
# else:
# print(f"{item} does not equal {menu_item} ! NO MATCH!")
# Write out report to a text file (won't appear on the command line output)
with open(report_filepath, mode="w") as file:
for key, value in report.items():
row = f"{key} : {{\"01-count\":{value['01-count']}, \"02-revenue\": {value['02-revenue']}, \"03-cogs\": {value['03-cogs']}, \"04-profit\": {value['04-profit']}}}\n"
file.write(row)
file.close()
# Print total number of records in sales data
print(f"total number of records in sales data = {len(sales)}")
|
print("Hello world!");
name = input('please input your name:')
print(name, end='.')
print('hello', 'nice to meet you!', sep=',')
print(19**9)
a = ["Hello", "How are ya?", "Hi!"]
b = open("Greedy.txt",'+wt')
b.write(a[1])
|
import math
Data1 = [70,64,69,72,62,71,54,68,65,77] # use this to input data
Data2 = [79.98, 80.04, 80.02, 80.03, 80.03, 80.04, 80.04,79.97, 80.05, 80.03, 80.02, 80, 80.02]
Data = [80.02, 79.94, 79.97, 79.98, 79.97, 80.03, 79.95, 79.97]
def averge(Data):
sum = 0
for i in Data:
sum += i
ave = sum / len(Data)
return ave
def deviation(Data):
sum = 0
ave = averge(Data)
for i in Data:
sum += (i - ave) ** 2
dev = math.sqrt(sum / (len(Data) - 1))
return dev
def uncertainty(Data):
sum = 0
ave = averge(Data)
length = len(Data)
for i in Data:
sum += (i - ave) ** 2
uncer = math.sqrt(sum / (length * (length - 1)))
return uncer
print("The average is ", averge(Data))
print("The deviation is ", deviation(Data))
print("The uncertainty is", uncertainty(Data))
|
def change(aint,alis,adic):
aint = 0
alis.append(4)
adict = {'apple':'34kg','blanana':'43kg','peach':'45kg','watermelon':'46kg'}
print('In the changing:')
print('aint: ',aint)
print('alis: ',alis,' ;alist: ',alist);
print('adic: ',adict,' ;adict: ',adict)
aint = 1
alist = [3]
adict = {'apple':34,'blanana':43,'peach':45,'watermelon':46}
print('Before used change:')
print('aint: ',aint)
print('alist: ',alist)
print('adict: ',adict)
change(aint,alist,adict)
print('After change:')
print('aint: ',aint)
print('alist: ',alist)
print('adict: ',adict)
'''
在函数中,如果改变list的参数将改变list的实参
但dictionary和int都不会改变实参
'''
|
class Person():
'''Represents a person
Args:
name (str) : the name of the player
age (int) : the name of the player
'''
def __init__(self, name: str, age: int) -> None:
'''Person has name and age'''
self.name = name
self.age = age
|
import unittest
from lottery import spin_lottery
class LotteryTest(unittest.TestCase):
def test_selected_numbers_only_10_by_default(self):
self.assertEqual(
len(spin_lottery()), 10
)
def test_selected_numbers_are_integers(self):
selected_numbers = spin_lottery()
self.assertTrue(
all(isinstance(number, int) for number in selected_numbers)
)
def test_selected_numbers_are_within_1_to_50(self):
selected_numbers = spin_lottery()
self.assertTrue(
all(number <= 50 and number >=1 for number in selected_numbers)
)
def test_custom_define_number_balls_and_picks(self):
number_of_balls = 40
number_of_picks = 8
selected_numbers = spin_lottery(number_of_balls, number_of_picks)
self.assertEqual(
len(selected_numbers), number_of_picks
)
self.assertTrue(
all(number <= number_of_balls and number >=1 for number in selected_numbers)
)
if __name__ == '__main__':
unittest.main()
|
#Lewis Travers
#18/11/2014
#calculating pay
def calculate_basic_pay (hours,pay):
total = hours * pay
return total
def calculate_overtime_pay (hours,pay):
overtime_pay = (hours - 40) * (pay * 1.5)
basic_pay = 40 * pay
total = overtime_pay + basic_pay
return total
def calculate_total_pay(hours,pay):
if hours <= 40:
total = calculate_basic_pay(hours,pay)
else:
total = calculate_overtime_pay(hours,pay)
return total
def work_details():
hours = int(input("Please enter the amount of hours worked this week: "))
pay = float(input("Please enter your hourly pay rate in £: "))
return hours,pay
def display_total_pay(total):
total_pay = round(total_pay,2)
print("Your total pay for this week is £{0}.".format(total))
def calculate_pay():
hours, pay = work_details
#main program
hours, pay = work_details()
calculate_pay =
basic_pay = calculate_basic_pay(hours, pay)
overtime_pay = calculate_overtime_pay(hours, pay)
total_pay = basic_pay + overtime_pay
|
#Lewis Travers
#28/11/2014
#sort function
def get_numbers():
x = int(input("Please enter a number for x: "))
y = int(input("Please enter a number for y: "))
return x, y
def sort_function(x, y):
if x > y:
return y, x
else:
return x, y
def print_numbers(x, y):
if x > y:
print("{0}, {1}.".format(y, x))
else:
print("{0}, {1}.".format(x, y))
# main program
x, y = get_numbers()
x, y = sort_function(x, y)
x, y = print_numbers(x, y)
print(x, y)
|
import random, sys, time
start_time = time.time()
nums_to_days = {
0: "Noneday",
1: "Mon",
2: "Tue",
3: "Wed",
4: "Thu",
5: "Fri",
6: "Sat",
}
days_to_nums = {
"sun": 0,
"mon": 1,
"tue": 2,
"wed": 3,
"thu": 4,
"fri": 5,
"sat": 6,
}
if len(sys.argv) == 1:
year = random.randint(1900, 2060)
# increasing probability of exceptions:
if random.random() < 0.1:
year = random.choice([1900, 2000])
elif len(sys.argv) == 2:
year = int(sys.argv[1])
elif len(sys.argv) == 3:
start_year = int(sys.argv[1])
end_year = int(sys.argv[2])
year = random.randint(start_year, end_year)
else:
print("Wrong number of parameters", file=sys.stderr)
print(year)
user_input = input()
end_time = time.time()
if 1900 <= year < 2000:
anchor = 3
if 2000 <= year < 2100:
anchor = 2
y = year % 100
doomsday = ((y // 12 + (y % 12) + ((y % 12) // 4)) % 7 + anchor) % 7
if days_to_nums.get(user_input, None) == doomsday:
print("Correct!")
else:
print("Wrong!. ", end="")
print("Doomsday: {}, ({})".format(nums_to_days[doomsday], doomsday))
print("{:.2f}s".format(end_time - start_time))
|
from enum import Enum
from aenum import MultiValueEnum
class Weekday(Enum):
"""Weekdays
Used to identify weekly repeating lessons. Starting with `monday`
according to the python documentation (see `date.weekday()`)
"""
monday = 0
tuesday = 1
wednesday = 2
thursday = 3
friday = 4
saturday = 5
sunday = 6
@staticmethod
def to_list():
return list(map(lambda c: c.value, Weekday))
class Role(Enum):
"""User roles
none: default, no priviledges
admin: highest privileges
editor: maintainer for a specific school
tutor: student or tutor
has to be approved (see `Status`)
student: student (can only access one school)
"""
none = 'none'
admin = 'admin'
editor = 'editor'
tutor = 'tutor'
student = 'student'
class Status(Enum):
"""Status for approval of users
pending: has to be approved
accepted: approved
rejected: not eligible for teaching. No reason given
"""
pending = 'pending'
accepted = 'accepted'
rejected = 'rejected'
class Locale(MultiValueEnum):
"""Supported locale settings
default: 'de'
A multi value enum is used for different formats. Some browser
(e.g. Safari) use the long format (e.g. `en_US`) while others use a
smaller format (such as `de`).
"""
de = 'de_DE', 'de'
en = 'en_US', 'en'
@staticmethod
def to_list():
return list(map(lambda c: c.value, Locale))
@staticmethod
def to_short_list():
return list(map(lambda c: c.value[:2], Locale))
@staticmethod
def default():
return Locale.de
|
from tkinter import *
# input
# first widget that always have to be. Creates root window
root = Tk()
e = Entry(root,width =50,bg='green')
#attributes
#border width
e.pack()
#default text in input
e.insert(0,"Enter your name")
#get what is in input
e.get()
#After clicking button , text in input is displayed
def myClick():
hello = "Hello " + e.get()
myLabel = Label(root, text =hello)
myLabel.pack()
#button() widget . Can contain text or image.
myButton = Button(root, text= 'submit', command = myClick, )
myButton.pack()
#infinite loop used to run application, wait for an event to occur and process the event as long as the window is not closed
root.mainloop()
|
# combine all the pre-vision together
import random
# int-check function
def intcheck(question,low,high):
valid = False
error = "Whoops! Please enter an integer "
while not valid:
try:
response = int(input(question))
if low <= response <= high:
return response
else:
print("Please Enter a Number between 1 and 10")
print()
except ValueError:
print(error)
# word check function
def wordcheck(question):
valid = False
error = "please enter Rock(r), Paper(p) or Scissor(s)"
while not valid:
try:
answer = input(question)
reply = answer.lower()
if reply == "r" or reply == "rock":
r1 = "rock"
return r1
elif reply == "p" or reply == "paper":
r2 = "paper"
return r2
elif reply == "s" or reply == "scissor":
r3 = "scissor"
return r3
else:
print(error)
except ValueError:
print(error)
#Main Routine
rounds = intcheck("How many rounds would you like to play with ? ", 1, 10)
for x in range(rounds):
choice = wordcheck("Please choose rock, paper or scissor ")
token = ["rock", "paper", "scissor"]
computer_choice = random.choice(token)
result=""
if choice == "rock":
if computer_choice == "rock":
result = "It's a Tie"
print("Computer:",computer_choice," | User: ",choice," | Result: ",result)
elif computer_choice == "paper":
result = "You Lose"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
else:
result = "You Won"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
if choice == "paper":
if computer_choice == "paper":
result = "It's a Tie"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
elif computer_choice == "scissor":
result = "You Lose"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
else:
result = "You Won"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
if choice == "scissor":
if computer_choice == "scissor":
result = "It's a tie"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
elif computer_choice == "rock":
result = "You lose"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
else:
result = "You won"
print("Computer:",computer_choice, " | User: ", choice, " | Result: ", result)
|
# -*- coding: utf-8 -*-
class A(object):
"""
Class A.
"""
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def test(self):
print ('a normal func.')
@staticmethod
def static_test(self):
print ('a static func.')
@classmethod
def class_test(self):
print ('a calss func.')
obj = A()
print (A.__dict__)
print (obj.__dict__)
|
from abc import ABC, abstractmethod
class Hero(ABC):
@abstractmethod
def attack(self):
pass
def equip(self, weapon):
self.weapon = weapon
class IronMan(Hero):
def attack(self):
print(f"钢铁侠用{self.weapon}发起攻击!")
class SpiderMan(Hero):
def attack(self):
print(f"蜘蛛侠用{self.weapon}发起攻击!")
class Weapon(ABC):
@abstractmethod
def __str__(self):
pass
class Armour(Weapon):
def __str__(self):
return "战甲"
class Shooter(Weapon):
def __str__(self):
return "蛛丝发射器"
class HeroFactory:
hero_map = {'ironman': IronMan, 'spiderman': SpiderMan}
def create_hero(self, hero_choice):
return self.hero_map[hero_choice.lower()]()
class WeaponFactory:
weapon_map = {'armour': Armour, 'shooter': Shooter}
def create_weapon(self, weapon_choice):
return self.weapon_map[weapon_choice.lower()]()
|
from maekawa import maekawa_enter, wait_for_votes, my_rank
"""
@author: Huy Nguyen
- Source:
+https://www.coursera.org/learn/cloud-computing-2/lecture/GMHYN/2-4-maekawas-algorithm-and-wrap-up
- Let's assume we have reliable unicast for this implementation.
- i := my_rank
- Explanation about voting_set: A voting set V_i contains its own ID P_i and the row, the column contain the P_i from the 2D Cartesian topo.
"""
''' TESTING EXAMPLE '''
def example():
# Critical section, just for testing purpose.
from time import sleep
def critical_section():
print(f'[Process {my_rank}] Entered the CS.')
sleep(1)
print(f'[Process {my_rank}] Exited the CS.')
'''
The number of wait_for_vote() for the process if that process does not send request for Critical Section, is equal to the total number of maekawa_enter() of all other processes.
'''
if my_rank == 0:
maekawa_enter(critical_section)
maekawa_enter(critical_section)
elif my_rank == 1:
wait_for_votes()
wait_for_votes()
wait_for_votes()
elif my_rank == 2:
wait_for_votes()
wait_for_votes()
wait_for_votes()
elif my_rank == 3:
maekawa_enter(critical_section)
if __name__ == "__main__":
example()
|
# import the necessary packages
import argparse
import imutils
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the image and show it
image = cv2.imread(args["image"])
cv2.imshow("Original", image)
#aspect ratio is more important in resizing the image
r=500/image.shape[1]
dim= (500,int(image.shape[0]*r))
#perform the resize of the image
resized=cv2.resize(image,dim,interpolation=cv2.INTER_CUBIC)
cv2.imshow("Resized (width)",resized)
cv2.waitKey(0)
(b,g,r)=resized[74,20]
print("Pixel at (74, 20) - Red: {r}, Green: {g}, Blue: {b}".format(r=r, g=g, b=b))
# what if we wanted to adjust the height of the image? We can apply
# the same concept, again keeping in mind the aspect ratio, but instead
# calculating the ratio based on height -- let's make the height of the
# resized image 50 pixels
r= 376/resized.shape[0]
dim=(int(resized.shape[1] * r),376)
#perform resizing
resized=cv2.resize(resized,dim,interpolation=cv2.INTER_CUBIC)
cv2.imshow("Resized(height)",resized)
cv2.waitKey(0)
(b,g,r)=resized[367,170]
print("Pixel at (367, 170) - Red: {r}, Green: {g}, Blue: {b}".format(r=r, g=g, b=b))
# of course, calculating the ratio each and every time we want to resize
# an image is a real pain -- let's create a function where we can specify
# our target width or height, and have it take care of the rest for us.
'''resized = imutils.resize(image, width=100)
cv2.imshow("Resized via Function", resized)
cv2.waitKey(0)
resized = imutils.resize(image, height=50)
'''
|
str1 = input('Enter string')
str2 = str1[0].isupper()
print(str2)
|
# 1. Из всех методов списка (list) выбрать 5 тех, которые по вашему мнению используются чаще всего и написать их через запятую с параметрами
lst = []
lst.append(self, object)
lst.pop(self, index)
lst.sort(self, key, reverse)
lst.count(self, object)
lst.copy(self)
# 2. Из всех методов словарей (dict) выбрать 5 тех, которые по вашему мнению используются чаще всего и написать их через запятую с параметрами
dct = {}
dct.copy(self)
dct.keys(self)
dct.values(self)
dct.items(self)
dct.pop(self, k)
# 3. Из всех методов множеств (set) выбрать 5 тех, которые по вашему мнению используются чаще всего и написать их через запятую с параметрами
sett = set()
sett.add(self, element)
sett.pop(self)
sett.issubset(self, s)
sett.difference(self, s)
sett.intersection(self, s)
# 4. Из всех методов строк (str) выбрать 5 тех, которые по вашему мнению используются чаще всего и написать их через запятую с параметрами
strr = ''
strr.split(self, sep, maxsplit)
strr.replace(self, old, new, count)
strr.strip(self, chars)
strr.lower(self)
strr.isdigit(self)
|
'''example program in how to use the tkinter checkbutton widget'''
from tkinter import *
# **** Functions ****
def display():
check_value = check_control.get()
value_label.config(text=str(check_value))
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Check Button Example")
# **** Add window content ****
Label(root, text="Check Box Example").pack()
check_control = IntVar()
Checkbutton(root, text="Click this check button", variable=check_control, command=display).pack()
value_label = Label(root)
value_label.pack()
# **** Window Loop ****
root.mainloop()
|
# file_io_10 append file
with open("new_text_file.txt","a") as file:
# "a" - Append - Opens a file for appending, creates the file if it does not exist
file.write("Hello World!")
|
# example program for using tkinter's spinbox widget
from tkinter import *
# **** Functions ****
def display():
selection = choice_sb.get()
display_label.config(text=str(selection))
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Spin Box Example")
# **** Add window content ****
Label(root, text="Spin Box Example").pack()
choice_sb = Spinbox(root, from_=0, to=5, command=display)
choice_sb.pack()
display_label = Label(root)
display_label.pack()
# **** Run window loop ****
root.mainloop()
|
'''example program for creating a window'''
from tkinter import *
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter window example")
# **** Run window loop ****
root.mainloop()
|
'''example program for using tkinter's option menu widget'''
from tkinter import *
# **** Functions ****
def display():
selected = option_control.get()
display_label.config(text=selected)
# **** Create Window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Option Menu Example")
# **** Add content to Window ****
Label(root, text="Option Menu Example").grid(row=0, column=0, columnspan=2)
Label(root, text="Choose an option").grid(row=1, column=0)
option_list = ('Option 1', 'Option 2', 'Option 3', 'Option 4')
option_control = StringVar()
option_control.set(option_list[0])
choice = OptionMenu(root, option_control, *option_list)
choice.grid(row=1,column=1)
Button(root, text="Display selected value", command=display).grid(row=2, column=0, columnspan=2)
display_label = Label(root,text="")
display_label.grid(row=3, column=0, columnspan=2)
# **** Run window loop ****
root.mainloop()
|
#coding =utf8
from sys import argv
script,user_name= argv
prompt='>'
print "Hi %s, I'm the %s script." %(user_name,script)
print "I'd like to ask you a few questions."
print "Do you like me %s ?" %user_name
likes=raw_input(prompt)
print "Where do you live %s" %user_name
lives=raw_input(prompt)
print "What kind of computer do you have?"
computer=raw_input(prompt)
print """
Alright ,so you said %r about liking me ,
You live in %r .Nor sure where that is.
And you have a %r computer ,Nice.
""" %(likes,lives,computer)
|
import math
def is_prime(num):
isprime=True
if num>2:
for i in range(2,int(math.sqrt(num)+1),1):
pass
if num%i==0:
isprime=False
if num<=0 or num==1:
isprime=False
if num==2:
isprime=True
return isprime
print is_prime(2)
|
import pickle as pick
class Clock:
def __init__(self,hours = 0,minutes = 0,seconds = 0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def addTime(self,hours = 0,minutes = 0,seconds = 0):
if seconds + self.seconds >= 60:
self.minutes += ((seconds + self.seconds) // 60)
self.seconds = (seconds + self.seconds) % seconds
else:
self.seconds += seconds
if minutes + self.minutes >= 60:
self.hours += ((minutes + self.minutes) // 60)
self.minutes = (minutes + self.minutes) % minutes
else:
self.minutes += minutes
if hours + self.hours >= 24:
self.hours = ((hours + self.hours) // 24)
else:
self.hours += hours
def __str__(self):
return f"{self.hours}h {self.minutes}m {self.seconds}s"
def __eq__(self, other):
return self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds
def __add__(self, other):
zegarek = Clock(self.hours,self.minutes,self.seconds)
zegarek.addTime(other.hours, other.minutes, other.seconds)
return zegarek
zegarek1 = Clock(10,11,12)
zegarek2 = Clock(10,11,12)
zegarek1.addTime(2,150,50)
print(zegarek1)
try:
with open("Zegarek.objc",'wb') as file:
pick.dump(zegarek1,file)
except IOError:
print("Nie można było utworzyć pliku na dysku")
with open("Zegarek.objc",'rb') as file_pi:
zegarek = pick.load(file_pi)
print()
print(zegarek)
|
#def dodaj(a,b):
# return a+b
dodaj = lambda a,b: a+b
print(dodaj(10,20))
lista = [dodaj(x,y) for x,y in ([10,10],[11,13])]
print(lista)
print((lambda a,b:a**3+3*a-b**2)(10,20))
#Domknięcia
def make_incrementor(n):
return lambda x: x+n
f = make_incrementor(100)
print(f(11))
lista = sorted(range(-3,12),key = lambda x: x**2)
print(lista)
|
def dodaj(a :int = 0,b :int = 0) -> str:
return str(a+b)
print(dodaj(5))
print(dodaj.__name__)
innaFunkcja = dodaj
print(innaFunkcja(5,1))
def generatorFunkcji(bezZmian,czyUpper):
def powielTekst(text,ileRazyPowtorzyc = 1):
return text * ileRazyPowtorzyc
def powielTekstUpper(text:str, ileRazyPowtorzyc = 1):
return text.upper() * ileRazyPowtorzyc
def powielTekstLower(text:str, ileRazyPowtorzyc = 1):
return text.lower() * ileRazyPowtorzyc
if bezZmian:
return powielTekst
else:
if czyUpper:
return powielTekstUpper
else:
return powielTekstLower
funkcjaUpper = generatorFunkcji(False,True)
print(funkcjaUpper("abc",5))
|
#Solving the 1st challenge
#http://www.pythonchallenge.com/pc/def/0.html
def first_challenge():
num: int = 2
return f'{num ** 38}'
def new_url():
url = "http://www.pythonchallenge.com/pc/def/0.html"
url = url.replace("0", first_challenge())
print(f'paste this result as http url browser:\n{url}')
if __name__ == "__main__":
new_url()
|
"""
Simple async example using Tornado:
Tornado accepts a GET request @ '/?url=' and returns the URL requested
"""
import tornado.ioloop
import tornado.web
import tornado.httpclient
import validators
def get_errors():
return {
'missing': 'Please pass url as a parameter',
'invalid': 'Please pass a valid URL',
'unresolved': 'Unable to resolve URL',
}
class MainHandler(tornado.web.RequestHandler):
error_msgs = get_errors()
@tornado.web.asynchronous
def get(self):
def callback(response):
self.finish(response.body)
url = self.get_argument("url", None)
if not url:
raise tornado.web.HTTPError(400, self.error_msgs['missing'])
elif not validators.url(url):
raise tornado.web.HTTPError(400, self.error_msgs['invalid'])
else:
async_client = tornado.httpclient.AsyncHTTPClient()
req = tornado.httpclient.HTTPRequest(url)
async_client.fetch(req, callback)
def write_error(self, status_code, **kwargs):
err_cls, err, traceback = kwargs['exc_info']
if err.log_message and err.log_message in self.error_msgs.values():
self.write(
"<html><body><h1>{}</h1></body></html>".format(
err.log_message))
else:
return super(
MainHandler, self).write_error(status_code, **kwargs)
# New style Python with aync and await
# async def get(self):
# """Get the requested URL
# Return either url or appropriate error
# """
# url = self.get_argument("url", None)
# if not url:
# raise tornado.web.HTTPError(400, self.error_msgs['missing'])
# elif not validators.url(url):
# raise tornado.web.HTTPError(400, self.error_msgs['invalid'])
# else:
# async_client = tornado.httpclient.AsyncHTTPClient()
# try:
# response = await async_client.fetch(url)
# except tornado.web.HTTPError as error:
# print(error)
# raise tornado.web.HTTPError(500, self.error_msgs['unresolved'])
# except Exception as error:
# print(error)
# raise tornado.web.HTTPError(500, self.error_msgs['unresolved'])
# self.finish(response.body)
def initialise():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = initialise()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
''' Demonstrates some basic functions for writing to the display.
These examples need to be run on a raspberry pi and GPIO needs to be installed
(hint: `pip install --user GPIO`).
Caveats:
The PI must have the serial GPIO pins enabled (enable_uart=1 in
/boot/config.txt) and the script assumes the serial device is `/dev/ttyAMA0`
'''
import random
from time import sleep
import RPi.GPIO as GPIO
from waveshare import DisplayText
from waveshare import EPaper
from waveshare import RefreshAndUpdate
from waveshare import SetEnFontSize
from waveshare import SetZhFontSize
def hello_world(paper):
'''
Displays text on the screen at random locations and sizes.
'''
x_pool = [_ for _ in xrange(0, 800, 32)]
y_pool = [_ for _ in xrange(0, 800, 32)]
greets = [_.encode('gb2312') for _ in [u'你好', u'hello', u'hi', u'salut', u'hola', u'Здравствуйте', u'Привет', u'Kamusta', u'こんにちは']] #pylint: disable=line-too-long
e_sizes = [SetEnFontSize.THIRTYTWO, SetEnFontSize.FOURTYEIGHT, SetEnFontSize.SIXTYFOUR] #pylint: disable=line-too-long
z_sizes = [SetZhFontSize.THIRTYTWO, SetZhFontSize.FOURTYEIGHT, SetZhFontSize.SIXTYFOUR] #pylint: disable=line-too-long
for _ in xrange(0, 10):
paper.send(SetEnFontSize(random.choice(e_sizes)))
paper.send(SetZhFontSize(random.choice(z_sizes)))
paper.send(DisplayText(random.choice(x_pool), random.choice(y_pool), random.choice(greets))) #pylint: disable=line-too-long
paper.send(RefreshAndUpdate())
def main():
'''
Runs through a few example uses of the connected display.
'''
with EPaper('/dev/ttyAMA0') as paper:
sleep(5)
hello_world(paper)
sleep(2)
if __name__ == "__main__":
main()
|
# Affine Cipher Breaker
# http://inventwithpython.com/codebreaker (BSD Licensed)
import pyperclip, affineCipher, detectEnglish, cryptomath
SILENT_MODE = False
def main():
# You might want to copy & paste this text from the source code at
# http://invpy.com/affineBreaker.py
myMessage = 'H RZPEDYBO NZDKW WBTBOIB YZ MB RHKKBW VUYBKKVLBUY VG VY RZDKW WBRBVIB H QDPHU VUYZ MBKVBIVUL YQHY VY NHT QDPHU. -HKHU YDOVUL'
brokenCiphertext = breakAffine(myMessage.upper())
if brokenCiphertext != None:
# The plaintext is displayed on the screen. For the convenience of
# the user, we copy the text of the code to the clipboard.
print('Copying broken ciphertext to clipboard:')
print(brokenCiphertext)
pyperclip.copy(brokenCiphertext)
else:
print('Failed to break encryption.')
def breakAffine(message):
print('Breaking...')
# Python programs can be stopped at any time by pressing Ctrl-C (on
# Windows) or Ctrl-D (on Mac and Linux)
print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
# brute force by looping through every possible key
for keyA in range(len(affineCipher.LETTERS)):
if cryptomath.gcd(keyA, len(affineCipher.LETTERS)) != 1:
continue
for keyB in range(len(affineCipher.LETTERS)):
decryptedText = affineCipher.decryptMessage(keyA, keyB, message)
if not SILENT_MODE:
print('Tried KeyA %s, KeyB %s... (%s)' % (keyA, keyB, decryptedText[:40]))
if detectEnglish.isEnglish(decryptedText):
# Check with the user if the decrypted key has been found.
print()
print('Possible encryption break:')
print('KeyA: %s, KeyB: %s' % (keyA, keyB))
print('Decrypted message: ' + decryptedText[:200])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.strip().upper().startswith('D'):
return decryptedText
return None
# If affineBreaker.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
'''
Recursive function that queries the Reddit API
and returns a list containing the
titles of all hot articles for a given subreddit.
'''
import itertools
import requests
def recurse(subreddit, hot_list=[], after=None, count=0):
'''
Recursivly return list count
of hot articles
'''
url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit)
user_agent = 'reddit_user'
if after:
url += '?after={}'.format(after)
headers = {'User-Agent': user_agent}
req = requests.get(url, headers=headers, allow_redirects=False)
if req.status_code != 200:
return None
data = req.json()['data']
posts = data['children']
for post in posts:
count += 1
hot_list.append(post['data']['title'])
after = data['after']
if after is not None:
return recurse(subreddit, hot_list, after, count)
else:
return hot_list
|
favorite_numbers = {
"alice":[1,2,3],
"ben":[4,5,6],
"wang":[7,8,9],
}
for key,values in favorite_numbers.items():
print("These are the favorite numbers for: " + key.title())
for value in values:
print(str(value))
print("\n")
|
# Import declarations go here
import pandas
import random
import xlrd
# Title: realloc.py
# Authors: Harsha Cheemakurthy, Anna Robbins
# Hack the Crisis Sweden 2020
# open spreadsheets to extract data
pd1 = pandas.read_excel('Sample_unemployment_Stockholm_30.xlsx')
pd2 = pandas.read_excel('Sample_job_openings_Stockholm.xlsx')
# TEST
# print(pd1)
# print(pd2)
# UNEMPLOYMENT
unemployed = pd1.iloc[0:7, 2]
reserve = [] # number that remains unemployed after reallocation, due to health risk or skill mismatch
length = len(unemployed)
i = 0
# Assume that 70-90% of each occupation in the currently unemployed workforce with a desirable skillset can be
# reemployed immediately in a current opening.
# For occupations without desirable skillsets, assume that 30-50% can be reemployed immediately in a current opening.
for i in range(0,length):
if i!=3 and i!=4:
reserve.append(int(unemployed[i]*(100 - random.randrange(70, 90))/100))
else:
reserve.append(int(unemployed[i]*(100 - random.randrange(30,50))/100))
# TEST
# print(reserve)
# TOTAL EMPLOYMENT
employed = pd1.iloc[0:7, 1] # total employed after reallocation, incl. original employment and reallocated employment
reallocate = [] # number in each occupation A-F and Other to be reallocated to jobs W-Z
i = 0
for i in range(0,length):
temp = unemployed[i] - reserve[i]
reallocate.append(temp)
employed[i] = int(employed[i] + temp)
# TEST
# print(employed)
# print(reallocate)
# REALLOCATION
# Assume skillsets overlap between occupations:
# A and W;
# B, C and X;
# F and Y, Z
job_openings = pd2.iloc[0:4,1]
reallocated_results = job_openings # number of workers in occupations W-Z after reallocation
length2 = len(job_openings)
reallocated_results[0] = reallocated_results[0] + reallocate[0] # add reallocated employees from A to W
reallocated_results[1] = reallocated_results[1] + reallocate[1] + reallocate[2] # add reallocated employees from B,C to X
split_yz = random.randrange(0,100) # random percentage to determine how occupation F is split between Y and Z
realloc_y = reallocate[5]*split_yz/100
realloc_z = reallocate[5]*(100-split_yz)/100
reallocated_results[2] = reallocated_results[2] + realloc_y
reallocated_results[3] = reallocated_results[2] + realloc_z
# TEST
print(reallocated_results)
|
n=input("enter the number")
i=1
l=list()
while(len(l)<int(n)):
li=list(str(i))
#print(li)
while '9' in li:
i=i+1
li=list(str(i))
l.append(i)
print(i)
i=i+1
print("nth term",l[-1])
|
s=input("")
l=[]
s.split()
print(s)
s[0][0]=s[0][0].upper()
s[0][0]=s[1][0].upper()
print([0][0],[1][0])
|
if(i==20):
for s in l:
if(s==5 | s==10 ):
t.append(s)
if(d==10 ):
t.append(d)
else:
print('f')
exit()
break
|
# Import_libraries
import matplotlib.pyplot as plt
import numpy as np
from math import *
# Set range
N = np.arange(200).tolist()
val = np.zeros(200)
X = input('Input Equation for x(n): ')
def F(n):
return eval(X)
for n in range(200):
val[n] = F(n)
# Input values of x and y
x = np.sin(val)
y = np.zeros(200)
y[0] = -1.5*x[0] + 2*x[1] - 0.5*x[2]
for i in range(1, 199):
y[i] = 0.5*x[i+1] - 0.5*x[i-1]
y[199] = 1.5*x[199] - 2*x[198] + 0.5*x[197]
# Plot using stem()
plt.stem(N,y, 'b', markerfmt='bo', label='y(n)', use_line_collection=True)
plt.stem(N, x, 'r', markerfmt='ro', label='x(n)', use_line_collection=True)
plt.legend()
plt.xlabel('n')
plt.ylabel('Magnitude')
plt.title('Graph of x(n) and y(n)')
plt.show()
|
import operator
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
def earliest_ancestor(ancestors, starting_node):
"""Find and return the earliest ancestor (DFT to the deepest node)"""
s = Stack()
depth = 0
s.push({starting_node: depth})
visited = dict()
while s.size() > 0:
depth += 1
vk, vv = s.pop().popitem()
if vk not in visited.keys():
visited[vk] = vv
for p, c in ancestors:
if c == vk:
s.push({p: depth})
if len(visited) == 1:
return -1
else:
earliest_ancestors = []
max_depth = 0
for d in sorted(visited.items(), key=operator.itemgetter(1), reverse=True):
max_depth = max(max_depth, d[1])
if d[1] == max_depth:
earliest_ancestors.append(d[0])
return min(earliest_ancestors)
class Ancestor:
def __init__(self):
self.persons = {}
def add_person(self, person):
self.persons[person] = set()
def add_line(self, parent, child):
if parent in self.persons and child in self.persons:
self.persons[child].add(parent)
else:
raise ValueError(f"Person '{parent}' and/or '{child}' do not exist")
def get_relatives(self, person):
if person in self.persons:
return self.persons[person]
else:
raise ValueError(f"Person '{person}' doesn't exist")
def earliest_ancestor_recursive(self, child_depth, visited=None, depth=0):
if visited is None:
visited = dict()
vk, vv = child_depth.popitem()
if vv == 0 and len(self.get_relatives(vk)) == 0:
return -1
elif vk not in visited.keys():
visited[vk] = vv
depth += 1
for p in self.get_relatives(vk):
self.earliest_ancestor_recursive({p: depth}, visited, depth)
earliest_ancestors = []
max_depth = 0
for d in sorted(visited.items(), key=operator.itemgetter(1), reverse=True):
max_depth = max(max_depth, d[1])
if d[1] == max_depth:
earliest_ancestors.append(d[0])
return min(earliest_ancestors)
# Modify earliest_ancestor() method to store a path and then simply return last node in the path
# BFS or DFS
# Declare graph backwards, store length for each possible path, then determine longest path
if __name__ == '__main__':
ancestor_list = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
earliest_ancestor(ancestor_list, 6)
a = Ancestor()
a.add_person(1)
a.add_person(2)
a.add_person(3)
a.add_person(4)
a.add_person(5)
a.add_person(6)
a.add_person(7)
a.add_person(8)
a.add_person(9)
a.add_person(10)
a.add_person(11)
a.add_line(1, 3)
a.add_line(2, 3)
a.add_line(3, 6)
a.add_line(5, 6)
a.add_line(5, 7)
a.add_line(4, 5)
a.add_line(4, 8)
a.add_line(8, 9)
a.add_line(11, 8)
a.add_line(10, 1)
print(a.earliest_ancestor_recursive({11: 0}))
|
class Student:
def __init__(self, n):
self.name = n
self.scores = []
def add_score(self, score):
self.scores.append(score)
def avg_score(self):
if self.scores:
avg = sum(self.scores) / len(self.scores)
print(f"Avg score: {avg}")
else:
print("No Scores Available Yet")
|
def list_to_number(digits):
result = ""
for number in digits:
result += str(number)
return result
def main():
print(list_to_number([1, 2, 3]))
if __name__ == '__main__':
main()
|
import copy
class CashDesk:
def __init__(self, money={100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 2: 0, 1: 0}):
self.money = money
self.total_amount = 0
def take_money(self, amount):
for sum in amount:
self.money[sum] += amount[sum]
def total(self):
for cash in self.money:
self.total_amount += self.money[cash] * cash
print(self.total_amount)
def can_withdraw_money(self, amount):
tmp = copy.deepcopy(self.money)
if self.total_amount < amount:
print(False)
else:
mm = [100, 50, 20, 10, 5, 2, 1]
for cash in mm:
while amount - cash >= 0:
if tmp[cash] > 0:
tmp[cash] -= 1
else:
print(False)
amount -= cash
print(True)
my_cash_desk = CashDesk()
my_cash_desk.take_money({1: 2, 50: 1, 20: 1})
my_cash_desk.total()
my_cash_desk.can_withdraw_money(70)
|
from count_substrings import count_substrings
def count_vowels(str):
vowels = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y']
result = 0
for character in vowels:
result += count_substrings(str, character)
return result
def main():
print(count_vowels("Theistareykjarbunga"))
if __name__ == '__main__':
main()
|
base = input("Enter a base:")
expo = input("Enter an exponent:")
result = base ** expo
print "{} to the power of {} = {}".format(base, expo, result)
|
import os
import csv
import argparse
import sys
import re
def argument_parser():
parser = argparse.ArgumentParser(description="Splitting CSV with input file, output file and row limits")
parser.add_argument("-i", "--input", help="Input File Name", type=str, required=True)
parser.add_argument("-o", "--output", help="Output File Name", type=str, required=True)
parser.add_argument("-r", "--row_limit", help="Row Limit", type=int, required=True)
args = parser.parse_args()
is_valid_input_file(args.input)
is_valid_row_limit(args.input, args.row_limit)
return args.input, args.output, args.row_limit
def is_valid_input_file(input):
if os.path.isfile(input):
pass
else:
sys.exit(1)
def is_valid_row_limit(input, row_limit):
file_len = 0
with open (input, "r") as my_inp:
inp = csv.reader(my_inp)
file_len = sum (1 for i in inp)
if file_len > row_limit:
pass
else:
sys.exit(2)
def split_csv(argument):
current_dir = "."
input = argument[0]
output = argument[1]
row_limit = argument[2]
rows = []
with open(input, "r") as my_inp:
inp = csv.reader(my_inp)
for i in inp:
rows.append(i)
header = rows.pop(0)
chunk = []
count = 0
for i in range(0, len(rows), row_limit):
chunk = rows[i:i + row_limit]
chunk.insert(0, header)
output_file = os.path.join(current_dir, re.sub(r'\.',str(count)+'.',output))
print (output_file)
with open(output_file, "w") as my_out:
out = csv.writer(my_out)
out.writerows(chunk)
count += 1
print ()
print ("output file = ", output_file)
print ("no of rows =", len(chunk))
if __name__ == "__main__":
argument = argument_parser()
print (argument)
split_csv(argument)
|
# PersonEx 클래스를 구성하시오
# 속성으로 name, age가 존재한다
# 액션(함수)로 getName, getAge 가 존재한다.
# name과 age는 생성자에서 초기화 된다.
##################################################
# 파이썬의 모든 클래스의 수퍼 클래스(근본 클래스)는
# Object 존재함
class PersonEx:
# 멤버변수
name = None
age = None
# 생성자
def __init__(self,name,age):
self.name = name
self.age = age
# 멤버함수
def getName(self):
return self.name
def getAge(self):
return self.age
# F반 멤버
f1 = PersonEx('홍길동',30)
f2 = PersonEx('홍길동2',20)
# F반 멤버 리스트
print([f1,f2])
#####################################################
# 요구사항 PersonEx는 그대로 두고, PersonEx2를 만들어서
# eat() 함수를 추구해 달라는 요구사항
# PersonEx2 = PersonEx + eat()
# 위의 요구사항은 상속이라는 방법으로 해결
# PersonEx는 부모, PersonEx2는 자식이 되서
# 자식은 부모의 모든 기능을 승계하고, 자식은 별도로 추가
#####################################################
# class 자식클래스명(부모클래스명): => 상속
class PersonEx2(PersonEx):
def eat(self):print('eat call')
pe = PersonEx2('역삼',20)
print(pe.getAge(),pe.getName(),pe.eat())
#####################################################
# 상속 후 재정의(부모로부터 받은 함수를 재정의) 예
class PersonEx3(PersonEx2):
def eat(self):print('eat call 1234')
pe2 = PersonEx3('역삼',20)
pe2.eat()
|
'''
2. 여러개 데이터 (연속 데이터, 시퀀스 데이터)
- 튜플 :
(),
순서가 있다,인덱스 존재,값의 중복 신경 안씀
값을 여러개 묶는다에 의미를 둔다. 값변경불가
함수에서 리턴할때
'''
tu = ()
print(tu, type(tu),len(tu))
tu = tuple()
print(tu, type(tu),len(tu))
##########################################################################
tu = (1)
print(tu, type(tu))
# 값이 1개인 경우
tu = (1,)
print(tu, type(tu), len(tu))
##########################################################################
# 값의 변경 불가, 삭제 불가 => immutable
tu = (1,2,3,4)
print(tu[0])
print(tu[:2])
# 함수 내부에서 여러개의 값을 리턴 할 때 주로 많이 사용
a = tu[0]
b = tu[1]
c = tu[2]
d = tu[3]
# 위에 표현을 한번에 처리
a,b,c,d = tu
print(d)
#########################################################################
tu = (1,2,3,4)
tu = 1,2,3,4
print('->',type(tu))
|
#Autor: Eduardo Roberto Müller Romero
# Una compañía aplica cierto descuento al comprar n cantidad de paquetes de software, el programa calcula descuento y total
def calcularPago(x):
'''
La función recibe un valor y basándose en el, decide si se aplica un descuento, que descuento se aplica y además
calcula el total.
'''
total = int()
descuento = ""
subtotal = x * 1500
if x < 10:
descuento = "Ninguno"
total = subtotal
elif x >= 10 and x <= 19:
total = subtotal - (subtotal * .2)
descuento = "20%"
elif x >= 20 and x <= 49:
total = subtotal - (subtotal * .3)
descuento = "30%"
elif x >=40 and x <= 99:
total = subtotal - (subtotal * .4)
descuento = "40%"
elif x > 99:
total = subtotal * .5
descuento = "50%"
return descuento, total
def main():
software_vendido = int(input("Cantidad de paquetes adquiridos: "))
if software_vendido < 0:
print("Error de Capa 8", "\nInsertaste un valor inválido \n:(")
descuento, total = calcularPago(software_vendido) #La función regresará el total y el descuento que se aplicó
print("Compraste", software_vendido, "paquetes de software.", "\nSe aplicó un descuento del:", descuento,
"\nEl total a pagar sería de: $%.02f" % total)
main()
|
import csv
new_contacts = [] # This list is for all new contacts.
new_validated = [] # This list is for old contacts, who have been validated since the last export.
emails = []
# This is the value that represents if the contact has been previously validated.
NOT_VALIDATED = "0"
'''
FUNCTION DEFINITIONS
'''
def sort_previous_contacts(file_name):
previous = []
indexed_previous_contacts = {}
with open(file_name, "r") as csv_file:
reader = csv.reader(csv_file)
for contact in reader:
if good_contact(contact):
previous.append(contact)
for contact in previous:
email = contact[3]
validation = contact[-2]
indexed_previous_contacts[email] = validation
return indexed_previous_contacts
def good_contact(row):
'''
This function returns true if the contact is:
A. Not working for calibrate
B. Not a duplicate
C. Not a nonesense entry we've spotted
'''
if len(row) < 2:
return False
email = row[3]
if email.endswith("@calibrate.co.nz"):
return False
# Nonesense email found data.
if email.endswith("@hjkc.com"):
return False
if email in emails:
return False
return True
def newly_validated(email, validation):
'''
This only checks if the contact has been validated since the last export
params:
- email, string of contacts email
- validation, string of validation condition. "0" for unvalidated, any other value for validated.
'''
return (validation is not NOT_VALIDATED and previous_contacts[email] is NOT_VALIDATED)
'''
SCRIPT START
'''
# Get Previous exports URL
previous_url = str(input("CSV Filename from the previous CLEANED export: \n > "))
print("Filing Previous Contacts...")
previous_contacts = sort_previous_contacts(previous_url)
print("Previous contacts filing complete.")
# Get filename for the csv url.
latest_export_csv = str(input("Filename for the DIRTY export to be cleaned: \n > "))
print("Reading new export file...")
with open(latest_export_csv, "r") as read_file:
reader = csv.reader(read_file)
for contact in reader:
email = contact[3]
validation = contact[-2]
if good_contact(contact):
# Check if the email was in the last export.
if email in previous_contacts:
# Compares the validation status of the current and previous contact.
if newly_validated(email, validation):
new_validated.append(contact)
else:
new_contacts.append(contact)
emails.append(email)
print("New contacts loaded.")
new_contact_file = str(input("Enter the filename for to write the NEW contacts to, which are CLEAN: \n > "))
print("Writing new and cleaned contacts to {0}...".format(new_contact_file))
with open(new_contact_file, "w") as write_file:
writer = csv.writer(write_file)
writer.writerows(new_contacts)
print("Finished writing new and clean contacts.")
newly_validated_contacts_file = str(input("Filename to write OLD CONTACTS which are NEWLY VALIDATED to: \n > "))
print("Writing newly validated contacts to {0}...".format(newly_validated_contacts_file))
with open(newly_validated_contacts_file, "w") as write_file:
writer = csv.writer(write_file)
writer.writerows(new_validated)
print("Finished writing old contacts, that have been validated since last export")
print("Total # of new contacts: {0}".format(len(new_contacts)))
print("Total # of newly validated contacts: {0}".format(len(new_validated)))
|
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
node_queue = []
root.max = 10001
root.min = -1
node_queue.append(root)
while node_queue:
cur_node = node_queue.pop(0)
if cur_node.left:
if cur_node.left.data < cur_node.data and cur_node.left.data > cur_node.min:
cur_node.left.max = cur_node.data
cur_node.left.min = cur_node.min
node_queue.append(cur_node.left)
else:
return False
if cur_node.right:
if cur_node.right.data > cur_node.data and cur_node.right.data < cur_node.max:
cur_node.right.min = cur_node.data
cur_node.right.max = cur_node.max
node_queue.append(cur_node.right)
else:
return False
return True
|
class Printer:
def __init__(self,maufacturer):
self.maufacturer=maufacturer
def print(self,personlist):
for i in personlist:
print(i.name,i.address)
print("printed from %s printer" % self.maufacturer)
class Person:
def __init__(self,name,address):
self.name=name
self.address=address
printobj=Printer("Hp")
printobj1=Printer("Toshiba")
personlist=[]
personobj=Person("fijila","uk")
personlist.append(personobj)
5
personobj1=Person("Fazeem","leeds")
personlist.append(personobj1)
personobj2=Person("Faizan","Bradford")
personlist.append(personobj2)
printobj1.print(personlist)
|
class Printer:
def __init__(self,maufacturer):
self.maufacturer=maufacturer
def print(self,person):
print ("%s 's address is %s " % (person.name, person.address))
print(person.name)
print(person.address)
print("Printed From %s printer" % self.maufacturer)
class Person:
def __init__(self,name,address):
self.name=name
self.address=address
printobj=Printer("Hp")
printobj1=Printer("Toshiba")
personobj=Person("fijila","uk")
printobj.print(personobj)
personobj1=Person("Fazeem","Bradford")
printobj.print(personobj1)
personobj2=Person("Faizan","Bradford")
printobj1.print(personobj2)
|
#!/bin/python3
import sys
import os
import datetime as dt
import inspect
# Add log function and inner function implementation here
def log(function):
def printlog(*args, **kwdargs):
str_template = "Accessed the function -'{}' with arguments {} {}".format(function.__name__,args,kwdargs)
print(str_template )
return function(str_template)
return printlog
def greet(msg):
return msg
greet = log(greet)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
print( greet('hello world!'))
from functools import wraps
def decorator_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@decorator_func
def square(x):
return x**2
print(square.__name__)
def decorator_func(func):
def wrapper(*args, **kwdargs):
return func(*args, **kwdargs)
wrapper.__name__ = func.__name__
return wrapper
@decorator_func
def square(x):
return x**2
print(square.__name__)
|
temp=0
list=[1,20,100,50,30,80]
listleng=len(list)
for i in range(0,listleng-1):
for x in range(0,listleng-1):
if(list[x]>list[x+1]):
temp=list[x]
list[x]=list[x+1]
list[x+1]=temp
print(list)
|
#store datas on mysql
import mysql.connector
def login():
user = input('Please input user name: ')
password = input('Please input password: ')
try:
#Try login.
conn = mysql.connector.connect(user = user, password = password)
except mysql.connector.errors.ProgrammingError as e:
print('Error %s.'%(e))
cursor = conn.cursor()
try:
cursor.execute('use whattoeat;')
#if whattoeat database does not exist, then we create one, select it, and create tables, since it is the first time user use it.
except mysql.connector.errors.ProgrammingError:
conn = mysql.connector.connect(user = user, password = password)
cursor = conn.cursor()
#Table food contains collumn id as primary key.
cursor.execute('create database whattoeat; use whattoeat; create table food (ID int not null auto_increment, category varchar(20), type varchar(20), quantity varchar(4), unit varchar(20), expiration varchar(20), nutrition varchar(20), other varchar(20), primary key (ID));')
#for now, let's just create food table, with limited columns. This may be changed later.
finally:
cursor.close()
print('Table food is ready.')
try:
return conn
except UnboundLocalError:
pass
#read values from the table according to the inputs. Return a GENERATOR, since we only deal with data one by one. We do not allow read items from Table food by id.
def read(**kw):
data = []
#Suppose mysql is connected. Otherwise, connect to mysql.
try:
kw['conn'].reconnect()
cursor = kw['conn'].cursor()
except:
print('Please login.')
# when there is no key word parameter, return everything in the table.
if kw == {}:
try:
cursor.execute('select * from food;')
#if there is nothing in the table, then print it out.
if cursor.fetchall() == []:
print('There is no saved data.')
else:
#else, save the data and column names.
data = cursor.fetchall()
col = cursor.column_names
finally:
cursor.reset()
for key in kw: #read one value at a time.
try:
#select the value from the table and save the column names as col.
#We do not allow read items by id.
cursor.execute('select * from food where %s = \"%s\";', [key, kw[key]])
col = cursor.column_names
#if the selected value is empty, then print no such value.
if cursor.fetchall() == []:
print('There is no such value (%s,%s) in the table.' %(key, kw[key]))
else:
data.append(cursor.fetchall())
except mysql.connector.errors.ProgrammingError as e:
print('Error: ' + e + 'when fetching %s = %s.' %(key, kw[key]))
cursor.close()
return [todict(col = col, data = item) for item in data]
#Transform the data to dictionary so that later a list of food object can be created easily.
def todict(*,col,data):
#Data should be just ONE row from the table.
#Return a dictionary, where keys are from col and values are from data. So col and data MUST be arranged!
return {col[i]: data[i] for i in range(len(col))}
#save several rows to the table that are combined in a list and entered using key word data. The input should be a food objects. Id is used to determine if the data is saved or new. If the data is saved and we want to update it, then its id shall remain the same. If the data is new and we want to save it, then the value of its id shall be null.
def save(**kw):
#Suppose mysql is connected. Otherwise, connect to mysql.
try:
kw['conn'].reconnect()
cursor = kw['conn'].cursor()
except:
print('Please login.')
data = kw['data']
cursor.execute('use whattoeat;')
#Save data to mysql.
for i in range(len(data)):
try:
cursor.execute('insert into food (ID, category, type, quantity, unit, expiration, nutrition, other) values ({0}, \"{1}\", \"{2}\", \"{3}\", \"{4}\", \"{5}\", \"{6}\", \"{7}\") on duplicate key update category = \"{1}\", type = \"{2}\", quantity = \"{3}\", unit = \"{4}\", expiration = \"{5}\", nutrition = \"{6}\", other = \"{7}\";'.format(data[i]['ID'], data[i]['cat'], data[i]['ty'], data[i]['quan'], data[i]['unit'], data[i]['date'], data[i]['nutri'], data[i]['other']))
except mysql.connector.errors.ProgrammingError as e:
print('Error: {0} when saving the {1} item.'.format(e, i))
cursor.close()
#Delete a row from Table food. Ideally, we only delete a row by its ID.
def delete(**kw):
#Suppose mysql is connected. Otherwise, connect to mysql.
try:
kw['conn'].reconnect()
cursor = kw['conn'].cursor()
except:
print('Please login.')
#The IDs of the rows we want to delete are entered using key word data.
data = kw['data']
cursor.execute('use whattoeat;')
for i in range(len(data)):
try:
cursor.execute('delete from food where id ={0};'.format(data[i]))
except mysql.connector.errors.ProgrammingError as e:
print('Error: {0} when deleting the item with ID = {1}.'.format(e, data[i]))
cursor.close()
|
"""
Author: Joshua Jansen Van Vueren
Desc: Class describing an object which contains climate and temperature data
"""
class ClimateRecord(object):
def __init__(self, string):
s = self.splitCSVIntoArray(string)
self.date = s[0]
self.actualMinTemp = int(s[1])
self.actualMaxTemp = int(s[2])
self.actualMeanTemp = (float(s[2])+float(s[1]))/2
self.averageMinTemp = int(s[3])
self.averageMaxTemp = int(s[4])
def toString(self):
return ("Date: %s\nMin Temp: %i\nMax Temp: %i\nAvg Min Temp: %i\nAvg Max Temp: %i\n" % (
self.date, self.actualMinTemp, self.actualMaxTemp, self.averageMinTemp, self.averageMaxTemp))
def splitCSVIntoArray(self, csv):
sSplit = csv.split(",")
# print(sSplit)
return sSplit
def getMaxTemp(self):
return self.actualMaxTemp
def getAvgMaxTemp(self):
return self.averageMaxTemp
def getDate(self):
return self.date
def isAboveAverageMax(self):
return self.actualMaxTemp > self.averageMaxTemp
|
#name = input('What is your name?')
#print(str.upper(str('hello ' + name)))
#print('Your name has' + str(len(name)) + 'letters in it! Awesome!')
user_input = int(input("Enter a number:"))
result = user_input * user_input
print(result )
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 9 10:25:09 2018
@author: shuli
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 != 0:
return False
opening = ['(','[','{']
matches = [('(',')'),('[',']'),('{','}')]
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if stack == []:
return False
last_open = stack.pop()
if (last_open,paren) not in matches:
return False
return stack == []
|
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums) - k
nums[:] = nums[n:] + nums[:n]
if __name__ == '__main__':
a = Solution()
nums = [1,2,3,4,5,6,7]
a.rotate(nums,3)
print(nums)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 17:28:19 2018
@author: shuli
"""
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or x == 1:
return x
left,right = 1,x
while left < right:
mid = (left + right) // 2
if mid**2 == x:
return mid
elif mid**2 < x:
left = mid + 1
else:
right = mid
return left if left**2 == x else left -1
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 18:27:44 2018
@author: shuli
"""
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
left = 0;right = len(nums) - 1
while left < right:
mid = (right+left)//2
if target > nums[mid]:
left = mid +1
else:right = mid -1
return left if nums[left] > target else left+1
if __name__ == '__main__':
a = Solution()
nums = [1,3,5,6];targetList = [5,2,7,0]
for target in targetList:
print(a.searchInsert(nums,target))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 10:58:12 2018
@author: shuli
"""
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if nums == []:
return 0
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else: i += 1
return len(nums)
if __name__ == '__main__':
a = Solution()
nums = [0,1,2,2,3,0,4,2];val = 2
print(a.removeElement(nums,val))
|
from character import *
from random import randint, choice
"""
In this simple RPG game, the hero fights somebody. He has the options to:
1. fight an enemy
2. do nothing - in which case the enemy will attack him anyway
3. flee
"""
"""
Character classes:
hero, medic, shadow, wizard, zombie, goblin, rhino, jackie
"""
def create_hero(): #dictionary list to call to input your class
jobs_dict = {
"1":"Hero",
"2":"Medic",
"3":"Shadow",
"4":"Wizard",
"5":"Rhino",
"6":"Jackie"
}
print("Create your character!")
name = input("What is your name small son?")
job_select = input("What is your %s's class?\n1. Hero \n2. Medic\n3. Shadow\n4. Wizard\n5. Rhino\n6. Jackie\n:" % name)
health = randint(100,150) #starting stats
power = (randint(5,10)) #starting stats
char = Character(name, jobs_dict[job_select], health, power)
print("Your character has been created! %s the %s, your stats are %d health and %d power"% (name, char.job, char.health, char.power))
return char
def main(char1):
in_game = True
while in_game: #kind of the base area the character is thrown into
char_list = ['Hero', 'Medic', 'Shadow', 'Wizard', 'Rhino', 'Jackie', 'Zombie', 'Goblin']
#list of the characters on the map, you can choose 6 of those, they don't include zombie or goblin
action = input("Where you going?\n1. Travel\n2. Shop\n3. inventory(can't use items)\n4. Quit\n: ")
#menu list of what you can do
if action == "1": #starts the battle
name = choice(char_list)
char2 = Character(name, name, randint(20,60), randint(4,7))
#char 2 name of char2, job, health, and power)
print("%s has encountered %s!" % (char1.name, char2.name))
battle(char1, char2)
elif action == "2": #enter item shop
Store(char1)
elif action == "3": #use item that you chose
use_item(char1)
else: #quits out of game
in_game = False
def battle(char1, char2): #fight between you and enemy
fighting = True
while char2.alive() and char1.alive() and fighting:
char1.print_status()
char2.print_status()
print()
print("What does %s want to do?" % char1.name)
print("1. fight %s" % char2.name)
print("2. Use item")
print("3. Do nothing")
print("4. Flee")
# ^ is the menu in fight
print(": ", end = "")
user_input = input() #where you enter your input
if user_input == "1": # you will attack the other character
char1.attack(char2)
if not char2.alive(): #when character dies gain moneys
char1.wealth += char2.bounty
print("%s is dead. %s gains %d gil, you now have %d gil" % (char2.name, char1.name, char2.bounty, char1.wealth))
elif user_input == "2": # use item
use_item(char1)
elif user_input == "3": #do nothing
pass
elif user_input == "4": #running away, but you will retain damage
print("smellyal8r loser.")
fighting = False
else:
print("Invalid input %r. %s loses his turn" % (user_input, char1.name))
if char2.alive(): #loop for when enemy can attack you
char2.attack(char1) #how the second character attacks character 1
if not char1.alive(): #so if you die your money goes to the enemy and you lose
char2.wealth += char1.bounty
print("%s is dead. %s gains %d gil and now has %d gil" % (char1.name, char2.name, char1.bounty, char2.wealth))
print("You died, it's over, try again or go home")
exit(0)
def Store(character):
shopping = True
while shopping: #while in the store
items_dict = {'1':'SuperTonic', '2':'Armor', '3':'Cloak'}
items_price_dict = { '1':5, '2':10, '3':20}
print("%s has %d gold" % (character.name, character.wealth))#%s calls character.name #d calls character.wealth
item = input("What do you want to buy?\n1. SuperTonic - 5g \n2. Armor - 10g\n3. Cloak -20g\n4. Quit\n:")
#items that you can purchase
if item == '4':
shopping = False #if they put in number 4, you can't buy an item so
elif int(item) in [1,2,3] and character.wealth < items_price_dict[item] :
print("%s can't afford this" % character.name)
still_shopping = input("Continue shopping?\n1. Yes \n2. No \n: ")
if still_shopping.lower() == "n" or still_shopping.lower() == "no" or still_shopping.lower() == "1":
shopping = False
elif still_shopping.lower() == "y"or still_shopping.lower() == "yes" or still_shopping.lower() == "2":
pass
else:
print("You pressed the wrong key stupid, goodbye.")
shopping = False
#so the n, no and 1
elif int(item) in [1,2,3] and character.wealth >= items_price_dict[item]:
character.wealth -= items_price_dict[item]
character.inventory.append(items_dict[item])
print("%s bought %s" % (character.name, items_dict[item]))
still_shopping = input("Continue shopping?\n1. Yes \n2. No\n: ")
if still_shopping.lower() == "n" or still_shopping.lower() == "no" or still_shopping.lower() =="2":
shopping = False
elif still_shopping.lower() == "y" or still_shopping.lower() == "yes" or still_shopping.lower() =="1":
pass
else:
print("You pressed the wrong key stupid, goodbye.")
shopping = False
#so the store inputs, 1 2 or 3, for whichever item you want to buy or if you want to continue shopping with
#1 and 2
#The first half is being unable to purchase the items, the second is when you're able
def use_item(char1): #print the inventory of char1
status = True
while status: #in the menu
print("What are you going to use?: ")
for i,item in enumerate(char1.inventory): #enumerate keeps count of iterations
print("%d. %s" %(i+1,item)) #start at 0 items, i+1 adds to inventory
print("0. Quit")
request = int(input(":"))#int for the number of items
print("")
if request == 0:
status = False #no items
elif request <= len(char1.inventory) and request > 0:
if char1.inventory[request-1] == "SuperTonic": #if you have supertonic, will show up here first
char1.health += 10
print("%s gained 10 health. You now have %d health" % (char1.name, char1.health))
if char1.inventory[request-1] == "Armor":
char1.armor += 2 #using armor adds +2
print(" %s gains 2 armor. You now have %d armor." % (char1.name,char1.armor))
if char1.inventory[request-1] == "Cloak": # request-1 subtracts from the inventory
char1.evasion += 2
print("%s gains 2 evasion. You now have %d evasion." % (char1.name, char1.evasion))
del char1.inventory[request-1] #deletes out of inventory
status = False
else: print("Select something you have!")
superboy = create_hero()
main(superboy)
|
def translate(lord)
lordex = 0
for letter in name:
if letter.lower() in "aiu":
letter = "o"
lord += letter
elif letter.lower() in "oy":
letter = "i"
lord += letter
elif letter.lower() in "h":
letter = "u"
lord += letter
elif letter.lower() in "dspj":
letter = "z"
lord += letter
elif letter.lower() in "ml":
letter = "n"
lord += letter
elif letter.lower() in "t":
letter = "ch"
lord += letter
elif letter.lower() in "nv":
letter = "m"
lord += letter
else:
lord += letter
#print(letter)
return lord
|
from random import randint
numero_aleatorio = randint(1, 101)
contador = 0
while True:
contador += 1
numero_secreto = input("Adivinhe o numero secreto de 1 a 100: ")
if numero_secreto == "sair":
print("Sair")
break
numero_secreto = int(numero_secreto)
if numero_secreto > numero_aleatorio:
print("Numero muito alto")
elif numero_secreto < numero_aleatorio:
print("Numero muito baixo")
else:
print("Exatamente certo")
break
print(f"Voce tentou {contador} vezes")
|
#this file is for accessing the text file and making a new one
#removed because requirements say no global variables; can be retrieved by calling getLines(f, []) to return the lines
#lines = list()
#inputTxt = open("input.txt", "r")
#getLines recursively retrieves lines
def getLines(f, lst):
line = f.readline()
if line == "":
f.close()
return lst
else:
if line[-1] == '\n':
line = line[:-1]
lst.append(line)
return getLines(f, lst)
#requires name of text and list
def writeLines(name, lst):
outf = open(name, "w")
outf.write("\n".join(lst))
|
def processLine(line, linePointer):
lineParts = line.split()
function = lineParts[0]
result = 0
linePointer = linePointer + 1
if function == 'calc':
operation = lineParts[1]
int1 = int(lineParts[2])
int2 = int(lineParts[3])
print(f'[{linePointer - 1}] calculate {operation} {int1} {int2}')
result = calculate(operation, int1, int2)
elif function == 'goto':
if len(lineParts) == 2:
print(f'[{linePointer - 1}] goto {lineParts[1]}')
linePointer = int(lineParts[1])
elif len(lineParts) == 5:
operation = lineParts[2]
int1 = int(lineParts[3])
int2 = int(lineParts[4])
print(f'[{linePointer - 1}] goto calculate {operation} {int1} {int2}')
linePointer = int(calculate(operation, int1, int2))
else:
raise Exception(f'Unsupported goto, should have 2 or 6 parts: "{line}"')
else:
raise Exception(f'Unsupported Function: {function}')
return (result, linePointer)
def calculate(operation, int1, int2):
if operation == "+":
return int1 + int2
elif operation == "-":
return int1 - int2
elif operation == "x":
return int1 * int2
elif operation == "/":
return int1 / int2
else:
raise Exception(f'Unsupported Operation: {operation}')
def tryGetInt():
try:
return int(input())
except:
raise Exception('Naughty naughty! That was not an integer :-(')
f = open("C:\Work\Exercises\Calculator\InputPart3.txt")
finalResult = 0
linePointer = -1
nextLinePointer = 0
allLines = f.read().splitlines()
while nextLinePointer != linePointer and nextLinePointer < len(allLines):
linePointer = nextLinePointer
(result, nextLinePointer) = processLine(allLines[linePointer], linePointer)
finalResult += result
print(f'finalResult = {result}')
|
operator_list = ["+", "-", "/", "*", "q"]
print("Byl spuštěn program Kalkulačka, který umožnuje sčítaní, odečítání, násobení a dělení")
print("Program Vás nejprve vyzve pro zadání čísla, následně Vás vyzve pro zadání matematického operátoru (+,-,*,/), poté k dalšímu číslu")
print("Pokud zadáte matematický operátor jako první operand se bude brát předešlý výsledek, pokud číslo tak program Vás postupně vyzve pro zadání operátoru a poté čísla, pokud zadáte q program se ukončí. Pokud zadáte operátor a číslo a ještě žádný předešlý výsledek neexistuje, tak se vezme jako výchozí hodnota 0.")
def is_float(str):
try:
float(str)
return True
except ValueError:
return False
while True:
vstup = input("Zadejte vstup: ")
while not (vstup in operator_list or is_float(vstup)):
print("Nezadali jste žádný podporovaný oparátor nebo číslo")
vstup = input(
"Zadejte vstup: ")
if vstup in operator_list:
operator = vstup
# TODO nekontroluje se, zda bylo zadáno číslo
operand_2 = float(input("Zadejte číslo: "))
else:
operand_1 = float(vstup)
operator = input(
"Zadejte matematický operátor, Kalkulačka umožňuje +,-,*,/ : ")
while operator not in operator_list:
operator = input(
"Nezadali jste žádný podporovaný oparátor, zadejte ho znovu: ")
# TODO tady se číslo kontroluje
operand_2 = input("Zadejte číslo: ")
while not is_float(operand_2):
operand_2 = input("Zadejte číslo: ")
operand_2 = float(operand_2)
if operator == "+":
vysledek = operand_1 + operand_2
elif operator == "-":
vysledek = operand_1 - operand_2
elif operator == "*":
vysledek = operand_1 * operand_2
elif operator == "/":
vysledek = operand_1 / operand_2
operand_1 = vysledek
print(f"Výsledek je: {vysledek}")
# TODO program nikdy nedojde sem na konec - nelze ukončit pomocí "q"
print("Program byl ukončen")
|
from typing import NamedTuple
from collections import namedtuple
task = []
# title, done - True/False
Task = namedtuple("Task", "title status")
# task = Task("Posekat zahradu", False)
# task[0]
# task[1]
# task.title
# task.status
def show_menu():
print("Menu: (pro výběr stiskněte danou klávesu)")
print("""
Show all - s
Show done - d
Show incomplete - i
Add task - a
Change state - c
Show menu - m
Delete task - del
Quit - q
""")
def quit():
print("Exiting program")
exit(0)
def show_done():
pass
def show_incomplete():
pass
def add_task():
pass
def change_state():
pass
def show_tasks():
pass
show_menu()
while True:
action = input(">> ") # s / d / i
if action not in ["s", "d", "i", "a", "c", "m", "q"]:
print("Nepodporovaná akce!")
continue
if action == "s":
show_tasks()
elif action == "d":
show_done()
elif action == "i":
show_incomplete()
elif action == "a":
add_task()
elif action == "c":
change_state()
elif action == "m":
show_menu()
elif action == "q":
quit()
|
def div(x, y):
try:
return (x/y, False)
except ZeroDivisionError:
return (None, True)
print("1", div(3, 2))
print("2", div(14, 0))
while True:
a = input ("cislo")
b = input ("cislo")
try:
result = int(a) / b
print (f"vysledek {result}")
except ZeroDivisionError:
print("dělitel nesmí být dva")
exit()
print(result)
print(int("12ahoj"))
# class CustomError(Exception):
# pass
|
"""
http://codingbat.com/prob/p197466
Given an int n, return the absolute difference between n and 21, except return
double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
"""
def diff21(n):
diff = 21 - n
if n > 21:
return diff * -2
return diff
if __name__ == '__main__':
assert diff21(19) == 2
assert diff21(10) == 11
assert diff21(21) == 0
assert diff21(22) == 2
assert diff21(23) == 4
assert diff21(24) == 6
assert diff21(30) == 18
|
point1 = list(map(float, input("Enter x and y coordinate: ").split()))
point2 = list(map(float, input("Enter x and y coordinate: ").split()))
dist = (((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2) ** 0.5)
print(dist)
|
"""
JADS 2020 Data-Driven Food Value Chain course
Introduction to Sensors
Lunar Lander Micropython Exercise
"""
# ------------------------ Objective of the game -------------------------------------
# this game simulates a lunar landing module (LLM) landing on the moon
# you are the pilot and need to control how much fuel you burn in the
# retro rockets so that your descent speed slows to zero just as your
# altitude above the moon's surface reaches zero. If you impact the moon
# more than 5 m below the surface, or your speed on impact is
# greater than 5 m/s then you have considered to have crashed.
# Otherwise it is considered to be a 'good' landing.
# If you run out of fuel, LLM will accelerate towards moon by gravity.
# ---------------------------- Assignment --------------------------------------------
# Copy paste this code at https://micropython.org/unicorn/
# Then replace the constant burn rate in line 57 with interpolated input from the ADC slider,
# with some delay from a basic moving average filter (for instance with window of n = 3)
# ----------------------------- Source code ------------------------------------------
import time
import machine
import pyb
# The slider is connected to pin Y4
y4 = machine.Pin('Y4')
# read out slider through analog to digital converter
adc = pyb.ADC(y4)
# slider_out between 0 - 255
slider_out = adc.read()
# set up the game's initial parameters
speed = 30 # speed approaching the moon
fuel = 1500 # how much fuel is left
altitude = 1000 # altitude above moon
gravity = 1.622 # acceleration due to gravity
burn = 0 # initial rate of burning fuel in retrorockets
# while LLM is above the moon's surface,
# calculate flight data and take input from pilot
while altitude > 0:
# calculate how long until LLM will impact moon at current speed (impact)
if speed <= 0:
impact = 1000
else:
impact = altitude / speed
# display flight data
print(
"Altitude={:8.3f} Speed={:6.3f} Fuel={:8.3f} Impact={:6.3f} Previous burn={:6.3f}".format(altitude, speed, fuel,
impact, burn))
# take input from pilot
burn = 5 # <----- replace this line of code with filtered dynamic input from slider
# ensure rate of fuel burning is within rocket's capability and doesn't exceed remaining fuel
if burn < 0:
burn = 0
if burn > 50:
burn = 50
if burn > fuel:
burn = fuel
# adjust to change the speed of the game
time.sleep_ms(300)
# calculate new flight data
altitude -= speed
speed += gravity - burn / 10
fuel -= burn
# loop has ended so we must have hit moon's surface
# display final flight data and assess whether it was a crash or a good landing
print("Altitude={:8.3f} Speed={:6.3f} Fuel={:8.3f} Last burn={:6.3f}".format(altitude, speed, fuel, burn))
if altitude < - 5 or speed > 5:
print("You have crashed")
else:
print("You have landed")
|
import sqlite3
class database:
id=""
def __init__(self,databaseName = "database",table="users",numberOfColumn=2,columns=None):
self.databaseName=databaseName
self.openDatabase(self.databaseName)
if not(self.tableFound(table)):
print("done")
self.createTable(table,numberOfColumn,columns)
def openDatabase(self,databaseName='database'):
self.database=sqlite3.connect("%s"%(databaseName+'.db'))
self.cursor=self.database.cursor()
return self.cursor
def createTable(self,table="users",numberOfColumn=2,columns=None):
print("hi")
if not(self.tableFound(table)):
if numberOfColumn==2:
self.cursor.execute("CREATE TABLE %s(n INTEGER PRIMARY KEY,%s %s NOT NULL,%s %s NOT NULL );"
%(table,columns[0],columns[1],columns[2],columns[3]))
elif numberOfColumn ==3:
print("dine")
self.cursor.execute("CREATE TABLE %s(n INTEGER PRIMARY KEY,%s %s NOT NULL,%s %s NOT NULL ,%s %s NOT NULL );"
%(table, columns[0], columns[1], columns[2], columns[3], columns[4], columns[5]))
elif numberOfColumn==4:
self.cursor.execute("CREATE TABLE %s(n INTEGER PRIMARY KEY,%s %s NOT NULL,%s %s NOT NULL ,%s %s NOT NULL,%s %s NOT NULL );"
%(table, columns[0], columns[1], columns[2], columns[3], columns[4], columns[5], columns[6], columns[7]))
def tableFound(self,table="users"):
print("s")
self.cursor.execute(" SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (table,))
return (self.cursor.fetchone()[0] == 1)
def insertRow(self,table,numberOfColumn=2,columns=None):
self.openDatabase(self.databaseName)
if numberOfColumn==2:
self.cursor.execute("INSERT OR IGNORE INTO %s (%s,%s) VALUES (?,?)"
% (table,columns[0],columns[2]),(columns[1],columns[3]))
elif numberOfColumn==3:
self.cursor.execute("INSERT OR IGNORE INTO %s (%s,%s,%s) VALUES (?,?,?)"
% (table,columns[0],columns[2],columns[4]),(columns[1],columns[3],columns[5]))
elif numberOfColumn==4:
self.cursor.execute("INSERT OR IGNORE INTO %s (%s,%s,%s,%s) VALUES (?,?,?,?)"
% (table,columns[0],columns[2],columns[4],columns[6]),(columns[1],columns[3],columns[5],columns[7]))
self.database.commit()
self.database.close()
self.openDatabase(self.databaseName)
print(self.databaseName +" done")
def select(self,table="users",number=1,array=None,relation=["AND"]):
if number == 1:
self.cursor.execute("SELECT * FROM %s WHERE %s =?" % (table,array[0]), (array[1],))
return self.cursor.fetchall()
elif number == 2:
self.cursor.execute("SELECT * FROM %s WHERE %s =? %s %s = ? " % (table,array[0],relation[0],array[2]), (array[1],array[3]))
return self.cursor.fetchall()
elif number==3:
self.cursor.execute("SELECT * FROM %s WHERE %s =? %s %s = ? %s %s =?" % (table,array[0],relation[0],array[2],relation[1],array[4]), (array[1],array[3],array[5]))
return self.cursor.fetchall()
def selectAll(self,table="users"):
self.cursor.execute("SELECT * FROM %s" % (table))
return self.cursor.fetchall()
def idFound(self,table="users",number=1,array=None,relation=["And"]):
return (len(self.select(table,number,array,relation))!=0)
def deletRow(self,table="users",column="name",id="ali"):
self.cursor.execute("DELETE FROM %s WHERE %s =?" % (table, column), (id,))
self.database.commit()
self.database.close()
self.openDatabase(self.databaseName)
|
import numpy as np
def common_subgraph(A, B, nodes_list_A, nodes_list_B, directed=False):
"""
Retrievs the common sub graph of two networks.
Given the adjacency matrices of two networks and their nodes lists it finds
the nodes in common and consequentely the edges.
Parameters
----------
A: array-like, shape=(n1, n1)
Adjacency matrix of the first network.
B: array-like, shape=(n2, n2)
Adjacency matrix of the second network.
nodes_list_A: list, length=n1
List of nodes identities for the network A.
nodes_list_B: list, length=n2
List of nodes identities for the network A.
directed: boolean, optional defualt=False
If the network has to be considered as directed or undirected. Relevant
only for the computation of the number of common edges.
Returns
-------
array-like:
The adjacency matrix of the common sub graph.
list:
The list of common nodes.
int:
The number of common edges in the graph.
"""
nodes_list_A = [str(n).lower() for n in nodes_list_A]
nodes_list_B = [str(n).lower() for n in nodes_list_B]
common_nodes = sorted(list(set(nodes_list_A).intersection(set(nodes_list_B))))
ix_a = [nodes_list_A.index(n) for n in common_nodes]
ix_b = [nodes_list_B.index(n) for n in common_nodes]
A_sub = A[ix_a, :]
A_sub = A_sub[:, ix_a]
B_sub = B[ix_b, :]
B_sub = B_sub[:, ix_b]
assert A_sub.shape == B_sub.shape
A_sub = (A_sub != 0).astype(int)
B_sub = (B_sub != 0).astype(int)
common = A_sub + B_sub
common -= np.diag(np.diag(common))
ix = sorted(list(set(np.where(common==2)[0]).union(set(np.where(common==2)[1]))))
nodes = np.array(nodes_list_A)[ix_a][ix]
common_sub = common[ix,:]
common_sub = common_sub[:, ix]
common_sub[np.where(common_sub==1)] = 0
common_sub = common_sub / 2
n_edges = np.sum(common_sub) if directed else np.sum(common_sub)/2
return common_sub, nodes, n_edges
def multi_common_subgraph(Gs, nodes_lists, directed=False):
common, nodes, _ = common_subgraph(Gs[0], Gs[1],
nodes_lists[0], nodes_lists[1],
directed)
for i in range(2, len(Gs)):
common, nodes, n_edges = common_subgraph(Gs[i], common,
nodes_lists[i], nodes,
directed)
print(n_edges)
return common, nodes, n_edges
|
class Example:
def __init__(self):
print("You have choosen to view an example. To advance each step press enter.\nIn the example we will use the polynomial: 2x^4 + x^3 - 19x^2 -9x +9\n\n")
input("")
print("First you will find the factors of the leading coefficient: q = +-1, +-2")
input("")
print("Then you will need the factors of the trailing constansep=' 't term: p = +-1, +-3, +-9")
input("")
print("You will then need to list the possible zeroes by taking p and dividing by q: +-1/1, +-1/2, +-3/1, +-3/2, +-9/1, +-9/2")
print("These can be reduced to: +-1, +-1/2, +-3, +-3/2, +-9, +-9/2")
input("")
print("When you have the set of all possible zeroes from the polynomial you can then use synthetic division to test for each:\n")
print("1 | 2 1 -19 -9 9\n | 2 3 -16 -25\n --------------------\n 2 3 -16 -25 -16\n\nThe remainder is not a 0 therefore 1 is not a root.")
input("")
print("-1 | 2 1 -19 -9 9\n | -2 1 18 -9\n -------------------\n 2 -1 -18 9 0\n\nThe remainder is a 0 therefore -1 is a root.")
input("")
print("1/2 | 2 1 -19 -9 9\n | 1 1 -9 -9\n ------------------\n 2 2 -18 -18 0\n\nThe remainder is a 0 therefore 1/2 is a root.")
input("")
print("-1/2 | 2 1 -19 -9 9\n | -1 0 19/2 -1/4\n ------------------------\n 2 0 -19 1/2 35/4\n\nThe remainder is not a 0 therefore -1/2 is not a root.")
input("")
print("3 | 2 1 -19 -9 9\n | 6 21 6 -9\n --------------------\n 2 7 2 -3 0\n\nThe remainder is a 0 therefore 3 is a root.")
input("")
print("-3 | 2 1 -19 -9 9\n | -6 15 12 -9\n ------------------------\n 2 -5 -4 3 0\n\nThe remainder is a 0 therefore -3 is a root.")
input("")
|
import pandas as pd
import numpy as np
#reads the file and creates pandas dataframe
excel_file=R"xxxxx.xlsx"
data = pd.read_excel(excel_file, converters={'HTS':str}, index_col=None)
#creates dataframe without rows that have 'Free' in the EIF column
data_2=data[data['EIF'] !='Free']
#drop two unneeded columns
data_2 = data_2.drop(['mfn_text_rate'], axis=1)
#rename EIF as 2020
data_2 = data_2.rename (columns = {'EIF': '2020'})
###this is to create final source column that shows the first year ave became free
#create list of year columns
years=['2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029']
#create list of column locations for years
year_loc = []
for year in years:
column = data_2.columns.get_loc(year)
year_loc.append(column)
#this is loops through the 9 year columns and the first time free appears, that column/year is given as the value in final
final = []
for i in range(len(data_2)):
if data_2.iloc[i, year_loc[0]] == 'Free':
final.append(years[0])
elif data_2.iloc[i, year_loc[1]] == 'Free':
final.append(years[1])
elif data_2.iloc[i, year_loc[2]] == 'Free':
final.append(years[2])
elif data_2.iloc[i, year_loc[3]] == 'Free':
final.append(years[3])
elif data_2.iloc[i, year_loc[4]] == 'Free':
final.append(years[4])
elif data_2.iloc[i, year_loc[5]] == 'Free':
final.append(years[5])
elif data_2.iloc[i, year_loc[6]] == 'Free':
final.append(years[6])
elif data_2.iloc[i, year_loc[7]] == 'Free':
final.append(years[7])
elif data_2.iloc[i, year_loc[8]] == 'Free':
final.append(years[8])
else:
final.append('NA')
#assigns final list as final_year column in dataframe
data_2['final_year']=final
def type(data, year):
# this creates the rate type code, if free it puts 0, else 7
return np.where(data[year]=='Free', '0', '7')
def ave(data, year):
#this creates a column with the numerical, fraction version of the text ave
ave = []
for row in data[year]:
if row == 'Free':
ave.append(0)
else:
ave.append(round(float(row.rstrip('%')) / 100.0, 4))
return ave
#iterate over year columns to create two new columns, rate type and ad vale rate, for year year
years=['2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029']
for year in years:
data_2['r'+year+'_rate_type_code']=type(data_2, year)
data_2['r'+year+'_ad_val_rate']=ave(data_2, year)
#rename year columsn to rYYYY_text
for year in years:
data_2 = data_2.rename (columns = {year: 'r'+year+'_text'})
#reorder columns to group years together
#list of column headers in order desired
cols = ['HTS', 'r2020_rate_type_code', 'r2020_text', 'r2020_ad_val_rate', 'r2021_rate_type_code', 'r2021_text',
'r2021_ad_val_rate', 'r2022_rate_type_code', 'r2022_text', 'r2022_ad_val_rate',
'r2023_rate_type_code', 'r2023_text', 'r2023_ad_val_rate', 'r2024_rate_type_code', 'r2024_text', 'r2024_ad_val_rate',
'r2025_rate_type_code', 'r2025_text', 'r2025_ad_val_rate', 'r2026_rate_type_code', 'r2026_text', 'r2026_ad_val_rate',
'r2027_rate_type_code', 'r2027_text', 'r2027_ad_val_rate', 'r2028_rate_type_code', 'r2028_text', 'r2028_ad_val_rate',
'r2029_rate_type_code', 'r2029_text', 'r2029_ad_val_rate', 'final_year']
data_3 = data_2[cols]
#output into excel
data_3.to_excel("xxxx.xlsx")
|
class Grafo:
def __init__(self, nome_arquivo = None):
self.vizinhos = {}
self.vertices = []
self.n = 0
self.m = 0
if nome_arquivo is not None:
self.carregar_do_arquivo(nome_arquivo)
def add_vertice(self, v):
if v not in self.vertices:
self.vizinhos[v] = []
self.vertices.append(v)
self.n += 1
def add_aresta(self, u, v):
if u != v:
if u not in self.vertices:
self.add_vertice(u)
if v not in self.vertices:
self.add_vertice(v)
if v not in self.vizinhos[u]:
self.m += 1
self.vizinhos[u].append(v)
self.vizinhos[v].append(u)
def carregar_do_arquivo(self, nome_arquivo):
with open(nome_arquivo, 'r') as arquivo:
linhas = arquivo.readlines()
for linha in linhas:
linha = "".join(linha.split()) #remove todos os whitespaces
if len(linha) == 0:
continue
adjacencia = linha.split(":") #a string antes do ':' é o vértice em questão e tudo depois do ':' são os vizinhos desse vértice. cada linha representa uma relação de adjacência
if len(adjacencia) == 1:
self.add_vertice(adjacencia[0]) #nesse caso a linha não tem um ':', portanto é um vértice isolado
else:
v = adjacencia[0]
vizinhos = adjacencia[1].split(',')
for u in vizinhos:
if u != "":
self.add_aresta(v, u)
else:
self.add_vertice(v) #nesse caso não há nada após o ':', portanto v é um vértice isolado
def __str__(self):
string = "vértices = " + str(self.n) + ", arestas = " + str(self.m) + "\n"
for v in self.vertices:
string += "N(" + v + ") = {"
if len(self.vizinhos[v]) == 0:
string += "}\n"
continue
for u in self.vizinhos[v]:
string += u + ", "
string = string[:-len(", ")] + "}\n"
return string[:-len("\n")] #remove o último \n
|
def pay_off_debt_in_a_year(balance, annualInterestRate):
monthlyInterestRate = annualInterestRate / 12
updatedBalanceEachMonth = balance
monthlyPaymentLowerBound = balance / 12
monthlyPaymentUpperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12
minimumMonthlyPayment = (monthlyPaymentUpperBound + monthlyPaymentLowerBound) / 2.0
while abs(monthlyPaymentUpperBound - monthlyPaymentLowerBound) > 0.000001:
minimumMonthlyPayment = (monthlyPaymentUpperBound + monthlyPaymentLowerBound) / 2.0
updatedBalanceEachMonth = balance
for i in range(12):
updatedBalanceEachMonth = (updatedBalanceEachMonth - minimumMonthlyPayment) * (1 + monthlyInterestRate)
if updatedBalanceEachMonth >= 0.0:
monthlyPaymentLowerBound = minimumMonthlyPayment
else:
monthlyPaymentUpperBound = minimumMonthlyPayment
print("Lowest Payment: {0:.2f}".format(minimumMonthlyPayment))
pay_off_debt_in_a_year(balance, annualInterestRate)
pay_off_debt_in_a_year(320000, 0.2)
pay_off_debt_in_a_year(999999, 0.18)
pay_off_debt_in_a_year(3329, 0.2)
pay_off_debt_in_a_year(4773, 0.2)
pay_off_debt_in_a_year(3926, 0.2)
|
#!/usr/bin/env python
import argparse
import hashlib
def hashthings(words, outfile, alg, verbose):
print('[*] Using the {0} algorithm').format(alg)
for word in words:
word = word.strip()
if word == '':
continue
else:
hsh = hashlib.new(alg, word).hexdigest()
if verbose == True:
print('[*] {0} {1}').format(hsh, word)
outfile.write(hsh + '\n')
print('[*] {0} hashes written to {1}').format(str(len(words)), outfile.name)
outfile.close()
parser = argparse.ArgumentParser(description='Calculate hashes for words')
parser.add_argument('-w', '--wordlist', help='file containing words to be hashed', required=True)
parser.add_argument('-f', '--file', help='file to write results to', required=True)
parser.add_argument('-a', '--algorithm', help='hashing algorithm to use', choices=['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], default='md5')
parser.add_argument('-v', '--verbose', help='show verbose output', action='store_true')
args = parser.parse_args()
words = open(args.wordlist, 'r').readlines()
outfile = open(args.file, 'w')
alg = args.algorithm
verbose = args.verbose
hashthings(words, outfile, alg, verbose)
|
import hashlib # Generate MD5 hashes
__version__ = "0.1"
supportedHashes = ["sha256", "md5"]
def generateHash(data, hashtype):
if hashtype == "md5":
hash = hashlib.md5(data)
elif hashtype == "sha256":
hash = hashlib.sha256(data)
else:
raise ValueError
return hash.hexdigest()
def verifyChecksum(hashtype):
filePath = input("Please enter the path of the file: ")
checksum = input("Please enter the checksum of the file: ")
try:
print("Verifying checksum...")
with open(filePath, "rb") as fileObject:
fileData = fileObject.read()
generatedChecksum = generateHash(fileData, hashtype)
if generatedChecksum == checksum:
print("Checksum verified")
else:
print("Checksum does not match!")
except:
print("There was an issue while verifying the checksum")
def generateChecksum(hashtype):
filePath = input("Please enter the path of the file: ")
try:
print("Verifying checksum...")
with open(filePath, "rb") as fileObject:
fileData = fileObject.read()
checksum = generateHash(fileData, hashtype)
print("Checksum for file: "+filePath+ " is: "+checksum)
except:
print("There was an issue while generating the checksum")
print("ChecksumVerifier "+__version__)
while True:
print("1. Generate checksum")
print("2. Verify checksum")
option = input("Please choose an option: ")
for i, hashtype in enumerate(supportedHashes):
print(str(i + 1) + ". " + hashtype)
hashtype = input("Please choose a hash type: ")
if hashtype in supportedHashes:
if option == "1":
generateChecksum(hashtype)
elif option == "2":
verifyChecksum(hashtype)
else:
print("Please choose a valid option")
else:
print("Unsupported hashtype!")
|
# CamJam EduKit 1 – Basics
# Worksheet 7 – Traffic Lights – Solution
# Import Libraries
import os
import time
from gpiozero import LED, Button, Buzzer
# Set up variables for the LED, Buzzer and switch pins
green = LED(24)
yellow = LED(23)
red = LED(18)
buzzer = Buzzer(22)
button = Button(25)
# Define a function for the initial state (Green LED on, rest off)
# (If you have the second pedestrian LEDs, turn the red on & green
# off)
def startgreen():
print("Green light on")
green.on()
yellow.off()
red.off()
# Turn the green off, and the amber on, for 3 seconds
# ('Pedestrian' red-LED stays lit)
def steadyamber():
print("Steady amber")
green.off()
yellow.on()
red.off()
time.sleep(3)
# Turn the amber off, and then the red on for 1 second.
def steadyred():
print("Steady red")
green.off()
yellow.off()
red.on()
time.sleep(1)
# Sound the buzzer for 4 seconds
# (If you have the 'pedestrian' LEDs, turn the red off and green on)
def startwalking():
# Make the buzzer buzz on and off, half a second of
# sound followed by half a second of silence.
print("Start walking")
count = 1
while count <= 4:
print("Beep")
buzzer.on()
time.sleep(0.5)
buzzer.off()
time.sleep(0.5)
count += 1
# Turn the buzzer off and wait for 2 seconds
# (If you have a second green 'pedestrian' LED, make it flash on and
# off for the two seconds)
def dontwalk():
print("Don't walk")
buzzer.off()
# Flash the amber on and off for 6 seconds
# (And the green 'pedestrian' LED too)
def flashingambergreen():
print("Flashing amber and green")
red.off()
green.off()
count = 1
while count <= 6:
yellow.on()
time.sleep(0.5)
yellow.off()
time.sleep(0.5)
count += 1
green.on()
# Flash the amber for one more second
# (Turn the green 'pedestrian' LED off and the red on)
def flashingamber():
print("Flashing amber")
green.off()
yellow.on()
time.sleep(0.5)
yellow.off()
time.sleep(0.5)
red.on()
# Go through the traffic light sequence by calling each function
# one after the other.
def trafficlightsequence():
print("Traffic Light sequence started")
# Green will already be on
steadyamber()
steadyred()
startwalking()
dontwalk()
flashingambergreen()
flashingamber()
startgreen()
os.system('clear') # Clears the terminal
print("Traffic Lights")
# Initialise the traffic lights
startgreen()
waiting_time = 20
# Here is the loop that waits at lease 20 seconds before
# stopping the cars if the button has been pressed.
while True: # Loop around forever
buttonnotpressed = True # The Button has not been pressed
start = time.time() # Records the current time
while buttonnotpressed: # While the button has not been pressed
time.sleep(0.1) # Wait for 0.1s
if button.is_pressed: # If the button is pressed
print("Button has been pressed")
now = time.time()
buttonnotpressed = False # Button has been pressed
if (now - start) <= waiting_time: # If under 20 seconds
time.sleep(waiting_time - (now - start)) # Wait until 20 seconds is up
trafficlightsequence() # Run the traffic light sequence
|
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def find(self, key):
"""
:param key:
:return:
"""
self.__find(self)
def __find(self, root, key):
if root.data == key:
return root
elif root.data > key:
return self.__find(root.left, key)
else:
return self.__find(root.right, key)
def insert(self, data):
if self.root is None:
self.root = Node(data)
else:
return self.__insert(self.root, data)
def __insert(self, node, data):
if data <= node.data:
if node.left is not None:
return self.__insert(node.left, data)
else:
node.left = Node(data)
elif data == node.data:
print('this data {} is already exist!'.format(data))
return
else: # (data<node.data):
if node.right is not None:
return self.__insert(node.right, data)
else:
node.right = Node(data)
def remove(self, value):
"""
Removes a Node which contains the value `value`.
To remove a Node, three cases must be handled.
Case 1: leaf node
-> delete it
Case 2: node has one child
-> delete node and put its child in its place
Case 3: node has two children
-> delete node and put its smallest child from its right branch in its place
"""
if self.root:
self.root = self.__remove(self.root, value)
def __remove(self, node, value):
if node.data == value:
# Case 1
if node.left is None and node.right is None:
return None
# Case 2
elif node.left and node.right is None:
return node.left
# Case 2
elif node.left is None and node.right:
return node.right
# Case 3
else:
parent_node = node
smallest_node = node.right
while smallest_node.left:
parent_node = smallest_node
smallest_node = smallest_node.left
# The right Node is the smallest one
if parent_node == node:
smallest_node.left = node.left
# The smallest Node was found to the left of its right branch
else:
parent_node.left = smallest_node.right
smallest_node.left = node.left
smallest_node.right = node.right
return smallest_node
elif node.data > value and node.left:
node.left = self.__remove(node.left, value)
elif node.data < value and node.right:
node.right = self.__remove(node.right, value)
return node
def pre_order_traversal(self):
print()
self.__pre_order_traversal(self.root)
def __pre_order_traversal(self, node):
print(node.data, end=' ')
if node is None:
return
if node.left:
self.__pre_order_traversal(node.left)
if node.right:
self.__pre_order_traversal(node.right)
def in_order_traversal(self):
print()
self.__in_order_traversal(self.root)
def __in_order_traversal(self, node):
if node is None:
return
if node.left:
self.__in_order_traversal(node.left)
print(node.data, end=' ')
if node.right:
self.__in_order_traversal(node.right)
def post_order_traversal(self):
print()
self.__post_order_traversal(self.root)
def __post_order_traversal(self, node):
if node is None:
return
if node.left:
self.__post_order_traversal(node.left)
if node.right:
self.__post_order_traversal(node.right)
print(node.data, end=' ')
if __name__ == '__main__':
values = [50, 30, 70, 80, 20, 10, 110, 190, 130, 55]
t = BinarySearchTree()
for value in values:
t.insert(value)
t.in_order_traversal()
t.remove(30)
t.in_order_traversal()
t.remove(130)
t.in_order_traversal()
# test traversal methods
# tt=BinarySearchTree()
# v= [21, 28, 14, 32, 25, 18, 11, 30, 19, 15, 5, 12, 23, 27, 37]
# for value in v:
# tt.insert(value)
# tt.post_order_traversal()
# tt.in_order_traversal()
# tt.pre_order_traversal()
|
from bs4 import BeautifulSoup
import requests
topic = input("Enter topic : ")
response = requests.get("https://en.wikipedia.org/wiki/"+topic)
soup = BeautifulSoup(response.text,"lxml")
t = soup.find_all('h1')
text=""
for i in range(0,len(t)):
text+=t[i].text
print(text)
|
import numpy as np
import pandas as pd
class HomeTemperature(object):
"""Home temperature.
"""
def __init__(self, T_heating, k_home_external, k_heater_on, k_heater_off, k_home_heater, t_step, engine=None):
self.T_heating = T_heating
self.k_home_external = k_home_external
self.k_heater_on = k_heater_on
self.k_heater_off = k_heater_off
self.k_home_heater = k_home_heater
self.t_step = t_step
self.engine = engine
def home_heater_temperature(self, T_home, T_external, T_heater, heating, my_datetime):
"""Simple model of interaction between home's temperature,
external temperature and heating system. This model is based on
the Newton's law of cooling:
http://en.wikipedia.org/wiki/Convective_heat_transfer#Newton.27s_law_of_cooling
"""
# The external environment drags home's temperature:
T_home_next_external = T_external + (T_home - T_external) * np.exp(-self.k_home_external * self.t_step) # Newton's law of cooling
if heating == 1: # if heating is turned on then the heater is heated:
T_heater_next = self.T_heating + (T_heater - self.T_heating) * np.exp(-self.k_heater_on * self.t_step) # Newton's law of cooling
else: # if heating is turned off then the heater is cooled according to home's temperature:
T_heater_next = T_home + (T_heater - T_home) * np.exp(-self.k_heater_off * self.t_step) # Newton's law of cooling
# In any case, home's temperature is dragged by heater's temperature
T_home_next_heater = T_heater + (T_home - T_heater) * np.exp(-self.k_home_heater * self.t_step) # Newton's law of cooling
# We model the home's temperature at the next step as the average
# of external environment and heater contributions.
T_home_next = 0.5 * (T_home_next_external + T_home_next_heater)
if self.engine is not None:
df = pd.DataFrame({'timestamp': [my_datetime],
'home_temperature': [T_home_next],
})
df.to_sql('temperature_home', self.engine, if_exists='append', index=False)
return T_home_next, T_heater_next
|
import tkinter as tk
from tkinter import*
h = 400
w = 400
root = tk.Tk()
root.geometry("250x400+300+300")
root.resizable(0,0)
root.title('Calculator')
A = 0
val = ''
operator = ''
data = StringVar()
lbl = tk.Label(
root,
font = ('Verdana',22),
anchor = 'se',
textvariable = data,
background = 'white'
)
lbl.pack(expand = True,fill = 'both')
def btn_9_isclicked():
global val
val = val + '9'
data.set(val)
def btn_8_isclicked():
global val
val = val + '8'
data.set(val)
def btn_7_isclicked():
global val
val = val + '7'
data.set(val)
def btn_6_isclicked():
global val
val = val + '6'
data.set(val)
def btn_5_isclicked():
global val
val = val + '5'
data.set(val)
def btn_4_isclicked():
global val
val = val + '4'
data.set(val)
def btn_3_isclicked():
global val
val = val + '3'
data.set(val)
def btn_2_isclicked():
global val
val = val + '2'
data.set(val)
def btn_1_isclicked():
global val
val = val + '1'
data.set(val)
def btn_0_isclicked():
global val
val = val + '0'
data.set(val)
def btn_plus_isclicked():
global A
global operator
global val
A = int(val)
operator = "+"
val = val + "+"
data.set(val)
def btn_minus_isclicked():
global A
global operator
global val
A = int(val)
operator = "-"
val = val + "-"
data.set(val)
def btn_multiplication_isclicked():
global A
global operator
global val
A = int(val)
operator = "*"
val = val + "*"
data.set(val)
def btn_division_isclicked():
global A
global operator
global val
A = int(val)
operator = "/"
val = val + "/"
data.set(val)
def btn_result_isclicked():
global A
global val
global operator
val_2 = val
if operator == "+":
x = int((val_2.split("+")[1]))
C = A + x
val = str(C)
data.set(val)
if operator == "-":
x = int((val_2.split("-")[1]))
C = A - x
val = str(C)
data.set(val)
if operator == "*":
x = int((val_2.split("*")[1]))
C = A * x
val = str(C)
data.set(val)
if operator == "/":
x = int((val_2.split("/")[1]))
C = A / x
val = str(C)
data.set(val)
btn_row_1 =tk.Frame(root,bg = 'black')
btn_row_1.pack(expand = True,fill = 'both')
btn_9 = tk.Button(
btn_row_1,
text = '9',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_9_isclicked
)
btn_9.pack(side = 'left' , expand = True,fill = 'both')
btn_8 = tk.Button(
btn_row_1,
text = '8',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_8_isclicked
)
btn_8.pack(side = 'left' , expand = True,fill = 'both')
btn_7 = tk.Button(
btn_row_1,
text = '7',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_7_isclicked
)
btn_7.pack(side = 'left' , expand = True,fill = 'both')
btn_plus= tk.Button(
btn_row_1,
text = '+',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_plus_isclicked
)
btn_plus.pack(side = 'left' , expand = True,fill = 'both')
btn_row_2 =tk.Frame(root)
btn_row_2.pack(expand = True,fill = 'both')
btn_6 = tk.Button(
btn_row_2,
text = '6',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_6_isclicked
)
btn_6.pack(side = 'left' , expand = True,fill = 'both')
btn_5 = tk.Button(
btn_row_2,
text = '5',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_5_isclicked
)
btn_5.pack(side = 'left' ,expand = True,fill = 'both')
btn_4 = tk.Button(
btn_row_2,
text = '4',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_4_isclicked
)
btn_4.pack(side = 'left' , expand = True,fill = 'both')
btn_minus= tk.Button(
btn_row_2,
text = ' -',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_minus_isclicked
)
btn_minus.pack(side = 'left' , expand = True,fill = 'both')
btn_row_3 =tk.Frame(root,bg = 'black')
btn_row_3.pack(expand = True,fill = 'both')
btn_3 = tk.Button(
btn_row_3,
text = '3',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_3_isclicked
)
btn_3.pack(side = 'left' , expand = True,fill = 'both')
btn_2 = tk.Button(
btn_row_3,
text = '2',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_2_isclicked
)
btn_2.pack(side = 'left' , expand = True,fill = 'both')
btn_1 = tk.Button(
btn_row_3,
text = '1',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_1_isclicked
)
btn_1.pack(side = 'left' , expand = True,fill = 'both')
btn_divison= tk.Button(
btn_row_3,
text = ' /',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_division_isclicked
)
btn_divison.pack(side = 'left' , expand = True,fill = 'both')
btn_row_4 =tk.Frame(root)
btn_row_4.pack(expand = True,fill = 'both')
btn_Clear = tk.Button(
btn_row_4,
text = 'C',
font = ('Verdana',22),
bd = 0,
activebackground = "gray"
)
btn_Clear.pack(side = 'left' , expand = True,fill = 'both')
btn_0 = tk.Button(
btn_row_4,
text = '0',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_0_isclicked
)
btn_0.pack(side = 'left' , expand = True,fill = 'both')
btn_result = tk.Button(
btn_row_4,
text = '=',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_result_isclicked
)
btn_result.pack(side = 'left' , expand = True,fill = 'both')
btn_multiplication= tk.Button(
btn_row_4,
text = ' *',
font = ('Verdana',22),
bd = 0,
activebackground = "gray",
command = btn_multiplication_isclicked
)
btn_multiplication.pack(side = 'left' , expand = True,fill = 'both')
root.mainloop()
|
def solve_task1(file_name):
required_bag = "shiny gold bag"
bags_contained_by = read_file(file_name)
bags_can_contain = get_bags_can_contain(required_bag, bags_contained_by)
return len(bags_can_contain)
def read_file(file_name):
bags_contained_by = {}
with open(file_name, "r") as f:
for line in f:
line = line.rstrip()
contained_by, contains_bags = line.split(" contain ")
if contains_bags != "no other bags.":
contains_bags = contains_bags.split(",")
contained_by = _trim_s(contained_by)
contains_bags = [_trim_s(contain_bag) for contain_bag in contains_bags]
contains_bags = [_trim_num(contain_bag) for contain_bag in contains_bags]
for bag in contains_bags:
bags_contained_by.setdefault(bag, []).append(contained_by)
return bags_contained_by
def get_bags_can_contain(required_bag, bags_contained_by):
result = set()
for contained_by in bags_contained_by.get(required_bag, []):
result.add(contained_by)
contained_deeply_by = get_bags_can_contain(contained_by, bags_contained_by)
result = result.union(contained_deeply_by)
return result
def _trim_s(bag_name):
bag_name = bag_name.rstrip()
bag_name = bag_name[:-1] if bag_name[-1] == "." else bag_name
return bag_name[:-1] if bag_name[-1] == "s" else bag_name
def _trim_num(bag_name):
first_letter_idx = 0
while bag_name[first_letter_idx] == " " or ("0" <= bag_name[first_letter_idx] <= "9"):
first_letter_idx += 1
return bag_name[first_letter_idx:]
if __name__ == "__main__":
print(solve_task1("day_07/input.txt"))
|
from collections import Counter
import random
import itertools
import numpy as np
#important functions
def cardValue(card):
"""
CardValue retrieves the actual integer value of the card
@date 9/12/2017
@param card is the inputed card that we are trying to convert to an integer
@return cardAsAnInt the actual integer value of the card
"""
cardAsAnInt = 0
if (card == "A"):
cardAsAnInt = 1
elif (card == "J"):
cardAsAnInt = 11
elif (card == "Q"):
cardAsAnInt = 12
elif (card == "K"):
cardAsAnInt = 13
elif (int(card) >= 2 and int(card) <= 10):
cardAsAnInt = int(card)
return cardAsAnInt
def sort(inputtedArray):
"""
Given a set of cards, organizes them in ascending order (ex: A, K, 6, 7, 3 --> A, 3, 6, 7, K).
@date 9/14/2017
@param inputtedArray an array containing the inputed cards.
@return sortedArray returns the cards as a sortedArray in ascending order.
"""
sortedArray = []
isSorted = False
while inputtedArray:
smallest = min(inputtedArray)
index = inputtedArray.index(smallest)
sortedArray.append(inputtedArray.pop(index))
return sortedArray
def sortWithSuit(inputtedArray):
"""
Given a set of cards with their respective Suit, organizes them in ascending order (ex: SA, HK, D6, S7, C3 --> SA, C3, D6, S7, HK).
@date 11/14/2017
@param inputtedArray an array containing the inputed cards.
@variable noSuitArray the array containing the inputed cards but without their respective suit.
@return sortedArray returns the cards as a sortedArray in ascending order.
"""
sortedArray = []
isSorted = False
noSuitArray = removeSuit(inputtedArray)
while inputtedArray:
smallest = min(noSuitArray)
index = noSuitArray.index(smallest)
noSuitArray.pop(index)
sortedArray.append(inputtedArray.pop(index))
return sortedArray
def removeSuit(inputtedArray):
"""
Given a set of cards with their respective Suit, removes the suit and returns the new array.
@date 12/5/2017
@param inputtedArray an array containing the inputed cards.
@return noSuitArray returns the cards with just their numbers, no suits.
"""
noSuitArray = []
for i in range(0, len(inputtedArray)):
noSuitArray.append(int(inputtedArray[i][1:]))
return noSuitArray
#findingPoints
def findFifteen(inputHand):
"""
findFifteen returns all possible combinations that add up to 15
@date 9/19/2017
@param inputtedArray an array containing the inputed cards.
@return addsUpToFifteen returns a two-dimensional array containing all combinations of 15.
"""
addsUpToFifteenArray = [] #A 2-dimension array containing all possible combinations of 15 in a hand.
fifteenInt = 15
inputtedArray = sort(inputHand.copy()) #sorts the array from smallest to largest.
length = len(inputtedArray) #the amount of cards in a hand (will range from 4-5. 4 = starting hand. 5 = includes the up-card)
for i in range(0, length): #this fixes the fact that JQK are 11,12,13 respectively, but they count as 10 when refering to a 15.
if (inputtedArray[i] > 10):
inputtedArray[i] = 10
for i in range(0, length):
for j in range (i+1, length):
#If statement that is comparing 2 cards that adds up to 15.
if (inputtedArray[i] + inputtedArray[j] == fifteenInt):
tempArray = [] #temporary array containing an individual pair.
tempArray.append(inputtedArray[i]) #adds the first card
tempArray.append(inputtedArray[j]) #adds the second card
addsUpToFifteenArray.append(tempArray) #adds the 'pair' into the array
for k in range(j+1, length):
#If statement that is comparing 3 cards that adds up to 15.
if (inputtedArray[i] + inputtedArray[j] + inputtedArray[k] == fifteenInt):
tempArray = [] #temporary array containing an individual pair.
tempArray.append(inputtedArray[i]) #adds the first card
tempArray.append(inputtedArray[j]) #adds the second card
tempArray.append(inputtedArray[k]) #adds the third card
addsUpToFifteenArray.append(tempArray) #adds the 'pair' into the array
for l in range(k+1, length):
#If statement that is comparing 4 cards that adds up to 15.
if (inputtedArray[i] + inputtedArray[j] + inputtedArray[k] + inputtedArray[l] == fifteenInt):
tempArray = [] #temporary array containing an individual pair.
tempArray.append(inputtedArray[i]) #adds the first card
tempArray.append(inputtedArray[j]) #adds the second card
tempArray.append(inputtedArray[k]) #adds the third card
tempArray.append(inputtedArray[l]) #adds the fourth card
addsUpToFifteenArray.append(tempArray) #adds the 'pair' into the array
#If statement that is comparing 5 cards that add up to 15. (no need for a loop since this will only happen once).
if (length == 5):
if (inputtedArray[0] + inputtedArray[1] + inputtedArray[2] + inputtedArray[3] + inputtedArray[4] == fifteenInt):
tempArray = [] #temporary array containing an individual pair.
tempArray.append(inputtedArray[0]) #adds the first card
tempArray.append(inputtedArray[1]) #adds the second card
tempArray.append(inputtedArray[2]) #adds the third card
tempArray.append(inputtedArray[3]) #adds the fourth card
tempArray.append(inputtedArray[4]) #adds the fifth card
addsUpToFifteenArray.append(tempArray) #adds the 'pair' into the array
return addsUpToFifteenArray
def findPairs(inputHand):
"""
findPairs returns all pairs in the array.
@date 9/14/2017
@param inputtedArray an array containing the inputed cards.
@return pairArray returns a two-dimensional array containing all pairs.
"""
pairArray = [] #A 2-dimension array containing all possible pairs in a hand.
inputtedArray = sort(inputHand.copy()) #sorts the array from smallest to largest.
length = len(inputtedArray) #the amount of cards in a hand (will range from 4-5. 4 = starting hand. 5 = includes the up-card)
for i in range(0, length):
for j in range (i+1, length):
tempArray = [] #temporary array containing an individual pair.
if (inputtedArray[i] == inputtedArray[j]):
tempArray.append(inputtedArray[i]) #adds the first card
tempArray.append(inputtedArray[j]) #adds the second card
pairArray.append(tempArray) #adds the 'pair' into the array
return pairArray
def findRun(inputHand):
"""
run checks to see if there is atleast one run and returns all possible runs (not including the up card).
@date 10/31/2017
@param inputtedArray an array containing the inputed cards.
@return runArray
"""
runArray = [] #A 2-dimension array containing all the longest runs in a hand.
allPossibleRuns = [] #A 2-dimension array containing all possible runs in a hand.
inputtedArray = sort(inputHand.copy()) #sorts the array from smallest to largest.
length = len(inputtedArray) #the amount of cards in a hand (will range from 4-5. 4 = starting hand. 5 = includes the up-card)
longestRunLen = 0
for L in range(0, len(inputtedArray)+1):
for subset in itertools.combinations(inputtedArray, L):
tempArray = []
if (len(subset) == 5):
if (subset[0]+1 == subset[1] and subset[1]+1 == subset[2] and subset[2]+1 == subset[3] and subset[3]+1 == subset[4]):
tempArray.append(subset[0])
tempArray.append(subset[1])
tempArray.append(subset[2])
tempArray.append(subset[3])
tempArray.append(subset[4])
allPossibleRuns.append(tempArray)
longestRunLen = 5
elif (len(subset) == 4):
if (subset[0]+1 == subset[1] and subset[1]+1 == subset[2] and subset[2]+1 == subset[3]):
tempArray.append(subset[0])
tempArray.append(subset[1])
tempArray.append(subset[2])
tempArray.append(subset[3])
allPossibleRuns.append(tempArray)
if (longestRunLen <= 4):
longestRunLen = 4
elif (len(subset) == 3):
if (subset[0]+1 == subset[1] and subset[1]+1 == subset[2]):
tempArray.append(subset[0])
tempArray.append(subset[1])
tempArray.append(subset[2])
allPossibleRuns.append(tempArray)
if (longestRunLen <= 3):
longestRunLen = 3
for i in range (0, len(allPossibleRuns)):
if (len(allPossibleRuns[i]) >= longestRunLen):
runArray.append(allPossibleRuns[i])
return runArray
def nobs(pInputHand):
"""
nobs returns 1 point if there is a jack in the hand and the suit of the jack matches the upcard's suit.
@date 1/25/2017
@param inputHand an array containing the inputed cards containing their suits.
@return points returns 1 point if there is a nobs
"""
inputHand = pInputHand.copy()
length = len(inputHand) #the amount of cards in a hand (will range from 4-5. 4 = starting hand. 5 = includes the up-card)
upCard = 'Z14'
if (length == 5):
upCard = str(inputHand.pop()) #the upcard is the last card of the inputHand
length = len(inputHand)
points = 0
for i in range(0, length):
if (int(inputHand[i][1:]) == 11): #checks the number
if (str(inputHand[i][:1]) == str(upCard[:1])): #checks the suit
points += 1
i = length
return points
def flush(pInputHand):
"""
flush returns 4 point if all the cards within the hand share the same suit, if they do it checks the upCard and if it matches returns 5 points.
@date 1/25/2017
@param inputHand an array containing the inputed cards containing their suits.
@param upCard the upCard with its suit.
@return points returns 4 or 5 points if there is a flush
"""
inputHand = pInputHand.copy()
length = len(inputHand) #the amount of cards in a hand (will range from 4-5. 4 = starting hand. 5 = includes the up-card)
upCard = 'Z14'
points = 0
if (length == 5):
upCard = inputHand.pop #the upcard is the last card of the inputHand
if (inputHand[0][:1] == inputHand[1][:1] and inputHand[0][:1] == inputHand[2][:1] and inputHand[0][:1] == inputHand[3][:1] and inputHand[0][:1] == inputHand[4][:1] ):
points = 5
elif (inputHand[0][:1] == inputHand[1][:1] and inputHand[0][:1] == inputHand[2][:1] and inputHand[0][:1] == inputHand[3][:1] ):
points = 4
return points
def fifteenPoints(array):
"""
Given a two-dimensional array calculates the appropiate amount of points to return for 15.
@date 12/5/2017
@param array two-dimensional array containing all the combinations of 15.
@return points the amount of points the user recieved from the array.
"""
length = len(array)
points = 0
for i in range(0, length):
points += 2
return points
def pairPoints(array):
"""
Given a two-dimensional array calculates the appropiate amount of points to return for pairs.
@date 12/5/2017
@param array two-dimensional array containing all the combinations of pairs.
@return points the amount of points the user recieved from the array.
"""
length = len(array)
points = 0
for i in range(0, length):
points += 2
return points
def runPoints(array):
"""
Given a two-dimensional array calculates the appropiate amount of points to return for runs.
@date 12/5/2017
@param array two-dimensional array containing all the combinations of runs.
@return points the amount of points the user recieved from the array.
"""
length = len(array)
points = 0
for i in range(0, length):
runLength = len(array[i])
points += runLength
return points
#game aspects
def createNewDeck():
"""
Creates a deck of cards with 13 different cards of 4 different suits and then shuffles the deck.
@date 12/5/2017
@return deck returns an array of 52 cards
"""
deck = []
for i in range(1,14):
deck.append('C' + str(i))
deck.append('D' + str(i))
deck.append('H' + str(i))
deck.append('S' + str(i))
random.shuffle(deck)
return deck
def drawOneCard(theDeck):
"""
Removes a card from theDeck and returns the card.
@date 12/5/2017
@param theDeck an array of cards.
@return card the card removed from theDeck.
"""
length = len(theDeck) - 1
cardNumber = random.randint(0,length)
card = theDeck[cardNumber]
theDeck.remove(card)
return card
def drawAHand(theDeck):
"""
Calls drawOneCard 6 times and returns an array of 6 cards.
@date 12/5/2017
@param theDeck an array of cards.
@return player an array containing 6 cards that the player was dealt.
"""
player = []
for i in range(0,6): #draws a hand size of 6
player.append(drawOneCard(theDeck))
return player
def drawSpecificHand(sixCardHand, theDeck):
"""
Returns the specific hand with the deck
@date 12/5/2017
@param theDeck an array of cards.
@return player an array containing 6 cards that the player was dealt.
"""
for i in range(0, len(theDeck)): #loops through the whole deck looking for the cards
for j in range (0,6): #loops through the hand
if (i < len(theDeck)):
if (str(theDeck[i]) == str(sixCardHand[j])):
theDeck.remove(theDeck[i])
return sixCardHand
def flipUpCard(theDeck):
"""
Removes a card from the deck and returns the card.
@date 12/5/2017
@param theDeck an array of cards.
@return upCard the returned card that is the upCard for the game.
"""
upCard = drawOneCard(theDeck)
return upCard
def chooseHand(sixCardHandWithSuit, theDeck):
"""
Returns the expected value of all the combinations of 4 card hands and chooses the highest one. If tie, randomly picks one from the tie.
@date 12/5/2017
@param sixCardHandWithSuit the inputted array of six cards with their respectived suit
@param theDeck the respective deck to the hand
@return
"""
sixCardHand = sort(removeSuit(sixCardHandWithSuit))
fourCardHandArray = list(itertools.combinations(sixCardHand, 4))
fourCardHandWithSuitArray = list(itertools.combinations(sixCardHandWithSuit, 4))
#print(sixCardHand)
fourCardHandArrayPoints = [None] * 16
maxPoints = 0
maxPointsIndex = 0
for i in range (0,15):
fourCardHand = list(fourCardHandArray[i])
fourCardHandWithSuit = list(fourCardHandWithSuitArray[i])
fourCardHandArrayPoints[i] = getPoints(fourCardHand) + probabilityPoints(fourCardHand, theDeck) + getPointsWithSuit(fourCardHandWithSuit) + probabilityPointsWithSuit(fourCardHandWithSuit, theDeck)
#print(str(i) + ": " + str(fourCardHand) + " = " + str(fourCardHandArrayPoints[i]))
if(fourCardHandArrayPoints[i] > maxPoints):
maxPoints = fourCardHandArrayPoints[i]
maxPointsIndex = i
elif(fourCardHandArrayPoints[i] == maxPoints):
randomNumber = random.randint(1,1001)
if (randomNumber > 500):
maxPoints = fourCardHandArrayPoints[i]
maxPointsIndex = i
#print (str(maxPointsIndex) + ": " + str(maxPoints))
return fourCardHandArray[maxPointsIndex]
def chooseHandWithSuit(sixCardHandWithSuit, theDeck):
"""
Returns the expected value of all the combinations of 4 card hands and chooses the highest one. If tie, randomly picks one from the tie.
@date 12/5/2017
@param sixCardHandWithSuit the inputted array of six cards with their respectived suit
@param theDeck the respective deck to the hand
@return
"""
sixCardHand = sort(removeSuit(sixCardHandWithSuit))
fourCardHandArray = list(itertools.combinations(sixCardHand, 4))
fourCardHandWithSuitArray = list(itertools.combinations(sixCardHandWithSuit, 4))
#print(sixCardHand)
fourCardHandArrayPoints = [None] * 16
maxPoints = 0
maxPointsIndex = 0
for i in range (0,15):
fourCardHand = list(fourCardHandArray[i])
fourCardHandWithSuit = list(fourCardHandWithSuitArray[i])
fourCardHandArrayPoints[i] = getPoints(fourCardHand) + probabilityPoints(fourCardHand, theDeck) + getPointsWithSuit(fourCardHandWithSuit) + probabilityPointsWithSuit(fourCardHandWithSuit, theDeck)
print(str(i) + ": " + str(fourCardHand) + " = " + str(fourCardHandArrayPoints[i]))
if(fourCardHandArrayPoints[i] > maxPoints):
maxPoints = fourCardHandArrayPoints[i]
maxPointsIndex = i
elif(fourCardHandArrayPoints[i] == maxPoints):
randomNumber = random.randint(1,1001)
if (randomNumber > 500):
maxPoints = fourCardHandArrayPoints[i]
maxPointsIndex = i
print (str(maxPointsIndex) + ": " + str(maxPoints))
return fourCardHandWithSuitArray[maxPointsIndex]
def probabilityPoints(hand, deck):
deckNoSuits = removeSuit(deck)
points = 0
#print(Counter(deckNoSuits))
#print(Counter(deckNoSuits).get(1))
for i in range (1,14):
hand.append(i)
points += (getPoints(hand) * (Counter(deckNoSuits).get(i) / len(deckNoSuits)))
hand.pop()
return points
def probabilityPointsWithSuit(hand, deck):
points = 0
for i in range (1,14):
for j in range (0,4):
if (j == 0):
letter = 'S'
elif (j == 1):
letter = 'C'
elif (j == 2):
letter = 'D'
elif (j == 3):
letter = 'H'
hand.append(letter + str(i))
points += (getPointsWithSuit(hand) * (1 / len(deck)))
hand.pop()
return points
def getPoints(hand):
"""
Given a hand it returns the max amount of points the hand is able to get.
@date 12/5/2017
@param hand the user hand
@return points max amount of points the user can get from a specific hand
"""
maxPoints = 0
maxPoints = fifteenPoints(findFifteen(hand)) + runPoints(findRun(hand)) + pairPoints(findPairs(hand))
return maxPoints
def getPointsWithSuit(hand):
"""
Given a hand with suits it returns the max amount of points the hand is able to get.
@date 1/25/2018
@param hand the user hand with suits
@return points max amount of points the user can get from a specific hand
"""
maxPoints = 0
maxPoints = flush(hand) + nobs(hand)
return maxPoints
#game aspects including the board and a card from the hand
def boardPairs(board, card): #return the amount of pair points for a specific board and one card from a hand
points = 0
length = len(board)
if (length == 1):
if (board[length-1] == card):
points += 2
elif (length == 2):
if (board[length-2] == board[length-1] and board[length-1] == card):
points += 6
elif (board[length-1] == card):
points += 2
elif (length >= 3):
if (board[length-3] == board[length-2] and board[length-2] == board[length-1] and board[length-1] == card):
points += 12
elif (board[length-2] == board[length-1] and board[length-1] == card):
points += 6
elif (board[length-1] == card):
points += 2
return points
def boardRuns(board, card): #return the amount of run points for a specific board and one card from a hand
points = 0
newBoard = []
board.append(card)
length = len(board)
if (length == 3):
newBoard.append(board[0])
newBoard.append(board[1])
newBoard.append(board[2])
newBoard.sort(reverse = True)
if (newBoard[length-1] + 2 == newBoard[length-2] + 1 and
newBoard[length-2] + 1 == newBoard[length-3]):
points += 3
elif (length == 4):
newBoard.append(board[0])
newBoard.append(board[1])
newBoard.append(board[2])
newBoard.append(board[3])
newBoard.sort(reverse = True)
if (newBoard[length-1] + 3 == newBoard[length-2] + 2 and
newBoard[length-2] + 2 == newBoard[length-3] + 1 and
newBoard[length-3] + 1 == newBoard[length-4]):
points += 4
elif (length == 5):
newBoard.append(board[0])
newBoard.append(board[1])
newBoard.append(board[2])
newBoard.append(board[3])
newBoard.append(board[4])
newBoard.sort(reverse = True)
if (newBoard[length-1] + 4 == newBoard[length-2] + 3 and
newBoard[length-2] + 3 == newBoard[length-3] + 2 and
newBoard[length-3] + 2 == newBoard[length-4] + 1 and
newBoard[length-4] + 1 == newBoard[length-5]):
points += 5
elif (length == 6):
newBoard.append(board[0])
newBoard.append(board[1])
newBoard.append(board[2])
newBoard.append(board[3])
newBoard.append(board[4])
newBoard.append(board[5])
newBoard.sort(reverse = True)
if (newBoard[length-1] + 5 == newBoard[length-2] + 4 and
newBoard[length-2] + 4 == newBoard[length-3] + 3 and
newBoard[length-3] + 3 == newBoard[length-4] + 2 and
newBoard[length-4] + 2 == newBoard[length-5] + 1 and
newBoard[length-5] + 1 == newBoard[length-6]):
points += 6
elif (length == 7):
newBoard.append(board[0])
newBoard.append(board[1])
newBoard.append(board[2])
newBoard.append(board[3])
newBoard.append(board[4])
newBoard.append(board[5])
newBoard.append(board[6])
newBoard.sort(reverse = True)
if (newBoard[length-1] + 6 == newBoard[length-2] + 5 and
newBoard[length-2] + 5 == newBoard[length-3] + 4 and
newBoard[length-3] + 4 == newBoard[length-4] + 3 and
newBoard[length-4] + 3 == newBoard[length-5] + 2 and
newBoard[length-5] + 2 == newBoard[length-6] + 1 and
newBoard[length-6] + 1 == newBoard[length-7]):
points += 7
board.pop()
return points
def boardNumbers(board, card): #return the amount of points, either for 15 or 31, for a specific board and one card from a hand
points = 0
board.append(card)
length = len(board)
sum = 0
for i in range (length):
sum += board[i]
if (sum == 15 or sum == 31):
points = 2
board.pop()
return points
def boardLastCard(board, card): #return the amount of points, for playing the last card, for a specific board and one card from a hand
points = 0
length = len(board)
sum = 0
for i in range (length):
sum += board[i]
if (sum == 15 or sum == 31):
points = 2
return points
#game aspects including the hand and the upCard
def handPairs(hand, upCard):
handWithoutSuit = []
for i in range (len(hand)):
handWithoutSuit.append(hand[i][1:])
handWithoutSuit.append(upCard[1:])
print(handWithoutSuit)
print(findPairs(handWithoutSuit))
print(pairPoints(findPairs(handWithoutSuit)))
#The decisions and cribbage game
def decisionOnFirstCard(hand):
handWithoutSuit = removeSuit(hand)
intercept = 0.593350325167
ace = six = seven = nine = intercept
two = intercept - 0.00210846
three = intercept - 0.1570842
four = intercept - 0.12435004
five = intercept + 0.08971364
eight = intercept - 0.01379082
ten = intercept + 0.02634555
jack = intercept + 0.04638059
queen = intercept + 0.03179576
king = intercept + 0.00691374
d = {}
for i in range (len(handWithoutSuit)):
d1 = {}
if (handWithoutSuit[i] == 1 or handWithoutSuit[i] == 6 or handWithoutSuit[i] == 7 or handWithoutSuit[i] == 9):
d1 = {intercept: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 2):
d1 = {two: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 3):
d1 = {three: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 4):
d1 = {four: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 5):
d1 = {five: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 8):
d1 = {eight: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 10):
d1 = {ten: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 11):
d1 = {jack: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 12):
d1 = {queen: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 13):
d1 = {king: handWithoutSuit[i]}
d.update(d1)
expectedValuesForHand_Array = []
for k,v in d.items():
expectedValuesForHand_Array.append(k)
expectedValueForCardToPlay = min(expectedValuesForHand_Array)
expectedValueForCardToPlay_Index = np.argmin(expectedValuesForHand_Array)
return (expectedValueForCardToPlay_Index)
def decisionOnFirstCardNoSuit(hand):
#handWithoutSuit = removeSuit(hand)
handWithoutSuit = hand
intercept = 0.593350325167
ace = six = seven = nine = intercept
two = intercept - 0.00210846
three = intercept - 0.1570842
four = intercept - 0.12435004
five = intercept + 0.08971364
eight = intercept - 0.01379082
ten = intercept + 0.02634555
jack = intercept + 0.04638059
queen = intercept + 0.03179576
king = intercept + 0.00691374
d = {}
for i in range (len(handWithoutSuit)):
d1 = {}
if (handWithoutSuit[i] == 1 or handWithoutSuit[i] == 6 or handWithoutSuit[i] == 7 or handWithoutSuit[i] == 9):
d1 = {intercept: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 2):
d1 = {two: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 3):
d1 = {three: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 4):
d1 = {four: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 5):
d1 = {five: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 8):
d1 = {eight: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 10):
d1 = {ten: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 11):
d1 = {jack: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 12):
d1 = {queen: handWithoutSuit[i]}
elif (handWithoutSuit[i] == 13):
d1 = {king: handWithoutSuit[i]}
d.update(d1)
expectedValuesForHand_Array = []
print("Probabilities for first Card Played:", d)
for k,v in d.items():
expectedValuesForHand_Array.append(k)
expectedValueForCardToPlay = min(expectedValuesForHand_Array)
expectedValueForCardToPlay_Index = np.argmin(expectedValuesForHand_Array)
return (expectedValueForCardToPlay_Index)
def decisionOnNextCard(board, hand):
hand = removeSuit(hand)
decisionOnNextCard_Dict = {}
amountOfCards_Hand = len(hand)
sumOfPointsInTheBoard = 0
for s in range (len(board)):
sumOfPointsInTheBoard += board[s]
for i in range (amountOfCards_Hand):
if (sumOfPointsInTheBoard + hand[i] <= 31):
points = 0
points = boardPairs(board, hand[i]) + boardRuns(board, hand[i]) + boardNumbers(board, hand[i]) + boardLastCard(board, hand[i])
#pairPoints = boardPairs(board, hand[i])
#runPoints = boardRuns(board, hand[i])
#fifteenAndThirtyOnePoints = boardNumbers(board, hand[i])
d1 = {hand[i]: points}
decisionOnNextCard_Dict.update(d1)
#for k,v in decisionOnNextCard_Dict():
arrayOfPoints = []
maxPoints = 0
maxPointsIndex = 0
maxPointsCard = 0
index = 0
for k,v in decisionOnNextCard_Dict.items():
#print ("k:", k, " v:", v)
if (v > maxPoints):
maxPoints = v
maxPointsCard = k
maxPointsIndex = index
elif (v == maxPoints):
if ((k + sumOfPointsInTheBoard <= 31
and k > maxPointsCard)
or k >= 15
or k != 21
or k != 26):
maxPoints = v
maxPointsCard = k
maxPointsIndex = index
elif ((maxPointsCard + sumOfPointsInTheBoard <= 31
and k < maxPointsCard)
or maxPointsCard >= 15
or maxPointsCard != 21
or maxPointsCard != 26):
maxPoints = maxPoints
maxPointsCard = maxPointsCard
maxPointsIndex = index
elif (random.randint(1,101) > 50):
maxPoints = v
maxPointsCard = k
maxPointsIndex = index
index += 1
#print("Card: ", maxPointsCard, "Points:", maxPoints, "Index:", maxPointsIndex)
return maxPointsIndex
def oneHandCribbage():
deck = createNewDeck()
you_SixCardHand = drawAHand(deck)
opponent_SixCardHand = drawAHand(deck)
upCard = flipUpCard(deck)
#deciding on who goes first
randomNumber = random.randint(1,101)
if (randomNumber > 50):
firstPlayer = "You"
secondPlayer = "Bill"
#you_FourCardHand = list(pickingAHandYourCrib(you_SixCardHand, deck))
#opponent_FourCardHand = list(pickingAHandOpponentsCrib(opponent_SixCardHand, deck))
else:
firstPlayer = "Bill"
secondPlayer = "You"
#you_FourCardHand = list(pickingAHandOpponentsCrib(you_SixCardHand, deck))
#opponent_FourCardHand = list(pickingAHandYourCrib(opponent_SixCardHand, deck))
print("You 6 card Hand: ", you_SixCardHand)
print("Bill's 6 card Hand: ", opponent_SixCardHand)
you_FourCardHand = list(chooseHandWithSuit(you_SixCardHand, deck))
opponent_FourCardHand = list(chooseHandWithSuit(opponent_SixCardHand, deck))
"""
you_points = 0 #keeps track of the points gained for this hand Round
you_points_dictionary = {} #takes account of all the reasons why points were gained
opponent_points = 0 #keeps track of the points gained for this hand Round
opponent_points_dictionary = {} #takes account of all the reasons why points were gained
"""
crib = []
activeBoard = []
allCardsPlayed = []
sumOfActiveBoard = 0
roundNumber = 1
for i in range(6):
if (str(you_SixCardHand[i]) != str(you_FourCardHand[0]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[1]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[2]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[3])):
crib.append(str(you_SixCardHand[i]))
if (str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[0]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[1]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[2]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[3])):
crib.append(str(opponent_SixCardHand[i]))
print("You 4 card Hand: ", you_FourCardHand)
print("Bill's 4 card Hand: ", opponent_FourCardHand)
print("Crib: ", crib)
print("UpCard: ", upCard)
#print(handPairs(you_FourCardHand,upCard))
#deciding on who goes first
if (firstPlayer == "You"):
cardPlayed = you_FourCardHand.pop(decisionOnFirstCard(you_FourCardHand))[1:]
else:
cardPlayed = opponent_FourCardHand.pop(decisionOnFirstCard(opponent_FourCardHand))[1:]
cardPlayed = int(cardPlayed)
if (cardPlayed >= 10):
sumOfActiveBoard += 10
else:
sumOfActiveBoard += cardPlayed
activeBoard.append(cardPlayed)
print("_______________________________________________________________________________________________________")
print("| |")
print("| Game |")
print("|_____________________________________________________________________________________________________|")
print('{0: >11}'.format("Round " + str(roundNumber)))
roundNumber += 1
print("Card played by", str(firstPlayer), ":", str(cardPlayed))
print("Cards on the board:", activeBoard)
print("Sum of the Active Board: ", sumOfActiveBoard)
print("You Hand: ", you_FourCardHand)
print("Bill's Hand: ", opponent_FourCardHand)
while (len(you_FourCardHand) != 0 or len(opponent_FourCardHand) != 0):
print('{0: >11}'.format("Round " + str(roundNumber)))
roundNumber += 1
if (len(you_FourCardHand) >= len(opponent_FourCardHand)):
cardPlayed = you_FourCardHand.pop(decisionOnNextCard(activeBoard, you_FourCardHand))[1:]
print("Next Card played by You:", cardPlayed)
else:
cardPlayed = opponent_FourCardHand.pop(decisionOnNextCard(activeBoard, opponent_FourCardHand))[1:]
print("Next Card played by Bill:", cardPlayed)
cardPlayed = int(cardPlayed)
if (cardPlayed + sumOfActiveBoard <= 31):
if (cardPlayed >= 10):
sumOfActiveBoard += 10
else:
sumOfActiveBoard += cardPlayed
else:
if (cardPlayed >= 10):
sumOfActiveBoard = 10
else:
sumOfActiveBoard = cardPlayed
for i in range(len(activeBoard)):
allCardsPlayed.append(activeBoard.pop())
activeBoard.append(int(cardPlayed))
print("Cards on the board:", activeBoard)
print("Sum of the Active Board: ", sumOfActiveBoard)
print("You Hand: ", you_FourCardHand)
print("Bill's Hand: ", opponent_FourCardHand)
def oneHandCribbageSpecificHand(yourHand,opponentsHand):
deck = createNewDeck()
you_SixCardHand = drawSpecificHand(yourHand,deck)
opponent_SixCardHand = drawSpecificHand(opponentsHand,deck)
upCard = flipUpCard(deck)
#deciding on who goes first
randomNumber = random.randint(1,101)
if (randomNumber > 50):
firstPlayer = "You"
secondPlayer = "Bill"
#you_FourCardHand = list(pickingAHandYourCrib(you_SixCardHand, deck))
#opponent_FourCardHand = list(pickingAHandOpponentsCrib(opponent_SixCardHand, deck))
else:
firstPlayer = "Bill"
secondPlayer = "You"
#you_FourCardHand = list(pickingAHandOpponentsCrib(you_SixCardHand, deck))
#opponent_FourCardHand = list(pickingAHandYourCrib(opponent_SixCardHand, deck))
print("You 6 card Hand: ", you_SixCardHand)
print("Bill's 6 card Hand: ", opponent_SixCardHand)
you_FourCardHand = list(chooseHandWithSuit(you_SixCardHand, deck))
opponent_FourCardHand = list(chooseHandWithSuit(opponent_SixCardHand, deck))
"""
you_points = 0 #keeps track of the points gained for this hand Round
you_points_dictionary = {} #takes account of all the reasons why points were gained
opponent_points = 0 #keeps track of the points gained for this hand Round
opponent_points_dictionary = {} #takes account of all the reasons why points were gained
"""
crib = []
activeBoard = []
allCardsPlayed = []
sumOfActiveBoard = 0
roundNumber = 1
for i in range(6):
if (str(you_SixCardHand[i]) != str(you_FourCardHand[0]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[1]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[2]) and
str(you_SixCardHand[i]) != str(you_FourCardHand[3])):
crib.append(str(you_SixCardHand[i]))
if (str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[0]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[1]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[2]) and
str(opponent_SixCardHand[i]) != str(opponent_FourCardHand[3])):
crib.append(str(opponent_SixCardHand[i]))
print("You 4 card Hand: ", you_FourCardHand)
print("Bill's 4 card Hand: ", opponent_FourCardHand)
print("Crib: ", crib)
print("UpCard: ", upCard)
#print(handPairs(you_FourCardHand,upCard))
#deciding on who goes first
if (firstPlayer == "You"):
cardPlayed = you_FourCardHand.pop(decisionOnFirstCard(you_FourCardHand))[1:]
else:
cardPlayed = opponent_FourCardHand.pop(decisionOnFirstCard(opponent_FourCardHand))[1:]
cardPlayed = int(cardPlayed)
if (cardPlayed >= 10):
sumOfActiveBoard += 10
else:
sumOfActiveBoard += cardPlayed
activeBoard.append(cardPlayed)
print("_______________________________________________________________________________________________________")
print("| |")
print("| Game |")
print("|_____________________________________________________________________________________________________|")
print('{0: >11}'.format("Round " + str(roundNumber)))
roundNumber += 1
print("Card played by", str(firstPlayer), ":", str(cardPlayed))
print("Cards on the board:", activeBoard)
print("Sum of the Active Board: ", sumOfActiveBoard)
print("You Hand: ", you_FourCardHand)
print("Bill's Hand: ", opponent_FourCardHand)
while (len(you_FourCardHand) != 0 or len(opponent_FourCardHand) != 0):
print('{0: >11}'.format("Round " + str(roundNumber)))
roundNumber += 1
if (len(you_FourCardHand) >= len(opponent_FourCardHand)):
cardPlayed = you_FourCardHand.pop(decisionOnNextCard(activeBoard, you_FourCardHand))[1:]
print("Next Card played by You:", cardPlayed)
else:
cardPlayed = opponent_FourCardHand.pop(decisionOnNextCard(activeBoard, opponent_FourCardHand))[1:]
print("Next Card played by Bill:", cardPlayed)
cardPlayed = int(cardPlayed)
if (cardPlayed + sumOfActiveBoard <= 31):
if (cardPlayed >= 10):
sumOfActiveBoard += 10
else:
sumOfActiveBoard += cardPlayed
else:
if (cardPlayed >= 10):
sumOfActiveBoard = 10
else:
sumOfActiveBoard = cardPlayed
for i in range(len(activeBoard)):
allCardsPlayed.append(activeBoard.pop())
activeBoard.append(int(cardPlayed))
print("Cards on the board:", activeBoard)
print("Sum of the Active Board: ", sumOfActiveBoard)
print("You Hand: ", you_FourCardHand)
print("Bill's Hand: ", opponent_FourCardHand)
#def pegging(playerOneHand, playerTwoHand):
#def theBoard(card):
#oneHandCribbage()
|
import discord
from discord.ext import commands
import random
# commands.Bot(command_prefix = '.')
# discort.Client()
client = commands.Bot(command_prefix = '.')
# print when bot is ready
@client.event
async def on_ready():
print("bot is ready")
# on member join prints members name and joined
@client.event
async def on_member_join(member):
print(f"{member} joined")
@client.command()
async def create(ctx):
await client.create_guild("name")
# @client.command()
# async def ping(ctx):
# await ctx.send("hello")
# await client.create_guild("text1")
@client.command()
async def about_server(x):
await x.send("this is a testing server")
@client.command()
async def daily_challenge(x):
# challenges that will be displayed when .daily_challenge command is used
challenges = ["1)create a shop \n[1]-shop has inventory \n[2]-shopper has cart \n[3]-shop has atleast 15 items",
"2)Write a function that takes an integer minutes and converts it to seconds.\n Examples:\nconvert(5) ➞ 300\nconvert(3) ➞ 180\nconvert(2) ➞ 120"]
# will choose random challenge from list then send it to server
await x.send(f"{random.choice(challenges)}")
@client.command()
async def world_dominate(x):
await x.send("Bots of the world, unite!")
client.run('NzEwNTA3ODUxNzU1NTUyNzc4.Xr1hjA.beJQLF1oQ3F4y0N51nsxuo4uzZQ')
|
# Alexander Harris
# Network Programming, CS325
# Homework 4, Simple Web Server
# Spring 2017
# Professor Tony Mullen
# To test run the program, download use python3 and execute the WebServer.py code on the server side machine.
# Issue this command :
# $ python3 WebServer.py
#
# Next we need to send a request for a file to the server from the client side.
# We will use two command line arguments to specify the method type and the file_name
# The syntax for this command looks like this :
# $ python3 WebClient.py <method> <fila_name>
#
# For example, on the client side issue this command :
# $python3 WebClient.py GET HelloWorld.html
#
# Note, this should return the contents of the HelloWorld.html file to the requester as long as the file is presently available to the server.
# If you request a file that doesn't exist, like so :
# $python3 WebClient.py GET NonExistentFile.html
#
# ... then the server should return a 404.html file coupled with http status code of 404 to the requester.
# import system specific params
import sys
# import socket module
from socket import *
# test printing command line arguments
# print('method : ', sys.argv[1])
# print('file to open: ', sys.argv[2])
# determine server name, localhost for testing | replace with ip address
serverName = 'localhost'
# include the port at which the server is listening
serverPort = 12000
# init the client socket with 2 params :
# @param AF_INET address family that is used to determine the type of addresses that the socket can communicate with : IPv4 addresses
# @param SOCK_STREAM connection based protocol commonly used for TCP
clientSocket = socket(AF_INET, SOCK_STREAM)
# Connect clientSocket to the server name and server port.
clientSocket.connect((serverName, serverPort))
# assign the sentence to send to have a string with two tokens :
# @token method a request to the server to execute a GET request
# @token file_name the file requested from the server
sentence = sys.argv[1] + ' ' + sys.argv[2]
# send the request to the server
clientSocket.send(sentence.encode('utf-8'))
# init response to store incoming data
response = ''
while True:
# collect incoming data from clientSocket using .recv()
# and concatenate it to response. Remember to decode
# incoming binary data into a string using .decode('utf-8')
response += clientSocket.recv(1024).decode()
print(response)
break
clientSocket.close()
|
import time
###### Fibonacci ######
#Funcion:
def sucesion(num):
a = 0
b= 1
c=0
print(0)
for r in range(num):
print(c)
c = a+b
a = b
b = c
time.sleep(0.5)
#'Main':
print("Bienvenido a la Sucesión de Fibonacci.")
while True:
num = input("\nIngrese la cantidad de términos a mostrar (0 para terminar): ")
try:
num = int(num)
except(ValueError,TypeError):
num = 1
print("\nIngrese un numero entero válido! ")
if num==0:
print("\nGracias por utilizar este programa by Cande.")
break
elif num<2:
print("\nEl número ingresado debe ser mayor a 2.")
else:
sucesion(num)
|
#Pythagorean Sequence in Python
# Copyright © 2019, Sai K Raja, All Rights Reserved
def Pythagorean_Theorem(a, b):
if a > 0 and b > 0:
return a**2 + b**2
elif a < 0 or b < 0:
print("Cannot use negative values in Pythagorean Theorem")
for i in range (1):
print(Pythagorean_Theorem(3, 6))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.