text stringlengths 37 1.41M |
|---|
import urllib2
"""
In this implementation, if the first 3 lines of a file are 'un:' or 'pw:', then retreive whatever is located at index 5 to the second last character and assign it to a variable.
"""
page = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/integrity.html')
for line in page:
if line[:3] == 'un:': un = line[5:-2]
if line[:3] == 'pw:': pw = line[5:-2]
username = un.decode('string_escape').decode('bz2')
password = pw.decode('string_escape').decode('bz2')
print 'The username is: {}\nThe password is: {}'.format(username, password)
|
import urllib2
"""This solution assumes rare to be the least occuring. It maps out the occurence of the characters and then finds the characters that occur the least number of times and uses that.
By splitting the raw_data using "<!--" we get three separate lists.
We're only interested in the third list hence "[2]"
rstrip() removes any whitespace from the end of the text (https://www.tutorialspoint.com/python/string_rstrip.htmhttps://www.tutorialspoint.com/python/string_rstrip.htm). It only leaves the text that we need. Doing line.rstrip removes the whitespace line by line. We join to remove any whitespace within the line itself so that we have one continuous block.
.get() method reference: https://stackoverflow.com/questions/2068349/understanding-get-method-in-python
We put the number of occurences of each character into a dictionary with the key as the character and the value as the number of occurences.
"""
page = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/ocr.html')
raw_data = page.read()
data = raw_data.split('<!--')[2]
s = ''.join([line.rstrip() for line in data])
OCCURENCES = {}
for c in s: OCCURENCES[c] = OCCURENCES.get(c, 0) + 1
min_val = min(OCCURENCES.itervalues()) # Iterate through the dictionary values(itervalues) and get the least value(min)
print ''.join([c for c in s if OCCURENCES[c] == min_val])
|
"""
The image at the bottom of the page is actually 10000 x 1 pixels
Above it is an image of a spiralled bun.
This is a hint that you need to create a spiral of the image at the bottom.
In the source you'll find <!-- remember: 100*100 = (100+99+99+98) + (... -->
These are the dimensions you're supposed to use to spiral.(coordinates_step in the code)
You're supposed to create a square spiral.
See: https://openclipart.org/detail/131341/square-spiral
You should use coordinates corresponding to the x and y axis and pick an appropriate starting point.
Once you have the image, create a new image that we're going to write pixels to.
We come up with a set of co-ordinates that we should go through and initialize a counter.
We also pick a starting point in this case x, y = -1, 0
range(100, 1, -2) gives an output of [100, 98, 96...2]
For each of those values in that range take each value and use it in coordinates_step
coordinates_step is the length over which we're going to put pixels
Where we're going to put the pixels is determined by the coordinates
We get a range of values from 0-3 (for index in range(4))
These will serve as our index values in coordinates_step
We inirialize a variable dimension and equate it to zero
While the value of dimension is less than the value of coordinates_step at a given index, we take that same index and use it to access the values in the coordinates list (coordinates[index])
coordinates is a list of tuples
The value for the x coordinate is located at index 0 in the tuple
The value for y is located at index 1
By doing x += coordinates[index][0] and y += coordinates[index][1] we ensure that we cover all possible coordinates without having to explicitly state them all i.e. (1, 1), (1, -1), (-1, 1), (-1, -1), (1,0), (0,1), (-1,0), (0,-1)
Since the picture is only 1 pixel long its y coordinate value is zero
The counter variable is supposed to represent the x axis and we increment it to go through all 10000 pixels in the picture
Once we get a pixel from the original image we put it into the new image at a specific length within the coordinates.
"""
username = 'huge'
password = 'file'
base64string = base64.b64encode('%s:%s' % (username, password))
link = urllib2.Request('http://www.pythonchallenge.com/pc/return/wire.png')
link.add_header('Authorization', 'Basic %s' % base64string)
page = urllib2.urlopen(link)
img = Image.open(page)
out = Image.new(img.mode, (100,100))
coordinates = [(1,0), (0,1), (-1,0), (0,-1)]
x, y = -1, 0 # This is out start point
counter = 0
for dimension_value in range(100, 1, -2): # see numbered_v2.py for why we use every second value in this range as the dimension_value
coordinates_step = [dimension_value, dimension_value-1, dimension_value-1, dimension_value-2]
for index in range(4):
dimension = 0
while dimension < coordinates_step[index]:
x += coordinates[index][0]
y += coordinates[index][1]
dimension += 1
out.putpixel((x, y), img.getpixel((counter, 0)))
counter += 1
print out.show()
|
while True:
try:
cantidad_amigos = int(input("Cuantos amigos tienes: "))
break
except ValueError:
print("No has introducido un numero!")
for cantidad in range(cantidad_amigos):
print("Hola", input("Nombre amigo:"))
|
#! /usr/bin/python3
def main():
import random
dice_rolls = int(input('How many dice would you like to roll?\n'))
dice_sides = int(input('How many sided die?\n'))
dice_sum = 0
for i in range(0,dice_rolls):
roll = random.randint(1,dice_sides)
dice_sum = dice_sum + roll
if roll == 1:
print(f'You rolled a {roll}! Critical Failure')
elif roll == dice_sides:
print(f'You rolled a {roll}! Critical Success!')
else:
print(f'You rolled a {roll}')
print(f'A total of {dice_sum}')
if __name__== "__main__":
main()
|
def iszhishu(tmpint):
if tmpint < 2:
return False
elif tmpint == 2:
return True
else:
x = int(tmpint ** 0.5)
for tmp in range(2, x + 1):
if tmpint % tmp == 0:
return False
return True
def get_zhishu_list(num):
tmplist = []
for i in range(num + 1):
if iszhishu(i):
tmplist.append(i)
return tmplist
def get_prime_list(count):
prime_list = [2]
j = 0
prime = 2
while j < count:
prime += 1
for tmp in prime_list:
if prime % tmp == 0:
break
else:
prime_list.append(prime)
j += 1
return prime_list
def get_prime_list_by_max(num):
prime_list = [2]
j = 0
prime = 2
while prime < num:
prime += 1
for tmp in prime_list:
if prime % tmp == 0:
break
else:
prime_list.append(prime)
j += 1
return prime_list
if __name__ == '__main__':
prime_list0 = get_zhishu_list(128)
print(prime_list0)
prime_list1 = get_prime_list(-1)
print(prime_list1)
prime_list3 = get_prime_list_by_max(-1)
print(prime_list3)
|
#Slots
#5/6/2013 @ 00:05
from tkinter import *
from random import *
class Player:
def __init__(self):
self.cash = 1500
self.loss = 0
self.win = 0
self.lossStreak = 0
self.bet = 1
def getCash(self):
return self.cash
def addCash(self, money):
self.cash += money
return self.cash
def subtractCash(self, money):
self.cash -= money
return self.cash
def numLoss(self,losses):
self.loss = losses + 1
return self.loss
def numWin(self, wins):
self.win = wins + 1
self.lossStreak = 0
return self.win, self.lossStreak
def numLossStreak(self, streak):
self.lossStreak = streak + 1
return self.lossStreak
def getBet(self, selectBet):
self.bet = selectBet
return self.bet
class Spin:
val = "y"
w1 = 0
w2 = 0
w3 = 0
#randomly gets three numbers for the three wheels of the slot machine
def getRanNum(self):
self.w1 = randrange(0,3)
self.w2 = randrange(0,3)
self.w3 = randrange(0,3)
return self.w1,self.w2,self.w3
def slots():
global root
root = Tk()
root.title("Slot Machine")
root.geometry("450x450+500+300")
#root.maxsize(450, 500)
#root.minsize(200, 200)
player = Player()
spin = Spin()
spinAgain = StringVar()
spinAgain = "y"
'''
bet = 1
win = IntVar()
win = 0
loss = IntVar()
loss = 0
lossStreak = IntVar()
lossStreak = 0
'''
value = "0"
Selection = StringVar()
selectBet = IntVar()
sb = selectBet.get()
line1Var = IntVar()
line2Var = IntVar()
line3Var = IntVar()
def betAmount():
sb = selectBet.get()
def clickSpin1():
clickSpin(spin, sb, spinAgain, player, line1Var, line2Var, line3Var)
def clickSpin(spin, sb, spinAgain, player, line1Var, line2Var, line3Var):
#print("You have spun")
spin.getRanNum()
wheel1 = Label(root, text = spin.w1, width = 1).grid(row=1,column=1)
wheel2 = Label(root, text = spin.w2, width = 1).grid(row=1,column=2)
wheel3 = Label(root, text = spin.w3, width = 1).grid(row=1,column=3)
sb = selectBet.get()
#print("sb = ", sb)
userBet = player.getBet(sb)
#print("userBet = ", userBet)
#Wheel spun three matching numbers
if spin.w1 == spin.w2 == spin.w3:
print(spin.w1,spin.w2,spin.w3)
print("YOU HAVE WON!")
wonLabel = Label(root, text = "YOU HAVE WON!").grid(row=25,column=2)
player.addCash(userBet)
player.win += 1
player.lossStreak = 0
print()
#print("win = ",win,"loss = ",loss,"lossStreak = ",lossStreak)
#If on a losing streak force wheel to select three matching numbers
elif player.lossStreak > 4:
called = 0
player.lossStreak = 0
while (spin.w1 != spin.w2) or (spin.w1 != spin.w3):
spin.getRanNum()
called += 1
print(spin.w1,spin.w2,spin.w3)
print("YOU HAVE WON!")
wonLabel = Label(root, text = "YOU HAVE WON!").grid(row=25,column=2)
player.addCash(userBet)
player.win += 1
print()
#print("win = ",win,"loss = ",loss,"lossStreak = ",lossStreak)
#Wheel did not spin three matching numbers
else:
print(spin.w1,spin.w2,spin.w3)
print("YOU LOSE")
loseLabel = Label(root, text = " YOU LOSE! ").grid(row=25,column=2)
player.subtractCash(userBet)
player.loss += 1
player.lossStreak += 1
print()
#print("win = ",player.win,"loss = ",player.loss,"lossStreak = ",player.lossStreak)
return player.loss, player.win, player.lossStreak
def chooseLine1():
print("You have choosen line 1")
#print("line1Var = ", line1Var)
if line1.select() == "1":
line1.deselect()
else:
line1.select()
line1Var.get()
#print("line1Var = ", line1Var)
def chooseLine2():
print("You have choosen line 2")
line2Var.get()
#print("line1Var = ", line2Var)
def chooseLine3():
print("You have choosen line 3")
line3Var.get()
#print("line1Var = ", line3Var)
def allLines():
line1.select()
line2.select()
line3.select()
spinButton = Button(root, text= 'SPIN',fg = "white",command = clickSpin1,
background = "dark green",borderwidth=5, padx= 25).grid(
row=10,column=2)
maxBet = Button(root, text= 'MAX BET',fg = "white", command = allLines,
background = "dark green",borderwidth=5, padx= 50).grid(
row=11,column=2)
quitButton = Button(root, text= 'quit',fg = "white", command= root.destroy,
background = "dark green",borderwidth=5, padx= 15).grid(
row=12,column=2)
cashLabel = Label(root, text = "Cash",width = 10).grid(row=15,column=2)
betField = Spinbox(root, from_=0, to=player.getCash(),increment = 10,
validate="all",textvariable = selectBet).grid(row=16,column=2)
line1 = Radiobutton(root, text='1', variable=Selection, command = chooseLine1, value='1')
line1.grid(row=1,column=4)
#line2 = Radiobutton(root, text='2', variable=Selection, command = chooseLine2, value='2')
#line2.grid(row=5,column=4)
#line3 = Radiobutton(root, text='3', variable=Selection, command = chooseLine3, value='3')
#line3.grid(row=9,column=4)
mainloop()
print("Your total winnings are: $", player.getCash()-1500)
print("You are walking away from the slot machine with: $",player.getCash())
print("Game Over. Good Bye.")
'''#This is what I used for the command line game:
def playLoop():
#Loop to allow user to choose when to activate the slot machine
while spinAgain != "n" and (player.getCash() != 0):
spinAgain = input("do you want to spin? (y/n)\n")
print()
if spinAgain != "n":
#print(type(bet), type(player.getCash()))
try:
print("Your cash total is: ", player.getCash())
bet = eval(input("How much do you want to bet?\n"))
print()
except SyntaxError:
print("Syntax Error; try again")
except NameError:
print("Name Error; try again")
#if bet <= int(player.getCash()):
#if bet > 0:
while bet > int(player.getCash()) or bet <= 0:
print("Your cash total is: ", player.getCash())
bet = eval(input("How much do you want to bet?\n"))
print()
#print("bet = ",bet, "player cash = ", player.getCash(),type(int(player.getCash())))
if spinAgain != "n":
spin.getRanNum()
#Wheel spun three matching numbers
if spin.w1 == spin.w2 == spin.w3:
print(spin.w1,spin.w2,spin.w3)
print("YOU HAVE WON!")
player.addCash(bet)
win += 1
lossStreak = 0
print()
#print("win = ",win,"loss = ",loss,"lossStreak = ",lossStreak)
#If on a losing streak force wheel to select three matching numbers
elif lossStreak > 4:
called = 0
lossStreak = 0
while (spin.w1 != spin.w2) or (spin.w1 != spin.w3):
spin.getRanNum()
called += 1
print(spin.w1,spin.w2,spin.w3)
#print("called = ", called)
#print(spin.w1,spin.w2,spin.w3)
#print()
print("YOU HAVE WON!")
player.addCash(bet)
win += 1
print()
#print("win = ",win,"loss = ",loss,"lossStreak = ",lossStreak)
#Wheel did not spin three matching numbers
else:
print(spin.w1,spin.w2,spin.w3)
print("YOU LOSE")
player.subtractCash(bet)
loss += 1
lossStreak += 1
print()
#print("win = ",win,"loss = ",loss,"lossStreak = ",lossStreak)
else:
print("You won ",win," times, but lost ",loss," times")
print("Your total winnings are: $", player.getCash()-1500)
print("You are walking away from the slot machine with: $",player.getCash())
print("Game Over. Good Bye.")
if player.getCash() == 0:
print("You won ",win," times, but lost ",loss," times")
print("You lost all your money :(")
print("Game Over. Good Bye.")
'''
slots()
'''
#still to do:
#print winnings on UI
#add multiple lines
#get Radio buttons working
'''
|
import unittest
# accepts a string of the form 1-2,4,5-9 and returns a list of numbers
# or the lengths of each segment
# asserts if ranges are out of order or duplicated
def Parse(input, lengths=False):
result = []
rangeLength = []
terms = input.split(',')
assert (len(terms) >= 1)
for term in terms:
subterms = term.split('-')
if (len(subterms) == 1): # is a single number
result.append(int(term.strip()))
rangeLength.append(1)
else: # is a range
assert (len(subterms) == 2)
a = int(subterms[0])
b = int(subterms[1])
assert (a < b)
for i in range(a, b + 1):
result.append(i)
rangeLength.append(b+1-a)
for i in range(1,len(result)):
assert (result[i-1]<result[i])
return result if lengths == False else rangeLength
class TestRanges(unittest.TestCase):
def test_single(self):
self.assertEqual(Parse('1'), [1])
self.assertEqual(Parse('1', lengths=True), [1])
def test_two(self):
self.assertEqual(Parse('1,4'), [1, 4])
self.assertEqual(Parse('1,4', lengths=True), [1, 1])
def test_sort(self):
with self.assertRaises(AssertionError):
Parse('4, 1')
def test_range(self):
self.assertEqual(Parse('1-3'), [1, 2, 3])
self.assertEqual(Parse('1-3', lengths=True), [3])
def test_all(self):
self.assertEqual(Parse('1-3 , 5,7, 8 - 9, 11-12'),
[1, 2, 3, 5, 7, 8, 9, 11, 12])
self.assertEqual(Parse('1-3 , 5,7, 8 - 9, 11-12', lengths=True),
[3,1,1,2,2])
if __name__ == '__main__':
unittest.main()
|
Other_name = input("Tell your name: ")
My_name_Correct = Other_name.lower()
My_name = "yevhen"
My_name == My_name_Correct
if My_name == My_name_Correct:
print("Good Boy, Yevhen")
else:
print(Other_name + ",your not Ivzhen")
|
# AOC 2019 - DAY 1
# Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space,
# safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
# Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete
# the first. Each puzzle grants one star. Good luck!
# The Elves quickly load you into a spacecraft and prepare to launch.
# At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
# Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round
# down, and subtract 2.
# For example:
# - For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
# - For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
# - For a mass of 1969, the fuel required is 654.
# - For a mass of 100756, the fuel required is 33583.
# The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your
# puzzle input), then add together all the fuel values.
# What is the sum of the fuel requirements for all of the modules on your spacecraft?
import math, os
def open_input():
cd = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(cd, "./input.txt")
return open(path, "r")
def calc_fuel(mass):
mass = int(mass)
return math.floor(mass/3)-2
def part1():
lines = open_input().readlines()
lines = map(calc_fuel, lines)
return sum(lines)
print part1()
# 10512200
# --- Part Two ---
# During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include
# additional fuel for the fuel you just added.
# Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and
# that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass,
# if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.
# So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the
# process, continuing until a fuel requirement is zero or negative. For example:
# A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so
# the total fuel required is still just 2.
# At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires
# 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
# The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
# What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate
# the fuel requirements for each module separately, then add them all up at the end.)
def part2():
lines = open_input().readlines()
f = []
for l in lines:
m = [calc_fuel(l)]
while True:
fuel = calc_fuel(m[-1])
if fuel > 0:
m.append(fuel)
else:
break
f.append(sum(m))
return sum(f)
print part2()
# 4939939 |
def ftp_calc(twenty_min_power, weight_in_lbs):
ftp = round(twenty_min_power * .95)
weight_in_kg = round(weight_in_lbs / 2.2, 2)
w_per_kg = round(ftp / weight_in_kg, 2)
print(f"Your FTP in watts per kilo is {w_per_kg}.")
ftp_calc(282, 165)
twenty_power = 282
pounds = 165
ftp_calc(twenty_power, pounds)
ftp_calc(int(input("What is your 20 minute power?")), int(input("What is your weight in pounds?")))
|
#Lists
#List is mutable data structure
#Empty list creation
my_list = []
my_list = list()
#Lists examples
my_list = [1, 2, 3]
my_list2 = ["a", "b", "c"]
my_list3 = ["a", 1, "Python", 5]
my_nested_list = [my_list, my_list2]
my_nested_list # return [[1, 2, 3], ['a', 'b', 'c']]
#Combine two lists together
#First way to use 'extend method'
combo_list = []
one_list = [4, 5]
combo_list.extend(one_list)
combo_list # return [4, 5]
#Second way just add one list to another
my_list = [1, 2, 3]
my_list2 = ["a", "b", "c"]
combo_list = my_list + my_list2
combo_list #return [1, 2, 3, 'a', 'b', 'c']
#List methods
a = [34, 23, 67, 100, 88, 2]
a.sort() # will sort list by ascendance IN PLACE, it mean that you cant use construction like this: a1 = a.sort() it will assign None value to a1
a.sort(reverse = True) # will sort by desc
#Slice operations are the same as with strings
|
# sys module
sys.argv # list of command line arguments that were passed to the Python script
argv[0] # return python script name. Depending on the platform that you are running on, the first argument may contain the full path to the script or just the file name
sys.executable # will return absolute path to python interpreter
sys.exit() # allows to exit from python.
# The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.
# Be sure to check if your operating system has any special meanings for its exit statuses so that you can follow them in your own application. Note that when you call exit, it will # raise the SystemExit exception, which allows cleanup functions to work in the finally clauses of try / except blocks.
# call_exit.py
import subprocess
code = subprocess.call(["python.exe", "exit.py"])
print(code)
# exit.py
import sys
sys.exit(0)
# result of executed call_exit.py will be 0
sys.path # retruns list of strings that specifies the search path for modules.
# According to the Python documentation, sys.path is initialized from an environment variable called PYTHONPATH, plus an installation-dependent default.
sys.path.append("/path/to/my/module") # will add to sys.path new path to python module
sys.platform # will show OS platform, for Win10 will return 'win32'
#sys.platform may be used to perform platform-specific stuff:
if os == "win32":
# use Window-related code here
import _winreg
elif os.startswith('linux'):
# do something Linux specific
import subprocess
subprocess.Popen(["ls, -l"])
sys.stdin / stdout / stderr
# The stdin, stdout and stderr map to file objects that correspond to the interpreter’s standard input, output and error streams, respectively. stdin is used for all input given to the interpreter except for scripts whereas stdout is used for the output of print and expression statements.
|
import os
import json
from flask import Flask, render_template, request, flash
if os.path.exists("env.py"):
import env
# we import the flask class from Flask dependency
app = Flask(__name__)
"""
We create an instance of the flask class and save it as a variable called app.
The first arguement of the Flask class, is the name of the application's
module, ie our package.
Since we're just using a single module, we can use __name__ which is
a built-in python variable. Flask needs this so it knows where to look
for templates and static files.
"""
app.secret_key = os.environ.get("SECRET_KEY")
@app.route("/")
def index():
"""
the @ symbol denotes a python decorator. Decorators wrap functions and
add additional functionality to functions.
The decorator lets python know that when we browse the root root directory,
that it should trigger the index function and retunr "Hello world"
"""
return render_template("index.html")
@app.route("/about")
def about():
with open("data/company.json", "r") as json_data:
# open's json file read-only and saves as variable json_data
data = json.load(json_data)
return render_template(
"about.html", page_title="About", company=data)
@app.route("/about/<member_name>")
def about_member(member_name):
member = {}
with open("data/company.json", "r") as json_data:
data = json.load(json_data)
for obj in data:
if obj["url"] == member_name:
member = obj
return render_template("member.html", member=member)
@app.route("/contact", methods=["GET", "POST"])
def contact():
if request.method == "POST":
flash("Thanks {}, we have received your message!".format(
request.form.get("name")))
return render_template("contact.html", page_title="Contact")
@app.route("/careers")
def career():
return render_template("careers.html", page_title="Careers")
if __name__ == "__main__": # _main_ = the name of the default module in python
app.run(
host=os.environ.get("IP", "0.0.0.0"),
port=int(os.environ.get("PORT", "5000")),
debug=True
)
"""
If name is equal to "main" (both wrapped in double underscores),
then we're going to run our app with the following arguments.
The 'host' will be set to os.environ.get("IP"),
and I will set a default of "0.0.0.0".
We're using the os module from the standard library to get the
'IP' environment variable if it exists, but set a default value if
it's not found.
You should only have debug=True while testing your application in
development mode, but change it to debug=False before you submit
your project.
"""
|
def get_api_url(method):
"""
Returns API URL for the given method.
:param method: Method name
:type method: str
:returns: API URL for the given method
:rtype: str
"""
return 'https://slack.com/api/{}'.format(method)
def get_item_id_by_name(list_dict, key_name):
for d in list_dict:
if d['name'] == key_name:
return d['id']
|
import random
from dict_names import first_name, middle_name, last_name
def name_gen():
num_of_name = random.randint(1, 3)
if num_of_name == 1:
return random.choice(first_name)
elif num_of_name == 2:
return random.choice(first_name) + random.choice(last_name)
elif num_of_name == 3:
return random.choice(first_name) + random.choice(middle_name) + random.choice(last_name)
pick_name = input("Generate username? (Y/N) ").lower()
while pick_name == "y":
name = name_gen()
if len(name) >= 20:
continue
else:
print(name)
pick_name = input("Re-pick? (Y/N) ").lower()
else:
print("Goodbye")
|
class ListNode:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
class LinkedList:
def __init__(self):
self.head = None
def add(self, value):
# If head is empty, set head
if self.head is None:
self.head = ListNode(value)
return
# Otherwise, find last node
node = self.head
while node.next is not None:
node = node.next
# Add after the last node
node.next = ListNode(value)
def delete(self, value):
prev = None
current = self.head
while current is not None:
if current.value == value:
if prev is None:
self.head = current.next
else:
prev.next = current.next
return
prev = current
current = current.next
def size(self):
count = 0
node = self.head
while node is not None:
count += 1
node = node.next
return count
|
# 9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
mail_dict = dict()
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
mail=''
for line in handle:
if line.startswith('From '):
words = line.split()
#print words
else:
continue
mail = words[1]
mail_dict[mail] = mail_dict.get(mail,0)+1
#through dict now, biggest
mail_count = mail_dict.values()
mail_count.sort()
max_count = mail_count[len(mail_count)-1]
for key,val in mail_dict.items():
if val == max_count:
print key, val
#print 'max wrd'
#print 'max count', mail_count[len(mail_count)-1]
|
import math
from tensorboardX import SummaryWriter
if __name__ == "__main__":
writer = SummaryWriter()
funcs = {"sin": math.sin, "cos": math.cos, "tan": math.tan}
for angle in range(-360, 360):
angle_rad = angle * math.pi / 180
for name, fun in funcs.items():
val = fun(angle_rad)
writer.add_scalar(name, val, angle)
writer.close()
"""
Here, we loop over angle ranges in degrees,
convert them into radians, and calculate our functions' values.
Every value is being added to the writer using the add_scalar function,
which takes three arguments: the name of the parameter,
its value, and the current iteration (which has to be an integer).
"""
"""
The result of running this will be zero output on the console,
but you will see a new directory created inside the runs directory with a single file.
To look at the result, we need to start TensorBoard:
rl_book_samples/Chapter03$ tensorboard --logdir runs --host localhost
TensorBoard 0.1.7 at http://localhost:6006 (Press CTRL+C to quit)
Now you can open http://localhost:6006 in your browser to see something like this:
as usual, needs tweeking to work.
python -m tensorboard.main --logdir="./runs"
""" |
import math
def main():
#escribe tu código abajo de esta línea
largo = float(input("(largo)>>>"))
ancho = float(input("(ancho)>>>"))
diagonal = math.sqrt(largo ** 2 + ancho ** 2)
print(diagonal)
if __name__=='__main__':
main()
|
import sqlite3
from creds import database,table
conn=sqlite3.connect(database)# your database name
cur=conn.cursor()
def confirm_exists(name):
cur.execute('SELECT Name FROM '+table+' WHERE Name like \'%'+name+'%\'')# MySQL query to search databse
# PS:If you want,you can search multiple table simultaneously. just need to use the UNION function in MySQL
entries=cur.fetchall()
return entries
def lookup(user_msg):
if(user_msg.lower() in ['bye','thank you']):# you can add as many phrase you like
return 'Happy to help.'
name=confirm_exists(user_msg.capitalize())
if len(name)==0:
return 'Oops, the media you are looking isn\'t in your collection.'
name=[str(i)[2:-3] for i in name] # strign manipulation to make the message look appealing
out='Heres what I found...\n'+'\n'.join(name)
return out |
import math
numbers=range(5)
print(numbers)
factorials = [math.factorial(num) for num in range(5)]
print(factorials) |
# -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html has a nice description of the framework
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
def testRightTriangleA(self):
self.assertEqual(classifyTriangle(3,4,5),'Right: 3,4,5 is a Right Triangle')
def testRightTriangleB(self):
self.assertEqual(classifyTriangle(4,3,5),'Right: 4,3,5 is a Right Triangle')
def testEquilateralTriangles(self):
self.assertEqual(classifyTriangle(1,1,1),'Equilateral: 1,1,1 is an Equilateral Triangle')
def testIsoscelesTriangles(self):
self.assertEqual(classifyTriangle(7,7,4), 'Isosceles: 7,7,4 is an Isosceles Triangle')
def testScaleneTriangles(self):
self.assertEqual(classifyTriangle(6,5,7), 'Scalene: 6,5,7 is a Scalene Triangle')
def testInputsGreaterThan200(self):
self.assertEqual(classifyTriangle(300,40,50), 'Invalid Input')
self.assertEqual(classifyTriangle(70,700,40), 'Invalid Input')
self.assertEqual(classifyTriangle(50,30,400), 'Invalid Input')
self.assertEqual(classifyTriangle(600,600,600), 'Invalid Input')
self.assertEqual(classifyTriangle(201,40,40), 'Invalid Input')
self.assertEqual(classifyTriangle(50,201,40), 'Invalid Input')
self.assertEqual(classifyTriangle(20,40,201), 'Invalid Input')
def testNegativeInputs(self):
self.assertEqual(classifyTriangle(-3,4,5), 'Invalid Input')
self.assertEqual(classifyTriangle(7,-7,4), 'Invalid Input')
self.assertEqual(classifyTriangle(5,3,-4), 'Invalid Input')
self.assertEqual(classifyTriangle(-1,-1,-1), 'Invalid Input')
def testDecimalInputs(self):
self.assertEqual(classifyTriangle(3.2,4,5), 'Invalid Input')
self.assertEqual(classifyTriangle(7,7.1,4), 'Invalid Input')
self.assertEqual(classifyTriangle(5,3,4.0), 'Invalid Input')
self.assertEqual(classifyTriangle(1.5,1.5,1.5), 'Invalid Input')
def testSumOfTwoSides(self):
self.assertEqual(classifyTriangle(3,4,9), 'Not A Triangle')
self.assertEqual(classifyTriangle(2,4,7), 'Not A Triangle')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
|
def fatorial(num):
if num ==1:
return 1
return num * fatorial(num-1)
|
import pygame
class SnakeBody(object):
def __init__(self, xPos, yPos, color, window):
'''initiate and draw a snake part'''
self.xPos = xPos
self.yPos = yPos
self.color = color
self.drawBody(window) #when created, draw the box
def drawBody(self, window):
'''draw the snake part to the screen'''
pygame.draw.rect(window, self.color, pygame.Rect(self.xPos, self.yPos, 15, 15)) #15, 15 is the size of the box
class SnakeHead(object):
def __init__(self, XYpos, color, window):
'''initiate the snake'''
#list(XYpos)[x] allows us to enter XYpos as a tuple!
self.xPos = list(XYpos)[0]
self.yPos = list(XYpos)[1]
self.temp_x = 0
self.temp_y = 0
self.color = color
self.window = window
self.length = 1
self.dead = False
self.time_elapsed = 0
self.fpsClock = pygame.time.Clock()
self.tail = []
self.head = SnakeBody(self.xPos, self.yPos, color, window)
self.direction = -1
# direction number corresponds to up, right, down, and left. see line #37
def getRect(self):
'''returns the rect of the snake'''
return pygame.Rect(self.xPos, self.yPos, 15, 15)
def updatePosition(self):
'''update the snakes position'''
dt = self.fpsClock.tick(15) #prevents snake from 'blinking'
self.time_elapsed += dt
keyPressed = pygame.key.get_pressed()
if(keyPressed[pygame.K_UP] and self.direction != 2): #so head doesn't go into the tail. same for lines #40, 43, & 46
self.direction = 0
self.temp_x, self.temp_y = 0, -15 #changes the box location based on size (15 * 15). same for lines #42, 45, 48
elif(keyPressed[pygame.K_RIGHT] and self.direction != 3):
self.direction = 1
self.temp_x, self.temp_y = 15, 0
elif(keyPressed[pygame.K_DOWN] and self.direction != 0):
self.direction = 2
self.temp_x, self.temp_y = 0, 15
elif(keyPressed[pygame.K_LEFT] and self.direction != 1):
self.direction = 3
self.temp_x, self.temp_y = -15, 0
if(self.time_elapsed > 50): #do this check pretty fast and often (.05 seconds)
self.tail.insert(0, SnakeBody(self.xPos, self.yPos, self.color, self.window)) #add the current head to the front of the tail
self.xPos += self.temp_x
self.yPos += self.temp_y
self.blitScreen(self.window) #draw the 'new snake'
if(len(self.tail) > self.length-1):
self.tail.pop(len(self.tail)-1) #remove the old tail
self.time_elapsed = 0 #reset
self.checkIfDead() #make sure the game's not over
def blitScreen(self, window):
'''draw the entire snake to the screen'''
for t in self.tail:
t.drawBody(window)
self.head
def checkIfDead(self):
'''make sure the snake is in bounds and not eating itself'''
for rect in self.tail:
if(rect.xPos == self.xPos and rect.yPos == self.yPos):
self.dead = True
if(self.xPos < 15 or self.yPos < 15 or self.xPos > 525 or self.yPos > 465):
self.dead = True |
string1 = "he's "
string2 = "probably "
string3 = "pining "
string4 = "for the "
string5 = "fjords"
print(string1 + string2 + string3 + string4 + string5)
print("he's " "probably " "pining " "for the " "fjords") # don't need the + sign to concatenate
print("Hello " * 5) # Hello Hello Hello Hello Hello
# print("Hello " * 5 + 4) #operaror precedence error
print("Hello " * (5+4)) #Hello Hello Hello Hello Hello Hello Hello Hello Hello
print("Hello " * 5 + "4") #Hello Hello Hello Hello Hello 4
today = "friday"
print("day" in today) #True
print("fri" in today) #True
print("thur" in today) #False
print("parrot" in "fjord") #False
|
def consistency_test(val1, val2, sigma1, sigma2) :
t = abs((val1 - val2))/(sigma1 + sigma2)
if t > 2 :
print("Inconsistent, t = ", t)
else :
print("Consistent, t = ", t)
|
import sys
import json
def bubbleSort(tableToSort):
result = tableToSort
for index in range(len(result) - 1, 0, -1):
for i in range(index):
if result[i] > result[i + 1]:
tmp = result[i]
result[i] = result[i + 1]
result[i + 1] = tmp
return result
file = open(sys.argv[1])
data = json.load(file)
nieposortowana = data['input_list']
print("\nNieposortowana: \n")
print(nieposortowana)
posortowana = bubbleSort(nieposortowana)
print("\nPsortowana: \n")
print(posortowana)
|
def get_numbers_from_file() -> None:
with open('numbers.txt') as my_file:
numbers = ''.join(my_file.readlines()).split(',')
for i in numbers:
print(i)
if __name__ == '__main__':
get_numbers_from_file()
|
# создание цикла по списку
#sps=[2,3,4,12,17345,-1,-15]
#for nbr in sps:
# a=nbr+1
# print(a)
# цикл на введенную с клавиатуры строку
#a=input("Введите строку :")
#print(a)
#for letter in a:
# print(letter)
#Цикл по оценкам
#maz = [
# {"kls":"2a", "marks":[4,4,5,4,5]},
# {"kls":"3б", "marks":[3,5,5,4]},
# {"kls":"10г", "marks": [5,5,3,4,4,4]}
#]
#
#a = 0
#d = 0
#b = int(len(maz))
#for number in range(b):
# c = int(len(maz[a]["marks"]))
# smarks = 0
# for num in range(c):
# z = int(maz[a]["marks"][num])
# smarks += z
# kl = maz[a]["kls"]
# d += (round(smarks/c,2))
# print(f"В классе {kl} средняя оценка {round(smarks/c,2)}")
# a += 1
#
#d1 = round(d/b,2)
#print(f"Средняя оценка в школе {d1}")
# Цикл While
def ask_user():
while True:
try:
usay = input("Как дела?")
if usay == "Хорошо":
break
except KeyboardInterrupt:
print("Пока!")
break
#ask_user()
# Работа со словарем
dic = {"Как дела?":"Хорошо!",
"Что делаешь?":"Программирую",
"Когда перерыв?":"Скоро",
"Пойдешь в кафе?":"С удовольствием!"}
def check(dic):
while True:
a = input("Введите Ваш вопрос :")
if a in dic and a != "Стоп":
print(dic[a])
else:
if a == "Стоп":
print("Спасибо за работу со словарем")
break
#check(dic)
# Исключения
def discounted(price, discount):
try:
price = abs(float(price))
discount = abs(float(discount))
if discount >= 100:
price_with_discount = price
else:
price_with_discount = price - (price * discount / 100)
print(price_with_discount)
except(TypeError, ValueError, SyntaxError):
print("Неверные данные")
discounted(2!0,5)
|
import os
import json
import torch
import numpy as np
def mean_std(dataloader_object, axis=None):
""" Compute the mean and standard deviation of a dataset.
Useful for test data normalization, when the mean and std are unknown.
Argument:
dataloader_object (torch.utils.data.DataLoader) - your dataset
axis (tuple, default=None) - the axis to compute mean and std
Return:
(mean, std)
TODO:
try to avoid numpy and use data native (torch.Tensor) operation
"""
sums = np.float64(0.0)
square_sums = np.float64(0.0)
n = np.float64(0.0)
for batch_idx, (data, target) in enumerate(dataloader_object):
data = data.numpy()
sums += np.sum(data, axis=axis)
square_sums += np.sum(data*data, axis=axis)
if axis:
n += np.prod(np.asarray(data.shape)[np.asarray(axis)])
else:
n += np.prod(data.shape)
mean = sums/n
std = (square_sums/n-mean**2)**0.5
return mean, std
def one_hot_tensor(idx, length):
""" Return a one hot tensor (1xlength) with 1 at idx and 0 at other position
Argument:
idx (int) - such that one_hot[idx] = 1.0
length (int) - length of the one hot tensor
Return:
torch.FloatTensor of size 1xlength
"""
one_hot = torch.FloatTensor(1, length).zero_()
one_hot[0][idx] = 1.0
return one_hot
def normalize(x):
""" Normalize (linear normalization), x to 0-1 range
Argument:
x (Variable, Tensor or Numpy array) - the data to be normalized
Return:
normalized data
Note:
datatype of x are supposed to be floating point,
other datatype such as int or uint may cause unexpected behaeviour
"""
if x.max() - x.min() == 0:
return x
return (x - x.min()) / (x.max() - x.min())
def get_conv_layer(model_name, layer=-1):
f = open(os.path.join(os.path.dirname(__file__), 'data/conv_layer_name.json'), 'r')
conv_layer_name = json.load(f)
f.close()
return conv_layer_name[model_name][layer]
def get_input_size(model_name):
f = open(os.path.join(os.path.dirname(__file__), 'data/input_size.json'), 'r')
input_size = json.load(f)
f.close()
return input_size[model_name]
|
import numpy as np
def softmax(a):
exp_a = np.exp(a)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
def softmax_solution(a):
c = np.max(a)
exp_a = np.exp(a - c)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
if __name__ == '__main__':
a = np.array([1010, 1000, 990])
#y = softmax(a) # 너무 큰 수 overflow -> nan 발생
y = softmax_solution(a)
print(y) |
l1 = [('a', 1), ('b', 2), ('c', 3)]
print(l1)
d1 = dict(l1)
print(d1)
st1 = "dfsdf"
l2 = list(st1)
d1 = {'x':1, 'y':2}
m1,m2 = d1
print(d1.it)
#i1, i2 = d1.items
print(m1, " ", m2, " ") |
#Sevren Gail
#Christopher Rendall
#Team 3 - Lab 14
import re #For regular expressions, to replace an undetermined number of spaces in eggs.txt.
#wordCount counts the number of total words in wordDict and returns the result.
def wordCount(wordDict):
count = 0
for key in wordDict:
count += wordDict[key]
return count
#mostCommonWord finds the word that occurs the most in dictionary wordDict.
def mostCommonWord(wordDict):
word = ""
count = 0
for key in wordDict:
if wordDict[key] > count:
word = key
count = wordDict[key]
return word
#printHeadlines() prints the headlines in The Otter Realm.
def printHeadlines():
file = open(pickAFile(), "rt")
data = file.read()
file.close()
blocks = data.split("rel=\"bookmark\">")
printNow("*** Otter Realm Breaking News! ***")
for i in range(1, len(blocks)):
block = str(blocks[i].split("</a")[0])
block = block.strip()
block = block.replace(" ", ' ') #Replace html space character.
block = block.replace("…", "...") #Replace the encoded ellipsis with an ellipsis
block = block.replace('', '\'') #Replace this character with an apostrophe.
block = block.replace('', '') #Replace this with nothing.
block = block.replace(chr(128), '') #Replace this weird space character with nothing.
printNow(block) #Print the headline.
#greenEggs reads the eggs.txt file input by the user, creates a dictionary with each unique word as a key
#and the key's value as the number of times that word occurs in the text. It also prints various
#information as per specifications.
def greenEggs():
file = open(pickAFile(), "rt")
data = file.read()
file.close()
data = data.replace('\n', ' ')
data = data.replace('-', ' ')
data = re.sub(' +', ' ', data)
wordList = data.split(' ')
wordDict = {}
for word in wordList:
if wordDict.has_key(word.lower()):
wordDict[word.lower()] += 1
else:
wordDict[word.lower()] = 1
printNow("Word counts per word:")
for key in wordDict:
printNow(key + ": " + str(wordDict[key]))
printNow("Total number of words in this story: " + str(wordCount(wordDict)))
printNow("Total number of unique words in this story: " + str(len(wordDict)))
printNow("Most Common Word: " + mostCommonWord(wordDict))
greenEggs()
#printHeadlines() |
####################
# CST-205 #
# Module 5 Lab 12 #
# Sevren Gail #
# Chris Rendall #
####################
from random import randint
class Object: #These are objects found around the mansion.
def __init__(self, name, description, permanence): #This constructor estabishes the name, description and permanence.
self.name = name #This is the name of the object.
self.description = description #This is the name of the object.
self.permanence = permanence #This is the permanence of the object (whether an object can be removed from the room).
self.uses = {} #This is a dictionary with a use (cause) as the key and the fallout (effect) as the value.
def setName(self, name): #This is the mutator for the name.
self.name = name
def printName(self): #This prints the name.
printNow(self.name)
def getName(self): #This is the accessor for the name.
return self.name
def setDescription(self, description): #This is the mutator for the description.
self.description = description
def printDescription(self): #This prints the description.
printNow(self.description)
def getDescription(self): #This is the accessor for the description.
return self.description
def setPermanence(self, permanence): #This is the mutator for the permanence.
self.permanence = permanence
def getPermanence(self): #This is the accessor for the permanence.
return self.permanence
def setUse(self, use, fallout): #This is the mutator for the uses. It adds a key if one doesn't exist and sets the value.
self.uses[use] = fallout
def removeUse(self, use): #This lets you remove a use from an item.
del self.uses[use]
def getUses(self): #This is the accessor for the list of uses.
return self.uses.keys()
def getFallout(self, use): #This is the accessor for a specific use.
return uses[use]
class Room: #These are rooms around the mansion.
def __init__(self, name, description): #This constructor estabishes the name and description.
self.name = name #This is the name of the room.
self.description = description #This is the description of the room.
self.directions = {} #This dictionary contains the directions you can go and the Rooms they lead to.
self.objects = [] #These are the objects in the room.
def setName(self, name): #This is the mutator for the name.
self.name = name
def printName(self): #This prints the name.
printNow(self.name)
def getName(self): #This is the accessor for the name.
return self.name
def setDescription(self, description): #This is the mutator for the description.
self.description = description
def printDescription(self): #This prints the description.
printNow(self.description)
def getDescription(self): #This is the accessor for the description.
return self.description
def getRoom(self, direction): #This returns the room that lies in the direction you want to go.
return self.directions[direction]
def setDirection(self, direction, room): #This creates a direction if one doesn't exist and sets the room there.
self.directions[direction] = room
def removeDirection(self, direction): #This removes a direction from the room.
del self.directions[direction]
def printDirections(self): #This prints the directions you can go.
for direction in self.directions.keys():
printNow(direction)
def getDirections(self): #This returns the list of direction names.
return self.directions.keys()
def addObject(self, object): #This adds an object to the room.
self.objects.append(object)
def removeObject(self, object): #This removes an object from the room.
if object in self.objects:
self.objects.remove(object)
def printObjects(self): #This prints the names of the objects in the room.
for object in self.objects:
object.printName()
def getObjects(self): #This returns a list of objects in the room.
return self.objects
def fullyDescribe(self): #This prints a description that also includes the name, directions and objects
printNow("------------" + self.getName().upper() + "------------")
self.printDescription()
printNow("")
if len(self.objects) == 0:
printNow("There are no objects in this room.")
else:
printNow("Here are the objects in the room:")
self.printObjects()
printNow("")
if len(self.directions) == 0:
printNow("You can't see a way out. Bummer!")
else:
printNow("Here are the directions you can go:")
self.printDirections()
def help(): #This prints the intro and directions.
#The intro is the introductory statement that explains the premise of the game.
intro = "Your millionaire father has passed away. You have now realized that if you do not find his will, your "
intro += "young stepmother will fabricate one and take everything. Right now your stepmother is working to acquire "
intro += "an eviction notice to remove you from this house. You remember your father telling you that he hid it in "
intro += "the library of his mansion. If you do not find the will soon, there is no hope."
#These instructions tell how to play the game.
instructions = "You can move around the house by indicating a direction to move (ex: Move North). "
instructions += "Feel free to abbreviate the commands (ex: Move n). "
instructions += "You can also look at objects around the house (ex: Look At Table) and pick up some of them (ex: Pick Up Sandwich). "
instructions += "Type inventory to see what you're holding. Try other commands too, like pull, push, open, use, etc... "
instructions += "Type help at any time to see these directions again."
printNow(intro)
printNow("")
printNow(instructions)
def move(direction): #This moves the user to the room in the indicated direction if the direction is valid.
global room
validDirections = ["north", "south", "east", "west", "up", "down", "n", "s", "e", "w", "u", "d"]
if direction == "n":
direction = "north"
if direction == "s":
direction = "south"
if direction == "e":
direction = "east"
if direction == "w":
direction = "west"
if direction == "u":
direction = "up"
if direction == "d":
direction = "down"
roomDirections = room.getDirections()
for i in range(0, len(roomDirections)):
roomDirections[i] = roomDirections[i].lower()
if direction == " ":
printNow("Move where?")
elif validDirections.count(direction) == 0:
printNow("That's not a direction...")
elif roomDirections.count(direction) == 0:
printNow("You cannot move that direction in this room.")
else:
room = room.getRoom(direction.capitalize())
def useCrowbar(): #This allows a user who has the crowbar in the library to move the bookshelf.
global room
global inventory
global bookshelfMoved
if room.getName() != "Library":
printNow("You cannot use the crowbar here.")
else:
for object in room.getObjects():
if object.getName() == "Bookshelf":
printNow("You use the crowbar to move the bookshelf, revealing a safe that was hidden behind it.")
printNow("The crowbar breaks just as the shelf moves aside.")
bookshelfMoved = true
room.setDescription(getLibraryDescription())
room.removeObject(object)
room.addObject(Object("Safe", "A sturdy looking standard dial safe. The words, \"kitchen, bathroom, bedroom\" are scrawled on it.", true))
removeInventory("Crowbar")
def removeInventory(item): #This removes object with name item from the inventory.
global inventory
for o in inventory:
if o.getName() == item:
inventory.remove(o)
def use(modifiers): #This calls useCrowbar when the user types use crowbar.
global inventory
if modifiers[0] == "crowbar":
for object in inventory:
if object.getName() == "Crowbar":
useCrowbar()
def displayInventory(): #This prints the inventory objects.
global inventory
if len(inventory) == 0:
printNow("You have nothing in you inventory. How sad...")
else:
printNow("You have the following in your inventory:")
for object in inventory:
printNow(object.getName())
def open(modifiers): #Open the safe if the user is in the library and the bookshelf is moved and the safe is closed.
global kitchenNumber
global bathroomNumber
global bedroomNumber
global room
global bookshelfMoved
global safeOpen
safeFound = false
if modifiers[0].lower() == "safe":
for o in room.getObjects():
if o.getName() == "Safe":
safeFound = true
if safeOpen:
printNow("The safe is already open...")
else:
number1 = requestInteger("Enter the first number of the combination:")
number2 = requestInteger("Enter the second number of the combination:")
number3 = requestInteger("Enter the third number of the combination:")
if number1 == kitchenNumber and number2 == bathroomNumber and number3 == bedroomNumber:
printNow("As you open up the safe you see a big red button inside.")
room.setDescription(getLibraryDescription())
room.addObject(Object("Button", "An invitingly bright red button.", true))
else:
printNow("That... didn't work. Did you just make those numbers up?")
if not safeFound:
printNow("There is no safe here...")
else:
printNow("You cannot open that...")
def push(modifiers): #Push the button if user is in the Library and the safe is open.
global room
global safeOpen
global trapDoorOpen
buttonFound = false
if modifiers[0].lower() == "button":
for o in room.getObjects():
if o.getName() == "Button":
buttonFound = true
if trapDoorOpen:
printNow("You press the button, but nothing happens.")
else:
printNow("As you push the button, a cleverly hidden trap door pops open in the middle of the floor.")
trapDoorOpen = true
room.setDescription(getLibraryDescription())
basement = Room("Basement", "The basement is a small dark room with a writing table. On it lies your father's will.")
basement.setDirection("Up", room)
basement.addObject(Object("Father's Will", "", false))
room.setDirection("Down", basement)
if not buttonFound:
printNow("There is no button here...")
else:
printNow("Pushing that does nothing...")
def performAction(action, modifiers): #This takes parsed actions and modifiers and performs the appropriate task.
if len(modifiers) == 0:
modifiers.append(" ")
moveActions = ["move", "go", "travel", "walk"]
helpActions = ["help", "?"]
directionActions = ["north", "south", "east", "west", "up", "down", "n", "e", "s", "w", "u", "d"]
lookActions = ["look", "l", "examine", "look"]
dropActions = ["drop"]
pickupActions = ["pickup", "get"]
inventoryActions = ["inventory", "i", "inv", "equipment", "backpack"]
pullActions = ["pull"]
useActions = ["use"]
openActions = ["open"]
pushActions = ["push", "press"]
if moveActions.count(action.lower()) > 0:
move(modifiers[0])
elif directionActions.count(action.lower()) > 0:
move(action)
elif helpActions.count(action) > 0:
help()
elif lookActions.count(action) > 0:
look(modifiers)
elif useActions.count(action) > 0:
use(modifiers)
elif openActions.count(action) > 0:
open(modifiers)
elif pushActions.count(action) > 0:
push(modifiers)
elif pickupActions.count(action) > 0:
pickup(modifiers)
elif inventoryActions.count(action) > 0:
displayInventory()
elif pullActions.count(action) > 0:
pull(modifiers)
else:
printNow("You can't do that...")
def pull(modifiers): #Pull the latch if the user is in the library and the latch is unpulled.
global latchPulled
global room
if modifiers[0] == " ":
printNow("Pull what?")
elif modifiers[0] == "latch" and room.getName() == "Library" and latchPulled == false:
printNow("You pull the latch and a trap door opens leading upward and a ladder extends down to the floor.")
attic = Room("Attic", "A dark and dusty room with a small amount of light coming in through a window at the top of the room.")
attic.setDirection("Down", room)
attic.addObject(Object("Crowbar", "A rusty steel crowbar that's seen better days.", false))
room.setDirection("Up", attic)
for o in room.getObjects():
if o.getName() == "Latch":
room.removeObject(o)
latchPulled = true
room.setDescription(getLibraryDescription())
else:
printNow("There is no " + modifiers[0] + " here.")
def look(modifiers): #Print the description of modifier if it exists.
global room
object = modifiers[0]
objects = room.getObjects()
objectFound = false
for i in range(0, len(objects)):
if objects[i].getName().lower() == object:
printNow(objects[i].getDescription())
objectFound = true
if(not objectFound):
printNow("There is no object by that name here...")
def pickup(modifier): #Add the item to inventory and remove from room if it exists and is not permanent.
global room
global inventory
objectFound = false
for object in room.getObjects():
if object.getName().lower() == modifier[0]:
if object.getPermanence() == false:
inventory.append(object)
printNow("You pick up the " + object.getName())
objectFound = true
room.removeObject(object)
else:
printNow(object.getName() + " will not fit in your inventory...")
objectFound = true
if not objectFound and modifier[0] != " ":
printNow("There is no " + modifier[0] + " here.")
elif not objectFound and modifier[0] == " ":
printNow("Pick up what?")
def parseCommand(commandList): #This parses the command.
verb = commandList[0]
modifiers = commandList
modifiers.pop(0)
performAction(verb, modifiers)
def fixCommand(command): #This cleans up the command to make it easier to parse.
command = command.replace("pick up", "pickup")
command = command.replace("look at", "look")
command = command.replace("the ", "")
return command
def initializeRooms(): #This sets up the rooms initially.
global kitchenNumber
global bathroomNumber
global bedroomNumber
library = Room("Library", getLibraryDescription())
kitchen = Room("Kitchen", "You are in the kitchen. There is a large stainless steel refrigerator.")
bedroom = Room("Bedroom", "You are in your father's bedroom. There is a large bed in the corner.")
entryway = Room("Entryway", "You are in the entryway to your father's mansion. There is a large door to the south.")
bathroom = Room("Bathroom", "You are in the bathroom. There is a large bathtub. The toilet is spotless.")
outside = Room("Outside", "You are outside. Your stepmother is there with the eviction notice. She locks you outside. How cold!")
library.setDirection("West", kitchen)
library.setDirection("East", bathroom)
library.setDirection("North", bedroom)
library.setDirection("South", entryway)
library.addObject(Object("Table", "A table made of old oak covered in a film of dust.", true))
library.addObject(Object("Bookshelf", "A bookshelf that seems slightly offset.", true))
library.addObject(Object("Latch", "A latch extending down from the ceiling.", true))
kitchen.setDirection("East", library)
kitchen.addObject(Object("Refrigerator", "A large stainless steel refrigerator with fridge magnet showing the number " + str(kitchenNumber), true))
bedroom.setDirection("South", library)
bedroom.addObject(Object("Bed", "A large bed covered by a plush comforter carefully embroidered with the number " + str(bedroomNumber), true))
bathroom.setDirection("West", library)
bathroom.addObject(Object("Bathtub", "A sizeable bath tub with a state of the art faucet.", true))
bathroom.addObject(Object("Toilet", "A spotless toilet. While it looks clean, it clearly stinks like the number " + str(bathroomNumber), true))
entryway.setDirection("North", library)
entryway.setDirection("South", outside)
return library
def getLibraryDescription(): #This returns the current description of the library.
global bookshelfMoved
global latchPulled
global trapDoorOpen
description = "You find yourself in a room surrounded by bookshelves."
if bookshelfMoved:
description += " There is a large sturdy dial safe in the wall."
else:
description += " There is a bookshelf that is slightly offset."
if latchPulled:
description += " There is a ladder leading upward."
else:
description += " In the ceiling there is a latch that looks just within reach."
if trapDoorOpen:
description += " A trap door gapes invitingly in the center of the floor."
return description
def playGame(): #This is the main loop.
global room
continuePlaying = true
inventory = []
while(continuePlaying):
printNow("")
room.fullyDescribe()
printNow("")
if room.getName() == "Basement":
printNow("You have found your father's will! Congratulations!")
if randint(1,10) > 5:
printNow("It says that you inherit everything! Score!")
else:
printNow("It says... that your step mom inherits everything... Let's just forget we found this, eh?")
continuePlaying = false
elif room.getName() == "Outside":
printNow("You facepalm your shortsightedness in coming outside. Oh, well. You probably wouldn't appreciate that fortune anyways.")
continuePlaying = false
else:
try:
command = requestString("Enter a command:").lower()
if(command != "exit"):
command = fixCommand(command)
parseCommand(command.split(' '))
else:
printNow("You gave up? I guess a multi-million dollar estate is overrated, right?")
continuePlaying = false
except:
printNow("You gave up? I guess a multi-million dollar estate is overrated, right?")
continuePlaying = false
kitchenNumber = randint(1,99) #This is the number found in the kitchen.
bathroomNumber = randint(1,99) #This is the number found in the bathroom.
bedroomNumber = randint(1,99) #This is the number found in the bedroom.
bookshelfMoved = false #This turns true when the user moves the bookshelf in the library.
latchPulled = false #This turns true when the user pulls the latch in the library.
trapDoorOpen = false #This turns true when the user opens the trap door in the library.
safeOpen = false #This turns true when the user opens the safe in the library.
room = initializeRooms() #This is the current room that the user is in.
inventory = [] #This is a list containing the objects carried by the user.
help()
playGame() |
class Animal(object):
def __init__(self):
self.type="animal"
def breed(self):
return Animal()
def makeNoise(self):
print "I am %s, I am an animal" % self.type
class Dog(Animal):
def __init__(self,numlegs):
self.type="dog"
self.eager=False
self.numlegs=numlegs
def woof(self):
print "Woof!!!!"
class Cat(Animal):
def __init__(self):
self.type="cat"
def meow(self):
print "Meow"
class ThreeLeggedEagerDog(Dog):
def __init__(self,myWoof):
super(ThreeLeggedEagerDog,self).__init__(3)
self.woof()
self.eager=True
self.myWoof = myWoof
def woof(self):
super(ThreeLeggedEagerDog,self).makeNoise()
print self.myWoof
# d = ThreeLeggedEagerDog("wooof woooof")
# print d.numlegs
# d.woof()
odie = Dog(4)
Dog.woof(odie)
odie.woof()
|
import math
def magnitude_3d_euclid(v):
'''Calculate 3d euclidian magnitude of the vector v
arg v: indexable of length 3
'''
return math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
def distance_3d_euclid(v1, v2):
'''Calculate 3d euclidian distance between vectors v1 and v2'''
return magnitude_3d_euclid(tuple(v2[i] - v1[i] for i in range(3)))
|
def print_menu():
print("1. Print all the Contacts")
print("2. Add a Contact")
print("3. Remove a Contact")
print("4. Lookup a Contact")
print("5. Quit the program")
print()
emailid = {}
numbers = {}
birthday = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("All contacts in your contact book are:")
for x in numbers.keys():
print("Name: ", x, "\tNumber:", numbers[x], "\temail id :",emailid[x], "\tBirthday :",birthday[x])
print()
elif menu_choice == 2:
print("Add Name, Number, E-Mail ID and Birthday")
name = input("Name: ")
phone = input("Number: ")
phone1 = input("email id: ")
phone2 = input("Birthday: ")
numbers[name] = phone
emailid[name] = phone1
birthday[name] = phone2
elif menu_choice == 3:
print("Remove Name and Number from your contacts")
name = input("Name: ")
if name in numbers:
del numbers[name]
else:
print(name, "was not found")
elif menu_choice == 4:
print("Search for a number")
name = input("Name: ")
if name in numbers:
print("The number is", numbers[name])
else:
print(name, "was not found")
elif menu_choice != 5:
print_menu() |
#7. Write a Python Program to read a input from the user and then check whether the given character is an alphabet, number or a special character. If it is an alphabet, convert in to UPPERCASE and vice-versa.
import string
a = input("Enter the String: ")
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
x = is_number(a)
y = a.isupper()
z = ord(a)
if x:
print("The String "+a+" is a Number")
else:
if (z>=0 and z<=47):
print(a+" is a Special Character!")
elif (z>=58 and z<=64):
print(a+" is a Special Character!")
elif(z>=91 and z<=96):
print(a+" is a Special Character!")
elif(z>=123 and z<=126):
print(a+" is a Special Character!")
else:
if y:
print("The String "+a+"is in UPPERCASE")
print ("The lowercase is "+a.lower())
else:
print("The String is in lowercase")
print ("The UPPERCASE is "+a.upper())
|
#2. Write a Python Program to implement swapping or exchanging two numbers.
first = int(input("Enter the First Number: "))
second = int(input("Enter the Second Number"))
print("Before Swap")
print ("The First Number is ",first," and the Second Number is ",second)
first = first + second
second = first - second
first = first - second
print ("After Swap")
print ("The First Number is ",first," and the Second Number is ",second)
|
#10. Check whether a given Number is Armstrong or not
n = int(input("Enter the Number: "))
m = n
s = 0
while (n>0):
r = n%10
n = n//10
s = (s+(r*r*r))
if(s==m):
print("The Number ",m," is Armstrong Number!")
else:
print("The Number is not a Armstrong Number!")
"""
num = int(input("enter a number: "))
length = len(str(num))
sum = 0
temp = num
while(temp != 0):
sum = sum + ((temp % 10) ** length)
temp = temp // 10
if sum == num:
print("armstrong number")
else:
print("not armstrong number")
"""
|
import math
import random
def halfthenumber(n):
n=n/2
return n
humannum=float(raw_input("Please Enter a number between 0 and 100 "))
compguess = random.randrange(0,100)
guesscount=1
#print "The Entered number between (0 and 1000) is : " + str(humannum)
#print "The Current Guess is : " + str(compguess)
l="lower"
u= "upper"
try:
while humannum != compguess:
ans=raw_input("Computer Guess is " +str(compguess)+" is your number l=lower or h=higher or s=same : ")
if ans == "l":
#print "Computer guess is higher"
p=round(compguess)-round(humannum)
compguess= halfthenumber(p)
print "The Current Computer Guess is : " +str(compguess)
guesscount +=1
elif ans == "h":
#print "Computer guess is lower"
p=round(humannum)+ round(compguess)
compguess= halfthenumber(p)
print "The Current Computer Guess is : " +str(compguess)
guesscount +=1
elif ans == "s":
print "you are correct,then number is "+str(compguess)
break
except:
print "Please enter the following only l=lower or h=higher or s=same"
print '\n'+"Computer took " +str(guesscount)+ " iterations to guess your number"
|
##### To Import Packages########
import math
import os
import random
##### End of Packages#########
##### Welcom Message#########
print "Welcome to Ravi's Math programs"
##### End of Welcome Messages #########
frect_area = 0
frect_perimeter=0
def conv_milestofeet(x):
feet=5280*float(x)
print x +" miles is equal to "+ str(feet) +" feet"
return feet
def conv_feettomiles(x):
miles=float(x)/5280
print x +" feet is equal to "+ str(miles) +" miles"
return miles
def conv_milestokm(x):
km =float(x)/0.621371
print x +" miles is equal to "+ str(km) +" Km"
return km
def conv_kmtomiles(x):
miles = float(x) *0.621371
print x +" Km is equal to "+ str(miles) +" miles"
return miles
def conv_hrsminsectosec(x,y,z):
hrstosec= float(x) * 3600
minstosec= float(y) * 60
totalsec=hrstosec+minstosec+float(z)
print x +" Hrs "+ y + " mins "+ z + " sec " + " is equal to " +str(totalsec)+" seconds"
return totalsec
def conv_secondstohrsminsec(x):
hrs=float(x)/3600.0
mins = (float(x) - (int((hrs))*3600))/60.0
sec = mins- int(mins)
print x + " seconds is equal to " +str(int(round(hrs)))+" hrs "+ str(int((mins))) + " mins "+ str(int(round((sec)*60.0))) + " secs"
return hrs
def conv_inchestocm(x):
cm=float(x)*2.54
print x +" inches is equal to " + str(cm)+" cm"
return cm
def conv_ftok(fahrenheit):
kelvin = (5.0 / 9) * (float(fahrenheit) - 32)
print "The Fahrenheit " +str(fahrenheit)+" in Kelvin is "+ str(kelvin) + " K"
return kelvin
def conv_cmtoinches(x):
inches=float(x)/2.54
print x +" centimeter is equal to " + str(inches)+" inches"
return inches
##################### Geometrical Shapes functions ##############################
def rect_area(x,y):
rectarea = float(x) * float(y)
# I am experiementing with globalvariables,the idea is to count the number of times
# this function has been called during a program execution, hence increamenting the frect_area variable by 1 each time
# this function is called
global frect_area
frect_area = frect_area+1
print "The Area of Rectangle is : " + str(area) +" sqcm"
return rectarea
def rect_perimeter(x,y):
rectperimeter = 2*(float(x) + float(y))
global frect_perimeter
frect_perimeter = frect_perimeter+1
print "The Perimeter of Rectangle is : " + str(p) +" cm"
return rectperimeter
def circle_area(r):
circlearea= 2* math.pi * float(r) **2
print "Area of a circle with a given radius of "+ str(r)+ " is "+ str(area)+ " sqcm"
return circlearea
def circle_circum(r):
circlecircum = 2*math.pi*float(r)
print "Circumference of a circle with a given radius of "+ str(r)+ " is "+ str(circum)
return circlecircum
def tri_areaH(s1,s2,s3):
# this is calculated as per Heron's formula for area of a triangle with the length of 3 given sides
#sp is semi perimeter
#sp=(float(s1)+float(s2)+float(s3))/2
s1=float(s1)
s2=float(s2)
s3=float(s3)
sp=(s1+s2+s3)/2
if sp == s1 or sp == s2 or sp == s3:
print "Impossible triangle exiting/returning"
return "Impossible triangle"
else:
'''
print "all ok"
print "sp = " + str(sp)
print "s1 = " + str(s1)
print "s2 = " + str(s2)
print "s3 = " + str(s3)
#print str(float(s1))
#print str(sp*(sp-float(s1))*(sp-float(s2))*(sp-float(s3)))
'''
triarea=math.sqrt(sp*(sp-s1)*(sp-s2)*(sp-s3))
print "Area of a triangle with sides "+ str(s1)+ "cm, "+ str(s2)+ "cm, "+str(s3)+"cm is "+ str(format(triarea, '.2f'))+ " sqcm"
return triarea
def distance_calc(x1,y1,x2,y2):
x=float(x1)-float(x2)
y=float(y1)-float(y2)
distance= math.sqrt((x**2)+(y**2))
print "The distance between ("+str(x1)+","+str(y1)+") and ("+ str(x2)+","+str(y2)+") is "+str(distance)
return distance
def tri_areawithcoordinates():
print "To Calculate Area of Triangle using Heron's forumula when the coordinate of the vertices are given"
try:
input = raw_input("Enter coordinates of vertices x1,y1,x2,y2,x3,y3 separated by commas: ")
input_list = input.split(',')
numbers = [float(x.strip()) for x in input_list]
print str(numbers)
print str(len(numbers))
s1=distance_calc(numbers[0],numbers[1],numbers[2],numbers[3])
s2=distance_calc(numbers[2],numbers[3],numbers[4],numbers[5])
s3=distance_calc(numbers[0],numbers[1],numbers[4],numbers[5])
ta=tri_areaH(s1,s2,s3)
except:
print "Please enter comma separated numbers"
print "error "+str(IOError)
finally:
print "In the finally clause"
return ta
################################# End of Shapes ##############################
def future_value(p,r,t):
fv= float(p) *(1+(0.01*float(r)))*float(t)
print "The future value of amt $"+str(p)+" at a given interest rate of "+str(r)+"%"+'\n'
print "for a duration of "+str(t)+" years is $"+str(fv)
return fv
########## Math functions #############
def print_digits(number):
"""Prints the tens and ones digit of an integer in [0,100)."""
print "The tens digit is " + str(number // 10) + ",",
print "and the ones digit is " + str(number % 10) + "."
def powerball():
"""Prints Powerball lottery numbers."""
print "Today's numbers are " + str(random.randrange(1, 60)) + ",",
print str(random.randrange(1, 60)) + ",",
print str(random.randrange(1, 60)) + ",",
print str(random.randrange(1, 60)) + ", and",
print str(random.randrange(1, 60)) + ". The Powerball number is",
print str(random.randrange(1, 60)) + "."
def is_even(num):
print "Inside is even function " + str(num)
ev = num % 2
if ev == 0:
print "This is even number"
else:
print "this is odd number"
return ev
def is_leap_year(year):
"""
Returns whether the given Gregorian year is a leap year.
"""
return ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0))
def testleap(year):
"""Tests the is_leapyear function."""
if is_leap_year(year):
print year, "is a leap year."
ly= 'True'
return ly
else:
print year, "is not a leap year."
ly= 'False'
return ly
########## Math functions #############
'''
rect_area(raw_input("Please Enter Length in cm: "),raw_input("Please Enter Breadth in cm: "))
rect_perimeter(raw_input("Please Enter Length in cm: "),raw_input("Please Enter Breadth in cm: "))
print "Area of rectangle function has been called: "+str(frect_area)+ " times"
print "Perimeter of rectangle function has been called: "+str(frect_perimeter)+ " times"
conv_milestofeet(raw_input("Please Enter Miles to convert into feet: "))
conv_feettomiles(raw_input("Please Enter Feet to convert into Miles: "))
conv_milestokm(raw_input("Please Enter Miles to convert into Km: "))
conv_kmtomiles(raw_input("Please Enter Km to convert into Miles: "))
print "To Convert Hrs, mins and seconds to Seconds:"
conv_hrsminsectosec(raw_input("Please Enter Hrs: "),raw_input("Please Enter Mins: "),raw_input("Please Enter Sec: "))
print "To Convert Seconds to Hrs, Mins, Seconds"
conv_secondstohrsminsec(raw_input("Please Enter Seconds to convert to Hrs Mins and Sec: "))
print "To convert Inches to Centimeters"
conv_inchestocm(raw_input("Please Enter Inches to convert to Cm: "))
print "To convert Centimeters to Inches"
conv_cmtoinches(raw_input("Please Enter Centimeters to convert to Inches: "))
print "To convert F to K"
conv_ftok(raw_input("Please Enter fahrenheit to Convert to Kelvin: "))
# From here it is Geometry
print "To Calculate the area of a Circle when its radius is given"
circle_area(raw_input("Please Enter radius in cm: "))
print "To Calculate the Circumference of a Circle when its radius is given"
circle_circum(raw_input("Please Enter radius in cm: "))
print "To Calculate the Future value of principle amount when the interest rate and the number of years is given"+'\n'
future_value(raw_input("Please Enter Principle in $: "),raw_input("Please Enter Rate of interest: "),raw_input("Please Enter numer of years: "))
print "When the coordinates are given find the distance between them"+'\n'
distance_calc(raw_input("Please Enter Position of x1: "),raw_input("Please Enter Position of y1: "),raw_input("Please Enter Position of x2: "),raw_input("Please Enter Position of y2: "))
print "When the sides of a triangle are given we can calculate the area using heron's formula"+'\n'
tri_areaH(raw_input("Please Enter length of side a in cm: "),raw_input("Please Enter length of side b in cm: "),raw_input("Please Enter length of side c in cm:: "))
print "To Calculate Area of Triangle using Heron's forumula when the length of the 3 sides is given"
#tri_areaH(10,20,30)
#tri_areaH(1,2,3)
#tri_areaH(4,5,6)
#tri_areaH(4.5,5.5,6.5)
#tri_areaH(4500,5500,6500)
print "To Calculate Area of Triangle using Heron's forumula when the coordinate of the vertices are given"
tri_areawithcoordinates()
print "The below function will split the number and gives the digits in 10's place and 1's place when a 2 digit number is given"
print_digits(98)
print '\n'+ "The Below function will call the random numbers and simulate the powerball lottery"
powerball()
powerball()
powerball()
is_even(7)
'''
t=testleap(1990)
print t
t=testleap(2000)
print t
t=testleap(2002)
print t
|
###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
def recursion(egg_weights, target_weight, choice, memo={}):
# I think we can remove this extra if
if target_weight == 0 or (not bool(egg_weights)):
return len(choice), choice
elif egg_weights[-1] > target_weight:
# right branch only
return recursion(egg_weights[:-1], target_weight, list(choice))
else:
item = egg_weights[-1]
left_choice = list(choice) + [item]
# check if finished
if target_weight - item == 0:
return len(left_choice), left_choice
else:
# go deeper into rabbit hole
left, left_result = recursion(egg_weights, target_weight - item, left_choice)
# when we only have 1 choice and already choose it (left), than we must use left
if len(egg_weights) == 1:
return len(left_result), left_result
right_choice = list(choice)
right, right_result = recursion(egg_weights[:-1], target_weight, right_choice)
result = left_result if left <= right else right_result
return len(result), result
def dp_make_weight(egg_weights, target_weight, memo={}):
length, result = recursion(egg_weights, target_weight, [], memo)
print(result)
return length
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
# egg_weights = (1, 2)
n = 99
print(f"Egg weights = {egg_weights}")
print(f"n = {n}")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()
|
class People:
def __init__(self , age=0, name=None):
self.__age = age
self.__name = name
def introMe(self):
print("Name: ",self.__name,"age: ", str(self.__age))
class Teacher(People):
def __init__(self , age=0, name=None, school=None):
super().__init__(age, name) #상위 클래스 속성 가져옴
self.school=school
def showSchool(self):
print("MySchool is ", self.school)
p1 = People(29, "Lee") # People 객체 호출
p1.introMe() # People.introMe() 호출
t1 = Teacher(48, "Kim", "HighSchool") # Teacher 객체
t1.introMe() # People.introMe() 호출
t1.showSchool() # Teacher.showSchool() 호출 |
ages = [10,30,45,18,21,8,19,20,28,33]
print('청소년:')
for a in filter(lambda x:x<20, ages):
print(a , end=" ");
print();
print(list(filter(lambda x:x%2!=1 , range(11)))) |
#str = input("문자를입력하세요")
str = 'I love Python'
word = "love"
print(len(str))
'''
for i in range(0,10,1):
print(word, end="")
print("");
'''
print(word * 10) #2
print(str[0])
print(str[:3])
print(str[len(str)-3:])
for j in range(-1, -len(str)-1, -1):
print(str[j], end="")
print("")
if(str[6].isalpha()): #7
print(str[6])
else:
print("문자가 없습니다")
print(word[1:len(word)-1]) #8번 -2가 더 깔끔
print(str.upper())
print(str.lower())
print(str.replace('o', 'e'))
|
days = {'January':31,
'February':28,
'March':31,
'April':30,
'May':31,
'June':30,
'July':31,
'August':31,
'September':30,
'October':31,
'November':30,
'December':31}
#1. 월 입력 일수 출력
'''
mon = input("월 입력")
print(days.get(mon))
'''
#2. 알파벳 순서로 모든 월 출력
'''
mon_list = list(days.keys())
print(sorted(mon_list)) # 정렬은 리스트에서
'''
#3. 일수가 31인 월 모두 출력
'''
for x in days : #비어있는 value의 키 출력
if days[x] == 31:
print(x, end=' ')
'''
#4. 월의 일수를 기준으로 오름차순으로 key-value 쌍을 출력
'''
import operator
sorted_days = sorted(days.items() , key = operator.itemgetter(1)) #key는 0 value는 1
print(sorted_days)
'''
#5. 사용자가 월을 3자리만 입력하면 월의 일수를 출력하라.
mon = input("월 입력(3문자):")
for x in days:
if(mon == x[:3]):
#print(x[:3])
print(days.get(x))
|
#튜플
t1 = (1,2,3,4,5) #소괄호 사용
print(t1)
t1 = 1,2,3 #소괄호 생략 가능
print(t1)
t1 = 1
print(type(t1))
t1 =1, #요소가 1개일 때는 ,을 붙인다.
print(type(t1))
t1 = tuple() # 빈튜플 생성
print(t1)
|
a=[] #빈리스트
for i in range(0,50): #0~49
a.append(i)
print(a)
#아래도 과제
# 1~50 가지 수의 제곱으로 구성되는 리스트
a=[]
for i in range(1, 51):
a.append(i**2)
print(a)
#L=[1,2,3] M=[4,5,6] LM=[5,7,9]인 리스트 만들기
L=[1,2,3]
M=[4,5,6]
LM=[]
for i in range(0,3):
LM.append(L[i] + M[i])
print(LM)
#과제는 날짜별로 출력해서 제출 |
def viewvoterlist():
b=int(input("candidate number political party\n1) BJP\n2) BSP\n3) Congress\n4) other"))
if(b==1):
f=open("bjp","r")
data=f.read()
f.close()
print("---------------------------------------Voter list of BJP-------------------------------------")
print(data)
elif(b==2):
f=open("bsp","r")
data=f.read()
f.close()
print("---------------------------------------Voter list of BSP-------------------------------------")
print(data)
elif(b==3):
f=open("congres","r")
data=f.read()
f.close()
print("---------------------------------------Voter list of CONGRESS------------------------------")
print(data)
elif(b==4):
f=open("other party","r")
data=f.read()
f.close()
print("---------------------------------------Voter list of OTHER PARTY-----------------------------")
print(data)
def addparty():
print(" \n\n Welcome to portal of ADD PARTY \n\n ")
l1= ["BJP","BSP","CONGRESS","OTHER"]
l1.insert(4,input("enter name"))
print("final list of party is :",l1)
def admin():
ad=int(input("\n1)View Voter List\n2)Add party\n3)Go back\n4)exit\n5)Change password\n"))
if(ad==1):
viewvoterlist()
elif(ad==2):
addparty()
elif(ad==3):
voter()
elif(ad==4):
exit()
else:
resetpass()
def congress():
co=open("congres","a")
co.write(" \n")
co.write(input( " Enter your name \n"))
co.close()
def other():
ot=open("other party","a")
ot.write(" \n")
ot.write(input( " Enter your name \n"))
ot.close()
def baspa():
bs=open("bsp","a")
bs.write(" \n")
bs.write(input( " Enter your name \n"))
bs.close()
def bhajpa():
bj=open("bjp","a")
bj.write(" \n")
bj.write(input( " Enter your name \n"))
bj.close()
def voter():
print("| WELCOME HERE |")
g=int(input("\n\n1)Vote now\n2)Don't have voter id, generate now!\n3)Admin\n4)About us\n5)exit\n\n select any one"))
if (g==1):
voting()
elif (g==2):
reg()
elif(g==3):
adminpass()
elif(g==4):
aboutus()
else:
quit()
def resetpass():
print("| RESET PASSWORD |")
p=open("password","w")
p.write(input("Enter your new password"))
p.close()
print("Password change successfully")
first()
def adminpass():
print("| |WELCOME ADMIN |")
p=open("password","r")
buffer=p.read()
if (input("Enter Password")) == buffer:
p.close()
print("--------------------------Successful------------------------------")
admin()
else:
e=int(input("\n\n################WRONG PASSWORD#####################\n\n1)Exit\n2)Voter \n3)Forgot password\n4)Try again !!!!!!select any one!!!!!!"))
if (e==1):
quit()
elif (e==2):
voting()
elif(e==3):
resetpass()
else:
adminpass()
def reg():
from random import randint
rand=str(randint(1000,5000))
print("| |Register Now| |")
name=input("enter your name")
print("Thank u for Registering: ",name)
print(" Note down your id : =",rand)
f=open("evm","a")
f.write (rand+"\n")
f.close()
v=int(input("you are done\n To move further click 0"))
if v==0:
voter()
def lis():
l1=["bjp","bsp","conngress","others"]
for i in range(len(l1)):
print (l1[i])
def vote():
print(" VOTE YOUR BEST CANDIDATE \n\n ")
b=int(input("candidate number political party\n1) BJP\n2) BSP\n3) Congress\n4) others"))
5
if(b==1):
bhajpa()
elif(b==2):
baspa()
elif(b==3):
congress()
else:
other()
zz=int(input("voted successfully\n 1)exit\n 2)Next vote"))
if(zz==1):
exit()
else:
voter()
def voting():
f=open("evm","r")
buffer = f.read()
if (input("enter your voter id number")) in buffer:
print("\n\nYes you are a true Voter\n***************VOTE NOW***************")
f.close()
vote()
else:
print ("\n\nCannot vote:(\n \n1)You are not registered\n2)You are under 18\n3)You already voted")
z=int(input(" Try Again !!!!!!!! - press 0 \n\nfor exit press1\n\npress 2 for registration"))
if(z==0):
voting()
elif(z==1):
exit()
else:
reg()
print("\n\n +++++++++___________Electronic Voting Machine_______________+++++++++++\n\n")
def first():
d=int(input("1)Admin\n2)Voter"))
if d==1:
adminpass()
elif(d==2):
voter()
first()
|
number = int(input("enter a number."))
print("Then number is {}".format(number)) |
# Corey Schultz
# 4/3/2016
import time
time.sleep(2)
print "Welcome to Prison Break!"
time.sleep(2)
print "The Interactive Prison Escape Game"
time.sleep(3)
print "Created by Corey Schultz"
time.sleep(3)
print "Let's Begin"
time.sleep(2)
import os
os.system("cls")
time.sleep(3)
# end of intro / start of game
# when values are selected but the other is the action, this is intentional, meant for comedic purposes (orange and left)
print "Klyde: Welcome, inmate #10G67D, to the Johnson Experimental Institute."
time.sleep(2) #delay for 5 seconds
print "Klyde: The kids they send in these days...keep getting younger and younger. It's a real shame. *shakes head* "
time.sleep(5) #delay for 5 seconds
print "Klyde: Well no point in sulking, I'm not the one spending the rest of my life in this hell hole. LOL! But, fortunately for you, you get to pick your own clothes! How exciting!"
time.sleep(2) #delay for 2 seconds
print "Klyde: Please select an orange or gray jumpsuit:"
answer = raw_input("Type 'orange' or 'gray' and hit the enter button ").lower()
if answer == "gray" or answer == "orange" :
time.sleep(3)
print "Klyde: Ah! Gray! What a fantastic choice! The hippopotamus herd! They'll be glad to have a man of your -er- type joining them. *giggles under breath* "
print "Klyde: My apologies but I do have more important work to be getting back to"
time.sleep(11)
print "Klyde: F.R.A.N.K. , the AI chip we have installed in your brain will take it from here. "
print "Klyde: Goodluck out there kiddo.*winks* "
time.sleep(9)
print "F.R.A.N.K: Welcome inmate #10G67D"
time.sleep(6)
name = raw_input("Please type in your name and press 'enter' ")
print "You : Please, call me " + name
time.sleep(5)
print "F.R.A.N.K: Alright, I will be the voice in your head from now on, " + name
time.sleep(5)
print "You : Great"
time.sleep(5)
print "F.R.A.N.K: Although I am artificial intelligence, I can still detect sarcasm sir and I do not appreciate it "
time.sleep(5)
print "You : Golly, you really are in my head"
time.sleep(5)
print "F.R.A.N.K: Johnson Experimental Institute : Founded in the 1930's by the late-great Cave Johnson himself! You may remember him for his most famous quote : 'when life gives you-' "
time.sleep(8)
print "You : yeah, I've heard it before bro "
time.sleep(4)
print "F.R.A.N.K: well then, as we approach a fork in the hallway here please select your path"
answer = raw_input("Please type 'left' or 'right' ").lower()
if answer == "left" or answer == "right" :
print "F.R.A.N.K: Right it is,please watch your step as we walk through this hallway"
time.sleep(5)
print "F.R.A.N.K: Now there is falling debris so please be careful"
time.sleep(5)
print " *BANG* *Giant Crashing Noise*"
answer == raw_input("Please insert a response to that event ")
time.sleep(4)
print "F.R.A.N.K: I am going to pretend I didn't hear that " + name
time.sleep(4)
print "You : holy smokes batman, what is this place"
time.sleep(4)
print "F.R.A.N.K: wait, I think I hear something..."
time.sleep(2)
print " *A GIANT ALIEN DROPS THROUGH THE CEILING LOOKING LIKE A CRAZY PREDATOR, WHY IS IT ALWAYS ALIENS?* "
answer = raw_input("Sir, you must decie quickly, do we 'fight' or 'run' ")
if answer == "fight" :
print " *I think you know that you're dead* "
answer = raw_input("Would you like to try again? type 'yes'or 'no' ")
if answer == "yes" :
print "lol too bad you lost"
time.sleep(4)
elif answer == "no" :
print "ok, goodbye"
time.sleep(4)
elif answer == "run" :
print "F.R.A.N.K: OK, let's get out of here " + name
time.sleep(3)
print " *You are now sprinting at full speed down a collapsing hallway, realizing how out of shape you are and that probably stealing that candy bar was not worth all this trouble* "
time.sleep(10)
answer = raw_input("F.R.A.N.K: Sir, we have reached a dead end with two staricases. You must quickly decide! 'up' or 'down' ")
if answer == "up" :
print "F.R.A.N.K: oh no, the explosion collapsed this staircase, we have to go down! "
elif answer == "down" :
print "F.R.A.N.K: excellent choice sir! "
print " * you enter a long, mysterius, dark hallway, and as F.R.A.N.K. turns on the flashlight in your fingers, you see a mysterious creature scuddle away* "
time.sleep(7)
print "*There is one doorway to your left and one to your right*"
answer = raw_input( name + "would you like to go to the 'left' or the 'right'? ")
if answer == "left":
print " *the door opens, at first, you see nothing. But you hear a groaning noise coming from the dark corner of the room* "
answer = raw_input("Do you approach 'go' the corner or 'leave' the room")
if answer == "go":
print "*you discover that the shape in the corner is another prisoner, who has dug a tunnel out of the prison*"
print "*the prisoner is seemingly deceptive and intimierdating"
answer = raw_input("Do you choose to trust the prisoner? 'yes' or 'no' ")
if answer == "yes" :
print "Congratualtions, you have escaped the prison and won"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "no" :
print "the alien has caught up to you, due to your lack of decisiveness"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "leave" :
print "*you exit the room, but the door to the right is locked, you are now forced to continue down the hallway*"
print "*at the end of the hallway you reach a door, which when opened reveals a blinding light*"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
elif answer == "right" :
answer = raw_input("the door to the right is locked. You may now either go to the door on the 'left' or 'continue' down the hallway ")
if answer == "left" :
print " *the door opens, at first, you see nothing. But you hear a groaning noise coming from the dark corner of the room* "
answer = raw_input("Do you approach 'go' the corner or 'leave' the room")
if answer == "go":
print "*you discover that the shape in the corner is another prisoner, who has dug a tunnel out of the prison*"
print "*the prisoner is seemingly deceptive and intimierdating"
answer = raw_input("Do you choose to trust the prisoner? 'yes' or 'no' ")
if answer == "yes" :
print "Congratualtions, you have escaped the prison and won"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "no" :
print "the alien has caught up to you, due to your lack of decisiveness"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "leave" :
print "*you exit the room, but the door to the right is locked, you are now forced to continue down the hallway*"
print "*at the end of the hallway you reach a door, which when opened reveals a blinding light*"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "continue":
print "*at the end of the hall you find an air vent*"
time.sleep(5)
print "*after 20 minutes of crawling and climbing through tight spaces, you finally reach the outside. Congratulations, you are free*"
time.sleep(6)
print "*now only if there were a way to remove F.R.A.N.K. ..."
time.sleep(2)
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(6)
# "if" break point
else :
print "F.R.A.N.K:: I quit , go home"
time.sleep(2)
print "F.R.A.N.K has exploded and blasted a hole in your brain. Just thought I should let you know ;)"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(7)
else :
print "Klyde: Ok smart guy let's get serious here, this is a prison"
answer == raw_input("Type 'orange' or 'gray' and hit the enter button ").lower()
if answer == "gray" or answer == "orange" :
time.sleep(3)
print "Klyde: Ah! Gray! What a fantastic choice! The hippopotamus herd! They'll be glad to have a man of your -er- type joining them. *giggles under breath* "
print "Klyde: My apologies but I do have more important work to be getting back to"
time.sleep(11)
print "Klyde: F.R.A.N.K. , the AI chip we have installed in your brain will take it from here. "
print "Klyde: Goodluck out there kid.*winks* "
time.sleep(9)
print "F.R.A.N.K: Welcome inmate #10G67D"
time.sleep(6)
name = raw_input("Please type in your name and press 'enter' ")
print "You : Please, call me " + name
time.sleep(5)
print "F.R.A.N.K.: Alright, I will be the voice in your head from now on, " + name
time.sleep(5)
print "You : Great"
time.sleep(5)
print "F.R.A.N.K: Although I am artificial intelligence, I can still detect sarcasm sir and I do not appreciate it "
time.sleep(5)
print "You : Golly, you really are in my head"
time.sleep(5)
print "F.R.A.N.K: Johnson Experimental Institute : Founded in the 1930's by the late-great Cave Johnson himself! You may remember him for his most famous quote : 'when life gives you-' "
time.sleep(8)
print "You : yeah, I've heard it before bro "
time.sleep(4)
print "F.R.A.N.K: well then, as we approach a fork in the hallway here please select your path"
answer = raw_input("Please type 'left' or 'right' ").lower()
if answer == "left" or answer == "right" :
print "F.R.A.N.K: Right it is,please watch your step as we walk through this hallway"
time.sleep(5)
print "F.R.A.N.K: Now there is falling debris so please be careful"
time.sleep(5)
print " *BANG* *Giant Crashing Noise*"
answer == raw_input("Please insert a response to that event ")
time.sleep(4)
print "F.R.A.N.K: I am going to pretend I didn't hear that " + name
time.sleep(4)
print "You : holy jolly ranchers, what is this place"
time.sleep(4)
print "F.R.A.N.K: wait, I think I hear something..."
time.sleep(2)
print " *A GIANT COCKROACH DROPS THROUGH THE CEILING LOOKING LIKE A METEOR* "
answer = raw_input("Sir, you must decie quickly, do we 'fight' or 'run' ")
if answer == "fight" :
print " *I think you know that you're dead* "
answer = raw_input("Would you like to try again? type 'yes'or 'no' ")
if answer == "yes" :
print "lol too bad you lost"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(4)
elif answer == "no" :
print "ok, goodbye"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(4)
elif answer == "run" :
print "F.R.A.N.K: OK, let's get out of here " + name
time.sleep(3)
print " *You are now sprinting at full speed down a collapsing hallway, realizing how out of shape you are and that probably stealing that candy bar was not worth all this trouble* "
time.sleep(10)
answer = raw_input("Sir, we have reached a dead end with two staricases. You must quickly decide! 'up' or 'down' ")
if answer == "up" :
print "F.R.A.N.K: oh no, the explosion collapsed this staircase, we have to go down! "
elif answer == "down" :
print "F.R.A.N.K: excellent choice sir! "
print " * you enter a long, mysterius, dark hallway, and as F.R.A.N.K. turns on the flashlight in your fingers, you see a mysterious creature scuddle away* "
time.sleep(7)
print "*There is one doorway to your left and one to your right*"
answer = raw_input( name + "would you like to go to the 'left' or the 'right'? ")
if answer == "left":
print " *the door opens, at first, you see nothing. But you hear a groaning noise coming from the dark corner of the room* "
answer = raw_input("Do you approach 'go' the corner or 'leave' the room")
if answer == "go":
print "*you discover that the shape in the corner is another prisoner, who has dug a tunnel out of the prison*"
print "*the prisoner is seemingly deceptive and intimierdating"
answer = raw_input("Do you choose to trust the prisoner? 'yes' or 'no' ")
if answer == "yes" :
print "Congratualtions, you have escaped the prison and won"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "no" :
print "the cockroach has caught up to you, due to your lack of decisiveness"
print "THE END"
print ("\n")
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "leave" :
print "*you exit the room, but the door to the right is locked, you are now forced to continue down the hallway*"
elif answer == "right" :
answer = raw_input("the door to the right is locked. You may now either go to the door on the 'left' or 'continue' down the hallway ")
print "*at the end of the hallway you reach a door, which when opened reveals a blinding light*"
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
if answer == "left" :
print " *the door opens, at first, you see nothing. But you hear a groaning noise coming from the dark corner of the room* "
answer = raw_input("Do you approach 'go' the corner or 'leave' the room")
if answer == "go":
print "*you discover that the shape in the corner is another prisoner, who has dug a tunnel out of the prison*"
print "*the prisoner is seemingly deceptive and intimierdating"
answer = raw_input("Do you choose to trust the prisoner? 'yes' or 'no' ")
if answer == "yes" :
print "Congratualtions, you have escaped the prison and won"
print "THE END"
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "no" :
print "the cockroach has caught up to you, due to your lack of decisiveness"
print "THE END"
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "leave" :
print "*you exit the room, but the door to the right is locked, you are now forced to continue down the hallway*"
print "*at the end of the hallway you reach a door, which when opened reveals a blinding light*"
print "*at the end of the hallway you reach a door, which when opened reveals a blinding light*"
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(8)
elif answer == "continue" :
print "*at the end of the hall you find an air vent*"
time.sleep(5)
print "*after 20 minutes of crawling and climbing through tight spaces, you finally reach the outside. Congratulations, you are free*"
time.sleep(6)
print "*now only if there were a way to remove F.R.A.N.K. ..."
time.sleep(2)
print "THE END"
print "Made by Corey Schultz"
print "Hack BCA III"
print "4/2/16 - 4/3/16"
print "Python"
time.sleep(6)
# end of game
|
from LanguageAbstract import *
"""
This module defines the concrete subclass, i.e. the ConcreteProduct class in the Factory pattern.
The language defined here is English.
"""
class LanguageEnglish(Language):
def addSounds(self, sounds):
"""
:param sounds: string
:return:
"""
englishPhoneme = ['i', 'ɪ', 'e', 'ɛ', 'æ', 'ə', 'u', 'ʊ', 'o', 'ʌ', 'ɑ'] + ['p', 'b', 'm', 'f', 'v', 'θ', 'ð', 's', 'z', 'ɹ', 'l',
't', 'd', 'n', 'ɾ', 'ʃ', 'ʒ', 'j', 'k', 'ɡ', 'ŋ', 'ʔ', 'h']
englishvowels = {}
englishpulmonics = {}
for sound in sounds:
if sound == " ":
continue
elif sound not in englishPhoneme:
print(sound, "is not a Phoneme in English.")
elif sound in self.vowelDict:
englishvowels[sound] = self.vowelDict[sound]
if sound not in self.vowels:
self.vowels.add(sound)
elif sound in self.pulmonicDict:
englishpulmonics[sound] = self.pulmonicDict[sound]
self.consonants.add(sound)
elif sound in self.otherDict:
englishpulmonics[sound] = self.otherDict[sound]
self.consonants.add(sound)
else:
if sound in self.clickDict:
print(sound + " is a Click." + self.languagename + " does not have clicks.")
elif sound in self.ejectiveDict:
print(sound + " is an Ejective." + self.languagename + " does not have ejectives.")
elif sound in self.implosiveDict:
print(sound + " is an Implosive." + self.languagename + " does not have implosives.")
else:
print(sound + " is NOT an IPA symbol.")
return englishvowels, englishpulmonics
def addRules(self, rs):
# Sanity check can be added here to improve the rule part,
# though for this project, we didn't specify such language specific rule constraints.
# That's why we'd like to override this function in subclasses
"""
:param rs: space-separated strings
:return:
"""
englishrules = []
for r in rs.strip().split(" "):
englishrules.append(r)
if r not in self.rules:
self.rules.add(rs)
return englishrules
|
from abc import ABC, abstractmethod
"""
This module defines the abstarct superclass LanguageCreator, i.e. the Creator in the Factory pattern
"""
class LanguageCreator(ABC):
# def __init__(self):
# self.data = {}
@abstractmethod
def createData(self, sounds, rules):
"""
:type sounds: str
:type rs: str
"""
language = None
dataDict = {}
return language, dataDict
def storeData(self, sounds, rules):
"""
:type sounds: str
:type rs: str
"""
language, dataDict = self.createData(sounds, rules)
outpath = "generatedData/" + language.name + "/"
for k, v in dataDict.items():
v.export(outpath+ k + ".wav", format="wav")
return
|
from abc import abstractmethod, ABC
class RuleComparator(ABC):
@abstractmethod
def greater_than(self, rule1, rule2):
pass
@abstractmethod
def lesser_than(self, rule1, rule2):
pass
class RuleComparatorF1(ABC):
@abstractmethod
def greater_than(self, rule1, rule2):
"""
precedence operator. Determines if this rule
has higher precedence. Rules are sorted according
to their f1 score.
"""
f1_score_self = rule1.calc_f1()
f1_score_other = rule2.calc_f1()
return f1_score_self > f1_score_other
@abstractmethod
def lesser_than(self, rule1, rule2):
"""
rule precedence operator
"""
return not rule1 > rule2
class RuleComparatorCBA():
pass |
# -*- coding: utf-8 -*-
import sys
import re
import math
from urllib.request import urlopen
"""
Реализовать функцию-генератор строки с таблицей умножения на число Х.
"""
def multiplication_table(x):
res = [str(x) +"x" + str(a) + "=" + str(a*x) for a in range(10)]
print ('\n'.join(res))
"""
Есть лог-файл какого-то чата. Посчитать «разговорчивость» пользователей
в нем в виде ник — количество фраз. Посчитать среднее число букв на участника чата.
"""
def chat_log_counter(filename):
log_file = open(filename,"rU")
result = {}
for n in log_file.readlines():
chat_member = re.search('\s(\w)+',n)
member_nik = str(chat_member.group())
if not member_nik in result:
result[member_nik] = 0
else:
result[member_nik] = result[member_nik] + 1
print (result)
def main():
#multiplication_table(3)
chat_log_counter("chat_log.txt")
if __name__ == '__main__':
main() |
def beber(idade):
if idade>=18:
print("Pode beber! ")
elif idade<18 and idade>0:
acomp = str(input("Você está acompanhado de algum responsável? "))
if acomp == "sim":
print("Pode beber se seu responsável deixar, mas faz isso escondido tá?")
else:
print("Não pode beber!")
else:
print("Insira uma idade válida!")
idade = int(input("Qual sua idade? "))
beber(idade)
|
def printList(val):
for k in range(len(val)):
if k != len(val)-1 and k != len(val)-2:
print(val[k], end=', ')
elif k == len(val)-2:
print(val[k], end=' and ')
else:
print(val[k])
spam = ['app', 'ban', 'tof', 'cat']
printList(spam)
vl = str(input('Введите строку: '))
lis = vl.split(" ")
printList(lis) |
#! python
# strongPass.py - функция проверки пароля.
import re
def checkPass(prompt):
# Сильным будет пароль не меньше 8 символов, в вернем и нихнем регистре и 1 цифра
# passRe = re.compile(r'(([0-9a-zA-Z]){8,})')
passRe = re.compile(r'([0-9a-zA-Z]){8,}')
passReDit = re.compile(r'.*(\d)+.*')
if passRe.match(prompt) and passReDit.match(prompt):
print('Pass ok')
else:
print('Bad pass')
checkPass('Password')
checkPass('Password12')
checkPass('12345678')
checkPass('Admin')
checkPass('Qwerty1234') |
import sys
import math
import random
def main():
# ./RSA.py init {size}
if(len(sys.argv) == 3):
if(sys.argv[1] == 'init'):
generate_key(int(sys.argv[2]))
elif(len(sys.argv) == 5):
# .RSA.py -e {plaintext} {n} {e}
if(sys.argv[1] == '-e'):
print(encrypt(sys.argv[2], int(sys.argv[3]), int(sys.argv[4])))
# .RSA.py -d {plaintext} {n} {d}
elif(sys.argv[1] == '-d'):
print(decrypt(sys.argv[2], int(sys.argv[3]), int(sys.argv[4])))
# end main()
def generate_key(size):
# 產生隨機質數 p 和 q
p = None
while(p == None):
temp = random.randrange(2**(size-1), 2**size)
if(is_prime(temp)):
p = temp
print('p:', p)
q = None
while(q == None):
temp = random.randrange(2**(size-1), 2**size)
if(is_prime(temp) and temp != p):
q = temp
print('q:', q)
n = p*q
print('n:', n)
phiN = (p-1)*(q-1)
# 從 1 - phiN 中取一個與 phiN 互質的 e
e = None
while(e == None):
temp = random.randrange(2**(size-1), 2**size)
if(math.gcd(temp, phiN) == 1):
e = temp
break
print('e:', e)
# 找一個 d 使 d * e ≡ 1 mod phiN
d = find_mode_inverse(e, phiN)
print('d:', d)
return p, q, n, e, d
# end generate_key()
def square_and_multiply(x, h, n): # Output x**h % n
y = x
bitH = [int(x) for x in bin(h)[2:]]
for i in range(1, len(bitH)):
y = y**2 % n
if bitH[i] == 1:
y = y * x % n
return y
# end square_and_multiply
def find_mode_inverse(a, m):
if math.gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (
u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
def is_prime(number): # 判斷質數
if(number < 2):
return False
elif(number == 2):
return True
elif(number % 2 == 0):
return False
# 測試 2 - sqrt(n) 中有無 n 的因數
elif(number < 1000):
temp = math.ceil(math.sqrt(number))
for i in range(3, temp, 2):
if(number % i == 0):
return False
return True
else:
return rabin_miller(number)
# end is_prime()
def rabin_miller(number):
# 找 u 和 r 使 p' -1 = 2**u * r
r = number - 1
u = 0
while r % 2 == 0:
r = r // 2
u += 1
# 做五次測試
for test in range(5):
# 找 a 使 a**r % p' != 1
a = random.randrange(2, number - 1)
temp = square_and_multiply(a, r, number)
if temp != 1:
# 找 a 使 a**r**2j != (p'-1) % p'
j = 0
while temp != (number - 1):
if j == u - 1:
# 找到的話為合數
return False
else:
j = j + 1
temp = square_and_multiply(temp, 2, number)
# 找不到就有可能是質數
return True
# end rabin_miller(num)
def encrypt(plaintext, n, e):
y = 0
for i in range(len(plaintext)):
y += (ord(plaintext[i])-33) * 90**(len(plaintext)-i)
y = square_and_multiply(y, e, n)
ciphertext = ''
for i in range(len(plaintext)):
char = y % 90
y //= 90
char = chr(char+33)
ciphertext = ciphertext + char
return ciphertext
# end encrypt()
def decrypt(ciphertext, n, d):
x = 0
for i in range(len(ciphertext)):
x += (ord(ciphertext[i])-33) * 90**(len(ciphertext)-i)
x = square_and_multiply(x, d, n)
plaintext = ''
for i in range(len(ciphertext)):
char = x % 90
x //= 90
char = chr(char+33)
plaintext = plaintext + char
return plaintext
# end encrypt()
if __name__ == "__main__":
main()
|
#Outline:
#1. File unshaad List butsaadag class
#2. List ~ QuestionAnswer/Class/
#3. Play
class ReadFile():
def __init__(self, fileName):
self.fileName = fileName
def getList(self):
myFile = open(self.fileName, 'r')
fullText = myFile.read()
fullText = fullText[:-1]
allData = fullText.split('\n')
#question answer split(',') object/QuesAns/ -> list
questions = []
for data in allData:
#Undsen gurvan ogno yu ve?,rgb
quesAndAns = data.split(',')
#QuestAns object uusgeed teriigee questions list append hiij bna
questions.append(QuestAns(quesAndAns[0], quesAndAns[1]))
return questions
class QuestAns():
def __init__(self, question, answer):
self.question = question
self.answer = answer
class Play():
def __init__(self):
self.counter = 0
self.mustPoint = 0
def getStarted(self):
test = ReadFile('ques.txt')
test = test.getList()
self.mustPoint = len(test)
for data in test:
print(data.question)
answer = input('Tanii hariult?')
if data.answer == answer:
print('Bayar hurgye ta zov hariulla!')
self.counter = self.counter + 1
else:
print('Uuchlaarai hariult buruu baina!')
if self.counter == self.mustPoint:
print('Bayar hurgye ta buh asuultand zow hariulla!')
else:
print('Ta', self.mustPoint, 'asuultnaas', self.counter, 'asuultand zow hariullaa!')
gameTest = Play()
gameTest.getStarted()
|
#limited scope experiment with grid and tiles
class TinyTile:
def __init__(self, name):
self.name = name
class TinyGrid:
def __init__(self,x,y=None):
# Assume square unless otherwise said
if (y is None):
y = x
tiny_array = []
for column in range (0,x):
new_column = []
for row in range (0,y):
its_name = "My name is {x},{y}".format(x=column, y=row)
print(its_name)
new_tile = TinyTile(its_name)
new_column.append(new_tile)
tiny_array.append(new_column)
self.grid = tiny_array
grid_3 = TinyGrid(3)
print(grid_3.grid[1][2].name)
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 13')
robotArm.randomLevel(1,7)
move = 1
# Jouw python instructies zet je vanaf hier:
robotArm.grab()
while robotArm.scan() != "":
for x in range(move):
robotArm.moveRight()
robotArm.drop()
move = move + 1
for x in range(move):
robotArm.moveLeft()
robotArm.grab()
# Na jouw code wachten tot het sluiten van de window:
robotArm.wait() |
def calculator(num1, operator, num2):
return {
"+" : num1 + num2,
"-" : num1 - num2,
"*" : num1 * num2,
"/" : num1 // num2 if num2 else "Can't divide by 0!"
}[operator] |
def correct_title(txt):
def func(x):
if x in "and the of in":
return x
else:
if "-" in x:
return "-".join(map(func,x.split("-")))
else:
return x[0].upper() + x[1:]
return " ".join(map(func,txt.lower().split(" "))) |
#!/bin/env/python
# Solution for : https://leetcode.com/problems/array-partition-i/description/
#
# To get the maximum sum, we need to include as many large numbers as possible
# Largest numbers at even positions would never win in min(ai,bi) selection so
# we have pick the numbers at odd position.
#
# It is an interesting problem to see an application of sorting.
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums) if nums is not None else nums
return sum(nums[0::2])
|
#!/usr/bin/env python
'''
Multiply two integers without using "*" operator.
'''
def mult(a, b):
"""
Multiplies two integers
"""
try:
a = int(a)
b = int(b)
# TODO
# 1) -ve numbers
# 2) If one number is 1 only or zero
if a == 0 or b == 0:
return 0
polarity = (a < 0) ^ (b <0)
if a < 0:
a = a - a -a
if b < 0:
b = b - b -b
if a == 1:
return b if not polarity else b - b - b
elif b == 1:
return a if not polarity else a - a - a
ans = 0
for i in range(b):
ans += a
return ans if not polarity else ans - ans - ans
except Exception as err:
raise
print mult(0,2)
print mult (-1,-2)
print mult(-1,2)
print mult(1, -2)
print mult(2,3)
print mult(10,15)
print mult(10.2, 32.4)
|
from multiprocessing import Pool, cpu_count
from joblib import Parallel, delayed
def parfor(task, processes, args):
"""Parallel For.
Applies a function *task* to each argument in *args*,
using a pool of concurrent processes.
Parameters
----------
task : function
Function object that should process each element in args.
processes : int
Maximum number of concurrent processes to be used in the pool.
If higher than multiprocessing.cpu_count(),
all processor's cores will be used.
args : any
Iterable object, where each element is an argument for task.
Returns
-------
out : iterable
Iterable object containing the output of
task(arg) for each arg in args.
"""
# Don't try to spawn more processes than available CPUs
num_cores = min(cpu_count(), processes)
pool = Pool(processes=num_cores)
return pool.map(task, args)
def parfor2(task, n_reps, processes, *args):
"""Parallel For.
Run function `task` using each argument in `args` as input,
using a pool of concurrent processes.
The `task` should take as first input the index of parfor iteration.
Parameters
----------
task : function
Function object that should process each element in `args`.
n_reps : int
Number of times the `task` should be run.
processes : int
Maximum number of concurrent processes to be used in the pool.
If higher than `multiprocessing.cpu_count()`,
all processor's cores will be used.
args : any, optional
Tuple with input arguments for `task`.
Returns
-------
out : list
List with iteration output, sorted (rep1, rep2, ..., repN).
"""
# Don't try to spawn more processes than available CPUs
num_cores = min(cpu_count(), processes)
return Parallel(n_jobs=num_cores, backend='multiprocessing')(
delayed(task)(i, *args) for i in range(n_reps))
if __name__ == "__main__":
from math import factorial
arguments = range(10)
res = [factorial(z) for z in arguments]
parres = parfor(factorial, 2, arguments)
print(parres)
def element_wise_power(idx, list_of_scalars):
print("Repetition {:} started...".format(idx))
list_of_scalars_pow = []
for obj_idx, obj in enumerate(list_of_scalars):
list_of_scalars_pow.append(list_of_scalars[obj_idx]**idx)
print("Repetition {:} ended...".format(idx))
return list_of_scalars_pow
parout = parfor2(element_wise_power, 4, 2, ([j for j in range(10)]))
print(parout)
|
import numpy as np
import matplotlib.pyplot as plt
from secml.figure import CFigure
fig = CFigure(fontsize=16)
# create a new subplot
fig.subplot(2, 2, 1)
x = np.linspace(-np.pi, np.pi, 100)
y = 2*np.sin(x)
# function `plot` will be applied to the last subplot created
fig.sp.plot(x, y)
# subplot indices are are the same of the first subplot
# so the following function will be run inside the previous plot
fig.subplot(2, 2, 1)
y = x
fig.sp.plot(x, y)
# create a new subplot
fig.subplot(2, 2, 3)
fig.sp.plot(x, y)
fig.subplot(2, 2, grid_slot=(1, slice(2)))
y = 2*np.sin(x)
fig.sp.plot(x, y)
plt.show()
|
def slidingwindow(nums: list, k: int) -> list:
if not nums: return []
window, res = [], []
for i, x in enumerate(nums):
if i >= k and window[0] <= i - k:
window.pop(0)
while window and nums[window[-1]] <= x:
window.pop()
window.append(i)
if i >= k - 1:
res.append(nums[window[0]])
enumerate
return res
if __name__ == '__main__':
print(slidingwindow([1, 2, 3, 1, 5, 2, 6], 3))
|
import sys
class Employee:
def __init__(self):
self.num = 0
self.salary = 0
self.name = ''
self.next = None
findword = 0
namedata = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
data = [[1001, 22222], [1002, 23451], [1003, 32456], [1004, 45678], [1005, 43214], [1006, 23332], [1007, 25552], ]
head = Employee()
if not head:
# raise ValueError('内存分配失败!')
print('内存分配失败!')
sys.exit()
head.num = data[0][0]
head.name = namedata[0]
head.salary = data[0][1]
head.next = None
ptr = head
for i in range(1, 7):
newnode = Employee()
newnode.num = data[i][0]
newnode.name = namedata[i]
newnode.salary = data[i][1]
newnode.next = None
ptr.next = newnode
ptr = ptr.next
ptr = head
i = 0
print('反转前节点数据:')
while ptr != None:
print('[{}{}{}] =>'.format(ptr.num, ptr.name, ptr.salary), end='')
i += 1
if i >= 3:
print()
i = 0
ptr = ptr.next
ptr = head
before = None
print('\n反转后节点数据:')
while ptr != None:
last = before
before = ptr
ptr = ptr.next
before.next = last
ptr = before
while ptr != None:
print('[{}{}{}] =>'.format(ptr.num, ptr.name, ptr.salary), end='')
i += 1
if i >= 3:
print()
i = 0
ptr = ptr.next
|
"""Calculate possibilities of flipping a coin."""
def full_probability(coin_probabilities: list[float], event_probabilities: list[float]) -> float:
"""Calculate full probability of flipping a coin and getting desired side.
Parameters
----------
coin_probabilities : list of float
Probabilities of choosing certain coin.
event_probabilities : list of float
Probabilities of getting desired side for each coin.
Returns
-------
float
Probability of getting desired side.
"""
return sum(
coin_probability * event_probability
for coin_probability, event_probability in zip(coin_probabilities, event_probabilities)
)
def bayes(coin_possibility: float, event_possibility: float, full_possibility: float) -> float:
"""Get next probability of choosing certain coin.
Parameters
----------
coin_possibility : float
Previous possibility of choosing this coin.
event_possibility : float
Possibility of getting desired side using this coin.
full_possibility : float
Probability of getting desired side.
Returns
-------
float
Next probability of choosing certain coin.
"""
return (coin_possibility * event_possibility) / full_possibility
def get_possibility_of_sequence(sequence: list[str], number_of_coins: int, possibilities: dict) -> list[float]:
"""Get possibility of sequence of events.
Parameters
----------
sequence : list of str
The sequence for which the possibilities will be calculated.
number_of_coins : int
Number of coins we can choose for flipping.py
possibilities : dict
Possibilities of getting desired side for each coin.
Returns
-------
list of float
Step by step possibilities of getting desired side.
Raises
------
ValueError
If number of coins is less than 1.
"""
if number_of_coins < 1:
raise ValueError(f'Number of coins({number_of_coins}) is less than 1.')
result_possibilities = []
# possibility of choosing certain coin at first step
coin_possibilities = [1 / number_of_coins] * number_of_coins
for side in sequence + ['H']:
result_possibilities.append(full_probability(coin_possibilities, possibilities['H']))
# update possibilities of choosing certain coin
coin_possibilities = [
bayes(
coin_possibilities[item],
possibilities[side][item],
full_probability(coin_possibilities, possibilities[side]),
)
for item in range(number_of_coins)
]
return result_possibilities[1:]
if __name__ == '__main__':
coin_possibilities_of_H = [0.1, 0.2, 0.4, 0.8, 0.9]
coin_possibilities = {'H': coin_possibilities_of_H, 'T': [1 - item for item in coin_possibilities_of_H]}
sequence = list('HHHTHTHH')
number_of_coins = 5
print([round(item, 2) for item in get_possibility_of_sequence(sequence, number_of_coins, coin_possibilities)])
|
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
j, k = float('inf'), float('inf')
d = float('inf')
for i in range(len(words)):
if words[i] == word1:
j = i
elif words[i] == word2:
k = i
if abs(j - k) <= d:
d = abs(j - k)
return d
|
'''
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
'''
def f(n):
if n == 0:
return 0
else:
return f(n-1)+100
num1 = int(input("请输入一个正整数:"))
print(f(num1))
'''
递归的使用
'''
|
'''
定义一个方法,接受一个整数,判断这个数为基数或者偶数,打印输出结果
'''
def checkNum(n):
try:
if n%2 ==0:
print("it is an odd number!")
else:
print("it is an even number!")
except:
print("{}不是一个整数!".format(n))
test = checkNum('s')
'''
利用偶数%2结果为0进行判断
''' |
#计算一个数的阶乘
def test(l):
if l == 1:
return 1
else:
return l*test(l-1)
print('请输入一个数字:', end='')
l = int(input())
print (test(l))
'''
学习点:在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
'''
|
'''
输入多个字符串,打印输出最长的那个
'''
def maxString():
str_input = input("请输入两个字符串:")
str_list = str_input.split(' ')
for s in str_list:
len1 = len(s)
len2 = 0
if len1>len2:
len2 = len1
print(str_list[len2])
'''
原题: 定义一个函数,接收两个字符串,打印输出最长的那个,如果相同长,那么全都输出打印出来
'''
def maxStr(str1,str2):
if len(str1) == len(str2):
print(str1,str2)
elif len(str1)>len(str2):
print(str1)
else:
print(str2)
#test = maxStr('123234','sdfjsjdflsdfjs')
test = maxString()
|
'''
字典的常用操作
'''
#get() 需要传一个key值
dict1 = {1:'abc','b':'weie','3':'abcid'}
dict2 = {1:'sdf',3:'cdf',2:'iend'}
result1 = dict1.get(1)
print(result1)
#dict.items() 输出字典内容以列表中的元组
#python3之后没有 iteritems
result2 = dict2.items()
print(result2)
#dict_items([(1, 'abc'), ('b', 'weie'), ('3', 'abcid')])
#排序
dict3={}
list1 = sorted(dict2.keys())
for i in list1:
dict3[i]=dict2[i]
print(dict3, dict2)
dict2.clear()
for j in list1:
dict2[j] = dict3[j]
print(dict3,dict2)
#反转 基本思路:遍历key values, 然后在新的字典中新的key等于value
dict4 = {'a':1,'b':2,'c':3}
new_dict = {}
for i,j in dict4.items():
new_dict[j]=i
print(new_dict)
#拷贝字典
dict5 = dict4.copy()
print(dict5)
|
'''
定义一个函数,计算两个数的和
'''
def sum(num1,num2):
return num1+num2
test = sum(2,3)
print(test) |
'''
网站要求用户输入用户名和密码进行注册。 编写程序以检查用户输入的密码的有效性。
以下是检查密码的标准:
1. [a-z]之间至少有1个字母
2. [0-9]之间至少有1个数字
1. [A-Z]之间至少有一个字母
3. [$#@]中至少有1个字符
4.最短交易密码长度:6
5.交易密码的最大长度:12
您的程序应接受一系列逗号分隔的密码,并将根据上述标准进行检查。 将打印符合条件的密码,每个密码用逗号分隔。
'''
import re
values = []
list_password = [x for x in input().split(',')]
for password in list_password:
if len(password)<6 or len(password)>12:
continue
else:
pass
if not re.search("[a-z]",password):
continue
elif not re.search("[0-9]",password):
continue
elif not re.search("[A-Z]",password):
continue
elif not re.search("[@#$]",password):
continue
elif re.search("\s",password):
continue
else:
pass
values.append(password)
print(','.join(values)) |
#定义一个类,有两个方法,getString:从控制台获取字符串,printString:以大写的形式打印字符串
class InputOutputString():
def __init__(self):
self.s = ''
def getString(self):
self.s = input()
def printString(self):
print(self.s.upper())
teststring = InputOutputString()
teststring.getString()
teststring.printString()
'''
学习知识点: upper() 方法将字符串中的小写字母转为大写字母。 str.upper()
'''
|
# Import modules
import os
import csv
# Paths to collect and write data
input_path = os.path.join('resources', 'budget_data.csv')
output_path = os.path.join('analysis', 'pnl_analysis.txt')
# Create lists to store data
revenue_changes = []
# Initialize variables
total_months = 0
total_revenue = 0
prev_revenue = 0
revenue_change = 0
greatest_increase = ["", 0]
greatest_decrease = ["", 9999999999999999999999]
# Open and read csv
with open(input_path, 'r', encoding='utf8') as pnl_file:
pnl_reader = csv.reader(pnl_file, delimiter=',')
# Read the header row first
pnl_header = next(pnl_reader)
# Read through each row of data after the header
for row in pnl_reader:
# Calculate totals
total_months = total_months + 1
total_revenue = total_revenue + int(row[1])
# Keep track of changes
revenue_change = int(row[1]) - prev_revenue
# Reset the value of prev_revenue
prev_revenue = int(row[1])
# Determine greatest increase
if (revenue_change > greatest_increase[1]):
greatest_increase[1] = revenue_change
greatest_increase[0] = row[0]
# Determine greatest decrease
if (revenue_change < greatest_decrease[1]):
greatest_decrease[1] = revenue_change
greatest_decrease[0] = row[0]
# Add to the revenue_changes list
revenue_changes.append(int(row[1]))
# Print output
print("Financial Analysis")
print("-------------------------")
print("Total Months: " + str(total_months))
print("Total Revenue: " + "$" + str(total_revenue))
print("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes), 2)))
print("Greatest Increase: " + str(greatest_increase[0]) + " ($" + str(greatest_increase[1]) + ")")
print("Greatest Decrease: " + str(greatest_decrease[0]) + " ($" + str(greatest_decrease[1]) + ")")
# Write output
with open(output_path, "w") as txt_file:
txt_file.write("Financial Analysis")
txt_file.write("\n")
txt_file.write("----------------------------")
txt_file.write("\n")
txt_file.write("Total Months: " + str(total_months))
txt_file.write("\n")
txt_file.write("Total Revenue: " + "$" + str(total_revenue))
txt_file.write("\n")
txt_file.write("Average Change: " + "$" + str(round(sum(revenue_changes) / len(revenue_changes), 2)))
txt_file.write("\n")
txt_file.write("Greatest Increase: " + str(greatest_increase[0]) + " ($" + str(greatest_increase[1]) + ")")
txt_file.write("\n")
txt_file.write("Greatest Decrease: " + str(greatest_decrease[0]) + " ($" + str(greatest_decrease[1]) + ")") |
import pygame
import random as rand
# Define ant class to make handling numerous ants easier
class Ant():
# Initialize the ant with a direction and position
def __init__(self,x,y,xVel,yVel):
self.pos = (x,y)
self.vel = (xVel,yVel)
def getDirection(self): # Get the direction of the ant
return self.vel
def setDirection(self, xVel,yVel):
self.vel = (xVel,yVel)
def getPosition(self):
return self.pos
def setPosition(self,x,y):
self.pos = (x,y)
def moveForward(self):
x,y = self.pos
xVel,yVel=self.vel
# Move by current vel
x+=xVel
y+=yVel
# make edges of screen wrap around
x%=80
y%=80
# Update ant pos
self.pos = (x,y)
# Create the cell matrix
CellMatrix = [[False for a in range(80)] for b in range(80)]
win = pygame.display.set_mode((800,800))
pygame.display.set_caption("Langton's Ant")
def drawAnt(ant:Ant):
# Draw the ant on the screen
x,y=ant.getPosition()
pygame.draw.rect(win, (255,0,0), ((x*10)+3,(y*10)+3, 4,4))
def redrawCell(x:int, y:int):
# Default state of the cell is black
col = (0,0,0)
if CellMatrix[y][x] == True: # If true cell is white
col = (255,255,255)
# Draw cell
pygame.draw.rect(win, col, (x*10,y*10,10,10))
# The state of activity for the simulation
active = False
# Keep track of all ants that are on the screen
Ants = []
# Main game loop
run = True
while(run):
# Update display for next simulation tick
#pygame.time.delay(100)
pygame.display.update()
# Event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
x,y = pygame.mouse.get_pos()
x,y=int(x//10),int(y//10)
NewAnt = Ant(x,y,0,1)
Ants.append(NewAnt)
drawAnt(NewAnt)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
active = not active
print('Active set to: '+str(active))
elif event.key == pygame.K_r:
print("Random filling board space")
CellMatrix = [[(rand.randint(0,2)==1 and True or False) for x in range(80)] for y in range(80)]
[[redrawCell(x, y) for x in range(80)] for y in range(80)]
elif event.key == pygame.K_c:
print("Clearing board space")
CellMatrix = [[False for x in range(80)] for y in range(80)]
Ants.clear()
win.fill((0,0,0))
if active == True:
# Simulation is active
# Queue all cells to be inverted and redrawn after frame
cellQueue = []
for ant in Ants:
# Loop through each ant on the screen
x,y = ant.getPosition()
xVel,yVel = ant.getDirection()
# If white cell turn left if black turn right
if CellMatrix[y][x] == True:
xVel,yVel = yVel,-xVel
else:
xVel,yVel= -yVel,xVel
# Update velocity and moveforwad
ant.setDirection(xVel,yVel)
ant.moveForward()
# Queue cell update
cellQueue.append([x,y])
# Register all cell updates
for x,y in cellQueue:
CellMatrix[y][x] = not CellMatrix[y][x]
redrawCell(x, y)
# Redraw all ants in the new frame
for ant in Ants:
drawAnt(ant) # Call for each ant too be redrawn
# Previous frame ants don't matter as the cell updates overlap them
|
import pandas as pd
import os
bank_csv = "Resources/budget_data.csv"
bank_df = pd.read_csv(bank_csv)
num_months = bank_df["Date"].count
net_total = bank_df["Profit/Losses"].sum()
difference_in_value = bank_df["Profit/Losses"].diff()
bank_df["Difference"] = difference_in_value
total_of_diff = bank_df["Difference"].sum()
number_of_diff = bank_df["Difference"].count()
average_of_diff = total_of_diff / number_of_diff
average_of_diff = round(average_of_diff,2)
bank_df_descending = bank_df.sort_values("Difference", ascending=False)
bank_df_descending = bank_df_descending.reset_index(drop=True)
highest_increase_amount = bank_df_descending.iloc[0]["Difference"]
highest_increase_date = bank_df_descending.iloc[0]["Date"]
budget_increasing = bank_df.sort_values('Difference')
budget_increasing = budget_increasing.reset_index(drop=True)
highest_decrease_amount = budget_increasing.iloc[0]['Difference']
highest_decrease_date = budget_increasing.iloc[0]["Date"]
print("-----------------------------------")
print("Financial Analysis")
print("-----------------------------------")
print(f"Total Months: {num_months}")
print("Total: ${:,.2f}".format(net_total))
print("Average Change: ${:,.2f}".format(average_of_diff))
print("Greatest Increase in Profits: " + highest_increase_date +
", ${:,.2f}".format(highest_increase_amount))
print("Greatest Decrease in Profits: " + highest_decrease_date +
", ${:,.2f}".format(highest_decrease_amount))
with open("financial_results.txt", 'w') as file:
file.write("-------------------------------------------------------\r\n")
file.write("Financial Analysis\r\n")
file.write(
"---------------------------------------------------------------\r\n")
file.write(f"Total Months: {num_months}\r\n")
file.write("Total: ${:,.2f}\r\n".format(net_total))
file.write("Average Change: ${:,.2f}\r\n".format(average_of_diff))
file.write("Greatest Increase in Profits: " + highest_increase_date +
", ${:,.2f}\r\n".format(highest_increase_amount))
file.write("Greatest Decrease in Profits: " + highest_decrease_date +
", ${:,.2f}\r\n".format(highest_decrease_amount)) |
# Advent of Code 2017 - Problem 1, Day 3
########################################
# You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
# They always take the shortest path: the Manhattan Distance between the location of the data and square 1.
# How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port?
input = 277678
def find_manhattan_distance(secret_num):
layer = 0
side_length = 1
# find spiral layer that contains secret num
while secret_num > side_length ** 2:
layer += 1
side_length += 2
if layer == 0:
return 0
# find corners of the square that contains secret num
corner_calc = side_length - 1
corner1 = side_length ** 2 # start with bottom right corner and go clockwise around square
corner2 = (corner1 - corner_calc)
# find side of the square that contains secret num
while secret_num <= corner2:
corner1 = corner2
corner2 = (corner1 - corner_calc)
# find distance from mid point of the square
mid = corner2 + (side_length//2)
if secret_num == mid:
return layer
dist_from_mid = abs(secret_num - mid)
return layer + dist_from_mid
# For testing:
#################
# Data from square 1 is carried 0 steps, since it's at the access port.
# Data from square 12 is carried 3 steps, such as: down, left, left.
# Data from square 23 is carried only 2 steps: up twice.
# Data from square 1024 must be carried 31 steps.
print("Answer: " + str(find_manhattan_distance(1)) + ' - this should be layer 0')
print("Answer: " + str(find_manhattan_distance(12)) + ' - this should be layer 3')
print("Answer: " + str(find_manhattan_distance(23)) + ' - this should be layer 2')
print("Answer: " + str(find_manhattan_distance(input)) + ' - this should be your final answer')
|
# coding: utf-8
# In[24]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
sess = tf.Session()
# # Debugging
# In normal code (in Python or otherwise), a pretty standard practice is to add conditionals in your code to look for certain behavior when something has gone awry. For example:
# In[28]:
y = np.array([1, 0, 2, 3, 4, 5], dtype=np.float32)
x = np.array([2, 1, 4, 6, 8, 10], dtype=np.float32)
t = x / y
m = np.mean(t)
v = np.var(t)
print((t - m) / np.sqrt(v))
# In the above, we're actually getting some reasonably helpful output from the iPython kernel. To debug this, we'd probably first start by adding some print statements, such as:
# In[29]:
print(np.any(np.isinf(t) | np.isnan(t)))
print(np.isinf(t) | np.isnan(t))
# which tells us that the second element of `t` is `nan` or `inf`. We can then print it:
# In[30]:
print(t[1])
# Or to be more fancy:
# In[31]:
print(t[np.where(np.isinf(t) | np.isnan(t))])
# That is using several thing at once: for a condition on t (whether it is nan or inf), find all the indices where the condition is true, and print all the values of t where it is true.
# # Debugging in TensorFlow
#
# Doing the same thing in TensorFlow is not as straightforward. In NumPy, we can print and exit in the middle of a program. In TensorFlow, we have to use the computation graph.
# In[34]:
x_tf = tf.constant(x)
y_tf = tf.constant(y)
t_tf = x_tf / y_tf
m_tf = tf.reduce_mean(t_tf)
v_tf = tf.reduce_mean((t_tf - m_tf) ** 2)
final = (t_tf - m_tf) / tf.sqrt(v_tf)
# In[36]:
print(sess.run(final))
# So now we want to go nan/inf hunting again in TensorFlow.
# In[41]:
print(sess.run(tf.reduce_any(tf.logical_or(tf.is_inf(t_tf), tf.is_nan(t_tf)))))
print(sess.run(tf.logical_or(tf.is_inf(t_tf), tf.is_nan(t_tf))))
# Or using the shorthand for tf.logical_or
# print(sess.run(tf.is_inf(t_tf) | tf.is_nan(t_tf)))
# I can still print known elements of Tensors, but conditionals will be challenging mid-way through the computation graph.
# In[42]:
print(sess.run(t_tf[1]))
# What we did in NumPy is not strictly possible in TensorFlow (this will throw a lot of errors). However, we can still use things like `tf.cond` and `tf.where` along with any of the `tf.reduce_*` operations.
# In[57]:
# sess.run(t_tf[tf.where(tf.is_inf(t_tf) | tf.is_nan(t_tf))])
# In[52]:
# If there are any bad elements of t, use x instead for future
# computations.
new_t = tf.cond(
tf.reduce_any(tf.is_inf(t_tf) | tf.is_nan(t_tf)),
lambda: x_tf,
lambda: t_tf)
print(sess.run(new_t))
# In[53]:
# For any bad elements of t, use elements of x instead for future
# computations.
new_t = tf.where(
tf.is_inf(t_tf) | tf.is_nan(t_tf),
x_tf,
t_tf)
print(sess.run(new_t))
# We can even add printing in the graph if we don't mind risking having big log files as we debug (this operation logs to standard error, which doesn't appeart to show up in Jupyter):
# In[56]:
new_t = tf.cond(
tf.reduce_any(tf.is_inf(t_tf) | tf.is_nan(t_tf)),
lambda: tf.Print(x_tf,
[x_tf, y_tf, t_tf, m_tf, v_tf],
"return x_tf, but have side effect of printing x,y,t,m,v: ",
# Print up to 100 elements of each tensor in the list
summarize=100),
lambda: t_tf
)
# Prints:
# I tensorflow/core/kernels/logging_ops.cc:79] \
# return x_tf, but have side effect of printing x,y,t,m,v: \
# [2 1 4 6 8 10][1 0 2 3 4 5][2 inf 2 2 2 2][inf][nan]
print(sess.run(new_t))
|
# Time Complexity :O(log n)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
# while there is a root
while root:
# if > and > check left
if root.val > p.val and root.val > q.val:
root = root.left
# if < and < check right
elif root.val < p.val and root.val < q.val:
root = root.right
else:
#else return True
return root |
"""
Tournament class: storage of teams, schedules and output methods
"""
from collections import namedtuple
TournamentDayTimings = namedtuple('TournamentDayTimings', 'date t_start t_end num_pitches') # Day-specific information
DayTiming = TournamentDayTimings
class Tournament(object):
def __init__(self):
self.teams = [] # List of team objects
self.schedule = None
class TournamentInfo(object):
"""
timings, details of a tournament
"""
def __init__(self, num_days: int, init_timings: DayTiming):
"""
Pass in simplest values on initialisation, set individual timings via method if required
"""
self.num_days = num_days
self.timings = [init_timings] * num_days
def set_day_timing(self, day: int, timings: DayTiming):
self.timings[day-1] = timings
|
data = input()
digits = ""
letters = ""
other = ""
for chr in data:
if chr.isdigit():
digits += chr
elif chr.isalpha():
letters += chr
else:
other += chr
print(digits)
print(letters)
print(other) |
force_book = {}
while True:
user_in_force = False
command = input()
if command == 'Lumpawaroo':
break
if ' | ' in command:
side, user = command.split(' | ')
if side not in force_book:
force_book[side] = []
for side, users in force_book.items():
for u in users:
if u == user:
user_in_force = True
break
if user_in_force:
break
if user_in_force:
continue
if user not in force_book[side]:
force_book[side].append(user)
elif ' -> ' in command:
user, side = command.split(' -> ')
if side not in force_book:
force_book[side] = []
if user not in force_book[side]:
force_book[side].append(user)
for s, users in force_book.items():
if s not in side:
while user in users:
force_book[s].remove(user)
print(f'{user} joins the {side} side!')
for side, users in sorted(force_book.items(), key=lambda x: (-len(x[1]), x[0])):
if users:
print(f'Side: {side}, Members: {len(users)}')
for user in sorted(users):
print(f'! {user}') |
def cal_factorial(n):
result = 1
for num in range(1, n + 1):
result *= num
return result
number_1 = int(input())
number_2 = int(input())
factorial_n = cal_factorial(number_1)
factorial_2 = cal_factorial(number_2)
end_result = factorial_n / factorial_2
print(f'{end_result:.2f}') |
command = input()
company_users = {}
while not command == 'End':
company, id = command.split(" -> ")
if company not in company_users:
company_users[company] = [id]
else:
if id in company_users:
command = input()
company_users[company].append(id)
command = input()
sorted_list = []
sorted_company = sorted(company_users.items(), key=lambda x: x[0])
for key, value in sorted_company:
print(f"{key}")
for v in value:
if v not in sorted_list:
sorted_list.append(v)
print(f"-- {v}")
sorted_list.clear()
|
data = input().split()
bakery = {}
for word in range(0, len(data), 2):
key = data[word]
value = data[word + 1]
bakery[key] = int(value)
search_product = input().split()
for product in search_product:
if product in bakery:
print(f'We have {bakery[product]} of {product} left')
else:
print(f"Sorry, we don't have {product}") |
import math
n = int(input())
highest_snowball_value = 0
highest_snowball_snow = 0
highest_snowball_time = 0
highest_snowball_quality = 0
snowball_value = 0
for each in range(n):
snowball_snow = int(input())
snowball_time = int(input())
snowball_quality = int(input())
snowball_value = math.ceil(snowball_snow / snowball_time) ** snowball_quality
if snowball_value > highest_snowball_value:
highest_snowball_value = snowball_value
highest_snowball_quality = snowball_quality
highest_snowball_snow = snowball_snow
highest_snowball_time = snowball_time
print(f'{highest_snowball_snow} : {highest_snowball_time} = {highest_snowball_value} ({highest_snowball_quality})')
|
array = [int(n) for n in input().split()]
command = input()
while not command == 'end':
split_command = command.split()
name = split_command[0]
if name == 'swap':
index_1 = int(split_command[1])
index_2 = int(split_command[2])
array[index_1], array[index_2] = array[index_2], array[index_1]
elif name == 'multiply':
index_1 = int(split_command[1])
index_2 = int(split_command[2])
sum_of_multiply = array[index_1] * array[index_2]
array[index_1] = sum_of_multiply
# array.insert(index_1, sum_of_multiply)
# remove_number = array[index_1]
# array[remove_number] = sum_of_multiply
elif name == 'decrease':
array = [x - 1 for x in array]
command = input()
array = [str(num) for num in array]
print(f"{', '.join(array)}") |
deck = input().split()
number_of_shuffles = int(input())
left_half = []
right_half = []
for shuffels in range(number_of_shuffles):
current_deck = []
half = int(len(deck)/2)
left_half = deck[0:half]
right_half = deck[half::]
for index_of_cars in range(len(left_half)):
current_deck.append(left_half[index_of_cars])
current_deck.append(right_half[index_of_cars])
deck = current_deck
print(deck) |
from collections import defaultdict
number_of_cars = int(input())
cars = defaultdict(dict)
for n in range(number_of_cars):
data = input()
car, mileage, fuel = data.split("|")
cars[car]['mileage'] = int(mileage)
cars[car]['fuel'] = int(fuel)
command = input()
while not command == "Stop":
name_command = command.split(" : ")
if name_command[0] == 'Drive':
car = name_command[1]
distance = name_command[2]
fuel = name_command[3]
enough_fuel = cars[car]['fuel'] - int(fuel)
if enough_fuel <= 0:
print(f"Not enough fuel to make that ride")
elif enough_fuel > 0:
cars[car]['fuel'] -= int(fuel)
cars[car]['mileage'] += int(distance)
print(f"{car} driven for {distance} kilometers. {fuel} liters of fuel consumed.")
if cars[car]['mileage'] >= 100000:
print(f"Time to sell the {car}!")
del cars[car]
elif name_command[0] == 'Refuel':
car = name_command[1]
fuel = name_command[2]
fuel = int(fuel)
total_fuel = cars[car]['fuel'] + fuel
if total_fuel >= 75:
difference = 75 - cars[car]['fuel']
cars[car]['fuel'] = 75
print(f"{car} refueled with {difference} liters")
else:
cars[car]['fuel'] = total_fuel
print(f"{car} refueled with {fuel} liters")
elif name_command[0] == 'Revert':
car = name_command[1]
kilometers = name_command[2]
kilometers = int(kilometers)
difference = cars[car]['mileage'] - kilometers
if difference < 10000 and cars[car]['mileage'] >= 10000:
cars[car]['mileage'] = 10000
command = input()
continue
else:
cars[car]['mileage'] = cars[car]['mileage'] - kilometers
print(f"{car} mileage decreased by {kilometers} kilometers")
command = input()
sorted_cars = sorted(cars.items(), key=lambda tkvp: (-tkvp[1]['mileage'], tkvp[0]))
for car, value in sorted_cars:
print(f"{car} -> Mileage: {value['mileage']} kms, Fuel in the tank: {value['fuel']} lt.") |
import re
data = input()
pattern = r"(^|(?<=\s))-?\d+(\.\d+)?($|(?=\s))"
dates = re.finditer(pattern, data)
for d in dates:
print(d.group(0), end=" ") |
product = input()
quantity = float(input())
def orders(current_product, current_quantity):
result = None
if current_product == 'coffee':
result = current_quantity * 1.50
elif current_product == 'water':
result = current_quantity * 1.00
elif current_product == 'coke':
result = current_quantity * 1.40
elif current_product == 'snacks':
result = current_quantity * 2.00
return result
print(f'{orders(product, quantity):.2f}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.