text stringlengths 37 1.41M |
|---|
"""
10-6. Addition:
One common problem when prompting for numerical input occurs when people
provide text instead of numbers. When you try to convert the input to an int,
you’ll get a TypeError. Write a program that prompts for two numbers. Add them
together and print the result. Catch the TypeError if either input value is not
a number, and print a friendly error message. Test your program by entering two
numbers and then by entering some text instead of a number.
"""
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(num1 + num2)
except ValueError:
print("a non-numerical value was entered")
|
"""
2-6. Famous Quote 2:
Repeat Exercise 2-5, but this time store the famous person’s name in a variable
called famous_person. Then compose your message and store it in a new variable
called message. Print your message.
"""
famous_person = "Srinivasa Ramanujan"
message = "An equation for me has no meaning, unless it expresses a thought of God."
print(famous_person + ' once said, "' + message + '"')
|
"""
3-7. Shrinking Guest List:
You just found out that your new dinner table won’t arrive in time for the
dinner, and you have space for only two guests.
• Start with your program from Exercise 3-6. Add a new line that prints a
message saying that you can invite only two people for dinner.
• Use pop() to remove guests from your list one at a time until only two names
remain in your list. Each time you pop a name from your list, print a message
to that person letting them know you’re sorry you can’t invite them to dinner.
• Print a message to each of the two people still on your list, letting them
know they’re still invited.
• Use del to remove the last two names from your list, so you have an empty
list. Print your list to make sure you actually have an empty list at the end
of your program.
"""
guests = ["Malcolm X", "Lee Kuan Yew", "Lim Bo Seng"]
print("Good news guys, I found a bigger table!")
guests.insert(0, "Barack Obama")
guests.insert(2, "Harriet Tubman")
guests.append("Adnan Bin Saidi")
print("I'm really sorry guys but I can only invite two people at the moment.")
adnan = guests.pop()
print("I'm really sorry " + adnan + " but I can't invite you for dinner.")
lim_bo_seng = guests.pop()
print("I'm really sorry " + lim_bo_seng + " but I can't invite you for dinner.")
lee_kuan_yew = guests.pop()
print("I'm really sorry " + lee_kuan_yew + " but I can't invite you for dinner.")
harriet_tubman = guests.pop()
print("I'm really sorry " + harriet_tubman + " but I can't invite you for dinner.")
print(guests)
print("Hey " + guests[0] + ", just to let you know, you're still invited!")
print("Hey " + guests[1] + ", just to let you know, you're still invited!")
del guests[0]
del guests[0]
print(guests)
|
"""
9-13. OrderedDict Rewrite:
Start with Exercise 6-4 (page 108), where you used a standard dictionary to
represent a glossary. Rewrite the program using the OrderedDict class and make
sure the order of the output matches the order in which key-value pairs were
added to the dictionary.
"""
from collections import OrderedDict
programming_terms = OrderedDict()
programming_terms["logical error"] = "problem occurs in code logic"
programming_terms[
"list comprehension"
] = "combines the for loop and the creation of new elements into one line"
programming_terms[
"conditional test"
] = "an expression that can be evaluated as True or False"
for programming_term, meaning in programming_terms.items():
print(programming_term + ": " + meaning)
|
"""
6-1. Person:
Use a dictionary to store information about a person you know. Store their
first name, last name, age, and the city in which they live. You should have
keys such as first_name, last_name, age, and city. Print each piece of
information stored in your dictionary.
"""
samuel = {"first_name": "samuel", "last_name": "yap", "age": 19, "city": "Singapore"}
print(samuel["first_name"])
print(samuel["last_name"])
print(samuel["age"])
print(samuel["city"])
|
"""
6-10. Favorite Numbers:
Modify your program from Exercise 6-2 (page 102) so each person can have more
than one favorite number. Then print each person’s name along with their
favorite numbers.
"""
favorite_numbers = {
"marie": [5, 6],
"elliot": [14, 12],
"samuel": [16, 3],
"jerry": [19, 20, 21],
"anna": [1, 5],
}
for person, favorite_numbers in favorite_numbers.items():
print(f"{person} favorite numbers are: ")
for number in favorite_numbers:
print(number)
|
b = True
n = ''
def checkIfSmallerThan1(a):
if a < 1:
return True
else: return False
while b == True:
n = (input('Please enter a number bigger than 1: '))
try:
n = int(n)
except ValueError:
print('Please enter a number bigger than 1:')
else: b = checkIfSmallerThan1(n)
def writeFibonnaci(c):
lista = [1]
count = 2
suma = 0
if c == 1:
return print(lista)
lista.append(1)
if c == 2:
return print(lista)
if c > 2:
while count <= c - 1:
suma = int(lista[count-1]) + int(lista[count-2])
lista.append(suma)
count = count + 1
return lista
print(writeFibonnaci(n))
|
n = ''
n = (input('Please enter a string: '))
def inverseWords(a):
str1 = ''
str2 = ''
i = 0
c = False
while i < len(a):
if a[i] != ' ':
str1 = str1 + a[i]
i = i + 1
else:
i = i + 1
c = True
str2 = ' '+ str2
if c == True or i == len(a):
str2 = str1 + str2
str1 = ''
c = False
return str2
print(inverseWords(n))
|
# --------------
# USER INSTRUCTIONS
#
# Now you will put everything together.
#
# First make sure that your sense and move functions
# work as expected for the test cases provided at the
# bottom of the previous two programming assignments.
# Once you are satisfied, copy your sense and move
# definitions into the robot class on this page, BUT
# now include noise.
#
# A good way to include noise in the sense step is to
# add Gaussian noise, centered at zero with variance
# of self.bearing_noise to each bearing. You can do this
# with the command random.gauss(0, self.bearing_noise)
#
# In the move step, you should make sure that your
# actual steering angle is chosen from a Gaussian
# distribution of steering angles. This distribution
# should be centered at the intended steering angle
# with variance of self.steering_noise.
#
# Feel free to use the included set_noise function.
#
# Please do not modify anything except where indicated
# below.
from math import *
import random
# --------
#
# some top level parameters
#
max_steering_angle = pi / 4.0 # You do not need to use this value, but keep in mind the limitations of a real car.
bearing_noise = 0.1 # Noise parameter: should be included in sense function.
steering_noise = 0.1 # Noise parameter: should be included in move function.
distance_noise = 5.0 # Noise parameter: should be included in move function.
tolerance_xy = 15.0 # Tolerance for localization in the x and y directions.
tolerance_orientation = 0.25 # Tolerance for orientation.
# --------
#
# the "world" has 4 landmarks.
# the robot's initial coordinates are somewhere in the square
# represented by the landmarks.
#
# NOTE: Landmark coordinates are given in (y, x) form and NOT
# in the traditional (x, y) format!
landmarks = [[0.0, 100.0], [0.0, 0.0], [100.0, 0.0], [100.0, 100.0]] # position of 4 landmarks in (y, x) format.
world_size = 100.0 # world is NOT cyclic. Robot is allowed to travel "out of bounds"
# --------
#
# extract position from a particle set
#
def get_position(p):
x = 0.0
y = 0.0
orientation = 0.0
for i in range(len(p)):
x += p[i].x
y += p[i].y
# orientation is tricky because it is cyclic. By normalizing
# around the first particle we are somewhat more robust to
# the 0=2pi problem
orientation += (((p[i].orientation - p[0].orientation + pi) % (2.0 * pi))
+ p[0].orientation - pi)
return [x / len(p), y / len(p), orientation / len(p)]
# --------
#
# The following code generates the measurements vector
# You can use it to develop your solution.
#
# gives us a sequence of measurements and a robot position using a a robot simulation
def generate_ground_truth(motions):
myrobot = robot()
myrobot.set_noise(bearing_noise, steering_noise, distance_noise)
Z = []
T = len(motions)
for t in range(T):
myrobot = myrobot.move(motions[t])
Z.append(myrobot.sense())
#print 'Robot: ', myrobot
return [myrobot, Z]
# --------
#
# The following code prints the measurements associated
# with generate_ground_truth
#
def print_measurements(Z):
T = len(Z)
print 'measurements = [[%.8s, %.8s, %.8s, %.8s],' % \
(str(Z[0][0]), str(Z[0][1]), str(Z[0][2]), str(Z[0][3]))
for t in range(1,T-1):
print ' [%.8s, %.8s, %.8s, %.8s],' % \
(str(Z[t][0]), str(Z[t][1]), str(Z[t][2]), str(Z[t][3]))
print ' [%.8s, %.8s, %.8s, %.8s]]' % \
(str(Z[T-1][0]), str(Z[T-1][1]), str(Z[T-1][2]), str(Z[T-1][3]))
# --------
#
# The following code checks to see if your particle filter
# localizes the robot to within the desired tolerances
# of the true position. The tolerances are defined at the top.
#
def check_output(final_robot, estimated_position):
error_x = abs(final_robot.x - estimated_position[0])
error_y = abs(final_robot.y - estimated_position[1])
error_orientation = abs(final_robot.orientation - estimated_position[2])
error_orientation = (error_orientation + pi) % (2.0 * pi) - pi
correct = error_x < tolerance_xy and error_y < tolerance_xy \
and error_orientation < tolerance_orientation
return correct
def particle_filter(motions, measurements, N=500): # I know it's tempting, but don't change N!
# --------
#
# Make particles
#
p = []
for i in range(N):
r = robot()
r.set_noise(bearing_noise, steering_noise, distance_noise)
p.append(r)
# --------
#
# Update particles
#
for t in range(len(motions)):
# motion update (prediction)
p2 = []
for i in range(N):
p2.append(p[i].move(motions[t]))
p = p2
# measurement update - measurement probability function which is part of implementation
w = []
for i in range(N):
w.append(p[i].measurement_prob(measurements[t]))
# resampling
p3 = []
index = int(random.random() * N)
beta = 0.0
mw = max(w)
for i in range(N):
beta += random.random() * 2.0 * mw
while beta > w[index]:
beta -= w[index]
index = (index + 1) % N
p3.append(p[index])
p = p3
return get_position(p)
## IMPORTANT: You may uncomment the test cases below to test your code.
## But when you submit this code, your test cases MUST be commented
## out.
##
## You can test whether your particle filter works using the
## function check_output (see test case 2). We will be using a similar
## function. Note: Even for a well-implemented particle filter this
## function occasionally returns False. This is because a particle
## filter is a randomized algorithm. We will be testing your code
## multiple times. Make sure check_output returns True at least 80%
## of the time.
## --------
## TEST CASES:
##
##1) Calling the particle_filter function with the following
## motions and measurements should return a [x,y,orientation]
## vector near [x=93.476 y=75.186 orient=5.2664], that is, the
## robot's true location.
##
motions = [[2. * pi / 10, 20.] for row in range(8)]
## These are the bearings to those 4 different landmarks
measurements = [[4.746936, 3.859782, 3.045217, 2.045506],
[3.510067, 2.916300, 2.146394, 1.598332],
[2.972469, 2.407489, 1.588474, 1.611094],
[1.906178, 1.193329, 0.619356, 0.807930],
[1.352825, 0.662233, 0.144927, 0.799090],
[0.856150, 0.214590, 5.651497, 1.062401],
[0.194460, 5.660382, 4.761072, 2.471682],
[5.717342, 4.736780, 3.909599, 2.342536]]
print particle_filter(motions, measurements)
# 2) You can generate your own test cases by generating
# measurements using the generate_ground_truth function.
# It will print the robot's last location when calling it.
#
number_of_iterations = 6
motions = [[2. * pi / 20, 12.] for row in range(number_of_iterations)]
#
# "Generate<u>ground<u>truth" gives us a sequence of measurements and
# a robot position that we can split as follows
# , using a robot simulation.
x = generate_ground_truth(motions) # gives us a sequence of measurements and a robot position,
# that we can split as follows, using a robot simulation
final_robot = x[0] # final robot position, the ground truth position
measurements = x[1]
estimated_position = particle_filter(motions, measurements) # particle filter estimated position
print_measurements(measurements)
print 'Ground truth: ', final_robot
print 'Particle filter: ', estimated_position
print 'Code check: ', check_output(final_robot, estimated_position)
|
# Create a DOCUMENTED function with an explicit name and variables
def Ingredients4Pancakes(pan, out=dict):
# The """ """ syntax encloses the function documentation
# It is automatically returnes by the ? syntax in the console
""" Return the ingredients to make pan pancakes
When fed a number of pancakes (pan), return the ingredients necessary
The output can be a tuple of all variables or a dict
Parameters
----------
pan : float
The number of pancakes to be made
Return
------
out : dict / tuple
The output, formatted as required
"""
# Use explicit variable names whenver possible
eggs, eg_u = pan/2+1, 'eggs'
milk, mlk_u = 2*pan, 'L'
toads, td_u = 10*pan, 'kg'
# ------ optional
# A good practice, if your function returns several arguments
# That may not be clear and it needs to be used by others
# Is to return a dict with explicit keys
if out is dict:
out = {'eggs':{'val':eggs,'units':eg_u},
'milk':{'val':milk,'units':mlk_u},
'toads':{'val':toads,'units':td_u}}
else:
out = (eggs, eg_u, milk, mlk_u, toads, td_u)
return out
def f2():
print("Fast-and-dirty coding")
|
list1=[]
list2=[]
a=int(input("Enter element to be assigned to first position"))
list1.append(a);
a=int(input("Enter element to be assigned to second position"))
list1.append(a);
x=list1[0];
list2.append(x);
print("Second list is",list2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 17:27:12 2019
@author: saskiajackson
"""
import numpy as np
import matplotlib.pyplot as plt
print(
'-------------------------------TO RUN THE CODE-------------------------------')
#below each function are a set of commented out lines that call the various functions
#to run the code, uncomment which function you would like to see
print(
'----------------------------------PART ONE-----------------------------------')
def initialconditions(n,m,left,right,bottom,top): #n is the number of rows and m is the number of columns
grid = 1 * np.zeros( (n,m) ) #creates grid of random integers between 0 and 50
for i in range(n):
grid[i,0] = left #sets the values in the grid to zero along the lhs, rhs, top and bottom of the grid
grid[i,n-1] = right
for j in range(m):
grid[0,j] = bottom
grid[m-1,j] = top
return grid
def GaussSeidel(n,m,conditions,voltage,capacitor='0',periodicboundary='0'):
count = 0
sumbefore = []
sumafter = []
grid = conditions
percentage = 10
while percentage > 1e-15: #convergence condition
sumbefore = np.copy(grid)
for i in range(1,n-1): #between 1 and n-1/m-1 to cover all the points in the grid except the edges
for j in range(1,m-1):
if capacitor =='yes':
if grid[i][j] != voltage and grid[i][j] != -voltage: #condition to ensure that the capacitor is not changed while the Gauss Seidel method is used
grid[i][j] = 0.25 * (grid[i-1][j] + grid[i+1][j] + grid[i][j-1] + grid[i][j+1])
if periodicboundary == 'yes':
if i == n-1 and j != n-1:
grid[i][j] = (0.25)*(grid[i-1][j]+grid[0][j]+grid[i][j-1]+grid[i][j+1])
elif j == n-1 and i != n-1:
grid[i][j] = (0.25)*(grid[i-1][j]+grid[i+1][j]+grid[i][j-1]+grid[i][0])
elif i == n-1 and j == n-1:
grid[i][j] = (0.25)*(grid[i-1][j]+grid[0][j]+grid[i][j-1]+grid[i][0])
else:
grid[i][j] = (0.25)*(grid[i-1][j]+grid[i+1][j]+grid[i][j-1]+grid[i][j+1])
else:
grid[i][j] = 0.25 * (grid[i-1][j] + grid[i+1][j] + grid[i][j-1] + grid[i][j+1])
sumafter = np.copy(grid)
difference = abs(sumafter - sumbefore)
percentage = abs(np.amax(difference)/np.amax(sumafter)) #defines a percentage difference of the matrix before and after iteration
count += 1 #determines the number of iterations completed until the convergence condition is satisfied
print('Number of iterations = ', count)
return grid
def colourplot(n,m,array,Xlabel,Ylabel,title,barlabel,tmax,arrows='0',extent='0'):
X,Y = np.meshgrid(np.arange(0,n), np.arange(0,m)) #creates a mesh grid of points that can be plotted onto
if extent == 'yes':
plt.contourf(X,Y, array,100,cmap='jet',extent=[0,tmax,0,0.5])
else:
plt.contourf(X,Y, array,100,cmap='jet') #plots the mesh grid with the grid values in a contour plot
plt.colorbar(label=barlabel)
plt.title(title)
plt.xlabel(Xlabel)
plt.ylabel(Ylabel)
if arrows == 'yes': #adds arrows on the colour plot to indicate the electric field
d = np.gradient(array)
plt.streamplot(X, Y, -d[1], -d[0], density = 1, color = 'black')
plt.show()
def capacitorboundary(n,m,sep,length,voltage):
grid = np.zeros( (n,m) )
top = int((m + sep)/2) #position of the top capacitor
left = int((n - length)/2) #position of the left hand side of the capacitors
right = int((n + length)/2) #position of the right hand side of the capacitors
bottom = int((m - sep)/2) #position of the bottom capacitor
grid[top,left:right] = voltage #sets the top capacitor to 100
grid[bottom,left:right] = -voltage
return grid
#def AdjacentPoints(V,i,j,Periodic=False):
# #This function averages over the adjacent 4 point in the grid
# #If periodic is true at the edge of the grid it will take the value of the
# #grid at the opposite side.
# n=V.shape
# if Periodic==False:
# #There is a subtelty that I had to keep in mind when progrmaing this
# #When i or j is equal to 0, i-1 or j-1 will be -1 which will return the
# #opposite bouandry point without any additional if statments.
# if i==0 or j==0 or i==n[0]-1 or j==n[1]-1:
# return V[i,j]
# else:
# return (1/4)*(V[i-1,j]+V[i+1,j]+V[i,j-1]+V[i,j+1])
# elif Periodic==True:
# if i==n[0]-1 and j!=n[1]-1:
# return (1/4)*(V[i-1,j]+V[0,j]+V[i,j-1]+V[i,j+1])
#
# elif j==n[1]-1 and i!=n[0]-1:
# return (1/4)*(V[i-1,j]+V[i+1,j]+V[i,j-1]+V[i,0])
#
# elif i==n[0]-1 and j==n[1]-1:
# return (1/4)*(V[i-1,j]+V[0,j]+V[i,j-1]+V[i,0])
#
# else:
# return (1/4)*(V[i-1,j]+V[i+1,j]+V[i,j-1]+V[i,j+1])
def compare():
xaxis = np.linspace(0,100,20)
x = [10,20,30,40,50,60,70,80,90,100]
y = [257,1099,2490,4415,6855,9808,13267,17216,21662,26591]
z = np.polyfit(x,y,2)
p = np.poly1d(z)
plt.plot(x,y,'.',xaxis,p(xaxis),'--')
plt.xlabel('Number of points on the grid')
plt.ylabel('Number of iterations')
plt.title('Comparing how the number of iterations change as the grid size increases')
plt.show()
n = 20
m = n
voltage = 50
tmax=0
#colourplot(n,m,GaussSeidel(n,m,initialconditions(n,m,0,0,0,100),voltage),' ',' ','Voltage over a known area with a set value of 100V along the top edge.','Voltage /V',tmax)
#
#colourplot(n,m,GaussSeidel(n,m,capacitorboundary(n,m,4,10,voltage),voltage,capacitor='yes'),' ',' ','Voltage experienced from two capacitor plates with opposite voltage.','Voltage /V',tmax,arrows='yes',)
colourplot(n,m,GaussSeidel(n,m,capacitorboundary(n,m,4,n,voltage),voltage,capacitor='yes',periodicboundary='yes'),' ',' ','Voltage experienced from two capacitor plates with opposite voltage.','Voltage /V',tmax,arrows='yes',)
#compare()
print(
'----------------------------------PART TWO-----------------------------------')
def definematrix(h, dt ,n, ice='0'): #h is the space step, dt is the time step, n is the number of points on the array
alpha = 59/(450*7900) #alpha = thermal conductivity/(density * specific heat)
x = (alpha*dt) / (h**2) #defines a value for x to use in the matrix
matrix = np.zeros( (n,n) )
for i in range(1,n-1):
matrix[i][i] = 1+2*x #sets the diagonal elements of the matrix to 1 + 2x
matrix[i][i+1] = -x #sets the off diagonal elements of the matrix to -x
matrix[i][i-1] = -x
matrix[0][0] = 1+3*x #sets the top left value of the matrix to be 1 + 3x
matrix[-1][-1] = 1+x #sets the bottom right corner of the matrix to be 1 + x
matrix[0][1] = matrix[-1,-2]=-x #sets the final off diagonal elements to -x
if ice == 'yes': #used when one end of the rod is emersed in an ice bath at 0 degrees
matrix[-1][-1] = 1 + 3*x #sets the bottom right corner of the matrix to be 1 + 3x (the same as the top left corner as they are now both boundary conditions)
return matrix,x
def temparray(n): #creates an array to for the inial rod matrix
rod = 20*np.ones( (n,1) )
return rod
def diffusion(n, tmax,Nt,ice='0'): #tmax is the maximum time that the simulation is run for
dt = tmax/Nt #determines the timestep
h=0.5/n #determines the value of h from the length of the rod (50cm) and the number of point in the array
matrix,x = definematrix(h, dt, n)
if ice == 'yes':
matrix,x = definematrix(h, dt, n, ice='yes')
rod = temparray(n)
rodarray = np.linspace(0,0.5,n) #used in plotting the length of the rod
for t in range(Nt):
rod[0][0] += 2*x*1000 #sets the initial value of the rod to 2*x*voltage of the heat reservoir
rod = np.linalg.solve(matrix,rod) #solves the matrix equation to find the rod temperatures after one iteration
if t%(Nt/10) == 0:
lineplot(rodarray,rod,int(tmax*(t/Nt)),'Distance along the rod /m','Temperature /degrees celsius','A graph comparing the temperature along the rod at various times')
plt.show()
return rod
def comparisongraph(n,tmax,Nt,ice='0'): #tmax is the maximum time that the simulation is run for
dt = tmax/Nt #determines the timestep
h=0.5/n #determines the value of h from the length of the rod (50cm) and the number of point in the array
matrix,x = definematrix(h, dt, n)
if ice == 'yes':
matrix,x = definematrix(h, dt, n, ice='yes')
rod = temparray(n)
comparison = rod.transpose()
for t in range(Nt):
rod[0][0] = 2*x*1000
rod = np.linalg.solve(matrix,rod) #solves the matrix equation to find the rod temperatures after one iteration
b = rod.transpose()
comparison = np.concatenate((comparison,b))
comparison = np.delete(comparison,0,axis=0)
colourplot(n,n,comparison,'Distance along rod','Time taken','Comparison of how the temperature changes along the rod and the time increases','Temperature /degrees celcius',tmax,extent='yes')
def lineplot(Xarray,Yarray,label,Xlabel,Ylabel,title):
plt.plot(Xarray,Yarray, label=label)
plt.xlabel(Xlabel)
plt.ylabel(Ylabel)
plt.title(title)
plt.legend()
def gradientplot(array,Ylabel,title,bartitle):
plt.cur_axes = plt.gca()
plt.cur_axes.axes.get_xaxis().set_ticks([])
plt.imshow(array, cmap='jet', vmin=0, extent = [0,17,50,0])
plt.ylabel(Ylabel)
plt.title(title)
plt.colorbar(label=bartitle)
plt.show()
n=300 #number of points in space used
tmax = 20000 #maximum time the simulation is run for
tmax2 = 3600 #the value of tmax used in the snapshot of temperature gradient over the rod distance
Nt = 1000 #number of points in time used
#gradientplot(diffusion(n,tmax2,Nt),'Distance along rod /cm','How the temperature varies along the rod at time %is' %tmax2,'Temperature /degrees celcius')
#print('When there is no heat loss from the far end of the rod')
#diffusion(n,tmax,Nt)
#comparisongraph(n,tmax,300)
#print('When one side of the rod is imersed in a block of ice at 0 degrees celcius')
#diffusion(n,tmax,Nt,ice='yes')
#comparisongraph(n,tmax,300,ice='yes')
|
"""
Create an implementation of the following:
A line of credit product. This is like a credit card except theres no card.
It should work like this:
- Have a built in APR and credit limit
- Be able to draw ( take out money ) and make payments.
- Keep track of principal balance and interest on the line of credit
- APR Calculation based on the outstanding principal balance over real number of days.
- Interest is not compounded, so it is only charged on outstanding principal.
- Keep track of transactions such as payments and draws on the line and when
they occured.
- 30 day payment periods. Basically what this means is that interest will not be
charged until the closing of a 30 day payment period. However, when it is charged,
it should still be based on the principal balance over actual number of days outstanding
during the period, not just ending principal balance.
Couple of Scenarios how it would play out:
Scenario 1:
Someone creates a line of credit for 1000$ and 35% APR.
He draws 500$ on day one so his remaining credit limit is 500$ and his balance is 500$.
He keeps the money drawn for 30 days. He should owe 500$ * 0.35 / 365 * 30 = 14.38$ worth
of interest on day 30. Total payoff amount would be 514.38$
Scenario 2:
Someone creates a line of credit for 1000$ and 35% APR.
He draws 500$ on day one so his remaining credit limit is 500$ and his balance is 500$.
He pays back 200$ on day 15 and then draws another 100$ on day 25. His total owed interest on
day 30 should be 500 * 0.35 / 365 * 15 + 300 * 0.35 / 365 * 10 + 400 * 0.35 / 365 * 5 which is
11.99. Total payment should be 411.99.
"""
class CreditAccount(object):
"""
Account tracking line of credit
Attributes
credit_limit
interest_rate
balance
transactions
"""
def __init__(self, txn_svc, acct_id, rate, limit):
self.txn_svc = txn_svc
self.account_id = acct_id
self.interest_rate = rate
self.credit_limit = limit
self.balance = 0
self.finance_charges = 0.0
def close_30day_period(self):
self.balance = self.balance * self.interest_rate
def show_balance(self):
print 'balance:' + '${0:.2f}'.format(self.balance) + ' acct:' + str(self.account_id)
def show_finance_charges(self):
print 'finance charges:' + '${0:.2f}'.format(self.finance_charges) + ' acct:' + str(self.account_id)
def show_total_payment(self):
print 'Account:' + str(self.account_id) + ' Total Payment:' + '${0:.2f}'.format(self.balance + self.finance_charges)
class Transaction(object):
"""
Track activity on an account
Attributes
account_id
day
amount
"""
def __init__(self, acct_id, day, amount):
self.account_id = acct_id
self.day = day
self.amount = amount
def get_acct(self):
return self.account_id
def get_day(self):
return self.day
def get_amount(self):
return self.amount
class TransactionService(object):
def __init__(self, period):
self.period = period
self.transactions = []
def withdraw(self, acct, day, amount):
print 'Account:' + str(acct.account_id) + ' Withdraw:' + '${0:.2f}'.format(amount)
if acct.credit_limit >= (acct.balance + acct.finance_charges + amount):
acct.balance = acct.balance + amount
t = Transaction(acct.account_id, day, amount)
self.insert_transaction(t)
else:
print 'ERROR: Exceeded Credit Limit'
def payment(self, acct, day, amount):
print 'Account:' + str(acct.account_id) + ' Payment:' + '${0:.2f}'.format(amount)
if 0 <= (acct.balance + acct.finance_charges) - amount:
acct.balance = acct.balance - amount
t = Transaction(acct.account_id, day, 0 - amount)
self.insert_transaction(t)
else:
print 'ERROR: Exceeded Balance Owed'
def insert_transaction(self, txn):
self.transactions.append(txn)
def show_transactions(self, acct_id):
print 'transactions: ' + ' acct:' + str(acct_id) + ' '
for txn in self.transactions:
if txn.get_acct() == acct_id:
print ' day:' + str(txn.get_day()) + ' amt:' + str(txn.get_amount())
def charge_interest(self, acct):
"""
run at the end of the payment period
balance * rate / days in year * days for each balance level
"""
print 'Charge Interest'
interest = 0
start_day_of_balance = 0
balance = 0
for txn in self.transactions:
if txn.get_acct() == acct.account_id:
days = txn.get_day() - start_day_of_balance
interest = balance * acct.interest_rate / 365 * days
start_day_of_balance = txn.get_day()
balance += txn.get_amount()
acct.finance_charges += interest
#print 'txn:' + str(txn.get_day()) + ' days:' + str(days) + ' int:' + str(interest) + ' fin:' + str(acct.finance_charges) + ' firstday:' + str(start_day_of_balance) + ' bal:' + str(balance) + ' amt:' + str(txn.get_amount())
days = self.period - start_day_of_balance
acct.finance_charges += balance * acct.interest_rate / 365 * days
#print 'acct:' + str(acct.account_id) + ' days:' + str(days) + ' int:' + str(interest) + ' fin:' + str(acct.finance_charges) + ' firstday:' + str(start_day_of_balance) + ' bal:' + str(balance) + ' amt:' + str(txn.get_amount())
def reset_period(self):
# preceding period transactions could be archived
self.transactions = []
def test_harness():
ts = TransactionService(30)
acct1 = CreditAccount(ts, 1, 0.30, 1000)
ts.withdraw(acct1, 1, 300)
ts.withdraw(acct1, 5, 300)
ts.withdraw(acct1, 5, 1300)
ts.payment(acct1, 10, 600)
ts.payment(acct1, 10, 600)
acct1.show_balance()
acct2 = CreditAccount(ts, 2, 0.30, 2000)
ts.withdraw(acct2, 10, 300)
acct2.show_balance()
ts.show_transactions(1)
ts.show_transactions(2)
ts.charge_interest(acct1)
acct1.show_balance()
acct1.show_finance_charges()
ts.charge_interest(acct2)
acct2.show_balance()
acct2.show_finance_charges()
acct2.show_total_payment()
ex1 = CreditAccount(ts, 3, 0.35, 1000)
ts.withdraw(ex1, 0, 500)
ts.charge_interest(ex1)
ex1.show_total_payment()
ex2 = CreditAccount(ts, 4, 0.35, 1000)
ts.withdraw(ex2, 0, 500)
ts.payment(ex2, 15, 200)
ts.withdraw(ex2, 25, 100)
ts.charge_interest(ex2)
ex2.show_total_payment()
if __name__ == "__main__":
test_harness()
|
import entity
from utils import Point, rand
def move_north(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to move north one unit.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
if environment.body.contains_point(Point(agent.body.top_left.position[0], agent.body.top_left.position[1] + 1)):
for item in agent.inventory:
item.body.top_left.position[1] += 1
item.body.bottom_right.position[1] += 1
agent.body.top_left.position[1] += 1
agent.body.bottom_right.position[1] += 1
agent.time += 1
return agent
def move_east(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to move east one unit.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
if environment.body.contains_point(Point(agent.body.bottom_right.position[0] + 1, agent.body.bottom_right.position[1])):
for item in agent.inventory:
item.body.top_left.position[0] += 1
item.body.bottom_right.position[0] += 1
agent.body.top_left.position[0] += 1
agent.body.bottom_right.position[0] += 1
agent.time += 1
return agent
def move_south(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to move south one unit.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
if environment.body.contains_point(Point(agent.body.bottom_right.position[0], agent.body.bottom_right.position[1] - 1)):
for item in agent.inventory:
item.body.top_left.position[1] -= 1
item.body.bottom_right.position[1] -= 1
agent.body.top_left.position[1] -= 1
agent.body.bottom_right.position[1] -= 1
agent.time += 1
return agent
def move_west(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to move west one unit.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
if environment.body.contains_point(Point(agent.body.top_left.position[0] - 1, agent.body.top_left.position[1])):
for item in agent.inventory:
item.body.top_left.position[0] -= 1
item.body.bottom_right.position[0] -= 1
agent.body.top_left.position[0] -= 1
agent.body.bottom_right.position[0] -= 1
agent.time += 1
return agent
def pickup_food(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to pickup food.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
foods = filter(lambda x: isinstance(x, entity.Food), entities)
if not agent.holding_food:
for food in foods:
if agent.body.contains_rectangle(food.body) and food.interactable:
agent.inventory.append(food)
food.interactable = False
agent.holding_food = True
break
agent.time += 1
return agent
def drop_food(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to drop food.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
nest = filter(lambda x: isinstance(x, entity.Nest), entities)[0]
if agent.holding_food:
for item in agent.inventory:
agent.inventory.remove(item)
if nest.body.contains_rectangle(agent.body):
nest.food_count += 1
else:
item.interactable = True
agent.holding_food = False
agent.time += 1
return agent
def random_walk(agent=None, entities=None, environment=None):
"""
Behavior that causes an agent to walk in a random direction for one time step.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
random_direction = rand.randint(0, 3)
if random_direction == 0:
return move_north(agent, entities, environment)
elif random_direction == 1:
return move_east(agent, entities, environment)
elif random_direction == 2:
return move_south(agent, entities, environment)
elif random_direction == 3:
return move_west(agent, entities, environment)
return agent
def return_home(agent=None, entities=None, environment=None):
"""
Behavior (naive) that causes an agent to return to the nest.
:param agent: The agent to perform the behavior.
:param entities: A list of entities in the simulation.
:param environment: The environment containing the agent.
:return: The updated agent.
"""
nest = filter(lambda x: isinstance(x, entity.Nest), entities)[0]
agent.time += int(agent.body.top_left.distance_to(nest.body.top_left))
agent.body.top_left.position[1] = (nest.body.top_left.position[1] + nest.body.bottom_right.position[1]) / 2
agent.body.bottom_right.position[0] = (nest.body.top_left.position[0] + nest.body.bottom_right.position[0]) / 2
agent.body.bottom_right.position[1] = (nest.body.top_left.position[1] + nest.body.bottom_right.position[1]) / 2
agent.body.top_left.position[0] = (nest.body.top_left.position[0] + nest.body.bottom_right.position[0]) / 2
return agent
|
from machine import Pin, ADC, PWM #importing Pin, ADC and PWM classes
from time import sleep #importing sleep class
led=PWM(Pin(14), 5000) #GPIO14 set as pin and 5000Hz as frequency
potentiometer=ADC(Pin(12)) #creating potentiometer object
potentiometer.width(ADC.WIDTH_12BIT) #setting ADC resolution to 10 bit
potentiometer.atten(ADC.ATTEN_11DB) #3.3V full range of voltage
while True:
potentiometer_value=potentiometer.read() #reading analog pin
print(potentiometer_value)
led.duty(potentiometer_value) #setting duty cycle value as that of the potentiometer value
sleep(0.1)
|
#!/usr/bin/env python
# coding: utf-8
# # Repeat 노드
# In[9]:
import numpy as np
# # 순전파
# D = 8
# N = 7
# x = np.random.rand(1,D) # (1,8)
# # x = np.random.rand(D,).reshape(1,-1) # (1,8)
# print(x,x.shape)
# print('-'*70)
# y = np.repeat(x,N,axis=0) # 수직(행) 방향, axis=0
# print(y,y.shape) # (7, 8)
# # In[15]:
# # 역전파 : sum
# dy = np.random.rand(N,D)
# print(dy,dy.shape) # (7, 8)
# print('-'*70)
# dx = np.sum(dy,axis=0,keepdims=True) # 수직방향 합, keepdims=True이면 2차원, False이면 1차원
# print(dx,dx.shape) # (1,8)
# # In[18]:
# a = np.array([[1,2,3,4]])
# np.sum(a, keepdims=True) # 2차원 유지
# # ### Sum 노드
# # In[22]:
# # 순전파
# D,N = 8,7
# x = np.random.rand(N,D)
# print(x,x.shape) # (7,8)
# print('-'*70)
# y = np.sum(x,axis=0,keepdims=True) # 수직방향 합, keepdims=True이면 2차원, False이면 1차원
# print(y,y.shape)
# # In[23]:
# # 역전파
# dy = np.random.rand(1,D) # (1,8)
# print(dy,dy.shape)
# print('-'*70)
# dx = np.repeat(dy,N,axis=0) # 수직(행) 방향, axis=0
# print(dx,dx.shape) # (7, 8)
# ### MatMul 노드
# In[24]:
class MatMul:
def __init__(self,W):
self.params = [W]
self.grads = [np.zeros_like(W)]
self.x = None
def forward(self,x):
W, = self.params
out = np.dot(x,W)
self.x = x
return out
def backward(self,dout):
W = self.params
dx = np.dot(dout,W.T)
dw = np.dot(self.x.T,dout)
self.grads[0][...] = dw # 깊은복사
return dx
# In[27]:
# a = np.array([1, 2, 3])
# b = np.array([4, 5, 6])
# print(hex(id(a)),hex(id(b)))
# a = b # 얕은 복사
# print(a)
# print(hex(id(a)),hex(id(b)))
# id(a) == id(b)
# In[28]:
# a = np.array([1, 2, 3])
# b = np.array([4, 5, 6])
# a[...] = b # 깊은 복사
# print(a)
# print(hex(id(a)),hex(id(b)))
# id(a) == id(b)
# In[31]:
# # np.zeros_like
# a = np.arange(12).reshape(3,4)
# b = np.zeros_like(a)
# b
# ### 시그모이드 계층
# In[32]:
class Sigmoid:
def __init__(self):
self.params, self.grads = [],[]
self.out = None
def forward(self,x):
out = 1 / (1 + np.exp(-x))
self.out = out
return out
def backward(self,dout):
dx = dout*self.out*(1 - self.out) # 공식 도출은 참고서적 참조
return dx
### ReLU 계층
class ReLU:
def __init__(self):
self.params, self.grads = [],[]
self.mask = None
self.out = None
def forward(self,x):
self.mask = (x <= 0) # x가 0 이하일 경우 0으로 변경
out = x.copy()
out[self.mask] = 0
return out
def backward(self,dout):
dout[self.mask] = 0 # x가 0 이하일 경우 0으로 변경
dx = dout
return dx
# ### Affine 계층 : MatMul 노드에 bias를 더한 계층, X*W + b
# In[33]:
class Affine:
def __init__(self,W,b):
self.params = [W,b]
self.grads = [np.zeros_like(W),np.zeros_like(b)]
self.x = None
def forward(self,x):
W , b = self.params
out = np.dot(x,W) + b
self.x = x
return out
def backward(self,dout):
W, b = self.params
dx = np.dot(dout,W.T)
dw = np.dot(self.x.T,dout)
db = np.sum(dout,axis=0)
self.grads[0][...] = dw # 깊은복사
self.grads[1][...] = db # 깊은복사
return dx
# ## Softmax with Loss 계층
# In[35]:
class SoftmaxWithLoss:
def __init__(self):
self.params,self.grads=[],[]
self.y = None # softmax의 출력값
self.t = None # 정답 레이블
def softmax(self,x):
if x.ndim == 2:
x = x - x.max(axis=1, keepdims=True) # nan출력을 방지
x = np.exp(x)
x /= x.sum(axis=1,keepdims=True)
elif x.ndim == 1:
x = x - np.max(x)
x = np.exp(x) / np.sum(np.exp(x))
return x
# https://smile2x.tistory.com/entry/softmax-crossentropy-%EC%97%90-%EB%8C%80%ED%95%98%EC%97%AC
def cross_entropy_error(self,y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 정답 데이터가 원핫 벡터일 경우 정답 레이블 인덱스로 변환
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size # 1e-7은 log(0)으로 무한대가 나오는걸 방지
def forward(self, x, t):
self.t = t
self.y = self.softmax(x)
# 정답 레이블이 원핫 벡터일 경우 정답의 인덱스로 변환
if self.t.size == self.y.size:
self.t = self.t.argmax(axis=1)
loss = self.cross_entropy_error(self.y,self.t)
return loss
def backward(self,dout=1):
batch_size = self.t.shape[0]
# dx = (self.y - self.t)/batch_size # 순수 Softmax계층 일경우
dx = self.y.copy()
dx[np.arange(batch_size), self.t] -= 1
dx *= dout
dx = dx / batch_size
return dx
# In[36]:
# # softmax 구현시에 지수값이 크면 오버플로발생으로 nan이 나오는 것을 방지하기 위해 입력 값의 촤대값을 빼주어 사용한다
# a = np.array([1010,1000,990])
# print(np.exp(a)) # [inf inf inf] , 무한대 값, 오버플로우 발생
# x = np.exp(a)/np.sum(np.exp(a))
# print(x) # [nan nan nan]
# c = np.max(a)
# print(a - c)
# x2 = np.exp(a - c)/np.sum(np.exp(a - c))
# print(x2) # [9.99954600e-01 4.53978686e-05 2.06106005e-09]
# ### 가중치 갱신
# In[38]:
# 확률적 경사하강법(Stochastic Gradient Descent)
class SGD :
def __init__(self,lr=0.01):
self.lr = lr
def update(self,params,grads):
for i in range(len(params)):
params[i] -= self.lr*grads[i]
# In[ ]:
class Adam:
'''
Adam (http://arxiv.org/abs/1412.6980v8)
'''
def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):
self.lr = lr
self.beta1 = beta1
self.beta2 = beta2
self.iter = 0
self.m = None
self.v = None
def update(self, params, grads):
if self.m is None:
self.m, self.v = [], []
for param in params:
self.m.append(np.zeros_like(param))
self.v.append(np.zeros_like(param))
self.iter += 1
lr_t = self.lr * np.sqrt(1.0 - self.beta2**self.iter) / (1.0 - self.beta1**self.iter)
for i in range(len(params)):
self.m[i] += (1 - self.beta1) * (grads[i] - self.m[i])
self.v[i] += (1 - self.beta2) * (grads[i]**2 - self.v[i])
params[i] -= lr_t * self.m[i] / (np.sqrt(self.v[i]) + 1e-7)
# https://dalpo0814.tistory.com/29
|
"""Create sequence of random numbers and plot with matplotlib.pyplot
Instructions: to get true random numbers, you should import "numpy",
a number-crunching package on which visual is based. Numpy has several
subpackages including "linalg" for doing linear algebra and "random"
for doing random number generation. To access high quality random
numbers you want to add
import numpy.random
Here I am only using uniform float random numbers on the interval [0,1),
so I only import the routine "random_sample" It can be used to generate
a single random number or a whole series of them.
Antonio Cancio
Phys 336/536
March 17, 2020
"""
import numpy as np
import matplotlib.pyplot as plt
maxPoints = 1000
# Doing this one step at a time would be slow, but possible
print("Scalar method of generating random number sequence\nUniform distribution")
iList = []
xList = []
for i in range(maxPoints):
x = np.random.random_sample()
iList.append(i)
xList.append(x)
# print(i, x)
plt.plot(iList, xList, color="red", label="list", linestyle="None", marker=".")
# generate sequence that is maxPoints long and store in an array
print("Array method of generating random number sequence\nUniform distribution")
iArray = np.arange(0, maxPoints, 1) # array of integers
xArray = np.random.random_sample(maxPoints) # array of random numbers
plt.plot(iArray, xArray, color="blue", label="array", linestyle="None", marker=".")
plt.ylabel("i")
plt.xlabel("Number")
plt.legend(loc="upper right", framealpha=0.96)
plt.show()
|
import imdb
import requests
from bs4 import BeautifulSoup as bs
from docx import Document
from docx.shared import *
document=Document()
# Create the object that will be used to access the IMDb's database.
ia = imdb.IMDb() # by default access the web.
# Search for a movie (get a list of Movie objects).
m_result = ia.search_movie(input('enter a movie name:\n'))
# for item in m_result:
movie_id=m_result[0].movieID
url='http://www.imdb.com/title/tt'+str(movie_id)+'/'
#print(url)
try:
source=requests.get(url).text
soup=bs(source,'lxml')
html=soup.prettify()
heading=soup.title.text
document.add_heading(heading,0).bold = True
bodi=soup.body.find('div',class_='summary_text')
document.add_heading('Description:', level=1)
document.add_paragraph(bodi.text.strip())
#print('description:',bodi.text.strip())
diractor=soup.body.find('span',class_='itemprop',itemprop='name')
#print('Director:',diractor.text)
document.add_heading('Director:', level=1)
document.add_paragraph(bodi.text.strip())
rating=soup.body.find('span',itemprop='ratingValue')
#print('Rating:',rating.text+'/10')
actors=soup.body.find('div',class_='article',id='titleCast').find_all('span',class_='itemprop',itemprop='name')
charactors=soup.body.find('div',class_='article',id='titleCast').find_all('td',class_='character')
print()
#print('Cast:')
document.add_heading('Cast:', level=1)
body=''
for i in range(len(charactors)):
body=body+actors[i].text.strip()+' as '+charactors[i].text.strip()+'\n'
document.add_paragraph(body)
print()
story_head=soup.body.find('div',class_='article',id='titleStoryLine').find('h2')
#print(story_head.text,':\n')
document.add_heading(story_head.text, level=1)
story_body=soup.body.find('div',class_='article',id='titleStoryLine').find('div',class_='inline canwrap')
#print(story_body.text.strip())
document.add_paragraph(story_body.text.strip())
genres=soup.body.find('div',class_='article',id='titleStoryLine').find('div',class_='see-more inline canwrap',itemprop='genre').find_all('a')
#print('Genere:')
document.add_heading('Genere:', level=1)
for g in genres:
#print(g.text,)
document.add_paragraph(g.text)
print()
release_date=soup.body.find('div',class_='article',id='titleDetails').find_all('div',class_='txt-block')
for i in range(2,len(release_date)-2):
#print(release_date[i].text.replace('See more »','').replace('Show more on','').replace(' IMDbPro »','').strip())
document.add_paragraph(release_date[i].text.replace('See more »','').replace('Show more on','').replace(' IMDbPro »','').strip())
document.add_page_break()
document.save('movie_data.docx')
except Exception as e:
print (e)
|
from translate import Translator
def main():
your_lang = str(input("Enter Your Language : "))
convert_lang = str(input("Translate " +your_lang+ " to : "))
words = str(input("Enter word to be converted to " +convert_lang + " : "))
translator = Translator(from_lang = your_lang,to_lang = convert_lang)
translate = translator.translate(words)
print(translate)
restart = input("Press r to Restart : ")
if (restart == "r"):
main()
main()
|
import random
def welcome():
pass
def pick():
with open('words.txt') as f:
lines = f.readlines()
word = random.choice(lines).strip()
return word
def guess(char, word, placeholder, attempts):
p_list = list(placeholder)
if char in word:
for i in range(len(word)):
if char == word[i]:
p_list[i] = char
else:
attempts -= 1
return ''.join(p_list), attempts
def play(word):
placeholder = '-' * len(word)
attempts = 10
while attempts > 0:
user_guess = input("Guess Letter: ").capitalize()
placeholder, attempts = guess(user_guess, word, placeholder, attempts)
print(placeholder)
if placeholder == word:
print('Win')
return True
print("Attempts: ", attempts)
return False
def main():
welcome()
while True:
word = pick()
win = play(word)
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 18:06:29 2021
"""
def construct_ordered_binaries(n: int):
if n == 1:
return ['0', '1']
ordered_binaries_previous = construct_ordered_binaries(n - 1)
ordered_binaries = ['0' + p for p in ordered_binaries_previous] + \
['1' + p for p in ordered_binaries_previous[::-1]]
return ordered_binaries
if __name__=="__main__":
n = 4
ordered_binaries = construct_ordered_binaries(n)
print(ordered_binaries)
|
def print_depth(data, lvl=1):
if type(data) is not dict:
return None
for k, v in data.items():
print("{0} {1}".format(k, lvl))
if type(v) is dict:
print_depth(v, lvl=lvl+1)
|
class TreeNode:
def __init__(self, data, parent = None):
self.data = data #data being the sugar in this case
self.children = [] #list to store children tree nodes
self.parent = parent #place to store parent if applicable
self.depth = 0 #depth just refers to length of the structure
def addOdd(self, sugar):
#root in this case is parent, sugar is potential child
#odd sugar ruleset
if sugar == 'GlcA2S':
if self.data == 'GlcNS' and self.depth == 2 or self.depth == 0:
#GlcA2S mostly exists in 3rd position, but can potentially exist in 1st position so we have an edge case for it
return 1
else:
return 0
elif sugar == 'IdoA':
if (self.data == 'GlcNS' or self.data == 'GlcNS6S') and self.depth == 2: #IdoA check only happens for 3rd position
if self.parent.data != 'GlcA2S':
return 1
else:
return 0
else:
return 0
elif sugar == 'IdoA2S':
if (self.data == 'GlcNS' or self.data == 'GlcNS6S') and self.depth < (size - 3): #compounds can only end with GlcA
if self.depth == 2: #to deal with GlcA2S 1st position edge case. We first check if we are at 3rd position
if self.parent.data != 'GlcA2S': #check if 1st postion is GlcA2S for GlcA2S edge case
return 1
else:
return 0
else:
return 1
else:
#this entire check is for the edge case where an IdoA2S can potentially transform 2 sites at around 50% yield.
if (size == 7 or size == 9) and (self.data == 'GlcNS' or self.data == 'GlcNS6S') and self.depth < (size - 1) and self.parent.data != 'GlcA2S' and self.parent.data == 'IdoA2S':
return 1
else:
return 0
elif sugar == 'GlcA':
if self.depth == 2: #refer to IdoA2S above for why this exists
if self.parent.data != 'GlcA2S': #check if 1st position sugar for GlcA2S edge case since it cannot be GlcA-GlcNS-GlcA2S-Tag
return 1
else:
return 0
else:
return 1
else:
return 0
def addEven(self, sugar):
#root in this case is parent, sugar is potential child
#even sugar ruleset
if sugar == 'GlcNAc':
if self.data == 'GlcA':
return 1
else:
return 0
elif sugar == 'GlcNS':
if (self.data == 'GlcA' or self.data == 'GlcA2S' or self.data == 'IdoA' or self.data == 'IdoA2S'):
return 1
else:
return 0
elif sugar == 'GlcNS6S':
if (self.data == 'GlcA' or (self.data == 'GlcA2S' and self.depth > 3) or self.data == 'IdoA' or self.data == 'IdoA2S'):
return 1
else:
return 0
elif sugar == 'GlcNAc6S':
if self.data == 'GlcA':
return 1
else:
return 0
elif sugar == 'GlcNS6S3S':
if self.data == 'IdoA2S' and self.checkSulfation():
return 1
else:
return 0
def checkSulfation(self):
#Function to through the path to see if there's a GlcNS6S3S
if self.parent is not None:
if self.data == 'GlcNS6S3S':
return 0
else:
if self.parent.checkSulfation():
return 1
else:
return 1
def addChild(self, n):
self.depth = n
#determine which sugar to add. the n + 1 is there because we always start with an odd sugar
if (n + 1) % 2 == 1: #if odd
for oddSugar in odd:
if self.addOdd(oddSugar):
self.children.append(TreeNode(oddSugar, self))
elif (n + 1) % 2 == 0: #if even
for evenSugar in even:
if self.addEven(evenSugar):
self.children.append(TreeNode(evenSugar, self))
def printTree(self, string = ""):
#function to print tree in console.
if self.children:
string += self.data + "-"
for child in self.children:
child.printTree(string)
else:
string += self.data
if string.split('-').pop() == "":
#check if last portion of string is ''. Will figure out why it keeps showing up at the end but until then this if statement is to catch it if it happens.
return 0
else:
#only print if longer than configed size
if len(string.split('-')) > size:
stringList = string.split('-')
reverseList = stringList[::-1]
print('-'.join(reverseList))
def buildTree(root, n = 0):
#n represents the level of depth (aka structure length)
if n == size:
#ends tree building once n equals sign
return 0
else:
root.addChild(n)
for child in root.children:
buildTree(child, n + 1)
return root
#odd sugars
odd = ['GlcA2S', 'GlcA', 'IdoA', 'IdoA2S']
#even sugars
even = ['GlcNAc6S', 'GlcNS6S', 'GlcNAc', 'GlcNS', 'GlcNS6S3S']
#config
size = 8 #length of a structure
tag = 'Az' #set initial tag
root = TreeNode(tag)
root = buildTree(root)
root.printTree() |
import datetime
print('Is Today Monday?')
today = datetime.date.today()
if today.weekday() == 1:
print('Yes.')
else:
print('No.')
|
def piramida_do_lewej(wysokosc):
for poziom in range(wysokosc):
print("#" * (2*poziom+1))
piramida_do_lewej(5)
def piramida(wysokosc):
for poziom in range(wysokosc):
print((" " * (wysokosc-poziom)),"#" * (2*poziom+1))
piramida(5) |
#!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
line = line.strip()
s = line.split(",")
country, market = line.split(",")
results = [market, "1"]
print("\t".join(results))
|
# based on the big 5 from experimentall psychology +evil/good +race relations
def get_race_character(race):
if race == "human":
race_character = CHARACTER_HUMAN
elif race == "elf":
race_character = CHARACTER_ELF
elif race == "dwarf":
race_character = CHARACTER_DWARF
elif race == "hobbit":
race_character = CHARACTER_HOBBIT
return(race_character)
def trim_traits(full_list):
opposite_traits = (
("Nervous","Resilient"),
("Outgoing","Solitary"),
("Agreeable","Stubborn"),
("Organized","Lazy"),
("Good","Evil"),
("High IQ","Low IQ"),
)
for pair in opposite_traits:
if pair[0] in full_list and pair[1] in full_list:
full_list.remove(pair[0])
full_list.remove(pair[1])
return(full_list)
CHARACTER_HUMAN = {
"Nervous": 5,
"Resilient": 5,
"Curious": 5,
"Simpleton": 5,
"Outgoing": 5,
"Solitary": 5,
"Agreeable": 5,
"Stubborn": 5,
"Organized": 5,
"Lazy": 5,
"High IQ" : 4,
"Low IQ" : 4,
"Good": 5,
"Evil": 5,
"Human hater": 1,
"Elf hater": 3,
"Dwarf hater": 3,
"Hobbit hater": 2,
}
CHARACTER_ELF = {
"Nervous": 1,
"Resilient": 6,
"Curious": 6,
"Simpleton": 1,
"Outgoing": 3,
"Solitary": 2,
"Agreeable": 5,
"Stubborn": 1,
"Organized": 5,
"Lazy": 4,
"High IQ" : 3,
"Low IQ" : 2,
"Good": 5,
"Evil": 1,
"Human hater": 3,
"Elf hater": 0,
"Dwarf hater": 6,
"Hobbit hater": 1,
}
CHARACTER_DWARF = {
"Nervous": 6,
"Resilient": 1,
"Curious": 1,
"Simpleton": 5,
"Outgoing": 5,
"Solitary": 1,
"Agreeable": 1,
"Stubborn": 5,
"Organized": 2,
"Lazy": 5,
"High IQ" : 2,
"Low IQ" : 3,
"Good": 1,
"Evil": 5,
"Human hater": 1,
"Elf hater": 6,
"Dwarf hater": 0,
"Hobbit hater": 2,
}
CHARACTER_HOBBIT = {
"Nervous": 4,
"Resilient": 4,
"Curious": 6,
"Simpleton": 3,
"Outgoing": 2,
"Solitary": 6,
"Agreeable": 6,
"Stubborn": 3,
"Organized": 4,
"Lazy": 4,
"High IQ" : 2,
"Low IQ" : 2,
"Good": 4,
"Evil": 4,
"Human hater": 1,
"Elf hater": 1,
"Dwarf hater": 1,
"Hobbit hater": 0,
} |
def computepay(h,r):
h = float(h)
r = float(r)
if h>40:
p = 40*r + ((h-40)*1.5*r)
return p
hrs = input("Enter Hours:")
rate = input("Enter rate per hour:")
p = computepay(hrs,rate)
print("Pay",p)
|
from typing import Any, Dict, List, Set, Tuple
object_1 = {
"name": "John",
"age": 30,
"address": {
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
object_2 = {
"name": "John",
"age": 30,
"address": {
"city": "Boston",
"state": "MA",
"zip": "02108"
}
}
def deep_equals(obj1: Any, obj2: Any) -> bool:
if type(obj1) != type(obj2):
return False
if isinstance(obj1, Dict):
if set(obj1.keys()) != set(obj2.keys()):
return False
for key in obj1.keys():
if not deep_equals(obj1[key], obj2[key]):
return False
return True
elif isinstance(obj1, (List, Tuple, Set)):
if len(obj1) != len(obj2):
return False
for elem1, elem2 in zip(obj1, obj2):
if not deep_equals(elem1, elem2):
return False
return True
else:
return obj1 == obj2
result = deep_equals(object_1, object_2)
print(result) # prints False |
i=63
print(i)
print('this is my test')
r=input('please enter radius')
r=float(r)
a=3.14*r*r
print('the area is ',a) |
def do_calculation():
command=input("Enter your command")
print("lets " + command + " some numbers")
input1 = input("Number 1>")
input2 = input("Number 2>")
number1 = int(input1)
number2 = int(input2)
if command == "+":
result = number1 + number2
elif command == "subtract":
result = number1 - number2
output = str(result)
if command == "add":
print(input1 + " + " + input2 + " = " + output)
elif command == "subtract":
print(input1 + " - " + input2 + " = " + output)
else:
print("This is the end")
do_calculation() |
from tkinter import *
import tkinter.messagebox
#you have to import messagebox because it is a submodule and submodules arent automatically imported
base = Tk()
#first parameter allows you to change window title
tkinter.messagebox.showinfo("Joelle's Program", "Soy un ouevo")
answer = tkinter.messagebox.askquestion("Question 1", "Do you like chili flakes?")
if answer == "yes":
print("You added 20 chili flakes to your inventory!")
base.mainloop() |
from tkinter import *
def doNothing():
print("ok ok I won't...")
# ------------ Main Menu ------------- #
base = Tk()
myMenu = Menu(base)
base.config(menu=myMenu)
# .config configures menu for you
# parameter name is menu
subMenu = Menu(myMenu) # subMenu goes INSIDE of menu
myMenu.add_cascade(label="File", menu=subMenu) # cascade is a drop down menu
subMenu.add_command(label="New Project...", command=doNothing) # adds elements to click under the drop down menu
subMenu.add_command(label="New ...", command=doNothing)
subMenu.add_separator() # just for user to see what menu items are related and what are not
# separator looks like a faint line that separates topics
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(myMenu)
# create another item in main menu
myMenu.add_cascade(label="Edit", menu=editMenu)
# add it as drop down functionality
editMenu.add_command(label="Redo", command=doNothing)
# ***************** Toolbar **************** #
toolbar = Frame(base)
#button(location, text, command)
InsertButt = Button(toolbar, text="Insert Image", command=doNothing)
#padding (pad) adds space between buttons
InsertButt.pack(side=LEFT, padx=2, pady=2)
printButt = Button(toolbar, text="Print", command=doNothing)
printButt.pack(side=LEFT, padx=2, pady=2)
#.pack() allows things to be displayed
toolbar.pack(side=TOP, fill=X)
#use fill X so that the toolbar is across the top no matter how large you create the window
# //////////////// Status Bar //////////////// #
status = Label(base, text="Preparing to do nothing...", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)
#bd stands for boarder
base.mainloop() |
n = 25
threshold = 0.001
approximation = n/2 # Start with some or other guess at the answer
count = 0
while True:
count += 1
better = float(approximation + n/approximation) / 2
if abs(approximation - better) < threshold:
print("better %s" % better)
break
approximation = better
print("Count %s" % count)
|
def htoi(str):
if str[0:2].lower() == "0x":
str = str[2:]
ret = 0
dig = len(str)
for c in str:
dig -= 1
add = 0
if 48 <= ord(c) and ord(c) <= 57:
add = (ord(c) - 48)
elif 65 <= ord(c) and ord(c) <= 70:
add = (ord(c) - 55)
elif 97 <= ord(c) and ord(c) <= 102:
add = (ord(c) - 87)
else:
raise ValueError("!")
ret += add * (16 ** dig)
return ret
if __name__ == "__main__":
print(htoi(input()))
|
import homework08
l = int(input("请输入长度:"))
w = int(input("请输入宽度:"))
# 实例化类
r = homework08.Rectangle(l, w)
# 求周长
r.get_perimeter()
# 求面积
r.get_area()
|
class Solution:
def Fibonacci(self, n):
if n == 0:
return 0
elif n == 1:
return 1
else:
res = [0]*(n+1)
res[0] = 0
res[1] = 1
res[2] = 1
for i in range(2, n + 1):
res[i] = res[i - 1] + res[i - 2]
print(res,res[n])
return res[n]
if __name__ == "__main__":
solution = Solution()
solution.Fibonacci(2) |
value = input()
try:
type_value = type(value)
if type_value == 'str':
value = int(value)
else:
pass
except ValueError:
print('Буквы в цифры не преобразовать!')
finally:
print('Дошел до finally')
# test
# ghbdtn - error
# 567 - all right
print(value) |
class PriorityQueue:
def __init__(self,element):
self.queue = [element]
def add(self, element):
i = 0
if self.isEmpty():
self.queue = [element]
return
while i < len(self.queue) and element[1] < self.queue[i][1]:
i += 1
self.queue.insert(i, element)
def pop(self):
return self.queue.pop()[0]
def contains(self,element):
return element in self.queue
def isEmpty(self):
return len(self.queue) == 0
|
import turtle
import keyboard
class Lefthandrule(turtle.Turtle):
def __init__(self, finish, walls):
turtle.Turtle.__init__(self)
self.shape("turtle")
self.color("red")
self.setheading(270)
self.penup()
self.speed(0)
self.finish = finish
self.walls = walls
self.hideturtle()
def try_up(self, not_goal):
x_cor = round(self.xcor(), 0)
y_cor = round(self.ycor(), 0)
if [x_cor, self.ycor()] in self.finish:
return False
# end_program()
if self.heading() == 90:
if [x_cor - 24, y_cor] in self.walls:
if [x_cor, y_cor + 24] not in self.walls:
self.forward(24)
else:
self.right(90)
else:
self.left(90)
self.forward(24)
return True
def try_down(self, not_goal):
x_cor = round(self.xcor(), 0)
y_cor = round(self.ycor(), 0)
if [x_cor, y_cor] in self.finish:
return False
# end_program()
if self.heading() == 270:
if [x_cor + 24, y_cor] in self.walls:
if [x_cor, y_cor - 24] not in self.walls:
self.forward(24)
else:
self.right(90)
else:
self.left(90)
self.forward(24)
return True
def try_left(self, not_goal):
x_cor = round(self.xcor(), 0)
y_cor = round(self.ycor(), 0)
if [self.xcor(), self.ycor()] in self.finish:
return False
# end_program()
if self.heading() == 0:
if [x_cor, y_cor + 24] in self.walls:
if [x_cor + 24, y_cor] not in self.walls:
self.forward(24)
else:
self.right(90)
else:
self.left(90)
self.forward(24)
return True
def try_right(self, not_goal):
x_cor = round(self.xcor(), 0)
y_cor = round(self.ycor(), 0)
if [self.xcor(), self.ycor()] in self.finish:
return False
# end_program()
if self.heading() == 180:
if [x_cor, y_cor - 24] in self.walls:
if [x_cor - 24, y_cor] not in self.walls:
self.forward(24)
else:
self.right(90)
else:
self.left(90)
self.forward(24)
return True
|
import RPi.GPIO as GPIO #Import Raspberry Pi GPIO library
import I2C_driver as LCD
import time
GPIO.setwarnings(False) #Ignore warning for now
GPIO.setmode(GPIO.BOARD) #Use physical pin numbering
LED=11
Switch =15
GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
#Set pin 15 to be an input pin and set initial value to be pulled low (off)
GPIO.setup(Switch, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
mylcd= LCD.lcd()
switch = 0
pre_switch = 0
while True:
#
if GPIO.input(Switch) == GPIO.HIGH:
time.sleep(0.2)
switch=~switch
if pre_switch!=switch:
mylcd.lcd_clear()
if switch==0:
mylcd.lcd_display_string("LED ON",1)
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)
mylcd.lcd_display_string("LED OFF",1)
pre_switch=switch
|
def reverseString(string):
print string[2:0:-1]
return string[::-1]
def main():
reverseString("HelloWorld")
main() |
import random
games_played = 1
print("Welcome to my game! Here are the rules:")
print("")
print("You are an international student and your goal is to reach the CMUQ campus. In order to do so, you will have to pass from four stages. In each stage you will get to choose between two options, but only one of them is the correct choice...\n")
while True:
ready = input("\nAre you ready to play? (yes/no): ")
if ready == "yes":
first_choice = input("\n1st stage: You arrive at your local airport but there is a long queue for security checking. Do you skip or wait (skip/wait): ")
if first_choice == "wait":
print("\nWell done, you proceed to the next stage!")
second_level = input("Second stage: You realize that you are late and you might miss your flight. Do you walk to the gate or run? (walk/run): ")
if second_level == "run":
print("\nWell done.. you go to stage three")
third_level = input("Third stage: You arrive at the airport in Qatar and you have to choose between two gates to go through. (gate 1/gate 2) : ")
if third_level == "gate 2":
print("\nWell done..you move on")
fourth_level = input("Fourth Stage: Finally, you have to choose between the taxi or the metro to get to campus. (taxi/metro) ")
if fourth_level == "taxi":
print("\nYou have successfully reached the CMUQ campus. You win!")
print("You won after "+str(games_played))
print("attempts")
break
elif fourth_level == "metro":
print("\nwrong option, but it is not over yet. The driver challenges you to a game of rock/paper/scissors. If you win, he'll drop you off', else you lose")
while True:
def choose_option():
user_choice = input("choose either rock,paper, or scissors: ")
return user_choice
def computer_option():
comp_choice = random.randint(1,3)
return comp_choice
user_choice = choose_option()
comp_choice = computer_option()
if user_choice == "rock":
if comp_choice == 1:
print("\nYou chose rock. The driver chose rock. You tied")
if comp_choice == 2:
print("\nYou chose rock. The driver chose paper.You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 3:
print("\nYou chose rock. The driver chose scissors. You win.")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if user_choice == "paper":
if comp_choice == 1:
print("\nYou chose paper. The driver chose rock. You win ")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 2:
print("\nYou chose paper. The driver chose paper. You tied")
if comp_choice == 3:
print("\nYou chose paper. The driver chose scissors. You lose.")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if user_choice == "scissors":
if comp_choice == 1:
print("\nYou chose scissors. The driver chose rock. You lose.")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 2:
print("\nYou chose scissors. The driver chose paper. You win")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 3:
print("\nYou chose scissors. The driver chose scissors. You tied")
elif third_level == "gate 1":
print("\nThis gate is under maintainance and is letting a limited number of people through. A number between 1 and 5 will be generated, if this number is even, you proceed, else you lose")
generate_number = input("Generate number? (yes): ")
if generate_number == "yes":
answer = random.randint(1,5)
print(answer)
if answer in [1,3,5]:
print("\nOdd number. You are now stuck at this gate and can't get through. You lost.")
games_played += 1
if answer in [2,4]:
print("\nEven number. You move on")
fourth_level = input("Fourth Stage: Finally, you have to choose between the taxi or the metro to get to campus. (taxi/metro) ")
if fourth_level == "taxi":
print("\nYou have successfully reached the CMUQ campus. You win!")
print("You won after "+str(games_played))
print("attempts")
break
elif fourth_level == "metro":
print("\nwrong option, but it is not over yet. The driver challenges you to a game of rock/paper/scissors. If you win, he'll drop you off', else you lose")
while True:
def choose_option():
user_choice = input("choose either rock,paper, or scissors: ")
return user_choice
def computer_option():
comp_choice = random.randint(1,3)
return comp_choice
user_choice = choose_option()
comp_choice = computer_option()
if user_choice == "rock":
if comp_choice == 1:
print("\nYou chose rock. The driver chose rock. You tied")
if comp_choice == 2:
print("\nYou chose rock. The driver chose paper. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 3:
print("\nYou chose rock. The driver chose scissors. You win.")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if user_choice == "paper":
if comp_choice == 1:
print("\nYou chose paper. The driver chose rock. You win ")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 2:
print("\nYou chose paper. The driver chose paper. You tied")
if comp_choice == 3:
print("\nYou chose paper. The driver chose scissors. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if user_choice == "scissors":
if comp_choice == 1:
print("\nYou chose scissors. The driver chose rock. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 2:
print("\nYou chose scissors. The driver chose paper. You win")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 3:
print("\nYou chose scissors. The driver chose scissors. You tied")
if second_level == "walk":
print("\nThats the wrong choice, but its not over yet. If you answer the following question correctly, the flight attendent will let you in, otherwise you lose")
trivia = input("Which country will host the 2020 FIFA World Cup?: ")
if trivia == "Qatar":
print("\nCorrect! You move on")
third_level = input("Third stage: You arrive at the airport in Qatar and you have to choose between two gates to go through. (gate 1/gate 2) : ")
if third_level == "gate 2":
print("\nYou proceed to the next level!")
fourth_level = input("Fourth Stage: Finally, you have to choose between the taxi or the metro to get to campus. (taxi/metro) ")
if fourth_level == "taxi":
print("\nYou have successfully reached the CMUQ campus. You win!")
print("You won after "+str(games_played))
print("attempts")
break
elif fourth_level == "metro":
print("\nwrong option, but it is not over yet. The driver challenges you to a game of rock/paper/scissors. If you win, he'll drop you off', else you lose")
while True:
def choose_option():
user_choice = input("choose either rock,paper, or scissors: ")
return user_choice
def computer_option():
comp_choice = random.randint(1,3)
return comp_choice
user_choice = choose_option()
comp_choice = computer_option()
if user_choice == "rock":
if comp_choice == 1:
print("\nYou chose rock. The driver chose rock. You tied")
if comp_choice == 2:
print("\nYou chose rock. The driver chose paper. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 3:
print("\nYou chose rock. The driver chose scissors. You win.")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if user_choice == "paper":
if comp_choice == 1:
print("\nYou chose paper. The driver chose rock. You win ")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 2:
print("\nYou chose paper. The driver chose paper. You tied")
if comp_choice == 3:
print("\nYou chose paper. The driver chose scissors. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if user_choice == "scissors":
if comp_choice == 1:
print("\nYou chose scissors. The driver chose rock. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 2:
print("\nYou chose scissors. The driver chose paper. You win")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 3:
print("\nYou chose scissors. The driver chose scissors. You tied")
if third_level == "gate 1":
print("\nThis gate is under maintainance and is letting a limited number of people through. A number between 1 and 5 will be generated, if this number is even, you proceed, else you lose")
generate_number = input("Generate number? (yes): ")
if generate_number == "yes":
answer = random.randint(1,5)
print(answer)
if answer in [1,3,5]:
print("\nOdd number. You are now stuck at this gate and can't get through. You lost.")
games_played += 1
if answer in [2,4]:
print("\nEven number. You move on")
fourth_level = input("Fourth Stage: Finally, you have to choose between the taxi or the metro to get to campus. (taxi/metro) ")
if fourth_level == "taxi":
print("\nYou have successfully reached the CMUQ campus. You win!")
print("You won after "+str(games_played))
print("attempts")
break
elif fourth_level == "metro":
print("\nWrong option, but it is not over yet. The driver challenges you to a game of rock/paper/scissors. If you win, he'll drop you off', else you lose")
while True:
def choose_option():
user_choice = input("choose either rock,paper, or scissors: ")
return user_choice
def computer_option():
comp_choice = random.randint(1,3)
return comp_choice
user_choice = choose_option()
comp_choice = computer_option()
if user_choice == "rock":
if comp_choice == 1:
print("\nYou chose rock. The driver chose rock. You tied")
if comp_choice == 2:
print("\nYou chose rock. The driver chose paper. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 3:
print("\nYou chose rock. The driver chose scissors. You win.")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if user_choice == "paper":
if comp_choice == 1:
print("\nYou chose paper. The driver chose rock. You win ")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 2:
print("\nYou chose paper. The driver chose paper. You tied")
if comp_choice == 3:
print("\nYou chose paper. The computer chose scissors. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if user_choice == "scissors":
if comp_choice == 1:
print("\nYou chose scissors. The driver chose rock. You lose")
print("You are now lost in Qatar. You lost")
games_played += 1
break
if comp_choice == 2:
print("\nYou chose scissors. The driver chose paper. You win")
print("Well done. You have reached the campus. You win")
print("You won after "+str(games_played))
print("attempts")
break
if comp_choice == 3:
print("\nYou chose scissors. The driver chose scissors. You tied")
else:
print("\nWrong answer.. your flight attendent is dissapointed in your lack of knowldegde and will not let you in. You lost")
games_played += 1
if first_choice == "skip":
print("\nYou are stopped for not follwoing instructions at the airport. You lost")
games_played += 1
if ready == "no":
print("\nOkay, come back when you're ready")
|
#loop_ex2.py
from matplotlib.pyplot import *
from numpy import *
myvect= ['a','b',3]
N = len(myvect)
for i in range(N):
item = myvect[i]
print('i = '+str(i))
print('item = '+str(item))
for item in myvect:
print(item)
print('this is the end of the loop')
|
#grosspay.py
#Michael McCann
from matplotlib.pyplot import *
from numpy import *
Hours = int(input("Please enter the number of hours:"))
RPH = int(input("please enter the rate per hour:"))
if (Hours < 40):
print('You worked less than 40 hours and your rate of pay is $'+str(RPH)+' per hour.')
grosspay_under40= (Hours*RPH)
print('You will receive $'+str(grosspay_under40)+' this week.')
elif (Hours ==40):
print('You worked exactly 40 hours and your rate of pay is $'+str(RPH)+ ' per hour.')
grosspay_40= (Hours*RPH)
print('You will receive $'+str(grosspay_40)+' this week.')
elif (Hours > 40):
print('You worked more than 40 hours and your rate of pay is $'+str(RPH)+' per hour.')
grosspay_40 =(40*RPH)
grosspay_over40= (1.5*(Hours-40)*RPH)
total_grosspay=(grosspay_40+grosspay_over40)
print('You will receive $'+str(total_grosspay)+' this week.')
|
a = '*' #a = *號
for i in range(1,13,2): # i 從1開始 間隔2個 到13 有 1,3,5,7,9,11
print("{0:^11s}".format(a*i)) #有11隔空格可以讓a*i值放入 ^:置中的意思
for i in range(9,0,-2):
print("{0:^11s}".format(a*i))
|
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(0,10)
Y1 = 0.05*X*X
plt.ylim(0, 5)
plt.plot(X, Y1, color='blue')
plt.fill_between(X, Y1, color='red', alpha='0.5')
plt.show()
|
def binary_search(array, item):
start = 0
end = len(array) - 1
while start <= end:
# 这两种写法是一样的,但 start + end 如果值很大容易溢出
# mid = (start + end) // 2
# 优化写法
mid = start + (end - start) // 2
if array[mid] == item:
return True
elif item < array[mid]:
end = mid - 1
else:
start = mid + 1
return False
|
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self._size = k
self._len = 0
self._deque = [0] * self._size
def insertFront(self, value: int) -> bool:
"""
Adds an item at the front of Deque. Return true if the operation is successful.
"""
if self.isFull():
return False
print(self._len)
for i in range(self._len):
print(i)
self._deque[self._len - i] = self._deque[self._len - i - 1]
self._deque[0] = value
self._len += 1
return True
def insertLast(self, value: int) -> bool:
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
"""
if self.isFull():
return False
self._deque[self._len] = value
self._len += 1
return True
def deleteFront(self) -> bool:
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
"""
if self.isEmpty():
return False
for i in range(self._len - 1):
self._deque[i] = self._deque[i + 1]
self._len -= 1
return True
def deleteLast(self) -> bool:
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
"""
if self.isEmpty():
return False
self._deque[self._len - 1] = 0
self._len -= 1
return True
def getFront(self) -> int:
"""
Get the front item from the deque.
"""
if self.isEmpty():
return -1
return self._deque[0]
def getRear(self) -> int:
"""
Get the last item from the deque.
"""
if self.isEmpty():
return -1
return self._deque[self._len - 1]
def isEmpty(self) -> bool:
"""
Checks whether the circular deque is empty or not.
"""
return self._len == 0
def isFull(self) -> bool:
"""
Checks whether the circular deque is full or not.
"""
return self._len == self._size
circularDeque = MyCircularDeque(3)
assert True == circularDeque.insertLast(1)
assert True == circularDeque.insertLast(2)
assert True == circularDeque.insertFront(3)
assert False == circularDeque.insertFront(4)
assert circularDeque.getRear() == 2
assert circularDeque.isFull() == True
print(circularDeque._deque)
assert circularDeque.deleteLast() == True
print(circularDeque._deque)
assert circularDeque.insertFront(4) == True
|
# -*- coding: utf-8 -*-
"""
EE4483
Implement TWO different search algorithms to find x^1/3 of any real number.
Note negative number too. (10 points)
a. Please briefly explain the search strategies of the two algorithms.
b. Prove that your algorithms guarantee to find the correct answer.
c. Compare the two search algorithms and their complexity; explain which one is better
and why it is better.
"""
import time
def binSearch (x,error):
if x == 0:
return 0
if abs(x) >1:
left = min(x,x/abs(x))
right = max(x,x/abs(x))
else:
left = min(0,x/abs(x))
right = max(0,x/abs(x))
rt = (left+right)/2
while abs(rt*rt*rt-x)>error:
if rt*rt*rt > x:
right = rt
else:
left = rt
rt = (left+right)/2
return rt
def newton(x, error):
rt = x
while abs(rt*rt*rt-x)>error:
## Assume y=rt^3-x, therefore we can use newton's method to find the root
y=rt**3 - x
rt = rt - y/(3*rt*rt)
return rt
# Input #
x = -1
error = 0.0000001
start_time_B = time.clock()
rt1 = binSearch(x,error)
stop_time_B = time.clock()
start_time_N = time.clock()
rt2 = newton(x,error)
stop_time_N = time.clock()
print("--- %s seconds ---" % (stop_time_B - start_time_B))
print("The solution of " +str(x)+" from Binary Search is "+str(rt1))
print("--- %s seconds ---" % (stop_time_N - start_time_N))
print("The solution of " +str(x)+" from Newton Method is "+str(rt2)) |
# dado 3 numeros inteiros verificar se os 3 numeros podem formar um triangulo
# eh triangulo se l1+l2 < l3, l1 + l3 < l2, l2 + l3 < l1
l1 = int(input("informe um lado do triangulo - 1\n"))
l2 = int(input("informe um lado do triangulo - 2\n"))
l3 = int(input("informe um lado do triangulo - 3\n"))
if ((l1+l2) > l3 and (l1 + l3) > l2 and (l2 + l3) > l1 ):
print("eh triangulo")
else:
print("false")
|
import os
from model.territory import Territory
from model.county import County
class Province(Territory):
'''This is class representing province - inherit from Territory'''
def __init__(self, name, types, number):
self.list_of_county = []
self.number_of_province = number
super().__init__(name, types)
@classmethod
def get_province(cls):
'''
Create new object Province. As attribute - proper data from list_of_territory.
'''
for row in cls.list_of_territory:
if row[1] == '':
return cls(row[4], row[5], row[0])
def add_county(self):
'''
Create list_of_county built of County objects. Except Vallue Error when data isn't integer.
'''
first_index_county = 0
for row in Territory.list_of_territory:
try:
index_county = int(row[1])
if index_county != first_index_county and self.number_of_province == row[0]:
county = County(row[4], row[5], index_county)
self.list_of_county.append(county)
first_index_county = index_county
except ValueError:
continue
|
#!./env/bin/python3
import argparse
import lsb_text as lsb
import os
from argparse import RawTextHelpFormatter
__name__ = "__main__"
usageExample = """
Examples about how to use this module:\n
python lsb.py hide -f FILENAME -t TEXT
It hide TEXT inside the a NEW_FILENAME file
python lsb.py unhide -f FILENAME
It unhide data from FILENAME file to a secret.txt file
python lsb.py unhide -f FILENAME -s 120
It unhide only the first 120 bits from FILENAME file to a secret.txt file
"""
parser = argparse.ArgumentParser(description="Tool to hide and unhide data from a png image.", epilog=f"{usageExample}",
formatter_class=RawTextHelpFormatter)
parser.add_argument("action", default=1, type=str,
help="hide or unhide. It is used to select if you hide or unhide a text into an image")
parser.add_argument("-f", "--file", type=str, help="path to the png image we are working on")
parser.add_argument("-t", "--text", type=str, help="text which will be hid in the image")
parser.add_argument("-s", "--size", type=int, help="print the size in bits of the data hid")
args = parser.parse_args()
if args.action == "hide":
if os.path.isfile(args.file) == False:
print(f"This image {args.file} doesn't exist")
elif args.text == None:
print("you should hide a text")
else:
lsb.hideText(args.file, args.text)
elif args.action == "unhide":
if os.path.isfile(args.file) == False:
print(f"This image {args.file} doesn't exist")
else:
if args.size != None and args.size > 0:
lsb.unhideText(args.file, args.size)
elif args.size == None:
lsb.unhideText(args.file)
else:
print(f"selected size {args.size} isn't correct")
|
class ExtensionHandler:
"""
This class is used to detect the extension of a file.
"""
def __init__(self, input_file):
self.input_file = input_file
def get_extension(self):
extension = self.input_file[::-1].split('.')[0][::-1].lower()
return extension if len(extension) else None |
# Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return 0
# Example
# input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
# ouptut: 5
def most_frequent_item_count(collection):
counter = 0
for i in collection:
freq = collection.count(i)
print(freq)
if freq > counter:
counter = freq
return(counter) |
#calculating tip amount
total = float(input("Enter the total amount: "))
tippercent=float(input("Enter the tip percentage: "))
# formatting the numbers into 2 decimal points
tipamount =format((total * tippercent),".2f")
print (f"The tip amount is {tipamount}") |
# example for hypotenuse.py
def calc(should_print=False):
print("""
Name: Hypotenuse Length
Operation : Finding length of the hypotenuse
Inputs : a->int/float , b->int/float
Outputs: c=>((a**2) + (b**2))**0.5 ->float
Author : rajkumawat
\n
""")
a = float(input("Enter a >>"))
b = float(input("Enter b >>"))
result = {}
result['inputs'] = [a, b]
result['outputs'] = [((a**2) + (b**2))**0.5]
if should_print:
print(f"Solution {result['outputs'][0]}")
else:
return result |
# unpack คือการเอาของออกจาก list
fruits = ["apple", "banana", "cherry"] # List same array
(
x,
y,
z,
) = fruits
print(x)
print(y)
print(z) |
#print(5 + 3) # Prints: 8
#sum_value = 5 + 3
#print(sum_value) # Prints 8
#my_list = [] # Initialize an empty list
#name = "John" # Initialize name variable to John
#my_list = my_list + name # Adding the current my_list variable to the string name
#print(my_list) # Prints: ['j','o','h','n']
#my_list = [1,2,3,4] # Initialize my_list
#my_list = my_list * 3 # Take my_list and multiply it by 3
#print(my_list) # Prints: [1,2,3,4,1,2,3,4,1,2,3,4]
#print(5 > 3) # Prints: True; since 5 is greater than 3
#result = 5 > 3 # You can store the result in a variable
#print(result) # Prints: True
#print(3 > 5) # Prints: False; since 3 is NOT greater than 5
#print(5 > 5) # Prints: False; since 5 is NOT greater than 5 (they are equal)
#x = 2 # Setting up the x variable
#if x < 3:
# x += 2 # This will run if x < 3, otherwise it will be skipped over
#print(x) # Since this is on a lower indentation level, this code will run regardless
#if x < 3:
# x += 2 # This will run if x < 3, otherwise it will be skipped over
#print(x) # Since this is on a lower indentation level, this code will run regardless
x = 2 # Setting up the x variable
if x < 3:
x += 2 # This will run if x < 3, otherwise it will be skipped over
else:
x -= 1 # This will run if x is not less than 3
print(x) # Since this is on a lower indentation level, this code will run regardless
if x < 3:
x += 2 # This will run if x < 3, otherwise it will be skipped over
else:
x -= 1 # This will run if x is not less than 3
print(x) # Since this is on a lower indentation level, this code will run regardless |
class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
#
def set(self, other):
self.x = other.x
self.y = other.y
#
def __copy__(self):
return Point(self.x, self.y)
#
# + operator
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
#
# - operator
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
#
# * operator
def __mul__(self, scalar):
return Point(self.x * scalar, self.y * scalar)
#
# / operator
def __div__(self, scalar):
return Point(self.x / scalar, self.y / scalar)
#
# += operator
def __radd__(self, other):
self.x += other.x
self.y += other.y
#
# -= operator
def __rsub__(self, other):
self.x -= other.x
self.y -= other.y
#
# *= operator
def __rmul__(self, scalar):
self.x *= scalar
self.y *= scalar
#
# /= operator
def __rdiv__(self, scalar):
self.x /= scalar
self.y /= scalar
#
# == operator
def __eq__(self, other):
return self.x == other.x and self.y == other.y
#
# Emulate a list of 2 items
def __len__(self):
return 2
#
def __getitem(self, index):
if index == 0:
return self.x
return self.y
#
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
#
#
def manhattanDistance(a, b):
return abs(a.x - b.x) + abs(a.y - b.y)
# |
# Ryan Soderberg
# DS2000-Sec02
int_list = input("Enter a sorted list of integers each in the range (0-99): ").split(
" "
)
# Convert list of strings to list of integers
int_list = [int(i) for i in int_list]
# Calculate mean
sum = 0
for i in int_list:
sum += i
mean = sum / len(int_list)
# Calculate median
if len(int_list) % 2 != 0: # Odd length
median_index = len(int_list) // 2
median = int_list[median_index]
else: # Even length
median_index = int(len(int_list) / 2)
median_index_two = median_index - 1
median = (int_list[median_index] + int_list[median_index_two]) / 2
# Calculate mode
# Find number of occurances of each int
counter = [0] * 100
for num in int_list:
counter[num] += 1
# Find possible modes - the number(s) that occur the most
min_count = 0
possible_modes = []
for i in range(len(counter)):
if counter[i] > min_count:
min_count = counter[i]
possible_modes = [i]
elif counter[i] == min_count:
possible_modes += [i]
# Find lowest int in possible_modes
lowest = possible_modes[0]
for num in possible_modes:
if num < lowest:
lowest = num
mode = lowest
print("Values: ", len(int_list))
print("Mean: ", round(mean, 1))
print("Median: ", median)
print("Mode: ", mode)
|
import pandas as pd
import plotly.express as px
print(" Kyra is VERY lazy ! She works as an sports-science data visualizer. But she never completes her excel sheets manually! Her boss always complains about her. Will you help Kyra with her work by creating a simple Raw data to visualized data and automate the process of data visualization ?? If yes , come on!")
def BG():
df=pd.read_csv('data.csv')
fig=px.bar(df,x='team',y='hours_played')
fig.show()
def SG():
df=pd.read_csv('data.csv')
fig=px.scatter(df,x='team',y='hours_played',size='players count',color='team',size_max=60,title="Info about PBL teams")
fig.show()
print("What do you want to do (BAR, SCATTER , LINE)???")
opt=str(input('if you want to make a BAR press 1, If you want to make a scatter press 2 -> '))
if opt=='1':
BG()
if opt=='2':
SG()
|
new_england_states = {
'Maine': 'ME',
'Vermont': 'VT',
'Massachusetts': 'MA',
'Connecticut': 'CT',
'Rhode Island': 'RI',
'New Hampshire': 'NH'
}
cities = {
'MA': 'Boston',
'NH': 'Manchester',
'CT': 'Hartford',
'VT': 'Burlington',
'ME': 'Portland',
'RI': 'Providence'
}
cities['MA'] = 'Boston'
cities['NH'] = 'Portsmouth'
print '-' * 10
print "MA Commonwealth has: ", cities['MA']
print "NH Live Free or Die has: ", cities['NH']
print '-' * 10
print "New Hampshire's abbreviation is: ", new_england_states['New Hampshire']
print "Maine's abbreviation is: ", new_england_states['Maine']
print '-' * 10
print "Connecticut has: ", cities[new_england_states['Connecticut']]
print "Rhode Island has: ", cities[new_england_states['Rhode Island']]
print '-' * 10
for state, abbrev in new_england_states.items():
print "%s abbreviation is %s" % (state, abbrev)
print '-' * 10
for abbrev, city in cities.items():
print "%s biggest city is %s" % (abbrev, city)
print '-' * 10
for state, abbrev in new_england_states.items():
print "%s state abbreviated is %s and has %s as it's biggest city." % (
state, abbrev, cities[abbrev])
print '-' * 10
state = new_england_states.get('Florida')
if not new_england_states:
print "I'm sorry, but there is no state named Florida in your list."
city = cities.get('FL', 'Does Not Exist')
print "The city for the state 'FL' is: %s" % city
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 00:04:11 2017
@author: pratyus
"""
def genPrimes():
yield 2
listOfPrimes = [2]
currentNo = 3
while True:
isPrime = True
for x in listOfPrimes:
if currentNo % x == 0:
isPrime = False
if isPrime == False:
currentNo += 1
else:
listOfPrimes.append(currentNo)
yield currentNo
|
"""
__author__ = 'Nicholas Widener'
__author__ = 'Trent Weatherman'
__version__ = 'October 2015'
Vertex class reads in our graph and
performs a depth first search on it
and performs the transitive closure operation.
Vertex class also checks for cycles in our graph.
"""
import sys
from collections import defaultdict
class Graph:
def __init__(self):
"""
Initialize the variable used in Graph
"""
self.dfsPaths = [] # list for dfsPaths
self.VertexList = {} # list for adjacent vertices
self.list1 = []
self.list2 = []
self.adjMatrix = []
self.original_adj_matrix = []
def startGraph(self, inputFile):
d = self.readInputGraph(inputFile)
f = self.matrix(inputFile)
userInput = input("Enter a source and destination:")
usr = userInput.split(" ", -1)
self.originalMatrix(inputFile)
print("[DFS paths: " + usr[0]+ ", " + usr[1] +"]")
self.readSourceDest(d, usr)
print("[Cycle]:")
cycle = self.cycle_exists(d)
if (cycle == True):
print("Cycle exists")
elif (cycle == False):
print("No cycle exists")
print("\n")
print("[TC]:")
self.warshall(f)
self.compare()
print("\n")
def readSourceDest(self, inFile, userInput):
for path in self.dfsSearch(inFile, userInput[0], userInput[1]):
if (userInput[0].isalpha() or userInput[1].isalpha()):
print('these are not valid inputs')
sys.exit(0)
else:
print(path)
print("\n")
def readInputGraph(self, inputFile):
"""
Reads specified input file and stores in
adjacency list
:param inputFile: file to be rad in
:return: the VertexList
"""
file = open(inputFile, 'r') # open the file and read it
for line in file: # for each element in the file
(vertex, val) = line.split() #vertex gets first value in the line, val gets second
if vertex not in self.VertexList: #if vertex not in VertexList
self.VertexList[vertex] = {val} #add adjacent pairs
else: #else
self.VertexList.get(vertex).add(val) #add the values
for i in list(self.VertexList.keys()): # for each element in the list of the vertex keys
for j in self.VertexList[i]: # for each vertex that's in i
if j not in self.VertexList: #if j is not in the vertex list
self.VertexList[j] = {} #we add it to the vertex list
return self.VertexList # return list of adjacent vertices
def getLists(self, inputFile):
#list1 = []
#list2 = []
#list3 = []
file = open(inputFile, 'r')
for line in file:
pair = line.split()
self.list1.append(pair[0])
self.list2.append(pair[1])
file.close()
return self.list1, self.list2
def matrix(self, inputFile):
self.getLists(inputFile)
n = 7
self.adjMatrix = [[0 for v in range(n)] for u in range(n)]
for i in range(len(self.list1)):
u = int(self.list1[i])
v = int(self.list2[i])
self.adjMatrix[u][v] = 1
return self.adjMatrix
def originalMatrix(self, inputFile):
self.getLists(inputFile)
n = 7
self.original_adj_matrix = [[0 for v in range(n)] for u in range(n)]
for i in range(len(self.list1)):
u = int(self.list1[i])
v = int(self.list2[i])
self.original_adj_matrix[u][v] = 1
return self.original_adj_matrix
def printMatrix(self, matrix):
for i in range(len(matrix)):
for k in range(len(matrix[0])):
print(matrix[i][k], " ", end='')
#print(i, k)
print('')
def compare(self):
for i in range(len(self.adjMatrix)):
for j in range(len(self.adjMatrix)):
if self.adjMatrix[i][j] == 1 and self.original_adj_matrix[i][j] == 0:
print(i, j)
def warshall(self, matrix):
assert (len(row) == len(matrix) for row in matrix)
n = len(matrix)
for k in range(n):
for i in range(n):
for j in range(n):
matrix[i][j] = matrix[i][j] or (matrix[i][k] and matrix[k][j])
return matrix
def dfsSearch(self, graph, start, end, path=[]):
"""
Performs a depth first search on
the graph that is read in from the file
:param graph: the graph that we are performing the search on
:param start: the starting vertex
:param end: the target vertex
:param path: a list of the paths
:return: the paths from the search
"""
path = path + [start] # path
if start == end: # if the start element and end element are the same
return [path] #return the list of paths
if start not in graph: # if the start element is not in the graph
print('Not Found') #prints out not found
return [] #return an empty list
paths = [] # path list
for node in graph[start]: # for node in the graph
if node not in path: #if not in the path
newpaths = self.dfsSearch(graph, node, end, path) #new paths we found
for newpath in newpaths: #for each new path in the list of new paths
paths.append(newpath) #add the new path to our list of paths
paths.sort() # sort our paths
return paths # return our paths
def cycle_exists(self, graph): # - G is a directed graph
color = {u: "white" for u in graph} # - All nodes are initially white
found_cycle = [False] # - Define found_cycle as a list so we can change
# its value per reference, see:
for u in graph: # - Visit all nodes.
if color[u] == "white":
self.dfs_visit(graph, u, color, found_cycle)
if found_cycle[0]:
break
return found_cycle[0]
def dfs_visit(self, graph, u, color, found_cycle):
if found_cycle[0]: # - Stop dfs if cycle is found.
# print('cycle exists')
return
color[u] = "gray" # - Gray nodes are in the current path
for v in graph[u]: # - Check neighbors, where G[u] is the adjacency list of u.
if color[v] == "gray": # - Case where a loop in the current path is present.
found_cycle[0] = True
return
if color[v] == "white": # - Call dfs_visit recursively.
self.dfs_visit(graph, v, color, found_cycle)
color[u] = "black" # - Mark node as done.
|
"""
Simple library for dealing with Dice Roll expressions
You can define a dice roll expression and then get its value like this:
d = DiceRollExpression("3d8")
You'll get three random values between 1 and 8 presented in a list.
E.g [3, 7, 2]
@author James Ravenscroft
"""
import random
from manalang import ManaLangTok, ManaLangException
class DiceRollException(ManaLangException):
pass
VALID_DICE_TYPES = ['4','6','8','10','12','20','100']
class DiceRollExpression(ManaLangTok):
def __init__(self, expr=""):
"""Validate a dice roll expression and then store it"""
try:
self._parse(expr)
except Exception as e:
raise DiceRollException("Invalid dice expression %s" % expr)
def _parse(self, expr):
"""Given a dice roll expression, parse validate and evaluate"""
rolls, dtype = expr.split("d")
assert dtype in VALID_DICE_TYPES
self.rolls = int(rolls)
self.dtype = int(dtype)
def value(self):
"""Evaluate a dice roll expression"""
return [random.randint(1,self.dtype) for
i in range(0,self.rolls)]
def __str__(self):
return "%dd%d" % (self.rolls, self.dtype)
def __repr__(self):
return "<DiceRollExpression '%dd%d'>" % (self.rolls, self.dtype)
|
# control statement
# if statement
temp = 40
if temp >= 40:
print ("room is hot")
age = 17
print ('voting system')
if age > 17:
print('congrats !!! you are eligible for voting')
else:
print('oh sorry!!! you are not eligible for voting process')
age = 35
if age < 22:
print("study hard !!! ")
elif age >21 and age <26:
print("your salary shoud be in the range of 10k - 50k")
elif age >25 and age <36:
print("your salary shoud be in the range of 50k - 2l")
elif age >35 and age<50:
print("your salary shoud be in the range of 2ll - 5l")
else:
print("no need to work ...enjoy the life ....!!!!")
# python program to check whether the given number is even or odd.
number =input("enter a number")
X = int(number)%2
if X == 0:
print("the number is even")
else:
print("the number is odd")
a=['cat','mouse','rat']
for counter in 'variable':
for x in a:
print(a)
len (a)
# control statement
#for loop
num1,num2=10,20
#range will generate sequence of no. syntax- range (start,end,step)
#syntax i for counter in variable:
for i in range(0,11,2):
print(i)
list1=['soun',"moun","pinky","guddu","duggu"]
print(list1)
#iterate the list with condition
for i in list1:
if i == "pinky":
print(i)
for i in list1:
if i == "pinky":
break
print(i)
#iterate the list with condition
for i in list1:
if i== "pinky":
continue
print(i)
dict1={ "name" : "newton",
"qual" : "me",
"city" : "pune"}
print(dict1)
#iterate the dict
for i in dict1:
print(i)
for i in dict1:
print(dict1[i])
for i in dict1.items():
print(i)
for i in dict1:
print('key is ',i, "and value is",dict1[i])
for key, value in dict1.items():
print('key is',key,"and value is",value)
#drew pattern
for i in range(6,1,-1):
for i in range(6,1,-1):
if i==1:
print(' * ')
#range can have negative no. as well
for i in range (-6,1):
print('range(-6,1)',i)
#write the python program to find out the average of a set of integers
num1=10
num2=20
num3=30
avg=(num1+num2+num3)/3
#avg=sum of all item/no of items
count=int(input("enter the count of numbers:"))
i=0
sum=0
for i in range (count):
x=int(input("enter an integer:"))
sum =sum+x
avg=sum/count
print("the average is:",avg)
|
import math
r = int(input())
def uclidean(r):
area = math.pow(r,2)*math.pi
print(round(area, 6))
def taxi(r):
area = math.pow(r,2)*2
print(round(area,6))
uclidean(r)
taxi(r) |
from heapq import heappush, heappop
import sys
input = sys.stdin.readline
#인접행렬이 아닌 인접 리스트 (딕트)를 사용하면 시간 초과가 일어나고
#이를 해결하기 위해서는 heap을 사용해야한다.
# heapq는 항상 최소값만을 리턴
#BFS구현이랑 동일하지만 heap을 사용한다는 것만 다름
V,E = list(map(int,input().split(' ')))
start = int(input())
graph = dict()
for i in range(1,V+1):
graph[i]=[]
for i in range(E):
u,v,w=list(map(int,input().split(' ')))
graph[u].append([v,w])
INF = float('inf')
visited = [INF]*(V+1)
def dijkstra(start):
queue=[]
heappush(queue, (0,start))
visited[start]=0
while queue:
cost, node=heappop(queue)
for n_node,n_cost in graph[node]:
if n_cost+visited[node] < visited[n_node]:
visited[n_node]=n_cost+visited[node]
heappush(queue,(visited[n_node], n_node))
dijkstra(start)
for i in range(1,V+1):
if visited[i]!=INF:
print(visited[i])
else:
print('INF')
|
b = list(input())
def judge():
q=[]
for i in b:
if (i==')' or i==']') and not q:
return False
if i==')':
val = q.pop()
if val!='(':
return False
elif i==']':
val = q.pop()
if val!='[':
return False
else:
q.append(i)
if not q:
return True
else:
return False
def inner(equation):
s=''
for _ in equation[:-2]:
s+=_
sums=eval(s)
t = eval(str(sums)+equation[-2]+equation[-1])
print(s)
return t
def solve(ss):
stack=[]
for s in ss:
if s=='(' or s=='[':
stack.append(s)
elif s==')':
if stack[-1] =='(':
stack[-1]=2
else:
tmp=0
for i in range(len(stack)-1,-1,-1):
if stack[i] == '(':
stack[-1] = tmp*2
break
else:
tmp+=stack[i]
stack=stack[:-1]
elif s==']':
if stack[-1]=='[':
stack[-1]=3
else:
tmp = 0
for i in range(len(stack)-1,-1,-1):
if stack[i]=='[':
stack[-1]=tmp*3
break
else:
tmp+=stack[i]
stack=stack[:-1]
return sum(stack)
re = judge()
if re:
print(solve(b))
else:
print(0)
exit()
|
import os.path
from tempfile import gettempdir
class File:
def __init__(self, path, data=""):
self.path = path
if data:
self.write(data)
def __add__(self, file_to_sum):
return File(os.path.join(gettempdir(), 'third.txt'), self.read() + file_to_sum.read())
def __str__(self):
return self.path
def __iter__(self):
self.current = 0
return self
def __next__(self):
lines = self.read().split('\n')
if self.current >= len(lines):
raise StopIteration
self.current += 1
return lines[self.current - 1]
def read(self):
with open(self.path, 'r') as f:
data = f.read()
return data
def write(self, data):
with open(self.path, 'w') as f:
f.write(data)
obj = File("C:\\python_data\\files and descriptors\\tmp\\file.txt")
obj.write("""4 Углубленный Python 2
4.1 Особые методы классов . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4.1.1 Магические методы . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4.1.2 Итераторы . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.1.3 Контекстные менеджеры . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Механизм работы классов . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.1 Дескрипторы . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.2 Метаклассы . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3 Отладка и тестирование . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3.1 Отладка . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3.2 Тестирование""")
obj2 = File("C:\\python_data\\files and descriptors\\tmp\\file2.txt")
obj2.write("""Оглавление
""")
obj3 = obj2 + obj
print(obj3) |
# Your code here
import random
import math
from time import time
def slowfun_too_slow(x, y):
v = math.pow(x, y)
v = math.factorial(v)
v //= (x + y)
v %= 982451653
return v
dictionary = {}
_s = time()
def slowfun(x, y):
"""
Rewrite slowfun_too_slow() in here so that the program produces the same
output, but completes quickly instead of taking ages to run.
"""
key = f'{x}{y}'
if key in dictionary and dictionary[key] is not None:
return dictionary[key]
else:
dictionary[f'{x}{y}'] = slowfun_too_slow(x, y)
return dictionary[f'{x}{y}']
# Your code here
# Do not modify below this line!
for i in range(50000):
x = random.randrange(2, 14)
y = random.randrange(3, 6)
print(f'{i}: {x},{y}: {slowfun(x, y)}')
print(f'{time() - _s:.5f}')
|
#part2
def number_of_bags_contained_in_color(color, contains_graph):
contained = contains_graph[color]
count = 0
i = 0
while i < len(contained):
current_number, current_color = contained[i]
count = count + current_number
contained_by_current = contains_graph[current_color]
for inside_number, inside_color in contained_by_current:
contained.append((current_number * inside_number, inside_color))
i = i + 1
return count
#part1
def colors_that_can_contain(color, is_contained_by_graph):
contained_by = is_contained_by_graph[color].copy()
i = 0
while i < len(contained_by):
current_color = contained_by[i]
if current_color in is_contained_by_graph.keys():
colors_that_contain_current = is_contained_by_graph[current_color]
for candidate_color in colors_that_contain_current:
if candidate_color not in contained_by:
contained_by.append(candidate_color)
i = i + 1
return contained_by
if __name__ == '__main__':
total = 0
with open("input07.txt", 'r') as input_file:
line = input_file.readline()
contains_graph = dict()
is_contained_by_graph = dict()
while (len(line) > 0):
container, contents = line.split(' contain ')
container = container.split(' ')[0:2]
container = container[0]+container[1]
contents = contents[:-2]
products = contents.split(', ')
contains_graph[container] = []
for product in products:
if product == 'no other bags':
continue
product_pieces = product.split(' ')
number = int(product_pieces[0])
product_color = product_pieces[1] + product_pieces[2]
contains_graph[container].append((number, product_color))
if product_color not in is_contained_by_graph.keys():
is_contained_by_graph[product_color] = []
is_contained_by_graph[product_color].append(container)
#print(products)
#print(container)
line = input_file.readline()
print(len(colors_that_can_contain('shinygold', is_contained_by_graph)))
print(number_of_bags_contained_in_color('shinygold', contains_graph)) |
class Node:
# --- Binary tree node --- #
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# --- Insert the data --- #
def insert(self, data):
if self.data:
# --- Insert on the left if the value is smaller than the current value --- #
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
# --- Insert on the right if the value is greater than the current value --- #
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
# --- Insert in the current node if it is empty --- #
else:
self.data = data
# --- Print tree by levels --- #
def printtree(self):
# --- Keep track of the values in the current level --- #
cur_level = [self]
while cur_level:
# --- Print all the values in a certain level on one line --- #
print(' '.join(str(node.data) for node in cur_level))
# --- Keep track of the next level values --- #
next_level = list()
for node in cur_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
# --- Move down to the next level --- #
cur_level = next_level
def identicaltree(root1, root2):
# --- If there is no tree, then we return true --- #
if root1 is None and root2 is None:
return True
# --- If there is a tree check if the nodes are the same, and recursively walk down the tree --- #
if root1 is not None and root2 is not None:
return ((root1.data == root2.data) and identicaltree(root1.left, root2.left) and identicaltree(root1.right, root2.right))
# --- If there are extra nodes or the data is different return False --- #
return False
print("Hello, I am a computer program that will insert whatever values you give me into a binary tree.")
print("Two binary trees actually, but let's go one at a time. We can start with the first tree.")
firsttree = input("Please enter the values that you would like inserted into the first tree separated by spaces: ").split()
try:
tree1 = Node(firsttree[0])
for i in range(len(firsttree)):
tree1.insert(firsttree[i])
except:
print("Please insert a value!")
print("I have made the first tree for you. I will start on the second one entering the values in the same way.")
secondtree = input("Please enter the values that you would like inserted into the second tree separated by spaces: ").split()
try:
tree2 = Node(secondtree[0])
for i in range(len(secondtree)):
tree2.insert(secondtree[i])
except:
print("Please insert a value!")
print("I will now test whether or not the two trees are identical to eachother. I can show you how I chose to store the trees.")
print("Would you like me print the two trees?")
printtrees = input("Type y for yes and n for no: ")
# --- If you entered the same values in a different order, the program may have stored them in a different way --- #
# --- For this reason, it may (and likely will) return False. You can check how the program stored the values here --- #
if "y" in printtrees:
tree1.printtree()
tree2.printtree()
print("Are your trees identical?", identicaltree(tree1, tree2))
|
"""
Question 2
Write a Python program to accept the user's first and last name and then
getting them printed in the the reverse order with a space between first name
and last name
"""
def name(x,y):
f_n = x[::-1]
l_n = y[::-1]
print(f_n + " " + l_n)
first_name = input("Enter your first name")
last_name = input("Enter your last name")
name(first_name, last_name)
|
# Clase que hará de modelo para la base de datos implemetada
class Persona(object):
#Contructor
def __init__(
self,
idPersona,
nombre,
apellidoPaterno,
apelidoMaterno,
rut,
observacion
):
self.idPersona = idPersona
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apelidoMaterno = apelidoMaterno
self.rut = rut
self.observacion = observacion
#Metodos
def getIdPersona(self):
return self.idPersona
def getNombre(self):
return self.nombre
def getApellidoPaterno(self):
return self.apellidoPaterno
def getApellidoMaterno(self):
return self.apelidoMaterno
def getRut(self):
return self.rut
def getObservacion(self):
return self.observacion
def setIdPersona(self, value):
self.idPersona = value
def setNombre(self, value):
self.nombre = value
def setApellidoPaterno(self, value):
self.apellidoPaterno = value
def setApellidoMaterno(self, value):
self.apellidoMaterno = value
def setRut(self, value):
self.rut = value
def setObservacion(self, value):
self.observacion = value
#at = Persona(1,'as', 'as', 'as', 'as', 'as')
#print(str(at.getRut()))
#if '@' not in value:
#raise Exception("Esto no parece ser una dirección de correo") |
from PIL import Image, ImageFont, ImageDraw
import textwrap, time
def draw_text_and_border(border_colour, paragraph, expansion):
width_text, height_text = draw.textsize(paragraph[0], font)
current_width = (screen_width - width_text)/2
current_height = (screen_height - height_text)/2 - (screen_height/4)
# Making a black border around the text so that it is readable on any background, Thanks to Alec Bennet for the base code to do this https://mail.python.org/pipermail/image-sig/2009-May/005681.html
for text_quotes in paragraph:
width_text, height_text = draw.textsize(text_quotes, font)
current_width = (screen_width - width_text)/2
if current_width < 20:
expansion += 5
paragraph = textwrap.wrap(content[quote_location], int(screen_width / expansion))
draw_text_and_border("black",paragraph,expansion)
break
else:
draw.text((current_width-1, current_height), text_quotes, font=font, fill=border_colour)
draw.text((current_width+1, current_height), text_quotes, font=font, fill=border_colour)
draw.text((current_width, current_height-1), text_quotes, font=font, fill=border_colour)
draw.text((current_width, current_height+1), text_quotes, font=font, fill=border_colour)
draw.text((current_width-1, current_height-1), text_quotes, font=font, fill=border_colour)
draw.text((current_width+1, current_height-1), text_quotes, font=font, fill=border_colour)
draw.text((current_width-1, current_height+1), text_quotes, font=font, fill=border_colour)
draw.text((current_width+1, current_height+1), text_quotes, font=font, fill=border_colour)
draw.text((current_width, current_height), text_quotes, font=font)
current_height += fontsize + dist_between_lines
# Opening the file with the quotes, this code is designed to work with a mass export of quotes from Moon Reader Plus for Android
# That being said, any text file with quotes will work if formatted correctly.
with open("Quotes.txt") as f:
content = f.readlines()
f.close()
#Generating Each Background
for i in range(int(((len(content) - 3)/2))):
# Handles the formatting of the text file that Moon Reader exports, the quotes start at line 6 then skip a line.
quote_location = 6 + (2*i)
# Opens the images stored in the "Wallpapers" folder. The imaages are simply named 1.jpg, 2.jpg, etc...
im = Image.open("Wallpapers/{}.jpg".format(i+1))
# Setting the width and height to the actual size of the image, allowing any size image to be used.
screen_width, screen_height = im.size
# Changes a large line of text into a list with the text broken 70 characters in.
paragraph = textwrap.wrap(content[quote_location], int(screen_width / 35))
# Takes the first line of the paragraph and makes it into a list.
first = list(paragraph[0])
# Deletes the second character until a letter comes up, that way the quote doesn't start with a space or comma.
while first[1].isalpha() == False:
first[1].pop()
# Makes the first letter in the sentence upper case.
first[1] = first[1].upper()
# Turns the list back into a string.
first = "".join(first)
# Returns it to the paragraph, now grammatically correct.
paragraph[0] = first
# Makes the fontsize proportional to the screen height, this way even smaller images can be used.
fontsize = int(screen_height /20)
# Sets the font to arial, feel free to change this to something else.
font = ImageFont.truetype("arial.ttf", fontsize)
# Draws the image.
draw = ImageDraw.Draw(im)
# Sets the width and height of the text to be proportional to the size of the text at the line
width_text, height_text = draw.textsize(content[quote_location], font)
dist_between_lines = 10
# Uses the function defined earlier to draw the text to the screen and add a black border to add readability.
draw_text_and_border("black",paragraph, 35)
# Displays the image
im.save("Complete/{}.jpg".format(i))
|
# PROGRAMME Exercice4_POUR;
# VARIABLE
# N : ENTIER;
# FACT : ENTIER;
# DEBUT
# ECRIRE ('Entrez la valeur de N : ');
# LIRE(N);
# TANT QUE (NON ENTIER(N) OU N <= 0) FAIRE
# ECRIRE ('Erreur de saisie : "N" DOIT etre un entier positif, veuillez ressaisir');
# LIRE(N);
# SI (N == 1 )
# ALORS
# FACT <- 1;
# SINON
# FACT <- 1;
# POUR I VARIANT DE 1 A N FAIRE
# FACT <- FACT * I;
# FAIT;
# ECRIRE('La factorielle de ' & CHAINE DE CARACTER(N) & ' est de : ' & CHAINE DE CARACTER(FACT));
# FIN;
n = input('valeur de N : ')
fact = 1
while not n.isdigit():
n = input('Erreur de saisie : "N" DOIT etre un entier positif, veuillez ressaisir : ')
n = int(n)
if n != 1 :
for i in range(1, n+1) :
fact = fact * i
print("la factorielle de {} est de : {}".format(n, fact))
n = input('valeur de N : ')
fact = 1
while not n.isdigit():
n = input('Erreur de saisie : "N" DOIT etre un entier positif, veuillez ressaisir : ')
n = int(n)
if n != 1 :
i = 1
while i <= n :
fact = fact * i
i += 1
print("la factorielle de {} est de : {}".format(n, fact))
|
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
def main(m, n):
limit = pow(10,9) + 7
if n < m:
m, n = n, m
n, m = n + m - 2, m - 1
num = factorial(n) / (factorial(m) * factorial(n - m))
print num % limit
if __name__ == '__main__':
tests_number = int(raw_input())
tests = [raw_input().split(" ") for r in range(tests_number)]
for n in tests:
main(int(n[0]), int(n[1]))
|
cafe = ''
max_c = 0
choice = ' '
while choice != 'MEOW':
cafe = input().split()
if cafe[0] == 'MEOW':
break
if int(cafe[1]) > max_c:
choice = cafe[0]
max_c = int(cafe[1])
print(choice)
|
initial = abs(int(input().strip()))
final = abs(int(input().strip()))
half = 0
while initial >= final:
half += 1
initial /= 2
print(half * 12)
|
def what_to_do(instructions):
size = len(instructions)
say = 'Simon says'
say_length = len(say)
index = instructions.find(say)
if index == 0:
answer = 'I ' + instructions[say_length + 1:size]
elif index == size - say_length:
answer = 'I ' + instructions[0:index]
else:
answer = "I won't do it!"
return answer
|
def check_email(string):
if string.find(" ") > - 1:
return False
at = string.find('@')
if at > 0:
if string[at + 2:].find('.') > - 1:
return True
else:
return False
else:
return False
|
import re
import types
from collections import Iterator
def compress(clean):
"""
Trims leading and trailing whitespace
Also compresses multiple spaces within a string
"""
if clean is None:
return None
clean = re.sub(r'[\r\n\t\xa0]', ' ', clean)
clean = re.sub(r' ?', ' ', clean)
clean = re.sub(r'\s+', ' ', clean)
return clean.strip()
def recursive_compress(data, empty_string_as_none=False,
remove_empty_keys=True):
'''
Recursive compress function
Accepts an object an tries to compress every sub-data if it is a string
empty_string_as_none is a flag to replace empty string with None value
'''
kwargs = {
'empty_string_as_none': empty_string_as_none,
'remove_empty_keys': remove_empty_keys
}
if isinstance(data, dict):
if remove_empty_keys:
return {compress(k): recursive_compress(v, **kwargs)
for k, v in data.items() if k}
else:
return {compress(k) if k else k: recursive_compress(v, **kwargs)
for k, v in data.items()}
elif isinstance(data, list):
return [recursive_compress(x, **kwargs) for x in data]
elif isinstance(data, types.GeneratorType) or isinstance(data, Iterator):
return (recursive_compress(x, **kwargs) for x in data)
elif isinstance(data, str):
compressed_data = compress(data)
if empty_string_as_none and not compressed_data:
compressed_data = None
return compressed_data
else:
return data
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 7. Diferencia entre el trafico total de entrada a Brodway frente al de salida.
import sys
num_of_columns = 0
primera_linea = True
data = sys.stdin.readlines()
for line in data:
fila = line.split(',')
# Parsing file attributes
if primera_linea:
firstLine = fila
primera_linea = False
else:
pasa_chequeo = False
# If the row's length is the same as the first line's and traffic goes or comes from Broadway, continue
if len(fila) == len(firstLine) and (fila[3].lstrip().rstrip() == 'BROADWAY' or fila[4].lstrip().rstrip() == 'BROADWAY'):
pasa_chequeo = True
# Remove first and last spaces of every element
for element in range(0, len(fila)):
fila[element] = fila[element].lstrip().rstrip()
# Check if elements ranging from 2 to 7 are digits
if element < 2 or element > 7:
if fila[element].isdigit():
pasa_chequeo = True
else:
pasa_chequeo = False
break
# If all of the above conditions are met, proceed to print data
if pasa_chequeo:
# Prining street that goes to broadway
print fila[3] + ',',
# Prining street that comes from broadway
print fila[4] + ',',
# Print data until last position
for data in range(7, len(firstLine) - 1):
print fila[data] + ',',
# Print last position
print fila[len(firstLine) - 1],
print ''
|
# Enter one line of comments
'''
Enter
Multiple
Lines
Of
Comments
'''
###############################################################################
## NICE HEADERS ##
###############################################################################
print 'we wont be learning Hello World' # inline commments should be avoided
##
#Excercise
##
# OK lets get started with
###############################################################################
## WORKING WITH FILES ##
# Covered in this Unit
# import
# getcwd()
# chdir()
# listdir()
# shutil(source,destination)
# open readlines
# close()
###############################################################################
'''
First step in working with files is being able to navigate to your files or
save your files using pythong programing rather than your file explorer.
lets first start by reading some files in. You downloaded a copy of Iowa liquor
Sales data from GitHUB. Hopefully you have had a chance to unzip the file and
have the file path readily available simple suggestion is to begin a directory
in your User name folder or simply your desktop for now.
'''
# Set your OS path where your files are stored
# getcwd() What is your Current Working directory
import os
os.getcwd()
# chdir() Change your default working directory - you dont want to do this often
import os
from pathlib import Path
path = Path('//Users//Matthew//Desktop//DATASETS')
os.chdir(path)
## EXERCISE
# Get Current working directory
##
# listdir() List all of the files in your directory
import os
files = os.listdir()
files
os.getcwd()
# shutil(src,dst) Move files
'''
1. Create a two folders on your desktop 1 called Hotel and 1 called Conference.
2. Create a file in your source folder called passenger.txt
3. Use shutil to move your passenger file back and forth from your Hotel to Conference
4. Check your folders to validate the file has moved, then try moving it back
'''
import shutil
shutil.move('C://Users//Matthew//Desktop//Hotel//passenger.txt', 'C://Users//Matthew//Desktop//Conference//passenger.txt')
'''
We will be using a lot of variables in our code loading your file path into a
variable will make it more flexible
'''
import shutil
hotel = 'C://Users//Matthew//Desktop//Hotel//passenger.txt'
conference = 'C://Users//Matthew//Desktop//Conference//passenger.txt'
shutil.move(conference,hotel)
## EXERCISE
# Move sales.csv, products.csv, stores.csv, counties.csv into the folder
# Iowa Liquor Sales
##
# open readlines
counties = open("counties.csv") # you may need to work with your path
counties.readlines()
# notice the \n that is a carraige return or enter key.
## EXERCISE
# open and read each of the files in the iowa liquor sales database
##
# time to create files, read files and write to files
# Open a file to write to 'W' or create one '+'
a = open("new_file.csv","w+")
# open your folder and see if the file was created
# Write a line to the document
a.write("First line in my doc.")
# Close file
a.close()
#Open file into variable
b = open("new_file.csv","r")
# use readlines to readlines into a variable
c = b.readlines()
b.close()
# output results to the screen
(c)
# Write several lines to a file and read them
t = open("multiline.csv", 'w+')
# Use Raw_inputs to create 3 lines of in your file
line1 = "line 1,Red"
line2 = "line 2,Blue"
line3 = "line 3,Green, 4.52"
t.write(line1)
t.write("\n") # \n is a carriage return that we are writing to file
t.write(line2)
t.write("\n")
t.write(line3)
t.write("\n")
t.close()
a = open("multiline.csv","r")
b = a.readlines()
a.close()
b
# Find your file and review it
'''
line1 = "line 1"
line2 = "line 2"
line3 = "line 3"
in the above code that you just ran try putting commas and more information
Then review your file again to see how it behaves
Example
line1 = "line 1,Red"
line2 = "line 2,Blue"
line3 = "line 3,Green, 4.52"
'''
## EXERCISE
# Create a file called names with names of friends family actors or fictional characters
# column for First Name, Last Name, age, Notes
##
# 'a+' Next append a line to the end of the file
# Open the file for appending text to the end
t= open("multiline.csv","a+")
t.write("append_test, 4")
t.close()
t
## EXERCISE
# Reopen your name file and add a new name to the file
##
''' PROJECT EXERCISE
Create a file that lists all the skills you have learned so far
rate yourself for each skill in a seperate column next to the skill
0 = Don't know
1 = Aquiring knowledge
2 = Can apply with 80% help from Google
3 = Can apply with 20% help from Google
4 = Can teach <20% help from Google
5 = Can design, review, optimize
What is your average score?
What areas are you doing great in, what areas do you need to study?
This Project will grow and be designed and redesigned several different ways
as you progress and revist.'''
###############################################################################
## BONUS ##
## Pandas reading files , Connecting to AWS ##
###############################################################################
'''
Pandas is something we will explore more in Python for Data III
However here is a small look into how Pandas can read files
Read Data From a file
Lets take a look at what the code is going to do. with most code you have to
be able to read it backwards. Yoda talk. so reading this backwards we are :
taking a counties.csv file and reading it using a read_csv functions from
pd(pandas) and then loading that data into a variable called a.
a = pd.read_csv('~/Desktop/DataSets/counties.csv')
You will want to adjust the link to navigate to where your file is located.'''
# read in the drinks data
import pandas as pd
a = pd.read_csv('~Matthew\Desktop\Datasets\counties.csv')
a
##
# Read in the data sets products, sales, stores
##
###############################################################################
## Connect to AWS and Perform a Select ##
## you may need to install psycopg2 using anaconda prompt and ##
## conda install psycopg2
## Connection to AWS is available per General Assembly ##
###############################################################################
''' This example shows how to connect to a database, and then obtain and use a
cursor object to retrieve records from a table.'''
import psycopg2
import sys
import pprint
import pandas
#Define our connection stri
conn_string = "host='analyticsga.cuwj8wuu6wbh.us-west-2.rds.amazonaws.com'dbname='iowa_liquor_sales_database' user='analytics_student' password='analyticsga'"
# print the connection string we will use to connect
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
print ("Connected!\n")
df = pd.read_sql_query('select * from products', conn)
df
|
import csv
Total_Votes=0
CandidateList=[]
Candidate_Votes={}
csvpath = 'C:\\DATA ANALYSTICS\\3-Homework-Python\\Phyton-Challenge-master\\PyPoll\\Resources\\election_data.csv'
output_path = "C:\DATA ANALYSTICS\\3-Homework-Python\\Phyton-Challenge-master\\PyBank\\Resources\Election_Votes.txt"
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
# Read the header row first (skip this step if there is now header)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
# Read each row of data after the header
for row in csvreader:
Total_Votes=Total_Votes+1
Candidate=row[2]
# Adding candidate not in the list already
if Candidate not in CandidateList:
CandidateList.append(Candidate)
Candidate_Votes[Candidate]=0
Candidate_Votes[Candidate] = Candidate_Votes[Candidate]+1
for Candidate in Candidate_Votes:
Votes=Candidate_Votes[Candidate]
Percentage=round(float(Votes) / float(Total_Votes),3)*100
print(str(Candidate)+":"+ str(Percentage)+"%"+"("+str(Votes)+")")
print("Election Results")
print("-----------------")
print("Total Votes :"+ str(Total_Votes))
print("--------------------")
|
from user import User
import pyperclip
import random
from account import Account
def create_user(user_name, password):
'''
creates a new user
'''
new_user = User(user_name, password)
return new_user
def save_user(user):
'''
will save new_users
'''
user.save_user()
def find_user_by_user_name(user_name):
'''Function that finds user_name by number'''
return User.find_user_by_user_name(user_name)
def display_users():
'''will return all saved users'''
return User.display_users()
def generate_passwords(user):
'''will generate passwords for various accounts'''
generate_accountPassword = user.generate_passwords()
return generate_accountPassword
def save_accounts(accounts):
'''function to save accounts'''
return accounts.save_accounts()
def find_useraccounts(login_user_name):
'''function to find user accounts'''
return UserAccount.find_useraccount(login_user_name)
def useraccount_exists(login_user_name, login_password):
'''function that will check if the user account exists'''
account_exists = Useraccount.useraccount_exists(login_password,login_user_name)
return account_exists
def create_account(username, password, website):
'''
function to create a new account
'''
new_account = UserAccount(username, password, website)
return new_account
def save_account(account):
'''
will save new account
'''
account.save_account()
def display_account(account):
'''
checks if account can be displayed
'''
return UserAccount.copy_account(account)
def main():
global login_name
global login_password
print("Welcome to password generator")
print("Kindly wait")
print("You name please?")
personal_name = input()
while True:
print("these shortcodes will help you navigate easily: '~new'-create a new account, '~sign'-log in to any of your accounts")
print("Input new or signIn")
if short_code == 'new':
print("Input username of your choice and automatically generate a password")
print()
name = input()
print()
passwords = generate_passwords()
save_user = (create_user(user_name, password))
print('\n')
print("You successfully created your new account")
print('\n')
break
elif short_code == 'signin':
print(
login_name = input()
login = usercredential_exists(login_name, login_password)
if login = True:
print("You have successfully logged in.Enjoy!!")
print()
break
else:
print("Please use one of the two codes provide
|
# This is a genetic algorithm to find the best solution to
# find the highest point of f(x) = x^2, 0 <= x <= 31
from random import randint
# Environment variables
size = 4 # Total individuals on each generation
mutation_odds = 1 # Odds to mutate
generations = 5 # Total generations
perfection = 31 # In our case all 5 bits equal to '1', or integer 31
answer = False
# Calculate fitness of an individual
# In our case it is pretty straight forward
def fitness (individual):
return int(individual, 2)
# Pick the parents
# Function will receive : current population, a list containing the fitness sum
# of each individual and the total fitness of the population
#
# It will pick a random int between 0 and total_fitness (indiv_odds)
# and find the first individual
# Then decrease the first individual fitness from the total fitness and
# from all individuals after that one, including itself
# This will turn the fitness of that individual into 0 and keep the fitness
# of the next individuals, making it impossible for the first individual to
# reproduce with itself
def parents (population, indiv_odds, temp_odds):
temp_indiv_odds = indiv_odds[:]
pick = randint(0, temp_odds - 1)
for index in range(size + 1):
if pick < temp_indiv_odds[index]:
break
first = population[index - 1]
pos = index
for index in range(pos, size + 1):
temp_indiv_odds[index] -= fitness(first)
temp_odds -= fitness(first)
pick = randint(0, temp_odds - 1)
for index in range(size + 1):
if pick < temp_indiv_odds[index]:
break
second = population[index - 1]
return first, second
# Mutate gene from an individual
# Simply change from 0 to 1 and vice versa in a given random position
def mutate (individual, position):
if (individual[position] == '0'):
individual = individual[:position] + '1' + individual[position + 1:]
else:
individual = individual[:position] + '0' + individual[position + 1:]
return individual
# Generate initial population
population = []
for _ in range(size):
# This will generate a random int between 0 and 31 (included)
# convert to binary
# and format to 5 bits with the leading 0s
population.append("{:05b}".format(randint(0, 31)))
# ===========================
for current_gen in range(generations):
print("Generation #" + str(current_gen + 1))
print(population)
print('=====================================')
print()
# We need to calculate the total fitness to do elitism
# The 'best' individuals will reproduce
# Total fitness will sum the fitness of each individual
# individual_odds will create a list that contains the sum of the current individual
# and all the previous ones.
#
# If the best individual is found within the current generation,
# the script will end
#
individual_odds = [0]
total_fitness = 0
for n, individual in enumerate(population):
total_fitness += fitness(individual)
individual_odds.append(total_fitness)
if (fitness(individual) == perfection):
answer = True
if (answer):
print('Individual found!')
break
# This will loop to pick the parents and append to a list containing
# the next generation.
# If a mutation happens, it will do a mutation in a random gene (position)
# of the last generated child
#
new_generation = []
for _ in range(size):
first, second = parents(population, individual_odds, total_fitness)
new_generation.append(first[:3] + second[3:])
if mutation_odds > randint(0, 100):
new_generation[-1] = mutate(new_generation[-1], randint(0, 4))
population = new_generation
|
import errno
import functools
import os
import shutil
import stat
import tempfile
import six
import attr
@attr.s
class ActionDecorator(object):
"""
Composable action decorators.
A ActionDecorator instance is a decorator which can be applied to
functions and methods. It performs its action *before* calling the
decorated function. Each ActionDecorator instance has an associate
action which is a function taking a single "context" argument.
The intended use of ActionDecorators is for chaining together strings
of actions needed to create a particular environment for the decorated
function. This is particularly useful in setting up tests.
Create and use ActionDecorators like this:
@ActionDecorator
def my_action(ctx):
print("Doing my_action")
@my_action
def some_func(ctx):
print("Doing some_func")
Calling some_func() now would give the following output:
Doing my action
Doing some_func
ActionDecorators have two features that make them useful over just
chaining normal decorator functions. Firstly, they are neatly composable:
ActionDecorator instances can be chained together using the | operator.
This creates a new ActionDecorator which can also be used to decorate
functions and methods: the actions for each ActionDecorator in the chain
are performed left-to-right before calling the decorated function.
e.g. if A, B, and C are ActionDecorator instances, then we can define
a new ActionDecorator D with:
D = A | B | C
@D
def some_func(ctx):
# Do stuff here
...
Now calling some_func() will perform A's action, then B's, then C's,
before finally calling the original some_func().
The second useful feature of ActionDecorators is the ability to easily
manage state and pass it between the actions in an ActionDecorator chain.
Each decorated action function must take a single "context" argument
(it can be named whatever you want). This context argument is essentially
just a placeholder: you can assign whatever you want to any attribute
with any name. The key is that this same context object is passed along
between each ActionDecorator in the chain, e.g.
@ActionDecorator
def init_x(ctx):
ctx.x = 0
@ActionDecorator
def inc_x(ctx):
ctx.x += 1
@ActionDecorator
def print_x(ctx):
print(ctx.x)
x_chain = init_x | inc_x | print_x
@x_chain
def my_func():
print("my_func")
Calling my_func() now results in:
2
my_func
Again, this *can* all be achieved with standard function decorators.
Using ActionDecorators instead simply makes it a bit clearer to read
and write.
"""
action = attr.ib()
# TODO: validate that attr is a function taking a single argument?
post_action = attr.ib(init=False, default=None)
def __call__(self, context_arg):
if six.PY3:
takes_context = isinstance(context_arg, str)
else:
takes_context = isinstance(context_arg, basestring)
if takes_context:
return lambda func: self._make_decorator(func, context_arg)
else:
return self._make_decorator(context_arg, None)
def _make_decorator(self, func, context_arg):
@functools.wraps(func)
def wrapper(*args, **kwargs):
ctx = type(self.action.__name__ + "_ActionDecoratorContext", (), {})()
self.action(ctx)
try:
if context_arg is not None:
kwargs[context_arg] = ctx
return func(*args, **kwargs)
finally:
if self.post_action is not None:
self.post_action(ctx)
return wrapper
def after(self, func):
self.post_action = func
def __rmul__(self, name):
"""
Name an ActionDecorator.
An instance of an ActionDecorator can be given a name by
pre-multiplying it with a string, e.g.
x = "name_of_x" * x
will assign "name_of_x" to x.__name__. This is just a way
of being able to give names to composed ActionDecorators.
"""
self.__name__ = name
return self
def __or__(self, other):
"""
Compose two ActionDecorators.
Takes two ActionDecorators and composes them to create a new
ActionDecorator whose action is to call the action of the left-hand
ActionDecorator and then call the action of the right-hand
ActionDecorator.
Arguments
---------
other {ActionDecorator} -- The second ActionDecorator in the
composition.
Returns
-------
{ActionDecorator} -- A new ActionDecorator which is the
left-to-right composition of these two
ActionDecorators.
"""
def then(ctx):
self.action(ctx)
other.action(ctx)
then.__name__ = self.action.__name__ + "_then_" + other.action.__name__
then = ActionDecorator(then)
if other.post_action or self.post_action:
def after(ctx):
try:
if other.post_action is not None:
other.post_action(ctx)
finally:
if self.post_action is not None:
self.post_action(ctx)
if other.post_action is None:
after_name = self.post_action.__name__
else:
after_name = other.post_action.__name__
if self.post_action is not None:
after_name += "_then_" + self.post_action.__name__
after.__name__ = after_name
then.after(after)
return then
@ActionDecorator
def mktempdir(ctx):
ctx.orig_dir = os.getcwd()
ctx.tmp_dir = tempfile.mkdtemp()
os.chdir(ctx.tmp_dir)
def handle_remove_readonly(func, path, exc):
excvalue = exc[1]
if excvalue.errno == errno.EACCES:
# If it's an access error, perhaps the file is read-only. Let's change
# the permissions and try again.
os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # 0777
func(path)
elif not os.path.exists(path):
pass
else:
raise excvalue
@mktempdir.after
def remove_tmp_dir(ctx):
os.chdir(ctx.orig_dir)
shutil.rmtree(ctx.tmp_dir, ignore_errors=False, onerror=handle_remove_readonly)
|
# --------------
# Code starts here
# Create the lists
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
# Concatenate both the strings
new_class = class_1 + class_2
print(new_class)
# Append the list
new_class.append('Peter Warden')
# Print updated list
print(new_class)
# Remove the element from the list
new_class.remove('Carla Gentry')
# Print the list
print(new_class)
# Create the Dictionary
courses = {'Math':65 , 'English':70 , 'History':80, 'French':70, 'Science':60}
# Slice the dict and stores the all subjects marks in variable
Math = 65
English = 70
History = 80
French = 70
Science = 60
# Store the all the subject in one variable `Total`
total = Math + English + History + French + Science
# Print the total
print(total)
# Insert percentage formula
# Print the percentage
percentage = (total/500) * 100
print(percentage)
# Create the Dictionary
mathematics = {'Geoffrey Hinton':78, "Andrew Ng":95, "Sebastian Raschka":65, "Yoshua Benjio":50, "Hilary Mason":70, "Corinna Cortes":66, "Peter Warden":75 }
max_marks_scored = max(mathematics,key =mathematics.get)
topper = max_marks_scored
print(topper)
# Given string
topper.split(" ", 1)
print(topper)
first_name = topper[7:10]
last_name = topper[0:6]
full_name = first_name + " " +last_name
certificate_name = full_name.upper()
print(certificate_name)
|
import os, pdb, copy
import filecmp
from collections import Counter
from dateutil.relativedelta import *
from datetime import date, datetime
def getData(file):
# get a list of dictionary objects from the file
#Input: file name
#Ouput: return a list of dictionary objects where
#the keys are from the first row in the data. and the values are each of the other rows
#pdb.set_trace()
"""This function takes in a file from your computer/files. It will return a
list of dictionaries. The keys are from the first row in the data provided,
with the values being the following rows. See comments on specific dets on how
the function runs.
"""
#Open the file
in_file = open(file, "r")
#Note: First line == header. Use next() to start reading from the second line
next(in_file)
#Grabs the first line read, which is the second line in the file...
line = in_file.readline()
#Emp list to append the dictionaries
list_of_dict = []
while line:
#Create dictionary, might also be able to do this outside the loop...
dic_file = {}
value = line.split(",")
#Establish/Make values
first_name = value[0]
last_name = value[1]
email = value[2]
class_year = value[3]
date_of_birh = value[4]
#Set up dictionary w/ keys and values
dic_file["First"] = first_name
dic_file["Last"] = last_name
dic_file["Email"] = email
dic_file["Class"] = class_year
dic_file["DOB"] = date_of_birh
list_of_dict.append(dic_file)
line = in_file.readline()
#Don't forget to close file at the end when using a while loop.
in_file.close()
return list_of_dict
#pass
def mySort(data,col):
# Sort based on key/column
#Input: list of dictionaries and col (key) to sort on
#Output: Return the first item in the sorted list as a string of just: firstName lastName
"""This function takes in a list of dictionaries and a key to sort on. This
function will return the first item/student in that sorted list as a string.
See comments for more specific dets.
"""
#Sort list based on key, but not a specific key
sort_list = sorted(data, key = lambda val: val[col])
#Grab the first item(index 0) in that sorted list
grab_first_item = sort_list[0]
#Grab the "first name" and "last name" key values from previous item
grab_first_n = str(grab_first_item["First"])
grab_first_l = str(grab_first_item["Last"])
return grab_first_n + " " + grab_first_l
#pass
def classSizes(data):
# Create a histogram
# Input: list of dictionaries
# Output: Return a list of tuples sorted by the number of students in that class in
# descending order
# [('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)]
"""This function takes in a list of dictionaries and returns a list of tuples
sorted by the number of students in that class from highest --> lowest.
"""
#Create an emp list for the tuples
list_tuple = []
#Estab values
fresh_count = 0
sopho_count = 0
junior_count = 0
senior_count = 0
#Sort students by Class key from highest to low.
list_stu = sorted(data, key = lambda col: col["Class"], reverse = True)
#List comprehension instead of for loop, and then take the number of stu in each class
#Probably could have shortened this into one longer loop, but oh well
senior_count = len([val for val in list_stu if val["Class"] == 'Senior'])
jun_count = len([val for val in list_stu if val["Class"] == 'Junior'])
soph_count = len([val for val in list_stu if val["Class"] == 'Sophomore'])
fresh_count = len([val for val in list_stu if val["Class"] == 'Freshman'])
list_tuple.append(("Senior", senior_count))
list_tuple.append(("Junior", jun_count))
list_tuple.append(("Sophomore", soph_count))
list_tuple.append(("Freshman", fresh_count))
#Sort list of the four classes by the second column(value) from high-->low
sort_list = sorted(list_tuple, key = lambda col: col[1], reverse = True)
return (sort_list)
#pass
def findMonth(a):
# Find the most common birth month form this data
# Input: list of dictionaries
# Output: Return the month (1-12) that had the most births in the data
"""This function takes in a list of dictionaries and returns the month (1-12)
that had the most births in the data. See comments for more spec details.
"""
#Made a deepycopy so OG data would not have been harmed/broken in any way
dif = copy.deepcopy(a)
#Want only the DOB keys-successful
for value in dif:
del value["Class"]
del value["Email"]
del value["First"]
del value["Last"]
#Now I have a list of the values from the DOB key
#Probably could have dif too...eh
data_dob = [val["DOB"] for val in dif]
#Emp list for the month specfic data
data_mo = []
#List of months/days/years
#Split at the "/" in order to get three cats
for str in data_dob:
value = str.split('/')
month = int(value[0])
day = int(value[1])
year = int(value[2])
data_mo.append(month)
#make emp dict in order to hold the key(num) and val(freq)
number_counter = {}
for number in data_mo:
#if that number is currently in the dict, then do not increment
#else increment before moving on to the next number
if number in number_counter:
number_counter[number] += 1
else:
number_counter[number] = 1
#sort using dict get function/ for values with the highest freq at the top
num = sorted(number_counter, key = number_counter.get, reverse = True)
#Just return the first num in list
top_1 = num[0]
return top_1
#pass
def mySortPrint(a,col,fileName):
#Similar to mySort, but instead of returning single
#Student, the sorted data is saved to a csv file.
# as first,last,email
#Input: list of dictionaries, col (key) to sort by and output file name
#Output: No return value, but the file is written
"""This function takes in a list of dictionaries and returns nothing. However, a
file is written in csv format.
"""
#Sort list by keys
sort_list = sorted(a, key = lambda val : val[col])
#Open file
f = open(fileName, "w")
#Run for loop where adding first name, last name, email to a file
for value in sort_list:
first = value["First"]
last = value["Last"]
email = value["Email"]
f.write(first + "," + last + "," + email + "\n")
f.close()
#pass
def findAge(a):
# def findAge(a):
# Input: list of dictionaries
# Output: Return the average age of the students and round that age to the nearest
# integer. You will need to work with the DOB and the current date to find the current
# age in years.
"""This function takes in a list of dictionaries and returns the average sum_age
of the students. The number returned is rounded to the nearest integer.
See comments below for specific details on how to do/what happens in the func.
"""
#Create a deepcopy so the OG data is not messed up accidently
dif = copy.deepcopy(a)
#Run a for loop in order to delete the keys not needed
for value in dif:
del value["Class"]
del value["Email"]
del value["First"]
del value["Last"]
#Now I have a list of the values from the DOB key ONLY
data_dob = [val["DOB"] for val in dif]
#Initialize an emp list for for a list of the years
data_year = []
#List of months/days/years
#Split at the "/" in order to get three categories
for str in data_dob:
value = str.split('/')
month = int(value[0])
day = int(value[1])
year = int(value[2])
data_year.append(year)
#Grab the current Year using datetime, 'date' will work, but is a diff format
now = datetime.now()
#Initialize an emp list for a list of current_age
current_age = []
#Run that for loop in order to get the current agesself.
#Note: abs() is needed for the years that are greater than the current year
for value in data_year:
age = abs(now.year - value)
current_age.append(age)
#Find average: sum/amount of numbers in list = aver
sum_age = sum(current_age)
amount = len(current_age)
return(int(sum_age/round(amount)))
#pass
################################################################
## DO NOT MODIFY ANY CODE BELOW THIS
################################################################
## We have provided simple test() function used in main() to print what each function returns vs. what it's supposed to return.
def test(got, expected, pts):
score = 0;
if got == expected:
score = pts
print(" OK ", end=" ")
else:
print (" XX ", end=" ")
print("Got: ",got, "Expected: ",expected)
return score
# Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not.
def main():
total = 0
print("Read in Test data and store as a list of dictionaries")
data = getData('P1DataA.csv')
data2 = getData('P1DataB.csv')
total += test(type(data),type([]),50)
print()
print("First student sorted by First name:")
total += test(mySort(data,'First'),'Abbot Le',25)
total += test(mySort(data2,'First'),'Adam Rocha',25)
print("First student sorted by Last name:")
total += test(mySort(data,'Last'),'Elijah Adams',25)
total += test(mySort(data2,'Last'),'Elijah Adams',25)
print("First student sorted by Email:")
total += test(mySort(data,'Email'),'Hope Craft',25)
total += test(mySort(data2,'Email'),'Orli Humphrey',25)
print("\nEach grade ordered by size:")
total += test(classSizes(data),[('Junior', 28), ('Senior', 27), ('Freshman', 23), ('Sophomore', 22)],25)
total += test(classSizes(data2),[('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)],25)
print("\nThe most common month of the year to be born is:")
total += test(findMonth(data),3,15)
total += test(findMonth(data2),3,15)
print("\nSuccessful sort and print to file:")
mySortPrint(data,'Last','results.csv')
if os.path.exists('results.csv'):
total += test(filecmp.cmp('outfile.csv', 'results.csv'),True,20)
print("\nTest of extra credit: Calcuate average age")
total += test(findAge(data), 40, 5)
total += test(findAge(data2), 42, 5)
print("Your final score is " + str(total))
# Standard boilerplate to call the main() function that tests all your code
if __name__ == '__main__':
main()
|
'''
Question 11
Level 2
Question:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Programmer Comment:
Examinner Comment:
''' |
'''
Question 28
Level 1
Question:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
Programmer Comment:
Examinner Comment:
''' |
from random import randint
word_list = ["DOG", "CAT", "PIG", "ANT", "KEY", "EYE", "LIP", "BUS", "MAP", "ELF", "COW", "BAT", "HAT", "BED",
"ICE"]
clue_list = ["i am a pet that has four legs,you might hear me barking",
"this is a feline whose lives can reach nine",
"this provides meat that you would eat and this is what gives you bacon",
"this is a type of insects with antennae on it's head and can be fire or red",
"to open a door you can knock or use this item to unlock",
"i am closed at night and give you sight",
"i have no voice and yet i speak to you,i tell all things in the world that people do",
"this vehicle makes frequent stops amd the ones you take to school are yellow",
"it can help you to find a route so that you don't get lost and go on",
"i am a little helper who makes your gift from santa clause",
"milk is what they make and give us a juicy steak",
"they are often found just hanging out upside down inside a cave",
"a chef's tall one is white ,i might be a beanie or a beret that's flat",
"when it gets dark every night,it's on me people sleeping",
"i float on the top of the water and am as cold as can be"]
def placer(letter, founded, chosen_word):
if letter in chosen_word:
if letter == chosen_word[0] and founded == "":
print(letter, dash, dash)
founded = founded + letter
elif letter == chosen_word[1] and founded == "":
print(dash, letter, dash)
founded = founded + letter
elif letter == chosen_word[2] and founded == "":
print(dash, dash, letter)
founded = founded + letter
elif letter == chosen_word[0] and founded == chosen_word[1]:
print(letter, founded, dash)
founded = founded + letter
elif letter == chosen_word[0] and founded == chosen_word[2]:
print(letter, dash, founded)
founded = founded + letter
elif letter == chosen_word[1] and founded == chosen_word[2]:
print(dash, letter, founded)
founded = founded + letter
elif letter == chosen_word[1] and founded == chosen_word[0]:
print(founded, letter, dash)
founded = founded + letter
elif letter == chosen_word[2] and founded == chosen_word[1]:
print(dash, founded, letter)
founded = founded + letter
elif letter == chosen_word[2] and founded == chosen_word[0]:
print(founded, dash, letter)
founded = founded + letter
elif letter == chosen_word[0] and founded == chosen_word[1] + chosen_word[2] or chosen_word[2] + \
chosen_word[1]:
print(chosen_word)
print("you won")
satisfy=True
elif letter == chosen_word[1] and founded == chosen_word[0] + chosen_word[2] or chosen_word[2] + \
chosen_word[0]:
print(chosen_word)
print("you won")
satisfy= True
elif letter == chosen_word[2] and founded == chosen_word[0] + chosen_word[1] or chosen_word[1] + \
chosen_word[0]:
print(chosen_word)
print("you won")
satisfy = True
def check(n):
if n == 3:
print("you lost")
else:
print("you won")
num = randint(0, 14)
chosen_word = word_list[num]
dash = "_"
founded = ""
print("the clue is :")
print(clue_list[num])
nu = 0
satisfy = False
while satisfy== False and nu < 3:
inp = input("enter a letter:")
inp1 = inp.upper()
if inp1 in chosen_word and inp1 not in founded:
placer(inp1, founded, chosen_word)
founded += inp1
elif inp1 in chosen_word and inp1 in founded:
print("already guessed")
nu += 1
else:
print("wrong")
nu += 1
check(nu)
|
# Реализовать базовый класс Worker ( работник), в котором определить атрибуты: name,
# surname, position ( должность), income ( доход). Последний атрибут должен быть
# защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, например,
# {"wage": wage, "bonus": bonus}. Создать класс Position ( должность) на базе класса Worker.
# В классе Position реализовать методы получения полного имени сотрудника ( get_full_name) и
# дохода с учетом премии ( get_total_income) . Проверить работу примера на реальных данных
# (создать экземпляры класса Position , передать данные, проверить значения атрибутов,
# вызвать методы экземпляров).
class Worker():
def __init__(self, name, surname, income):
self.name = name
self.surname = surname
self._income = income
class Position(Worker):
def get_full_name(self):
return self.name + " " + self.surname
def get_total_income(self):
return self._income["wage"] + self._income["bonus"]
p_name = input("Введите имя сотрудника: ")
p_surname = input("Введите фамилию сотрудника: ")
p_wage = float(input("Введите размер оклада: "))
p_bonus = float(input("Введите размер премии: "))
p_income = {"wage": p_wage, "bonus": p_bonus}
pos1 = Position(p_name, p_surname, p_income)
print("Полное имя сотрудника", pos1.get_full_name())
print("Доход сотрудника с учётом премии", pos1.get_total_income()) |
# Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года
# относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict.
# Решение через list
try:
while True:
month = int(input('Введите номер месяца от 1 до 12(если хотите завершить програму введите 0(ноль)): '))
if month == 0:
quit()
season = ["зимой", "зимой", "весной", "весной", "весной", "летом", "летом", "летом", "осенью", "осенью", "осенью",
"зимой"]
print("Этот месяц ", season[month - 1])
except ValueError:
print('Введено не число!')
except IndexError:
print('Месяцев не может быть больше 12!') |
# Реализовать программу работы с органическими клетками, состоящими из ячеек. Необходимо
# создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий
# количеству ячеек клетки (целое число). В классе должны быть реализованы методы
# перегрузки арифметических операторов: сложение ( __add__() ), вычитание ( __sub__()) ,
# умножение ( __mul__()) , деление ( __truediv__()) . Данные методы должны применяться т олько
# к клеткам и выполнять увеличение, уменьшение, умножение и целочисленное (с округлением
# до целого) деление клеток, соответственно.
# Сложение. Объединение двух клеток. При этом число ячеек общей клетки должно равняться
# сумме ячеек исходных двух клеток.
# Вычитание. Участвуют две клетки. Операцию необходимо выполнять только если разность
# количества ячеек двух клеток больше нуля, иначе выводить соответствующее сообщение.
# Умножение. Создается общая клетка из двух. Число ячеек общей клетки определяется как
# произведение количества ячеек этих двух клеток.
# Деление. Создается общая клетка из двух. Число ячеек общей клетки определяется как
# целочисленное деление количества ячеек этих двух клеток.
# В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и
# количество ячеек в ряду. Данный метод позволяет организовать ячейки по рядам.
# Метод должен возвращать строку вида * ****\n*****\n*****. .., где количество ячеек между \ n
# равно переданному аргументу. Если ячеек на формирование ряда не хватает, то в последний
# ряд записываются все оставшиеся.
# Например, количество ячеек клетки равняется 12, количество ячеек в ряду — 5. Тогда метод
# make_order() вернет строку: *****\n*****\n** .
# Или, количество ячеек клетки равняется 15, количество ячеек в ряду — 5. Тогда метод
# make_order() вернет строку: *****\n*****\n***** .
class Ceil():
def __init__(self, size):
self.size = size
def __add__(self, other):
self.size = self.size + other.size
return self
def __sub__(self, other):
ceil_sub = self.size - other.size
if ceil_sub < 0:
print("Нельзя вычитать из меньшей клетки большую")
else:
self.size = ceil_sub
return self
def __mul__(self, other):
self.size = self.size * other.size
return self
def __truediv__(self, other):
self.size = self.size // other.size
return self
def make_order(self, num):
num_full_rows = self.size // num
last_row = ''.join([char*(self.size % num) for char in '*'])
row = ''.join([char*num for char in '*']) + '\n'
result_str = ''.join(row * num_full_rows) + last_row
return result_str
cl_1 = Ceil(7)
print(cl_1.make_order(3))
cl_2 = Ceil(3)
cl_3 = cl_1 + cl_2
print("cl_3 = cl_1 + cl_2 = ", cl_3.size)
cl_4 = cl_3 - cl_2
print("cl_4 = cl_3 - cl_2 = ", cl_4.size)
cl_5 = cl_4 * cl_2
print("cl_5 = cl_4 * cl_2 = ", cl_5.size)
cl_6 = cl_5 / cl_2
print("cl_6 = cl_5 / cl_2 = ", cl_6.size)
|
# Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое
# слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить
# только первые 10 букв в слове.
my_list = input('Введите слова разделенные пробелом: ').split(" ")
i = 1
for item in my_list:
print(f"{i} {item[:10]}")
i+= 1 |
# programming exercises chapter 3
# exercise 2
# A program that calculates the cost per square inch of a pizza
#changes for programming exercise 5, chapter 6
import math
def pizzaAr(diameter):
pizza = math.pi * (diameter/2)**2
return pizza
def pizzaprice(price,pizza):
pricepsq = price / pizza
return pricepsq
def main():
diameter = eval(input("Enter a diameter of the pizza in inches: "))
price = eval(input("Enter the price of the pizza in Euro: "))
pizza = pizzaAr(diameter)
pricepsq = pizzaprice(price, pizza)
print("The cost per square inch is:", pricepsq)
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.