text
stringlengths 37
1.41M
|
---|
import math
num1 = int(input("ENter the number : "))
#legend method
flag = 1
num2 = int(math.sqrt(num1))+1
for each in range(2,num2):
c = num1%each
if c==0:
flag =0
print ("divisible by", each )
break
if flag==1:
print ("Number is prime ")
else :
print ("Number is not prime")
|
list1 = [1,21,31,1,41,5,101,0,0,4,1,5,6,0,0,1,4,5] #[21,4,4,5,5....... 0, 0,0,0,0]
def fun1(a,b): #1,21,31,41,5,0,0,4,5,6,0,0,4,5
c = a-b
if a ==0 or b==0:
return 1
else :
return c
list1.sort(cmp=fun1)
print (list1)
|
import re
import urllib
url = "http://www.thapar.edu/faculties/category/departments/computer-science-engineering"
html = urllib.urlopen(url)
text=html.read()
p1 = r'\b[\w.-]+?@\w+?\.\w+?\b' #[email protected]
p1 = re.compile(p1)
m1 = re.findall(p1, text)
for email in m1:
print (email)
|
str1 = "waht we think we we become"
for n in range(len(str1)):
if str1.find('we',n)==n:
print n
#print [n for n in xrange(len(text)) if text.find('la', n) == n]
|
list1 = [("Mohit", 80, 31),("Ravender", 80,30),("Bhaskar narayan das", 70,34)]
for k,v,i in list1:
print (k.ljust(20," "),v,i)
|
str1 = "What we think we become"
i = 0
for each in str1:
if each== 'e':
i = i +1
print (i)
|
marks = int(raw_input("Please enter the marks\t"))
grade = ""
if marks>89:
grade = 'A'
elif marks > 70:
grade = "B"
elif marks > 60:
grade = 'C'
else :
grade ='D'
print "Grade of the student is ", grade
|
#from collections import namedtuple
import collections
emp1 =collections.namedtuple("Learntek", 'name age empid', rename= False ) # creating own data type
record1 = emp1('shankar',28, 123456)
print (record1)
print (record1.name)
print (record1.age)
record1= record1._replace(age=25)
print (record1.age)
print (record1.empid)
print (record1)
|
list1 = [1,2,3,4,5,6,7,67,34,12]
'''
def fun1(a):
t = a%2
if t ==1:
return 0
else :
return 1
'''
final_list = filter(lambda a: a%2,list1)
print final_list
|
list1 = [1,2,3,4,5,"a",1.1,5,6]
for each in list1:
print (each)
|
import re
pattern = "this"
text = " in this world nothing is permanent this is last number this"
for match in re.findall(pattern,text):
print "found", match
for match in re.finditer(pattern,text):
print match
s = match.start()
e = match.end()
print "Found", match.re.pattern, s, "from", e
print re.finditer(pattern,text)
|
#variables
#list_of_number = [0, 1, 2, 'blue', 4, 'green'] #list of numbers and strings
# for loops
#for elem in list_of_number:
# print(elem)
#Another for loop example
#for elem in list_of_number: #Goes through each element in the list
# if type(elem) == str: #checks if there is a string element
# continue # tells the loop to continue on to the next element
# print(elem) #prints the elements in the loops that are not strings
#range loop
#for i in range(5):
# print(i)
#while loop
i = 0
#while i < 10:
# print(i)
# i+=1
#i = 0
#while True: #loops forever
# print(i) #prints i
# i = i + 1 # incremets it
# if i == 11: #stops once i reaches 10
# break #break the for loop
|
PI = 3.14
def some_function(x, y, z):
final = x + y + z
return(final)
output = some_function(5, 6, 7)
print(output)
def greet_friend(name, greeting, sentence):
output = "{2}, {0}! {1}".format(greeting, name, sentence)
return(output)
greeting = greet_friend("Jazsmin", "Hey", "How are you do today?")
print(greeting)
def greet_user(greeting):
user = input("Please enter your name. ")
print("{}, {}!".format(greeting, user))
greet_user("Hello")
|
from urllib.request import urlopen
from bs4 import BeautifulSoup
#访问网站时的异常处理
from urllib.error import HTTPError
#判断两种错误的方法(服务器不存在;获取界面发生错误/不存在)
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html.read())
title = bsObj.body.h1
except AttributeError as e:
return None
return title
title = getTitle("http://www.pythonscraping.com/pages/page1.html")
if title == None:
print("Title could not be found")
else:
print(title)
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
#html = urlopen("http://www.pythonscrap.com/")
#服务器不存在
"""
if html is None:
print("URL is not found")
else:
None
#获取界面发生错误
try:
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
except HTTPError as e:
print(e)
"""
bsObj = BeautifulSoup(html.read())
print(bsObj.h1)
print(bsObj.html.h1)
|
'''
List comprehensions
'''
# e.g.
import random
my_list = [random.randint(1, 1000) for i in range(1, 13)]
print(my_list)
'''
Decorators
'''
'''
What if we want to add some further functionality in certain function by using another function?
Here we can use a decorator function to get through the problem in a neat way. Let's see how it works
with an example.
'''
# e.g.
def title_decorator(print_value_function):
def wrapper(*args, **kwargs):
print_value_function(*args, **kwargs)
return wrapper
@title_decorator
def print_value_function(name, age):
print(name + " your age is " + str(age) + ".\n")
print_value_function("Symeon", 26)
'''
Lambdas expressions
'''
'''
A lambda expression is a shorthand for defining a function in a one line function code.
'''
'''
Syntax:
name_of_function = lambda variable: actions
'''
# e.g.
contains_a = lambda word: True if 'a' in word else False
# e.g.
long_string = lambda string: True if len(string) > 12 else False
# e.g.
ends_in_a = lambda my_word: True if my_word[-1] == 'a' else False
print(contains_a("Banana")) # and so on
|
print("Icount:")
print("hens", 25.0 + 30.0 / 6.0)
# gibt ergebnis von 100 - (75 % 4) 1.* 2.% 3.-
print("roosters", 100.0 - 25.0 * 3.0 % 4.0)
#gibt eggs: aus
print("eggs:")
#gibt das ergebnis aus 1.1/4 2.4%2 3.strichrechnungen
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("is it true that 3 + 2 < 5 -7?")
#gibt in true oder false aus ob das > oder < zutrifft
print(3 + 2 < 5 -7)
print("what is 3 + 2?", 3 + 2)
print("what is 5 - 7", 5 - 7)
print("Oh thats why its false")
print("some more")
print("is it greater?", 5 > -2)
print("is it greater or equal", 5 >= -2)
print("is it less or eqal?", 5 <= -2)
|
types_of_anus = 10
x = f"there are {types_of_anus} types od anus."
#gives binary the string binary
binary = "binary"
do_not = "dont't"
y = f"one know {binary} one {do_not}"
print(x)
print(y)
#give out the string in x which givs out the 10 from types of anus
print(f"i said : {x}")
print(f"i also said: '{y}'")
#set hilarious = false
hilarious = False
joke_evaluation = "isn't that joke so funny?! {}"
w = "this is the left side of..."
e = "a string with a right side."
print(w + e)
|
"""
1. Write a program that asks the user for their name, then opens a file called “name.txt” and writes that
name to it.
2. Write a program that opens “name.txt” and reads the name (as above) then prints,
“Your name is Bob” (or whatever the name is in the file).
3. Create a text file called “numbers.txt” (You can create a simple text file in PyCharm with Ctrl+N, choose
“File” and save it in your project). Put the numbers 17 and 42 on separate lines in the file and save it:
17
42
Write a program that opens “numbers.txt”, reads the numbers and adds them together then prints the
result, which should be… 59.
"""
out_file = open("name.txt", "w")
user_name = str(input("Please enter your name: "))
print(user_name, file=out_file)
out_file.close()
in_file = open("name.txt", "r")
user_name = in_file.read()
print("Your name is {}".format(user_name))
in_file.close()
total_sum = 0
in_file = open("numbers.txt", "r")
for line_str in in_file:
total_sum = total_sum + int(line_str)
print("The total sum is {}".format(total_sum))
|
"""
Create a series of widgets for a list of names
"""
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.core.window import Window
class NameListApp(App):
"""Main program. Create a series of labels for a list of names."""
_names = ["Adam", "Bill", "Charlie", "David"]
def build(self):
Window.size = (600, 400)
self.title = "Name List"
self.root = Builder.load_file('name_list.kv')
self.create_widget()
return self.root
def create_widget(self):
# Create label for each person
for name in self._names:
temp_label = Label(text=name, id=name)
self.root.ids.entity_container.add_widget(temp_label)
NameListApp().run()
|
'''This Programme Takes Random Number And Genrates given no. of triangles. It also finds the incircle and calculates the area of maximum cirlce possible. At the end it generates a parallelogram parallel to y-axis and having the minimum area that covers all the triangles.'''
import sys
import random
import math
import graphviz as gv
from subprocess import call
#Graphviz variable Graph_detail contains all details regarding the graph
GRAPH_DETAIL = gv.Graph(format='dot')
GRAPH_DETAIL.node('inv_node', style='invis', pos='0, 0!')
GRAPH_DETAIL.node('inv_node_corner', style='invis', pos='1600, 1600!')
GRAPH_DETAIL.edge('inv_node', 'inv_node_corner', style='invis')
n = 0
class Triangle:
'''Takes two random co-ordinate generated in range of 400-1200 and calculates the position of third vertex accordingly. In case cant generte than again takes random number till all the three vertices generated. Also calcultes the area of triangle, circle'''
#Constructor Initializes all the triangle co-ordinates and calculates the co-ordinate of third vertex. Calculates Triangle area, Circle Area
#Also contains all geters to get value of all varibles of triangle class
def __init__(self, x1, y1, x2, y2,):
self.x1 = x1
self.x2 = x2
self.x3 = -1
self.y1 = y1
self.y2 = y2
self.y3 = -1;
s60 = math.sin((60 * math.pi)/180)
c60 = math.cos((60 * math.pi)/180)
self.tx3 = c60 * (self.x1 - self.x2) - s60 * (self.y1 - self.y2) + self.x2
self.ty3 = s60 * (self.x1 - self.x2) + c60 * (self.y1 - self.y2) + self.y2
self.tx4 = c60 * (self.x1 - self.x2) + s60 * (self.y1 - self.y2) + self.x2
self.ty4 = -1*s60 * (self.x1 - self.x2) + c60 * (self.y1 - self.y2) + self.y2
while(self.x3<400 or self.y3<400 or self.x3>1200 or self.y3>1200):
if self.tx3>400 and self.ty3>400 and self.tx3<1200 and self.ty3<1200:
self.x3 = self.tx3;
self.y3 = self.ty3;
elif self.tx4>400 and self.ty4>400 and self.tx4<1200 and self.ty4<1200:
self.x3 = self.tx4;
self.y3 = self.ty4;
else:
self.x1 = random.uniform(400, 1200)
self.x2 = random.uniform(400, 1200)
self.y1 = random.uniform(400, 1200)
self.y2 = random.uniform(400, 1200)
self.tx3 = c60 * (self.x1 - self.x2) - s60 * (self.y1 - self.y2) + self.x2
self.ty3 = s60 * (self.x1 - self.x2) + c60 * (self.y1 - self.y2) + self.y2
self.tx4 = c60 * (self.x1 - self.x2) + s60 * (self.y1 - self.y2) + self.x2
self.ty4 = -1*s60 * (self.x1 - self.x2) + c60 * (self.y1 - self.y2) + self.y2
self.side_length = math.sqrt((self.x2-self.x1)**2 + (self.y2-self.y1)**2)
self.triangle_area = ((math.sqrt(3))*(self.side_length)*self.side_length)/4
self.circle_radius = (math.sqrt(3)*self.side_length)/6
self.circle_x = ((self.x1*self.side_length) + (self.x2*self.side_length) + (self.x3*self.side_length))/(3*(self.side_length))
self.circle_y = ((self.y1*self.side_length) + (self.y2*self.side_length) + (self.y3*self.side_length))/(3*(self.side_length))
self.circle_area = (math.pi)*(self.circle_radius)*(self.circle_radius)
#returns triangle area
def get_triangle_area(self):
return self.triangle_area
#returs triangle side length
def get_side_length(self):
return self.side_length
#returns x1 co-ordinate
def get_x1(self):
return self.x1
#returns x2 co-ordinate of triangle
def get_x2(self):
return self.x2
#returns x3 co-ordinate of triangle
def get_x3(self):
return self.x3
#returns y1 co-ordinate of triangle
def get_y1(self):
return self.y1
#returns y2 co-ordinate of triangle
def get_y2(self):
return self.y2
#returns y3 co-ordinate of triangle
def get_y3(self):
return self.y3
#returns x cordinate of center of circle
def get_circle_x(self):
return self.circle_x
#returns y cordinate of center of circle
def get_circle_y(self):
return self.circle_y
#returns radius of circle
def get_circle_radius(self):
return self.circle_radius
#returns area of circle
def get_cirlce_area(self):
return self.circle_area
def make_Triangle(x, *args):
'''Make all the triangles in the graph'''
s1 = str(x.get_x1()) + "," + str(x.get_y1()) + "!"
GRAPH_DETAIL.node('a'+ str(x), label="", shape="point", pos=s1)
s1 = str(x.get_x2()) + "," + str(x.get_y2()) + "!"
GRAPH_DETAIL.node('b' + str(x), label="", shape="point", pos=s1)
s1 = str(x.get_x3()) + "," + str(x.get_y3()) + "!"
GRAPH_DETAIL.node('c' + str(x), label="", shape="point", pos=s1)
GRAPH_DETAIL.edge('a' + str(x), 'b' + str(x))
GRAPH_DETAIL.edge('b' + str(x), 'c' + str(x))
GRAPH_DETAIL.edge('c' + str(x), 'a' + str(x))
def make_Circle(x, *args):
'''make all the circles'''
s1 = str(x.get_circle_x()) + ',' + str(x.get_circle_y()) + '!'
GRAPH_DETAIL.node('c1' + str(x), label="", shape='circle', pos = s1, width=str(x.get_circle_radius()/36.4), color='green')
class Point2D(object): #convex hull source :
#References
#https://github.com/berkaykicanaoglu/Convex-Hull-using-Monotone-Chain/blob/master/convex-//hull.py
# constructor for the point class
def __init__(self, x, y):
self.x = x
self.y = y
# override the representation method
def __repr__(self):
return "(%f, %f)" %(self.x, self.y)
def getCoordinates(self):
return [self.x, self.y]
class Line2D(object):
# constructor for the line class
def __init__(self, point1, point2):
self.p1 = point1
self.p2 = point2
# calculate the slope of the line
self.slope = (self.p2.y - self.p1.y) \
/ (self.p2.x - self.p1.x)
# set the variable derivative
if self.slope > 0:
self.derivative = "positive"
elif self.slope == 0:
self.derivative = "none"
else:
self.derivative = "negative"
# return the slope
def getSlope(self):
return self.slope
def orientation(self,line2):
# get slopes
slope1 = self.getSlope()
slope2 = line2.getSlope()
# get difference
diff = slope2-slope1
# determine orientation
if diff > 0:
return -1 # counter-clockwise
elif diff == 0:
return 0 # colinear
else:
return 1 # clockwise
#----------------------------
# Helper functions
#----------------------------
def getX(point):
return point.x
def getY(point):
return point.y
def sortPoints(point_list):
point_list = sorted(point_list,key = getX)
# This function do not account for comparison
# of two points at the same x-location. Resolve!
return point_list
def ConvexHull(point_list):
# initalize two empty lists for upper
# and lower hulls.
upperHull = []
lowerHull = []
# sort the list of 2D-points
sorted_list = sortPoints(point_list)
for point in sorted_list:
if len(lowerHull)>=2:
line1 = Line2D(lowerHull[len(lowerHull)-2],\
lowerHull[len(lowerHull)-1])
line2 = Line2D(lowerHull[len(lowerHull)-1],\
point)
while len(lowerHull)>=2 and \
line1.orientation(line2) != -1:
removed = lowerHull.pop()
if lowerHull[0] == lowerHull[len(lowerHull)-1]:
break
# set the last two lines in lowerHull
line1 = Line2D(lowerHull[len(lowerHull)-2],\
lowerHull[len(lowerHull)-1])
line2 = Line2D(lowerHull[len(lowerHull)-1],\
point)
lowerHull.append(point)
# reverse the list for upperHull search
reverse_list = sorted_list[::-1]
for point in reverse_list:
if len(upperHull)>=2:
line1 = Line2D(upperHull[len(upperHull)-2],\
upperHull[len(upperHull)-1])
line2 = Line2D(upperHull[len(upperHull)-1],\
point)
while len(upperHull)>=2 and \
line1.orientation(line2) != -1:
removed = upperHull.pop()
if upperHull[0] == upperHull[len(upperHull)-1]:
break
# set the last two lines in lowerHull
line1 = Line2D(upperHull[len(upperHull)-2],\
upperHull[len(upperHull)-1])
line2 = Line2D(upperHull[len(upperHull)-1],\
point)
upperHull.append(point)
# final touch: remove the last members
# of each point as they are the same as
# the first point of the complementary set.
removed = upperHull.pop()
removed = lowerHull.pop()
# concatenate lists
convexHullPoints ={
"lowerHull" : lowerHull ,
"upperHull":upperHull}
return convexHullPoints
def main():
FILE1 = open(sys.argv[1], "r")
for x in FILE1:
n = int(x)
collection = []
#Random co-ordinate generation of n triangles
for i in range(0, n):
t1 = Triangle(random.uniform(400, 1200), random.uniform(400, 1200), random.uniform(400, 1200), random.uniform(400, 1200))
collection.append(t1)
for x in collection:
make_Triangle(x)
make_Circle(x)
print x.get_x1(), x.get_y1(), x.get_x2(), x.get_y2(), x.get_x3(), x.get_y3(), x.get_triangle_area(), x.get_circle_x(), x.get_circle_y(), x.get_cirlce_area(), x.get_circle_radius()
# Read the points from the vertices of random triangles
point_list = []
for x in collection:
point = Point2D(x.get_x1(),x.get_y1())
point_list.append(point)
point = Point2D(x.get_x2(),x.get_y2())
point_list.append(point)
point = Point2D(x.get_x3(),x.get_y3())
point_list.append(point)
# call the convex hull (Monotone Chain) function
convexSet_list = ConvexHull(point_list)
min_x=getX(convexSet_list['lowerHull'][0]);
max_x=getX(convexSet_list['lowerHull'][0]);
for point in set(convexSet_list['lowerHull']+convexSet_list['upperHull']):
if getX(point) < min_x :
min_x=getX(point)
if getX(point) > max_x :
max_x=getX(point)
best_para={
"area":1600*1600,
"points":[]
}
new_list=convexSet_list['lowerHull']+convexSet_list['upperHull']
#intialised with max area possible
for i in range(len(new_list)):
if (i==len(new_list)-1): #taking adjacent edges
x1=getX(new_list[i])
y1=getY(new_list[i])
x2=getX(new_list[0])
y2=getY(new_list[0])
else:
x1=getX(new_list[i])
y1=getY(new_list[i])
x2=getX(new_list[i+1])
y2=getY(new_list[i+1])
b = x2 - x1 #ax +by +c=0
a = y1 - y2
c = - 1 * (a * x1 +b * y1)
farthest_point = new_list[0];
distance=abs(a*getX(new_list[0]) + b * getY(new_list[0]) + c)
for point in range(1,len(new_list)):
if distance < abs(a*getX(new_list[point]) + b * getY(new_list[point]) + c): #this is not actual distance I have not divided
farthest_point = new_list[point]; #with square_root(a*a+b*b) since it is constant
distance = abs(a*getX(new_list[point]) + b * getY(new_list[point]) + c)
c2 = -1 *(a * getX(farthest_point) + b * getY(farthest_point))
#Parallel Line passing from the farthest point
py1 = (-c - a * min_x)/b
py2 = (-c - a * max_x)/b
py3 = (-c2 - a * max_x)/b
py4 = (-c2 - a * min_x)/b
area = (abs(min_x * (py2-py4) + max_x * (py4-py1) + min_x * (py1-py2))+abs(min_x * (py2-py3) + max_x * (py3-py4) + max_x * (py4-py2)))/2
if best_para['area'] > area:
best_para['area']=area
best_para['points']=[(min_x,py1),(max_x,py2),(max_x,py3),(min_x,py4)]
px1 = best_para['points'][0][0]
py1 = best_para['points'][0][1]
s = str(px1) + "," + str(py1) + "!"
GRAPH_DETAIL.node('parraleogram_a', label="", shape="point", pos=s)
px2 = best_para['points'][1][0]
py2 = best_para['points'][1][1]
s = str(px2) + "," + str(py2) + "!"
GRAPH_DETAIL.node('parraleogram_b', label="", shape="point", pos=s)
px3 = best_para['points'][2][0]
py3 = best_para['points'][2][1]
s = str(px3) + "," + str(py3) + "!"
GRAPH_DETAIL.node('parraleogram_c', label="", shape="point", pos=s)
px4 = best_para['points'][3][0]
py4= best_para['points'][3][1]
print px1, py1, px2, py2, px3, py3, px4, py4,best_para["area"]
s = str(px4) + "," + str(py4) + "!"
GRAPH_DETAIL.node('parraleogram_d', label="", shape="point", pos=s)
GRAPH_DETAIL.edge('parraleogram_a', 'parraleogram_b', color='red')
GRAPH_DETAIL.edge('parraleogram_b', 'parraleogram_c', color='red')
GRAPH_DETAIL.edge('parraleogram_c', 'parraleogram_d', color='red')
GRAPH_DETAIL.edge('parraleogram_d', 'parraleogram_a', color='red')
file_output = open('outputGraph.dot', 'w')
file_output.write(str(GRAPH_DETAIL))
file_output.close()
call(["neato","-n", "-Tpng", "outputGraph.dot", "-o", "graph_image.png"])
if __name__=="__main__":
main()
|
print('hello')
num =0
for (num < 100
print("hello", num)
|
"""OOP examples for module 2"""
import pandas as pd
class MyDataFrame(pd.DataFrame):
"""Inheriting from Pandas DataFrame Class proof of concept"""
def num_cells(self):
return self.shape[0] * self.shape[1] # returns number of cells in df
class BareMinimumClass:
"""Basic proof of concept"""
pass
class Complex:
def __init__(self, realpart, imagpart):
"""
Constructor for complex numbers.
Complex numbers have a real part and imaginary part.
"""
self.r = realpart
self.i = imagpart
def add(self, other_complex):
self.r += other_complex.r
self.i += other_complex.i
def __repr__(self):
return '({}, {})'.format(self.r, self.i)
class SocialMediaUser:
""" A social media class that takes name, location, and upvotes"""
def __init__(self, name, location, upvotes=0):
self.name = str(name)
self.location = location
self.upvotes = int(upvotes)
def recieve_upvotes(self, num_upvotes=1):
self.upvotes += num_upvotes
def is_popular(self):
return self.upvotes > 100
class Animal:
"""General Representation of Animals"""
def __init__(self, name, weight, diet_type):
self.name = str(name)
self.weight = float(weight)
self.diet_type = diet_type
def run(self):
return "Vroom, Vroom, I go quick"
def eat(self, food):
return "Huge fan of that " + str(food)
# inheriting from Animal class
class Sloth(Animal):
"""Inheriting from the Animal Class"""
def __init__(self, name, weight, diet_type, num_naps):
# super is referring to the Animal class - lets us use those attribute declerations
super().__init__(name, weight, diet_type)
self.num_naps = int(num_naps)
# new method not within the Animal class
def say_something(self):
return "This is a sloth of typing"
# overwrites the run method from the parent (Animal) class
def run(self):
return "I am slow sloth guy"
class Person():
def __init__(self, name, age, bloodtype, haircolor):
self.name = str(name)
self.age = int(age)
self.bloodtype = str(bloodtype)
self.haircolor = str(haircolor)
def birthday(self):
"""
Increases age by 1
"""
return self.age + 1
def hairchange(self, color):
"""
changes the hair color
"""
return str(color)
# This condition will only hold true if the module is ran (python oop_example.py) and not imported
if __name__ == '__main__':
num1 = Complex(3, 5)
num2 = Complex(4, 2)
num1.add(num2)
print(num1.r, num1.i)
user1 = SocialMediaUser('Justin', 'Provo')
user2 = SocialMediaUser('Nick', 'Logan', 200)
user3 = SocialMediaUser(name='Carl', location='Costa Rica', upvotes=100000)
user4 = SocialMediaUser('George Washington', 'Djibouti', 2)
print('name: {}, is popular: {}, num upvotes: {}'.format(user4.name, user4.is_popular(), user4.upvotes))
print('name: {}, is popular: {}, num upvotes: {}'.format(user3.name, user3.is_popular(), user3.upvotes))
name = Person('Justin', 17, 'o', 'black')
name1 = Person('Joe', 25, 'b', 'blond')
print('Hello, {}! my name is {}, nice to meet you!'.format(name.name, name1.name))
print("Today's birthday is {}! he is turning {}.".format(name.name, name.birthday()))
print("{}'s hair is the color {}. He wants to dye it to match {}'s hair. {}'s hair is now {}.".format(name.name, name.haircolor, name1.name, name.name, name.hairchange('blond')))
|
#'intersection (commune) de deux Sets et supprimez ces éléments du premier Set
set1 = {23,11,3,4,13,8,34,54,6,29}
set2 = {11,4,2,36,345,78,23,867,788}
intersection = set1 & set2 #l'intersection de set 1 et de set 2
print("intercection",intersection)
set1 = set1 - intersection #set 2 apres la suppression
print("Set 1 après suppression :",set1)
|
#e un programme pour itérer une liste donnée et compter l'occurrence de chaque élément et créer un dictionnaire pour montrer le nombre de chaque élément
List= [7,8,45,7,234,5,21,678,1,345,234,1,1,1,7]
dict={} #la dictionnaire
for i in List:
List.count(i)
dict[i]=List.count(i)
print (dict)
|
# let's write a script that tells us the most common character in
# adventures of sherlock holmes.
with open("english/adventures_of_sherlock_holmes.txt", 'r', encoding="utf8") as rf:
text = rf.read()
unique_characters = set(text)
# current most common character
most_common_character = []
# how often character occurs
character_freq = 0
# go through each character and count how often it occurs
for char in unique_characters:
if char != " ":
# get frequency
freq = text.count(char)
# check if freq is greater than character_freq
if freq > character_freq:
character_freq = freq
most_common_character = [char]
elif freq == character_freq:
most_common_character.append(char)
print(f"The most common character is {most_common_character}, which occurs {character_freq} times.")
print(f"The length of this text is {len(text)}, with {len(unique_characters)} unique characters")
|
# let's write a script that tells us the most common character in
# adventures of sherlock holmes.
with open("english/adventures_of_sherlock_holmes.txt", 'r', encoding="utf8") as rf:
text = rf.read().lower()
# tokenize the text into words
words = text.split(" ")
print(words[100:110])
unique_word = set(words)
# current most common character
most_common_word = []
# how often character occurs
word_freq = 0
# go through each character and count how often it occurs
for word in unique_word:
if word != "":
# get frequency
freq = words.count(word)
# check if freq is greater than word_freq
if freq > word_freq:
word_freq = freq
most_common_word = [word]
elif freq == word_freq:
most_common_word.append(word)
print(f"The most common character is {most_common_word}, which occurs {word_freq} times.")
print(f"The length of this text is {len(words)}, with {len(unique_word)} unique words")
|
# lists!
# an ordered container for information/python objects
# create a list with square brackets and each item is seperated
# with a comma
name_list = ["Juan", "Rogier", "Ying", "Cindy"]
# a list can be empty
empty_list = []
# can contain basic data types
int_list = [1, 2, 3, 4, 5, 6, 7]
float_list = [1.0, 3.4, -.5]
# you can mix datatypes
mixed_list = [1, "hello", 4.4]
# you can have lists of lists
list_list = [[1,3], [2,4,6], ["tree", "rock", "boat", "gorge"]]
# lists always keep the same order
int_list = [4, 12, -1, 2, 5]
#print first item
print(int_list[0])
# print last item
print(int_list[-1])
# get a slice from a list
print(int_list[2:4])
# get index of -1
print(int_list.index(-1))
# change value in list
int_list[2] = 10
print(int_list)
# add an item to a list
int_list.append(6)
print(int_list)
# remove item from list
removed_value = int_list.pop(1)
print(int_list)
print(removed_value)
# add value at index
int_list.insert(1,42)
print(int_list)
# we can turn strings into lists
greeting = "Hello, my name is Paul"
# Turn into a list
greeting_list = list(greeting)
print(greeting_list)
# more turn into list
greeting_words = greeting.split(" ")
print(greeting_words)
# turn back into list
new_greeting = " ".join(greeting_words)
print(new_greeting)
# get the lenght of a list
len(int_list)
min(int_list)
max(int_list)
int_list.reverse()
print(int_list)
int_list.sort(reverse=True)
print(int_list)
name_list.sort()
print(name_list)
|
"""
Integers vs. Strings 0
Write a script that displays the sum and product of two numbers.
This script uses 4 variables. Your script should do the same with 2.
"""
x = 10
y = 20
print(x+y)
print(x*y)
|
"""
Integers vs. Strings 1
1. How many variables are used in this script, and what are their names?
2. What does Python say the types of these variables are?
3. Fix the spacing between the words, and describe how you did it.
"""
someText = 'Oh happy day.'
otherText = "I'm on my way."
together = ('someText + otherText')
#3 i put the two variables together to add them
#2 python says they are both Strings
#1 there is two variables
|
# To-do: How do I add integers to fractions etc?
# Is it okay to use in-place modification for binary operations?
class breuk:
def euclidesalg(self, a, b):
while a > 0 and b > 0:
if a > b:
a -= b
else:
b -= a
return a
def __init__(self, numerator=0, denominator=1):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return str(self.numerator) + '/' + str(self.denominator)
# x<y
def __lt__(self,other):
if self.numerator/self.denominator < other.numerator/other.denominator:
return True
else:
return False
# x<=y
def __le__(self,other):
if self.numerator/self.denominator <= other.numerator/other.denominator:
return True
else:
return False
# x==y
def __eq__(self,other):
if self.numerator == other.numerator and self.denominator == other.denominator:
return True
else:
return False
# x!=y
def __ne__(self,other):
if self.numerator == other.numerator and self.denominator == other.denominator:
return False
else:
return True
# x>y
def __gt__(self,other):
if self.numerator/self.denominator > other.numerator/other.denominator:
return True
else:
return False
# x>=y
def __ge__(self,other):
if self.numerator/self.denominator >= other.numerator/other.denominator:
return True
else:
return False
# Unary arithmetic operations
def __neg__(self):
numerator = -self.numerator
return breuk(numerator, self.denominator)
def __pos__(self):
numerator = +self.numerator
return breuk(numerator,self.denominator)
def __abs__(self):
numerator = abs(self.numerator)
return breuk(numerator,self.denominator)
# Binary arithmetic operations
# a/b + c/d = (ad + cb) / bd
def __add__(self, other):
numerator, denominator = self.numerator*other.denominator + other.numerator*self.denominator , self.denominator*other.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b - c/d = (ad - cb) / bd
def __sub__(self, other):
numerator , denominator = self.numerator*other.denominator - other.numerator*self.denominator , self.denominator*other.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b * c/d = ac / bd
def __mul__(self, other):
numerator , denominator = self.numerator*other.numerator , self.denominator*other.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b / c/d = ad / bc
def __truediv__(self, other):
numerator , denominator = self.numerator*other.denominator , self.denominator*other.numerator
output = breuk(numerator,denominator)
output.normalize()
return output
# Binary arithmetic operations, reversed
# a/b + c/d = (ad + cb) / bd
def __radd__(self, other):
numerator , denominator = other.numerator*self.denominator + self.numerator*other.denominator , other.denominator*self.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b - c/d = (ad - cb) / bd
def __rsub__(self, other):
numerator , denominator = other.numerator*self.denominator - self.numerator*other.denominator , other.denominator*self.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b * c/d = ac / bd
def __rmul__(self, other):
numerator , denominator = other.numerator*self.numerator , other.denominator*self.denominator
output = breuk(numerator,denominator)
output.normalize()
return output
# a/b / c/d = ad / bc
def __rtruediv__(self, other):
numerator , denominator = other.numerator*self.denominator , other.denominator*self.numerator
output = breuk(numerator,denominator)
output.normalize()
return output
# Casting to integer and float
def __int__(self):
return int(self.numerator / self.denominator)
def __float__(self):
return float(self.numerator / self.denominator)
# Deel beide argumenten door hun grootste gemene deler
def normalize(self):
a = abs(max(self.numerator,self.denominator))
b = abs(min(self.numerator, self.denominator))
# Gives largest common divisor of a and b
lcd = self.euclidesalg(a,b)
self.numerator = self.numerator // lcd
self.denominator = self.denominator // lcd
|
# The quicksort code won't be commented, since it's a common algorithm.
from random import randint
from time import time_ns as time
def quicksort(list, left=0, right=-1):
"""Sorts a list L by using quicksort. Fails for lists that have more than
1000 elements of the same value."""
if right == -1:
right = len(list) - 1
idx = split(list, left, right)
if idx-1 > left:
quicksort(list, left, idx-1)
if idx+1 < right:
quicksort(list, idx+1, right)
def split(list, left, right):
pivot = randint(left, right)
comparison = list[pivot]
list[pivot], list[right] = list[right], list[pivot]
idx = left
for j in range(left, right):
if list[j] < comparison:
list[idx], list[j] = list[j], list[idx]
idx += 1
list[idx], list[right] = list[right], list[idx]
return idx
'''
difficulties = [int(x) for x in input().split()]
smartness = [int(x) for x in input().split()]
# Sort both inplace
quicksort(difficulties)
quicksort(smartness)
solved = True
for idx, problem in enumerate(difficulties):
if not (problem <= smartness[idx] and problem >= smartness[idx]/2):
# Fail :(
solved = False
break
if solved:
print("mogelijk")
else:
print("onmogelijk")
'''
times = []
for exp in range(25):
try:
randlist = [randint(0, 1000) for x in range(2 ** exp)]
tic = time()
quicksort(randlist)
toc = time()
times.append(toc-tic)
print("Finished size", 2**exp, "in", (toc-tic)/10**9, "seconds.")
except RecursionError:
print("Reached recursion depth.")
pass
print(times)
|
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('Olá Python!')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
n1 = int (input('Digite um valor: '))
n2 = int (input('Digite outro valor: '))
p = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print('A soma entre {} e {} vale {}'.format(n1, n2, p))
print('O produto é: {}, a divisão é: {}, a divisão inteira é: {}, e a exponenciação é: {}'.format(m, d, di, e))
|
import tkinter as tk
class PongLogicGui:
"""
Den här klassen skickar information mellan de olika widgetarna. Den innehåller också
gameLoop som styr rörelser i PongArea. Den här klassen hämtar information från en
widget genom att definiera en funktion som tilldelas widgeten och den skickar information
till en widget som adderat sig som en listener av sin typ.
"""
def __init__(self, gameLogic=None):
self.gameLogic = gameLogic
self.play = False
self.root = tk.Tk()
self.pongArea = PongArea(self.root, width=300, height=100, bg='white')
self.pongAreaObjects = self.pongArea.objects
menuFunctions = [self.stop, self.start, self.paus, self.restart]
self.menu = Menu(self.root, menuFunctions)
self.pongArea.pack(side=tk.LEFT)
self.menu.pack()
# menu functions
def start(self):
self.play = True
self.gameLoop()
def stop(self):
print("sett self.play = False")
self.play = False
def paus(self):
print("self.play", self.play)
def restart(self):
pass
# END menu functions
def gameLoop(self):
if self.play:
print("hello hello hello")
self.root.after(1000, self.gameLoop)
def mainloop(self):
self.root.mainloop()
class PongArea(tk.Canvas):
"""
Representation av spelytan. Här ritas paddlar och boll.
"""
def __init__(self, root, **kwargs):
super(PongArea, self).__init__(root, **kwargs)
self.objects = []
self.objects.append(self.create_oval(50, 25, 50 + 50, 25 + 50, fill="blue"))
class Menu(tk.Frame):
"""
Meny med knapparna start, stop, paus, och restart.
"""
def __init__(self, root, funcList=None, **kwargs):
super(Menu, self).__init__(root, **kwargs)
if funcList is None:
funclist = [None, None, None, None]
self.buttons = [Stop(self, text='Stop', command=funcList[0]), Start(self, text='Start', command=funcList[1]),
Paus(self, text='Paus', command=funcList[2]), Restart(self, text='Restart', command=funcList[3])]
for button in self.buttons:
button.pack()
class Button(tk.Button):
"""
En knapp. Alla knapp objekt ärver den här klassen.
"""
def __init__(self, root, **kwargs):
super(Button, self).__init__(root, **kwargs)
class Start(Button):
def __init__(self, root, **kwargs):
super(Start, self).__init__(root, **kwargs)
class Stop(Button):
def __init__(self, root, **kwargs):
super(Stop, self).__init__(root, **kwargs)
class Paus(Button):
def __init__(self, root, **kwargs):
super(Paus, self).__init__(root, **kwargs)
class Restart(Button):
def __init__(self, root, **kwargs):
super(Restart, self).__init__(root, **kwargs)
|
# 内部函数对外部函数作用域里变量的引用(非全局变量)则称内部函数为闭包
def counter(start=0):
count=[start]
def incr():
count[0]+=1
return count[0]
return incr
c1=counter(10)
print(c1())
# 结果:11
print(c1())
# 结果:12
# nonlocal访问外部函数的局部变量
# 注意start的位置,return的作用域和函数内的作用域不同
def counter2(start=0):
def incr():
nonlocal start
start+=1
return start
return incr
c1=counter2(5)
print(c1())
print(c1())
c2=counter2(50)
print(c2())
print(c2())
print(c1())
print(c1())
print(c2())
print(c2())
|
#!/bin/python
# 1.1 Are all symbols in string unique?
def sym_unique(str):
symbols = []
unique = True
for e in str:
if unique is False:
break
if e in symbols:
unique = False
break
else:
symbols.append(e)
print(unique)
# 1.3 Are two strings anagrams?
def anagrams(str1, str2):
t1 = sorted(tuple(str1))
t2 = sorted(tuple(str2))
res = (t1 == t2)
print(res)
#1.4 Replace all whitespaces with '%20'
def spaces(data):
res = ''
for e in data:
if e == ' ':
res += '%20'
else:
res += e
print(res)
#1.5 Zip strings with same symbols counters (aaabbc -> a3b2c). If result > original then return original
def zip_str(data):
last = None
cnt = 0
res = ''
for i in range(len(data)):
e = data[i]
if last is None:
last = e
continue
if last == e:
if cnt == 0:
cnt = 2
else:
cnt+=1
else:
res += last
last = e
if cnt > 1:
res += str(cnt)
cnt = 1
res += last
if cnt > 1:
res += str(cnt)
print(data)
if len(res) < len(data):
print(res)
else:
print(data)
#1.7 is str2 shift of str2? Use 'in' only once
def is_shift(str1, str2):
res = False
if len(str1) != len(str1):
return res
t1 = sorted(tuple(str1))
t2 = sorted(tuple(str2))
if t1 != t2:
return res
tmp = ''
for i in range(len(str1)):
for j in range(len(str2)):
if str1[i] == str2[j]:
print(i)
print(j)
k = j
while str2[k] == str1[k]:
k+=1
if k == len(str1) - 1:
print (str2[j:k])
return res
### RUN
#sym_unique("abr")
#anagrams('abra', 'bara')
#spaces('this is a test')
#zip_str('aaabbcdeeef')
res = is_shift('erbottlewat', 'waterbottle')
print(res)
|
#OUTPUT
#1
#1 2
#1 2 3
#1 2 3 4
#1 2 3 4 5
#1 2 3 4 5 6
n = int(input("select number of rows:", ))
def num_patt1(n):
for i in range(0, n):
for j in range(0, i+1):
print(i+1, end=" ")
print("\r")
if __name__ == '__main__':
num_patt1(n)
|
import random
import colorama
from termcolor import colored
GUESS = 'Guess #{}: '
PROMPT = 'Pick a number between 1 and {}'
LESS = 'My number is LESS THAN (<) {}'
GREATER = 'My number is GREATER THAN (>) {}'
def difficulty_output():
print('Guessing Game')
print('Choose your difficulty')
print('1 - Easy (1-10)')
print('2 - Less Easy (1-100)')
print('3 - Crazy Town (1-1000)')
def get_choice():
n = 0
while not n:
try:
difficulty_output()
choice_num = input('Difficulty choice: ')
n = int(choice_num)
except ValueError:
n = 0
finally:
if not 1 <= n <= 3:
n = 0
print('Not a valid option. Please try again')
print()
return n
def game_loop(n):
start_range = 1
end_range = 10**n
random.seed()
guess_me = random.randint(start_range, end_range)
user_guess = 0
num_guesses = 1
print(PROMPT.format(end_range))
while user_guess != guess_me:
try:
nb_guess = input(GUESS.format(num_guesses))
user_guess = int(nb_guess)
except ValueError:
user_guess = -1
finally:
if 1 > user_guess or user_guess > end_range:
print(PROMPT.format(end_range))
elif guess_me < user_guess:
print(colored(LESS.format(user_guess), 'green', attrs=['bold']))
num_guesses += 1
elif guess_me > user_guess:
print(colored(GREATER.format(user_guess), 'red', attrs=['bold']))
num_guesses += 1
print()
print('Good Job! It took you {} guesses.'.format(num_guesses))
if __name__ == '__main__':
colorama.init()
continue_game = 'y'
while continue_game == 'y':
game_loop(get_choice())
print()
continue_text = input('Play again (Yes or No): ')
if continue_text:
continue_game = continue_text[0].lower()
else:
continue_game = 'n'
|
name = input("*****:enter the god name:*****")
print(len(name))
print()
|
from random import randint
INITIAL_POPULATION = 1000
def main():
print("Welcome to the Gopher Population Simulator")
print("Starting Population:", INITIAL_POPULATION)
population = INITIAL_POPULATION
for x in range(1, 10):
gophersBirth = randint(int(population * 0.1), int(population * 0.2))
gophersDeath = randint(int(population * 0.05), int(population * 0.25))
print("Year,", x)
print(5 * "*")
print(gophersBirth, "gophers were born.", gophersDeath, "died")
population = population - gophersDeath + gophersBirth
print("Population:", population, "\n")
main()
|
from excecoes import LanceInvalido
class Usuario:
def __init__(self, nome, carteira):
self.__nome = nome
self.__carteira = carteira
def propoe_lance(self, leilao,valor):
if not self.__valor_eh_valido(valor):
raise LanceInvalido('O usuário não pode propor lances maior do que o valor contido na carteira ! __SALDO INSUFICIENTE__')
lance = Lance(self, valor)
leilao.propoe(lance)
self.__carteira -= valor
@property
def nome(self):
return self.__nome
@property
def carteira(self):
return self.__carteira
def __valor_eh_valido(self, valor):
return valor <= self.__carteira
class Lance:
def __init__(self, usuario, valor):
self.usuario = usuario
self.valor = valor
class Leilao:
def __init__(self, descricao):
self.descricao = descricao
self.__lances = []
self.maior_lance = 0.0
self.menor_lance = 0.0
def propoe(self, lance: Lance):
if self.lance_eh_valido(lance):
if not self.__tem_lances():
self.menor_lance = lance.valor
self.maior_lance = lance.valor
self.__lances.append(lance)
@property
def lances(self):
return self.__lances[:]
def __tem_lances(self):
return self.__lances
def __usuarios_diferentes(self, lance):
if self.__lances[-1].usuario != lance.usuario:
return True
else:
raise LanceInvalido('O usuário não pode dar dois lances seguidos.')
def __valor_maior_que_lance_anterior(self, lance):
if lance.valor > self.__lances[-1].valor:
return True
else:
raise LanceInvalido('O valor do lance deve ser maior que o lance anterior')
def lance_eh_valido(self,lance):
return not self.__tem_lances() or (self.__usuarios_diferentes(lance) and
self.__valor_maior_que_lance_anterior(lance))
|
"""Module that handles displaying of adventure-games story"""
import curses
import textwrap
class StoryScreen:
"""Story Screen Class, can display parts of the games' story"""
def __init__(self, screen):
"""StoryScreen's init function"""
# hold current screen
self.screen = screen
# Print the Story-Screen to given screen.
def print(self):
"""Prints story-screen"""
screen_size = self.screen.getmaxyx()
story_win = curses.newwin(screen_size[0], screen_size[1], 0, 0)
story_win.addstr(1, 4, "Story Name")
story_image = curses.newwin(
int(screen_size[0] * 0.50), int(screen_size[1] - 5), 2, 3)
story_image.border()
story_win.addstr(
int(screen_size[0] * 0.92), int(screen_size[1]*0.845),
"Weiter (w)")
text = "Lorem ipsum dolor sit amet, consetetur "
text += "et accusam et justo duo dolores et"
text += "ea rebum. Stet clita kasd gubergren, no sea takimata"
text += "sanctus est Lorem ipsum dolor sit amet."
text += "Lorem ipsum dolor sit amet, consetetur sadipscing"
text += "elitr, sed diam nonumy eirmod tempor "
text += "invidunt ut labore et dolore magn"
story = curses.newwin(int(screen_size[0] * 0.35),
int(screen_size[1] - 5),
int(1 + screen_size[0] * 0.55), 3)
story_size = story.getmaxyx()
story.border()
story_content = curses.newwin(
int(story_size[0] * 0.74), int(story_size[1]*0.95),
int(screen_size[0] * 0.63), 5)
story_content.addstr(1, 0, textwrap.fill(text, 750))
self.screen.clear()
story_win.refresh()
story_image.refresh()
story.refresh()
story_content.refresh()
|
"""
Interfaces for Monster
from utility
"""
class Monster:
"""
Interfaces class for Monster
"""
def __init__(self, str_monst, room, item, name):
self.str = str_monst
self.item = item
self.room = room
self.name = name
# Monsterkampf, von Monster-Event aufgerufen
def fight(self, player, monster_event):
"""
This defines how the Player wins or looses
and what event will be triggered
"""
if self.str <= player.str:
monster_event.player_win(self.item)
else:
monster_event.player_loose(self.item)
|
#!/usr/bin/python
import time
import datetime
class Singleton:
""" A python singleton """
class __impl:
"""the actual singleton implementation """
def __init__(self):
""" Save a timestamp of when created """
self.ts = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
def return_id(self):
return id(self)
def return_timestamp(self):
return(self.ts)
__instance = None
def __init__(self):
if Singleton.__instance is None:
Singleton.__instance = Singleton.__impl();
def return_timestamp(self):
return self.__instance.return_timestamp()
s1 = Singleton()
print id(s1), s1.return_timestamp()
time.sleep(5)
s2 = Singleton()
print id(s2), s2.return_timestamp()
print "Different id but same timestamp"
|
# Program by Muhammad Bagus Zulmi
# Url to problem : https://open.kattis.com/problems/modulo
# http://www.mbaguszulmi.com
def main():
distinct = []
for i in range(10):
mod = input()%42
if mod not in distinct:
distinct.append(mod)
del i
print len(distinct)
if __name__ == '__main__':
main()
|
# Program by Muhammad Bagus Zulmi
# Url to problem : https://open.kattis.com/problems/boatparts
# http://www.mbaguszulmi.com
def main():
inputStr = raw_input().split()
p = int(inputStr[0])
n = int(inputStr[1])
day = 0
partName = []
for i in range(n):
name = raw_input()
if name not in partName:
partName.append(name)
if len(partName) == p and day == 0:
day = i+1
partName = []
if day != 0:
print day
else:
print 'paradox avoided'
if __name__ == '__main__':
main()
|
# Program by Muhammad Bagus Zulmi
# Url to problem : https://open.kattis.com/problems/beavergnaw
# http://www.mbaguszulmi.com
def main():
pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
dInner = []
while 1:
inputStr = raw_input().split()
if inputStr[0] == '0' and inputStr[1] == '0':
break
else:
d = int(inputStr[0])
v = int(inputStr[1])
total = 2*pi*((d/2.)**3)
inner = total - (total/3) - v
inner *= 3./2
dInner.append(((inner/(2*pi))**(1./3))*2)
for i in dInner:
print '%.9f'%(i)
if __name__ == '__main__':
main()
|
import os
import json
file_source = 'data/words.json'
score_source = 'data/scores.txt'
file_length = 0
"""
Get the length of the word list
"""
def get_file_length():
return file_length
"""
Set the length on the word list
"""
def set_file_length(length):
global file_length
file_length = length
"""
Get the info for the next question
"""
def get_question(index):
with open(file_source) as json_questions:
questions = json.loads(json_questions.read())
set_file_length(len(questions))
return questions[index] if index < len(questions) else None
"""
Inialize the game with some default values
"""
def initialize(username):
score = 0
question = get_question(0)
game_length = get_file_length()
data = {
'question_index': 0,
'spanish': question['spanish'],
'english': question['english'],
'username': username,
'current_score': score,
'length': game_length
}
return data
"""
Get the top 10 highest scores
"""
def get_high_score():
with open(score_source) as scores:
scores = [score for score in scores.readlines()[1:]]
ordered_scores = []
for score in scores:
value = (score.split(':')[0].lower().strip(), int(score.split(':')[1].lower().strip()))
ordered_scores.append(value)
return sorted(ordered_scores, key=lambda val: val[1])[::-1][:10]
"""
Set the users score
"""
def set_high_score(username, score):
#Get Highscores
high_scores = get_high_score()
with open(score_source, 'a') as scores:
#This make sure the user and score does not exist already
if not(str(username), int(score)) in high_scores:
scores.write('\n{0}:{1}'.format(str(username), str(score)))
|
#!/usr/bin/env python
# Name:
# Student number:
'''
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
'''
import csv
from pattern.web import URL, DOM
TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series"
BACKUP_HTML = 'tvseries.html'
OUTPUT_CSV = 'tvseries.csv'
def extract_tvseries(dom):
amount_series = 0
amount_info = 5
# check how many series there are to be scraped
for Series in dom.by_class("lister-item-content"):
amount_series += 1
# create 2D array of appropriate size
tvseries = [[0 for x in range(amount_info)] for y in range(amount_series)]
count = 0
# grab all Series and the details to then enter into the 2D array
for Series in dom.by_class("lister-item-content"):
# for all subsequent for loops, make sure the content isn't None or an empty string
# also convert all unicode characters to normal characters
# finally add them to their appropriate spot in the 2D array
# grab Series name
for Item in Series.by_class("lister-item-header"):
title = Item.by_tag('a')[0].content.encode("windows-1252")
if title in ("", None):
tvseries[count][0] = "Empty"
else:
tvseries[count][0] = title
# grab rating
for Item in Series.by_class("ratings-imdb-rating"):
rating = Item.by_tag("strong")[0].content.encode("windows-1252")
if rating in ("", None):
tvseries[count][1] = "Empty"
else:
tvseries[count][1] = rating
# grab Genre
for Item in Series.by_class("genre"):
genre = Item.content[1:-12].encode("windows-1252")
if genre in ("", None):
tvseries[count][2] = "Empty"
else:
tvseries[count][2] = genre
# grab Actors
actorList = []
for Item in Series.by_tag("p")[2].by_tag("a"):
actorList.append(Item.content.encode("windows-1252"))
actors = ", ".join(actorList)
if actors in ("", None):
tvseries[count][3] = "Empty"
else:
tvseries[count][3] = actors
# grab Runtime
for Item in Series.by_class("runtime"):
runtime = Item.content[:-4].encode("windows-1252")
if runtime in ("", None):
tvseries[count][4] = "Empty"s
else:
tvseries[count][4] = runtime
count += 1
#return [] # replace this line as well as appropriate
return tvseries;
def save_csv(f, tvseries):
# '''
# Output a CSV file containing highest rated TV-series.
# '''
writer = csv.writer(f)
writer.writerow(['Title', 'Rating', 'Genre', 'Actors', 'Runtime'])
tvseries = tvseries
count = 0
# write the data of each entree in the 2D array
for series in tvseries:
writer.writerow([tvseries[count][0], tvseries[count][1], tvseries[count][2], tvseries[count][3], tvseries[count][4]])
count += 1
# ADD SOME CODE OF YOURSELF HERE TO WRITE THE TV-SERIES TO DISK
if __name__ == '__main__':
# Download the HTML file
url = URL(TARGET_URL)
html = url.download()
# Save a copy to disk in the current directory, this serves as an backup
# of the original HTML, will be used in grading.
with open(BACKUP_HTML, 'wb') as f:
f.write(html)
# Parse the HTML file into a DOM representation
dom = DOM(html)
# Extract the tv series (using the function you implemented)
tvseries = extract_tvseries(dom)
# Write the CSV file to disk (including a header)
with open(OUTPUT_CSV, 'wb') as output_file:
save_csv(output_file, tvseries)
|
#!usr/bin/python/
# -*- coding: utf-8 -*-
#list列表
classmates = ["aa","bb","cc"]
print(len(classmates))
print(classmates[-1])
#tuple元祖 区别 tuple一旦初始化就不能修改
classmatess = ("aa","bb","cc")
print(classmatess)
print(classmatess[1])
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[2][2])
#循环
sum = 0
for x in [1,2,3,4,5,6,7,8,9,10]:
sum = sum + x
print(sum)
print(list(range(5)))
n = 1
while n <= 100:
if n > 10:
break
print(n)
n = n + 1
print("end")
#dict & set
#Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
#相当于Map
d = {"aa" : 20 , "bb" : 30 ,"cc" : 35}
print(d["bb"])
d.pop("aa")
print(d)
#set是一组key的集合,不能重复
|
'''
2048实现方法
'''
list_merge = [2, 2, 2, 0]
map = [
[2, 0, 2, 0],
[4, 4, 2, 0],
[0, 4, 0, 4],
[2, 2, 0, 4],
]
# 1.定义函数,将list_merge列表中的零元素移动到末尾
# 例如2 0 2 0 ——> 2 2 0 0
# 0 0 2 0 ——>2 0 0 0
# 0 0 2 0 ——>2 0 0 0
# 4 0 2 4 ——>4 2 4 0
# def move_zero_end(zero):
# for k in range(len(zero) - 1):
# for i in range(len(zero) - 1):
# if zero[i] == 0:
# zero[i], zero[i + 1] = zero[i + 1], zero[i]
def move_zero_end():
'''
从后往前判断是否为0
如果为0从列表删除,在列表最后添加一个0
'''
for i in range(len(list_merge) - 1, -1, -1):
if list_merge[i] == 0:
del list_merge[i]
list_merge.append(0)
def move_add():
'''
调用0向后移动函数
判断相邻的两个数是否相同
相同则合并
'''
move_zero_end()
for i in range(len(list_merge) - 1):
if list_merge[i] == list_merge[i + 1]:
list_merge[i] = list_merge[i] * 2
del list_merge[i + 1]
list_merge.append(0)
# for i in range(len(zero) - 1):
# for k in range(i + 1, len(zero)):
# if zero[i] == zero[k]:
# zero[i] = zero[i] * 2
# del zero[k]
# zero.append(0)
def move_left():
'''
二维列表左移操作
'''
global list_merge # 修改全局变量
for i in map: # 循环取出map列表的值
list_merge = i # 赋值到list_merge列表
move_add() # 进行相加
def move_right():
'''
二位列表向右移动操作。
'''
global list_merge
for i in map:
list_merge = i[::-1] # 单个列表进行切片倒序
move_add() # 倒叙完成后进行相同且相邻数值的相加
i[::-1] = list_merge # 相加完成后再进行一个切片翻转
def list_matrix(par_matrix):
'''
二维列表斜角45度对折翻转,行变列,列变行
'''
for i in range(len(par_matrix)):
for k in range(i, len(par_matrix)):
par_matrix[i][k], par_matrix[k][i] = par_matrix[k][i], par_matrix[i][k]
def move_update():
'''
向上移动使用翻转函数进行翻转在进行向左移动操作,再进行翻转
'''
list_matrix(map)
move_left()
list_matrix(map)
def move_down():
'''
向上移动使用翻转函数进行翻转在进行向右移动操作,再进行翻转
'''
list_matrix(map)
move_right()
list_matrix(map)
move_update()
print(map)
|
print('Hello World')
salse = 'tomato'
if salse.startswith('toma'):
print("it's probably tomato...")
else:
print("not tomato")
order_description = """
The client ask for a pizza with less cheese.
Intead of cheese, he would like to have more jam
"""
print(order_description)
|
import sqlite3
from socket import *
class sql:
def __init__(self):
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
# Check if table users does not exist and create it
cursor.execute('''CREATE TABLE IF NOT EXISTS
clients(row INTEGER PRIMARY KEY unique, origin_ip TEXT unique, new_ip TEXT , port INTEGER)''')
#print cursor.execute("SHOW CREATE TABLE clients")
# Commit the change
self.db.commit()
self.row = self.find_rows()
except Exception as e:
# Roll back any change if something goes wrong
# self.db.rollback()
raise e
#finally:
#self.db.close()
def insert_ip(self,sock, addr , porti): #at the moment insert only old ip and mac
print self.row
self.row = self.row +1
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''INSERT INTO clients(row, origin_ip, new_ip, port)
VALUES(?,?,?,?)''', (self.row, str(addr[0]), ".", porti)) #change new ip
self.db.commit()
except Exception as e:
# Roll back any change if something goes wrong
self.db.rollback()
#raise e
def find_rows(self):
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''SELECT max(row) FROM clients ''')
if cursor.fetchone()[0]:
return cursor.fetchone()[0]
return 0
except Exception as e:
# Roll back any change if something goes wrong
self.db.rollback()
return 0
def get_ip(self,row):
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''SELECT origin_ip FROM clients WHERE row=?''', (row,)) #change to new
return cursor.fetchone()[0]
except Exception as e:
raise e
def get_port(self, row):
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''SELECT port FROM clients WHERE row=?''', (row,)) # change to new
return cursor.fetchone()[0]
except Exception as e:
raise e
def remove_ip(self, addr):
try:
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''SELECT row FROM clients WHERE origin_ip=?''', (addr,))
row_removed = cursor.fetchone()[0]
cursor.execute('''DELETE FROM clients WHERE row = ? ''', (row_removed,))
for i in range(0,self.row - row_removed):
cursor.execute('''UPDATE clients SET row = ? WHERE row = ? ''',
(row_removed - i, row_removed))
self.db.commit()
self.row -=1
except Exception as e:
# Roll back any change if something goes wrong
self.db.rollback()
raise e
def update(self): #if crush and port change...
pass
def get_row(self, ip_dst):
self.db = sqlite3.connect('ip_table')
cursor = self.db.cursor()
cursor.execute('''SELECT row FROM clients WHERE origin_ip=?''', (ip_dst,))
row_ip = cursor.fetchone()
return row_ip
#db = sqlite3.connect('ip_tables')
#cursor = db.cursor()
#cursor.execute("DROP TABLE clients")
#print "yay"
|
from typing import List
from rl.agent import DiscreteAgent
from rl.environment import DiscreteEnvironment
from rl.episode import Episode
from rl.experience_tuple import ExperienceTuple
class SequentialGame:
"""
Game where the agent takes decisions sequentially. At every step,
the Agents see the Environment state it is located in, chooses an
action and transitions to a new state of the Environment. The
Environment rewards the Agent's action with some scalar value. This
process is repeated until the Agent reaches a terminal state of the
Environment.
"""
def __init__(self, agent: DiscreteAgent, environment: DiscreteEnvironment):
"""
Setups a sequential Game for the input Agent in the input
Environment.
:param agent: The Agent that will take sequential decisions.
:param environment: The Environment where the Agent will take
decisions.
"""
assert agent is not None, "Constructor input 'agent' should not be " \
"None."
assert environment is not None, "Constructor input 'environment' " \
"should not be None."
self._agent = agent
self._environment = environment
self._current_episodes_experience_tuples = []
self._current_state = None
def play_one_episode(self) -> Episode:
"""
Makes the Agent play a single Episode in the Environment.
:return: The single Episode played.
"""
self._setup_new_episode()
while not self._current_state.is_final():
self._move_to_next_state()
return Episode(self._current_episodes_experience_tuples)
def play_multiple_episodes(self, number_of_episodes: int) -> List[Episode]:
"""
Makes the Agent play multiple Episodes in the Environment.
:param number_of_episodes: Number of Episodes to play.
:return: A list of the played Episodes.
"""
assert number_of_episodes >= 1, "Input 'number_of_episodes' should " \
"be at least one."
return [self.play_one_episode() for _ in range(number_of_episodes)]
def _setup_new_episode(self):
self._current_episodes_experience_tuples = []
self._current_state = self._environment.get_initial_state()
def _move_to_next_state(self):
"""
Makes the Agent move from the current state to the next state
and logs the transition.
:return: None
"""
agent_choice = self._agent.choose_action(state=self._current_state)
experience_tuple = self._environment.evaluate_agent_choice(agent_choice)
self._agent.observe_experience_tuple(experience_tuple)
self._log_experience_tuple(experience_tuple)
self._current_state = experience_tuple.end_state
def _log_experience_tuple(self, experience_tuple: ExperienceTuple):
self._current_episodes_experience_tuples.append(experience_tuple)
|
# coding=utf-8
print("Hello World")
# Listas
fruits = ["Apple","Orange","Watermelon"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
print(fruits[-1])
print(fruits[-2])
print(fruits[-3])
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
from_2_to_6 = numbers[2:7]
print(from_2_to_6)
greater_than_4 = numbers[5:]
print(greater_than_4)
print(numbers[::2])
print(numbers[1::2])
print(4 in numbers)
# Diccionarios
fighter = { "name": "Chuck", "last_name": "Norris", "technique": "Karate" }
print fighter["name"] #NUNCA SE ACCEDE ASÍ A LAS CLAVES DE DICCIONARIO
print fighter.get("nombre")
# True, False, None ==> TRUE, FALSE, NULL
def print_fruits(fruits_list):
for fruit in fruits_list:
print(fruit)
print_fruits(fruits)
print("así")
|
"""
A base class for different point location algorithms
"""
from abc import ABC, abstractmethod
from node import dist, ch, rel
import functools
class PointLocation(ABC):
def __init__(self, tree):
self.tree = tree
self.basictouchno=0
self.splittouchno=0
self.mergetouchno=0
@abstractmethod
def nn(self, point):
pass
@abstractmethod
def nndist(self, point, nn = None):
pass
@abstractmethod
def removepoint(self, point):
pass
@abstractmethod
def addnode(self, node):
pass
@abstractmethod
def updateonremoval(self, node):
pass
@abstractmethod
def updateoninsertion(self, node):
pass
@abstractmethod
def updateonsplit(self, node):
pass
class ParallelPointLocation(PointLocation):
def __init__(self, tree, points):
PointLocation.__init__(self, tree)
def nn(self, point):
child = self.tree.root.getchild()
if dist(child,point) > self.tree.cr * self.tree.tau ** child.level:
return self.tree.root
return self.nnhelper(point, {child}, child.level) or self.tree.root
def nnhelper(self, point, currentnodes, level):
if len(currentnodes) != 0:
self.basictouchno += len(currentnodes)
if len(currentnodes) == 0 or \
point.distto(*[n.point for n in currentnodes]) > self.tree.cr * self.tree.tau ** level:
return None
children = ch(currentnodes)
nextlevel = max(n.level for n in children)
nextnodes = {n if n.level == nextlevel else n.par
for n in children if dist(n, point) <= self.tree.cr * self.tree.tau ** nextlevel}
self.basictouchno += len(children)
nn = self.nnhelper(point, nextnodes, nextlevel)
if nn:
return nn
self.basictouchno += len(currentnodes)
return min(currentnodes, key = lambda n : point.distto(n.point))
# return nn if nn else min(currentnodes, key = lambda n : point.distto(n.point))
def nndist(self, point, nn = None):
return dist(nn or self.nn(point), point)
def removepoint(self, point): pass
def addnode(self, node): pass
def updateonremoval(self, node): pass
def updateoninsertion(self, node): pass
def updateonsplit(self, node): pass
class SinglePathPointLocation(PointLocation):
def __init__(self, tree, points):
PointLocation.__init__(self, tree)
def nn(self, point):
currentnode = self.tree.root
nextnode = self.tree.root.getchild()
self.basictouchno += 1
while dist(nextnode, point) <= self.tree.cr * self.tree.tau ** nextnode.level:
currentnode = nextnode
allnodes = ch(rel(currentnode))
nextlevel = max(n.level for n in allnodes)
nextnode = min(allnodes,
key = functools.partial(self.mincoveringdist, point = point, level = nextlevel))
return currentnode
def mincoveringdist(self, node, point, level):
dst = dist(node, point)
self.basictouchno += 1
return dst if dst <= self.tree.cr * self.tree.tau ** level else float('inf')
def nndist(self, point, nn = None):
return dist(nn or self.nn(point), point)
def removepoint(self, point): pass
def addnode(self, node): pass
def updateonremoval(self, node): pass
def updateoninsertion(self, node): pass
def updateonsplit(self, node): pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pythonCalculIMC.py
#
# Copyright 2014 yves Mercadier <[email protected]>
#
def entree():
#Les entrees du programme
print ("Votre IMC \n")
poid = int(input("Quelle est ton poid? "))
taille = float(input("Quelle est ta taille? "))
return poid,taille
def metier(poid,taille):
#le calcul
IMC = poid/taille**2
return IMC
def pourImpression(IMC):
strImpression="";""
if IMC>16.5:
strImpression="\nTu es en famine :-)"
if IMC>16.5 and IMC<18.5:
strImpression="\nTu es maigre"
return strImpression;
print (" ---> Debut du programme.\n")
poid,taille=entree()
IMC=metier(poid,taille)
print(pourImpression(IMC))
print ("\n ---> Fin du programme.")
|
# Chain of resposibility
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional
class AutomationHandler(ABC):
"""The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request."""
@abstractmethod
def set_next(self, handler: Handler) -> Handler:
pass
@abstractmethod
def handle(self, request) -> Optional[str]:
pass
class AbstractAutomationHandler(AutomationHandler):
"""The default chaining behavior can be implemented inside a base handler class."""
_next_handler: Handler = None
def set_next(self, handler: Handler) -> Handler:
self._next_handler = handler
return handler
@abstractmethod
def handle(self, request: Any) -> str:
if self._next_handler:
return self._next_handler.handle(request)
return None
"""
All Concrete Handlers either handle a request or pass it to the next handler in
the chain.
"""
class AutomationA(AbstractAutomationHandler):
def handle(self, request: Any) -> str:
if request == "A":
return f"AutomationA: {request}"
else:
return super().handle(request)
class AutomationB(AbstractAutomationHandler):
def handle(self, request: Any) -> str:
if request == "B":
return f"AutomationB: {request}"
else:
return super().handle(request)
class AutomationC(AbstractAutomationHandler):
def handle(self, request: Any) -> str:
if request == "C":
return f"AutomationC {request}"
else:
return super().handle(request)
def client_code(handler: Handler) -> None:
"""
The client code is usually suited to work with a single handler. In most
cases, it is not even aware that the handler is part of a chain.
"""
for automation in ['A', 'D', 'B', 'C']:
print(f"\nClient: Start automation {automation}?")
result = handler.handle(automation)
if result:
print(f"\t{result}", end="")
else:
print(f"\t Automation {automation} has not been initiated.", end="")
if __name__ == "__main__":
automation_a = AutomationA()
automation_b = AutomationB()
automation_c = AutomationC()
automation_a.set_next(automation_b).set_next(automation_c)
print("Chain: Automation A > Automation B > Automation C")
client_code(automation_a)
print("\n")
print("Subchain: Automation B > Automation C")
client_code(automation_b)
print("\n")
"""
Result:
Chain: Automation A > Automation B > Automation C
Client: Start automation A?
AutomationA: A
Client: Start automation D?
Automation D has not been initiated.
Client: Start automation B?
AutomationB: B
Client: Start automation C?
AutomationC C
Subchain: Automation B > Automation C
Client: Start automation A?
Automation A has not been initiated.
Client: Start automation D?
Automation D has not been initiated.
Client: Start automation B?
AutomationB: B
Client: Start automation C?
AutomationC C
"""
|
#列表
print([i for i in range(5)]);
print("------------------------------------------------");
print([(i,j) for i in range(3) for j in range(2)]);
|
import random
import sys
import time
from os import path
import textwrap
from player import *
from tiles import *
from settings import *
from combats import *
import pickle
class Game:
def __init__(self):
self.game_solved = False
self.moved = False
def title_screen(self):
"""
defines the title screen and gets user input.
'play' starts the game
'help' opens the game_help menu
'quit' exits the program
"""
print('####################')
print('# WELCOME #')
print('####################')
print('# - PLAY - #')
print('# - HELP - #')
print('# - QUIT - #')
print('####################')
valid = True
while valid:
choice = input('').lower()
for word in ['play','help','quit']:
if choice == 'play':
self.play_screen()
valid = False
return
elif choice == 'help':
self.help_menu
valid = False
elif choice == 'quit':
sys.exit()
valid = False
def help_menu(self):
"""
This defines the help menu and takes user back to the
title screen
"""
self.game_help()
title_screen()
def play_screen(self):
chosen = False
print("[1]: Create new game")
print("[2]: Load game")
while not chosen:
choice = int(input("> "))
if choice == 1:
self.new()
self.game_setup()
chosen = True
elif choice == 2:
self.load()
chosen = True
else:
pass
def new(self):
self.rooms = rooms
self.player = Player()
def save(self):
with open(os.path.join(save_folder, 'saves.txt'),'r') as ff:
saves = [line.strip() for line in ff]
print(saves)
with open(os.path.join(save_folder, self.player.name), 'wb') as f:
pickle.dump([self.rooms, self.player], f, protocol = 2)
with open(os.path.join(save_folder, 'saves.txt'),'a') as f:
if self.player.name not in saves:
f.write("{}\n".format(self.player.name))
else:
pass
time.sleep(0.5)
print("saving")
time.sleep(0.5)
self.speech("zzz\n")
self.speech("zzz\n")
time.sleep(0.5)
print("Saved \"{}\"'!".format(self.player.name))
def load(self):
saves = []
with open(os.path.join(save_folder, 'saves.txt'),'r') as f:
for line in f:
saves.append(line)
if len(saves) == 0:
print("There are no save files...")
return
else:
print("Which save file do you wish to load")
for i, line in enumerate(saves):
print("[{}]: {}".format(i + 1, line))
chosen = False
while not chosen:
choice = input("> ")
if choice in CHOICES:
for i, line in enumerate(saves):
if str(i + 1) == choice:
with open(os.path.join(save_folder, line.strip()), 'rb') as f:
self.rooms, self.player = pickle.load(f)
chosen = True
break
else:
print("Please select save game number.")
def game_help(self):
"""
This prints the help menu that can be accessed ingame.
"""
print("""Type 'move' and then the direction. e.g. move north.
type 'look' to investigate the room.
type 'take' and then the item you wish to take. e.g. take key.
type 'drop' and then the item you wish to drop. e.g. drop key.
type 'equip' and then the item you wish to equip. e.g. equip sword.
type 'unequip' and then the item you wish to unequip. e.g. unequip sword.
type 'inspect' and then the item you wish to inspect. e.g. inspect key.
type 'heal' and then the item you wish to use. e.g. heal apple.
type 'inventory' to see what you currently have in your inventory.
type 'equipped' to see what you currently have equipped.
type 'describe' to see the description of the current room.
type 'trade' to trade with a merchant.
type 'try key' to attempt to open a locked door or chest.
type 'info' to receive current player information.
type 'help' to see this list at any time.
type 'quit' to leave the game.""")
def speech(self, text):
for character in text:
sys.stdout.write(character)
time.sleep(0.02)
def prompt(self, player):
"""
This first section of code ensures that the relevant room updates are run only upon entering the room by checking
whether the previous action was a 'move'. If it was, the self.move attribute is True and the following code is run.
After this code block, the self.moved attribute is reset to False. Choosing the 'move' action will switch self.moved
to True.
"""
if self.moved:
for i, room in enumerate(self.rooms):
if player.location == room.location and isinstance(room, QuestRoom):
room.update(player)
elif player.location == room.location and isinstance(room, BlockedRoom):
room.update(player, place)
self.moved = False
command = input('').split()
if len(command) == 3:
if command[1] in ADJECTIVES:
command = [command[0], "{} {}".format(command[1], command[2])]
else:
print("I don't understand...")
if command[0] in ['move']:
if player.move(command[1], self.rooms):
self.check(self.get_location(), player)
self.describe()
self.moved = True
elif command[0] in ['look']:
player.look(self.get_location())
elif command[0] in ['inspect']:
player.inspect(command[1], self.get_location())
elif command[0] in ['take']:
player.take(command[1], self.rooms)
elif command[0] in ['drop']:
player.drop(command[1], self.get_location())
elif command[0] in ['equip']:
player.equip(command[1])
elif command[0] in ['unequip']:
player.unequip(command[1])
elif command[0] in ['heal','eat','drink']:
player.heal(command[1])
elif command[0] in ['info']:
player.info()
elif command[0] in ['try']:
player.open(command[1], self.get_location())
elif command[0] in ['trade']:
room = self.get_location()
if isinstance(room, Shop):
room.barter(self.player)
elif command[0] in ['rest','sleep']:
if player.sleep(self.get_location(), Inn):
self.save()
elif command[0] in ['inventory', 'i']:
player.print_inventory()
elif command[0] in ['equipped']:
player.print_equipped()
elif command[0] in ['describe']:
self.describe()
elif command[0] in ['exits']:
self.get_location().show_exits()
elif command[0] in ['quit']:
sys.exit()
elif command[0] in ['map', 'm']:
self.print_map()
def get_location(self):
for i, room in enumerate(self.rooms):
if room.location == self.player.location:
return room
def describe(self):
place = self.get_location()
print(place.desc)
place.show_exits()
if isinstance(place, LockedRoom):
for i in range(len(place.exits)):
if place.exits[i] != place.new_exits[i]:
print("The door to the {} is locked.".format(DIRECTIONS[i]))
break
elif isinstance(place, LootRoom):
print("There's a chest here.")
elif isinstance(place, QuestRoom) and not place.done:
place.intro()
def check(self, place, player):
if isinstance(place, EnemyRoom) and place.enemy is not None:
mob = place.enemy
self.fight(player, mob)
def fight(self, player, mob):
c = Combat(player, mob)
c.battle(player,mob)
if not mob.is_alive():
if mob.weapon.wearable == True or mob.weapon.takeable == True:
place.items.append(mob.weapon)
print("The {} drops its {}.".format(mob.name, mob.weapon.name))
if mob.armour.wearable == True:
place.items.append(mob.armour)
print("The {} drops its {}.".format(mob.name, mob.armour.name))
if mob.loot is not None:
place.items.append(mob.loot)
print("The {} drops a {}!".format(mob.name, mob.loot.name))
place.enemy = None
def game_setup(self):
"""
This is the character creation and game setup.
Player input is used to determine character name.
"""
self.game_help()
input("Press any key to continue.")
os.system('cls')
named = False
while not named:
print("What's your name?")
name = input("> ")
sure = False
while not sure:
print("Are you sure?")
check = input("> ")
if check.lower() in ['yes','y']:
self.player.name = name
return
else:
break
os.system('cls')
print("Welcome {}, to the town of Borovik.".format(self.player.name))
"""
This section contains the 'print_map' method and assoicated 'check_zone' method. The players coordinates are spoofed
to ensure that the map drawn in the console shows the section of the world they are in. The map is read in line-by-line
from a .prn file. The .prn files were generated from an excel spreadsheet. Each cell consisted of 5 spaces in the .prn
file with the character in the cell in the middle of the 5 spaces. The player's location is calculated based on the spoofed
coordinates and the offset and then an X is inserted at that position to represent the player.
The 'check_zone' method returns the zone and the spoofed coordinates (player's coordinates relative to the origin of the
map zone they are in).
"""
def print_map(self):
zone = self.check_zone(self.get_location().location, **zones)[0]
new_location = (self.check_zone(self.get_location().location, **zones)[1], \
self.check_zone(self.get_location().location, **zones)[2])
current_map = []
world_map = '{}.prn'.format(os.path.join(map_folder, zone))
with open(os.path.join(map_folder, world_map),'r') as f:
for line in f:
current_map.append(line)
for j, line in enumerate(current_map):
if new_location[1] == j:
a = list(line)
a[(new_location[0] - 1) * 5 + 2] = 'X'
current_map[j] = ''.join(a)
for i, line in enumerate(current_map):
print(line)
def check_zone(self, player_location, **kwargs):
for i, key in enumerate(kwargs):
if kwargs[key][0] < player_location[0] < kwargs[key][0] + kwargs[key][2] \
and kwargs[key][1] < player_location[1] < kwargs[key][1] + kwargs[key][3]:
return (key, player_location[0] - kwargs[key][0], \
player_location[1] - kwargs[key][1])
"""
This section contains the main 'game_loop' method which collects user input via the 'prompt' method wrapped in a try-except
statement to handle invalid input. The traders' wares and the enemy tiles are updated based on the count variable which ticks
up every cycle of the loop.
"""
def game_loop(self):
"""
This is the main game loop.
"""
count = 0
while not self.game_solved:
count += 1
try:
self.prompt(self.player)
except:
pass
if count % 200 == 0:
for i, room in enumerate(self.rooms):
if isinstance(room, Shop):
room.update_wares()
if count % 25 == 0:
for i, room in enumerate(self.rooms):
if isinstance(room, EnemyRoom):
room.random_mob()
if not self.player.is_alive():
sys.exit()
|
def binary_search(value, array):
mid = len(array) / 2
if value == array[mid]:
return True
elif value < array[mid]:
return binary_search(value, array[0:mid-1])
else:
return binary_search(value, array[mid+1:-1])
|
'''
Created on Mar 19, 2014
@author: Daniel Corroto
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
'''
def getCicleLength(x):
found = [-1 for _ in range(x)]
rem = 1 % x
count = 0
while rem > 0 and found[rem] == -1:
found[rem] = count
rem = rem * 10 % x
count += 1
return count - found[rem] if rem > 0 else 0
num, length = (0, 0)
for i in xrange(3, 1001, 2):
l = getCicleLength(i)
if (l > length):
num, length = (i, l)
if (i > 1000):
break
print num, length
|
'''
Created on Mar 20, 2014
@author: Daniel Corroto
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
'''
def isFifthPower(x):
temp = 0
temp = x
while x > 0:
temp += (x % 10) ** 5
x //= 10
return temp == temp
print sum([i for i in xrange(10, 10 ** (5 + 1)) if isFifthPower(i)])
|
'''
Created on Mar 19, 2014
@author: Daniel Corroto
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
'''
from numberUtil import getDivisors
def d(n):
temp = reduce(lambda x, y: x + y, getDivisors(n))
return temp - n
count = 0
for i in range(2,10000):
a = d(i)
if (a > i):
b = d(a)
if (b == i and b < 10000):
count += a+b
print count
|
'''
Created on Mar 19, 2014
@author: Daniel Corroto
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
'''
from numberUtil import getDivisors
def triangleNumberGenerator():
count = 1
num = 0
while True:
num += count
yield num
count += 1
def getTriangleNumberByDivisors(x):
for i in triangleNumberGenerator():
if (len(getDivisors(i)) > x):
return i
print getTriangleNumberByDivisors(500)
|
from enum import Enum
from random import choice
class Methods(Enum):
NN = 0
NV = 1
VV = 2
NC = 3
class Types(Enum):
"Types of words that can occur in dictionaries"
NOUN = 0
VERB = 1
CUSS = 2
|
#HackerRank
#Print Function
#Solution
#For PYTHON 3
n = int(input())
for i in range(1,n+1):
print(i,end="")
|
"""String Methods
.strip() #removes spaces at the ends of the string
.split() #changes on string into a list of strings
.join() #puts together a list of strings into one string
.center() #centralizes a string by adding spaces at the sides
.replace() #exchanges one type of word with another in a string
.lower() #changes all letters in the string to lowercase
.upper() #puts all letters in uppercase
.find() #searches for a sub-string (word) in the given string. Returns -1 if not found
.title() #capitalizes the first letter of each word in a string"""
# write a program that creates an acronym of the sentences given to it
sentence = "world health organisation"
# desired result WHO
words = sentence.split()
print(words)
acronym = ""
for word in words:
acronym = acronym + word[0]
"""print(word[0]) #indexing"""
print (acronym.upper())
|
# program to check if a number is even or odd
# 25.02.21
"""Hi!
Welcome to my even or odd number checker.
To begin please enter a number below... """
num1 = int(input('Enter a number: '))
if num1%2 == 0:
print('The number entered is even')
elif num1%2 !=0:
print('The number you entered is odd')
|
#We will use our made classifier to predict the features :[4,2,1,1,1,2,3,2,1],[4,9,7,6,8,5,4,9,7];
#We will also get the accuracy of our classifier
#NOTE;
# 1- We recreate our data by framing it into dictionary format;
# 2- We split the data ourselves into training and testion set;
# 3- We train the training data and then test the testing data and predict accuracy
import random
import numpy as np
import pandas as pd
from collections import Counter
#THE K-Nearest Neighbor classifier function
def KNearestNeighbors(data,predict,k=5):
distances =[]
for i in data:
for j in data[i]:
Eucledian_distance = np.linalg.norm(np.array(j)-np.array(predict))
#in the data we have a more than 2-d features ; so for faster calculation of Eucledian distance we use inbuilt ;
#linear algebra function of numpy
distances.append([Eucledian_distance,i])#making a list as [[distance,class],[distance,class]]
vote = []
for i in sorted(distances)[:k]:
vote.append(i[1]) #Appending the first 3 classes of the sorted array
l = Counter(vote).most_common(1)[0][0] #Counting the votes ; segregating the most common
#; returning class of most common to l
return l
#NOTE
#4 for Malignant ;
#2 for Benign ;
df = pd.read_csv("C:\\Users\\ABX9801\\Documents\\breast-cancer-wisconsin.data")
df.replace('?',-99999,inplace =True)
df.drop(['id'],1,inplace = True)
d = df.astype(float).values.tolist()#converting all string values of data to float and passing them into a list
random.shuffle(d)
test_size = 0.2
X_train = {2 : [], 4 : []}
X_test = {2 : [], 4 : []}
traindata = d[:-int(test_size*len(d))]
testdata = d[-int(test_size*len(d)):]
for i in traindata:
X_train[i[-1]].append(i[:-1])
for i in testdata:
X_test[i[-1]].append(i[:-1])
correct = 0
total = 0
for i in X_test:
for j in X_test[i]:
temp = KNearestNeighbors(X_test,j,k=3)
if(temp==i):
correct+=1
total+=1
accuracy = (correct/total)
print(accuracy)
t = KNearestNeighbors(X_train,[4,9,7,6,8,5,4,9,7],k=5) # u can change the above list
print(t)
|
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps=PorterStemmer()
example_words=["python","pythoner","pythoning","pythoned"]
# for w in example_words:
# print(ps.stem(w))
new_text="it is very important to be pythonly while pythoning with python."
words=word_tokenize(new_text)
for w in words:
print(ps.stem(w))
|
#!/usr/bin/env python3.6
from Credentials import Credentials
from User import User
def create_account(user_name,password):
'''
Function to create a new account
'''
new_account = User(user_name,password)
return new_account
def save_user_detail(user):
'''
Function to save a new user account
'''
user.save_user_details()
def verify_user(user_name,password):
'''
Function that verifies the existance of the user before creating credentials
'''
checking_user = Credentials.check_user(user_name,password)
return checking_user
def create_credentials_account(account_user_name,password,account_name):
'''
Function to create a credential account
'''
new_credential_account = Credentials(account_user_name,password,account_name)
return new_credential_account
def generate_password():
'''
Function to generate a password for the user
'''
paswrd_g = Credentials.generate_password()
return paswrd_g
def save_user_credentials(credentials):
'''
Function to save contact
'''
credentials.save_user_credentials()
def del_user_credentials(credentials):
'''
Function to delete a credential
'''
credentials.delete_user_credentials()
def display_user_credentials():
'''
Function that returns all the saved credentials
'''
return Credentials.display_user_credentials()
def main():
print("Hello!! Welcome to our PasswordLock App. What is your name?")
user_name=input()
print(f"Hi {user_name}. what do you want to do?")
print('\n')
while True:
print("use the following short codes : CR - creating a new account,LG - to login, EXI - to exit")
short_code = input().upper()
if short_code == "EXI":
print("bye .......")
break
elif short_code == 'CR':
print("New account")
print("-"*20)
print("Enter your UserName:")
user_name=input()
print("Enter your password")
pass_word=input()
# print("Enter your accountName")
# ac_name=input()
save_user_detail(create_account(user_name,pass_word))
print('\n')
print(f"A new account {user_name} {pass_word} has been successfully created")
print('\n')
elif short_code =='LG':
print("-"*20)
print('')
print("Enter your account details to login")
print('\n')
user_name = input("enter your username:")
password = input("enter your password:")
user_exists = verify_user(user_name,password)
if user_exists == user_name:
print("\n")
print("please use those shortcodes to continue: ")
print("-"*30)
print("enter: AD - to create credential , DS - to display credential , DL - to delete crdential,EX - to exit the application ")
short_code = input().upper()
if short_code == 'EX':
print("bye....")
break
elif short_code == 'AD':
print('\n')
print("enter your credential account details:")
account_user_name = input("enter your account user name:")
account_name = input("enter your account name:")
print('\n')
print("select password option: AP - for the app to generate it for you , SEL - for yourself to generate it ")
short_code = input().upper()
print("-"*50)
if short_code == 'AP':
print('\n')
password = generate_password()
# break
elif short_code == 'SEL':
print('\n')
password = input("enter your password:")
else :
print("invalid input")
save_user_credentials(create_credentials_account(account_user_name,password,account_name))
print('\n')
print(f"credential account :{account_user_name} ,{password},{account_name} has been successfully created")
print('\n')
elif short_code == 'DS':
if display_user_credentials():
print("here is your credentials's list:")
print('\n')
for cred in display_user_credentials():
print(f"{account_user_name} ,{password},{account_name}")
print('\n')
else:
print('\n')
print("you don't seem to have any credential yet, please create one")
else:
print("invalid input!!")
if __name__ == '__main__':
main()
|
import pygame
import common, graphics
from pygame.locals import *
pygame.init()
def spawn_mob():
#
to_spawn=0
if common.round<=5:
to_spawn=common.round*2
elif common.round<=10:
to_spawn=common.round*3
elif common.round<=20:
to_spawn=common.round*2
else:
to_spawn=common.round
#
class Zombie(object):
def __init__(self, x,y, species):
self.x=x
self.y=y
self.type=species
def search(self):
if common.last_frame>=10:
common.last_frame=0
for i in xrange(0,len(common.zomb_list)):
self.x=common.zomb_list[i][0]
self.y=common.zomb_list[i][1]
#print 'zombie', i,'\'s pos is', self.x, self.y
if common.arena[self.y][self.x-2]==0:
#print common.arena[self.y][self.x-1-1]
if self.x>common.player_pos[0]:
print 'move left'
self.x-=1
#print common.arena[self.y][self.x]
if common.arena[self.y-1][self.x]==0:
if self.x<common.player_pos[0]:
print 'move right'
self.x+=1
#if self.y>common.player_pos[1]:
# print 'move up'
# self.y-=1
#if self.y<common.player_pos[1]:
# print 'move down'
# self.y+=1
common.zomb_list[i][0]=self.x
common.zomb_list[i][1]=self.y
def move(self):
#gives zombies motion at speed according to self.species
pass
def attack(self):
#gives damage to player according to self.species
pass
def draw(self):
for i in xrange(0,len(common.zomb_list)):
x=common.zomb_list[i][0]*50-50
y=common.zomb_list[i][1]*50-50
if common.zomb_list[i][2]==0:
common.zombie1=pygame.transform.rotate(graphics.zombie1, 0)
elif common.zomb_list[i][2]==1:
common.zombie1=pygame.transform.rotate(graphics.zombie1, 90)
elif common.zomb_list[i][2]==2:
common.zombie1=pygame.transform.rotate(graphics.zombie1, 90)
elif common.zomb_list[i][2]==3:
common.zombie1=pygame.transform.rotate(graphics.zombie1, 270)
common.screen.blit(common.zombie1, [x,y])
#pygame.draw.rect(common.screen, (0,255,0), (x,y,50,50))
class Player(object):
def __init__(self,x,y, weapon, ammo, key):
self.x=x
self.y=y
self.weapon=weapon
self.ammo=ammo
self.key=key
def spawn(self):
self.ammo=100000
def move(self):
self.x-=1
self.y-=1
if self.key==273:
if common.arena[self.y-1][self.x]==0:
common.player_pos[1]-=1
common.directytion='up'
elif self.key==276:
if common.arena[self.y][self.x-1]==0:
common.player_pos[0]-=1
common.direction='left'
elif self.key==274:
if common.arena[self.y+1][self.x]==0:
common.player_pos[1]+=1
common.direction='down'
elif self.key==275:
if common.arena[self.y][self.x+1]==0:
common.player_pos[0]+=1
common.direction='right'
def shoot(self):
pass
def death(self):
pass
def draw(self):
if common.direction=='up':
common.player=pygame.transform.rotate(graphics.player, 180)
elif common.direction=='left':
common.player=pygame.transform.rotate(graphics.player, 270)
elif common.direction=='down':
common.player=pygame.transform.rotate(graphics.player, 0)
elif common.direction=='right':
common.player=pygame.transform.rotate(graphics.player, 90)
common.screen.blit(common.player, [self.x*50-50,self.y*50-50])
#ignore, this was old version of Zombie.search()
def search(self):
#searches for player
if common.last_frame>=10:
for i in xrange(0,len(common.zomb_list)):
self.x=common.zomb_list[i][0]
self.y=common.zomb_list[i][1]
print self.x,self.y
#check for wall here
#if common.arena[self.y][self.x-1]!=1:
if self.x>common.player_pos[0]:
self.x-=1
common.zomb_list[i][2]=3
#here
#if common.arena[self.y][self.x+1]!=1:
if self.x<common.player_pos[0]:
self.x+=1
common.zomb_list[i][2]=1
#here
#if common.arena[self.y-1][self.x]:
if self.y>common.player_pos[1]:
self.y-=1
common.zomb_list[i][2]=0
#and here
#if common.arena[self.y+1][self.x]:
if self.y<common.player_pos[1]:
self.y+=1
common.zomb_list[i][2]=2
common.zomb_list[i][0]=self.x
common.zomb_list[i][0]=self.y
common.last_frame=0
|
def cipher(string):
result = ''
for char in string:
if char.islower():
result += chr(219 - ord(char))
else:
result += char
return result
if __name__ == '__main__':
s = 'Test Stringa'
print s
print '\nEncode'
print cipher(s)
print '\nDecode'
print cipher(cipher(s))
|
#1.Write a program that uses input to prompt a user for their name and then welcomes them.
name = input('Enter your name')
print('Welcome',name)
#2.Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature."""
celsius = float(input("Enter temperature in celsius: "))
fahrenheit = (celsius * 9/5) + 32
print('%.2f Celsius is: %0.2f Fahrenheit' %(celsius, fahrenheit))
#3.Write a Python program to convert degree to radian."""
pi=22/7
degree= float(input("input degrees :"))
radian= degree*(pi/180)
print('%.2f degree is: %0.2f radian' %(degree, radian))
|
'''
[linha 45] Deveria trabalhar com k[i+1] e k[i] pois quando i=0,
k[i-1] = k[-1] = 20 (primeiro teste). Essa também é a causa da
lentidão do programa. ** Nesse caso, precisaria adicionar 1 ao k
final pois o último a ser testado foi o k[i+1].
[linha 53 e 58] 'if' e 'else' desnecessários.
[linha 76] Precisa adicionar 1 ao k final pois o último a ser
comparado foi o k[j+1].
'''
import math as mt
import numpy as np
print("esse programa deseja calcular a integral da Gaussiana")
#função que deseja calcular a integral
def fun(y):
return 1/mt.sqrt(2*mt.pi) * mt.exp(-y**2/2)
#definição do método dos trapézios
def trapezio(fun,a,b,k):
delta = (b - a)/2**k
t = 1 #é o j do somátorio (chama de t por ser do trapézio)
ft=[] #fj da fórmula
for t in range(1,2**k):
f = fun(a + t*delta)
ft.append(f)
t += 1
T = delta/2 * (fun(a) + 2*sum(ft) + fun(b))
return T
#definição do método de Simpson pelo método dos trapézios
def simpson(Tki,Tki1):
return Tki1 + (Tki1 - Tki)/3
a = -2 #intervalo inferior
b = 2 #intervalo superior
precisao = 10**-6
k = np.array(range(0,21,1)) #como 2**20 é um número grande, logo o k seria menor que esse valor
#achar a ordem de K pela convergência no método dos trapézios
k_trapezio = 0
for i in range(len(k)):
if abs(trapezio(fun, a,b, k[i+1])- trapezio(fun, a, b ,k[i])) < precisao:
break
else:
k_trapezio = k[i+2]
#na primeira iteracao nao vai atingir a precisao, entao vai pro else. na segunda iteracao o i vai ser 1, mas o k será em relação ao 2, pois o programa vai breakar, entao o k que vai parar vai ser k[2]
#achar a ordem de K pela convergência no método de Simpson usando o método dos trapézios
count_simpson = 0
for j in range(len(k)):
if j == 0:
Tkj = trapezio(fun, a,b, k[j]) #esse é o Tk-1 da formula
Tkj1 = trapezio(fun, a,b, k[j+1]) #esse é o TK da formula
Sx = simpson(Tkj,Tkj1)
else:
Tkj = trapezio(fun, a,b, k[j])
Tkj1 = trapezio(fun, a,b, k[j+1])
Sx = simpson(Tkj,Tkj1)
if abs(Sx - S_anterior) < precisao:
break
else:
k_simpson = k[j+1]
S_anterior = Sx #como o primeiro valor de j é 0, o primeiro S_anterior(Sx-1) será o S0
""" Para otimizar o programa: quando a integral vai de -a até a podemos fazer 2 * integral da função em [0,a].
Contudo, isso funciona apenas em funções pares, em funções impares, como sen(x), a integral de [-a,a] dá 0, logo essa otimização não funcionaria."""
print("a integral da Gaussiana calculada pelo método dos trapézios nos intervalo [%.d,%.d] é %.3f e o k que gera a melhor aproximação é %d" %(a,b,trapezio(fun, a,b,k_trapezio),k_trapezio))
print("pelo método de Simpson a integral é %.3f e o k que gera a melhor aproximação é %d" %(Sx,k_simpson))
|
'''
Gabriella
- [linha 45] Erro na condição para o programa não rodar para um x
inicial com derivada próxima de zero:
usou '>' em vez de '<' (feito)
- [linha 52] Erro na função para o valor da raíz:
usou 'dxi' em vez de 'derivada(xi)' (corrigido)
2.5/5
'''
# -*- coding: utf-8 -*-
"""NR
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1QDuEoIEzi7dgC4MwNdrgYJa1xh2ssrXm
"""
import matplotlib.pyplot as plt
import numpy as np
print("Esse programa implementa o método Newton-Raphson de para achar a primeira raiz positiva de f(x) = eˆ(-x) - sin(x*pi/2) \n")
#função que desejamos encontrar a raiz
def f(x):
return np.exp(-x) - np.sin(np.pi*x/2)
#derivada da funcao f(x) calculada analiticamente
def derivada(x):
return -np.exp(-x) - (1/2)*np.pi*np.cos(np.pi*x/2)
#faz o gráfico da função acima com os valores de x e y definidos
x = np.linspace(0,4,200)
y = f(x)
plt.plot(x,y)
plt.title("Função")
plt.grid(True)
plt.show()
xi = float(input("Olhe o gráfico acima e determine o x desejado \n"))
limite = 100 #número maximo de iterações
precisao = 1*10**-7
precisao_derivada = 1*10**-5
dxi = derivada(xi)
#essa parte nao esta funcionando NS PQ???
if abs(dxi) < precisao_derivada: # numeros cujas derivadas não são zero, mas serão muito perto e darão uma raiz muito distante
print("Não é possivel encontrar a raiz por este valor de x")
else:
Nit = 0 #contador para o número de iterações
delta = 100
while abs(delta) > precisao and Nit<limite:
x = xi - f(xi)/derivada(xi) # valor próximo x que será usado
delta = (x - xi) #função com o valor de x
xi = x
Nit = Nit + 1
print("O número de iterações : %.d \ne a raiz é %.3f" %(Nit,x))
|
def quick_sort(nums):
""" Быстрая сотрировка"""
n = len(nums)
if n < 2:
return nums
low, same, high = [], [], []
pivot = nums[n // 2]
for i in range(n):
if nums[i] < pivot:
low.append(nums[i])
elif nums[i] > pivot:
high.append(nums[i])
else:
same.append(nums[i])
return quick_sort(low) + same + quick_sort(high)
random_list_for_sort = [11, 5, 21, 4, 0, 9, 44, 3, 2, 8]
print("Исходный список: ", random_list_for_sort)
print("Отсортированый: ", quick_sort(random_list_for_sort))
|
from sklearn.feature_extraction.text import CountVectorizer
#一个语料库
corpus = [
'This the the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vectorizer = CountVectorizer(ngram_range=(2,2))
X = vectorizer.fit_transform(corpus)
print("词汇:索引",vectorizer.vocabulary_)
print("句子的向量:")
print(X.toarray())#元素为每个词出现的次数
|
# -*- coding:utf-8 -*-
# python解释器查找变量顺序:L > E > G > B
def get_pass_100(val):
print('%x' % id(val))
# local
passline = 60
if val >= passline:
print("pass")
else:
print("fail")
def in_func(): # (val, )
print(val)
in_func()
# 返回函数名(函数对象入口地址)
return in_func
def get_pass_150(val):
print('%x' % id(val))
# local
passline = 90
if val >= passline:
print("pass")
else:
print("fail")
def in_func(): # (val, )
print(val)
in_func()
# 返回函数名(函数对象入口地址)
return in_func
# global
passline = 80
f_100 = get_pass_100(70)
f_100()
# 函数f,即in_func的第一个参数地址和local变量val地址同
print(f_100.__closure__)
f_150 = get_pass_150(70)
f_150()
print(f_150.__closure__)
print("=" * 60)
# 为了减少上述代码量,把get_pass_100和get_pass_150合为一体,passline以参数形式传入
def set_total_score(passline):
def get_pass(val):
print('val: %x' % id(val)) # 立即数
print('passline: %x' % id(passline))
if val >= passline:
print("pass")
else:
print("fail")
return get_pass
f_100_60 = set_total_score(60)
f_150_90 = set_total_score(90)
print(f_100_60.__closure__)
f_100_60(70)
print(f_150_90.__closure__)
f_150_90(70)
|
"""
Directories module contains directory specific manipulation rules. Please
note that those rules which can be used for files and directories are
located in other modules like :mod:`hammurabi.rules.operations` or
:mod:`hammurabi.rules.attributes`.
"""
import logging
import os
from pathlib import Path
import shutil
from hammurabi.rules.common import SinglePathRule
class DirectoryExists(SinglePathRule):
"""
Ensure that a directory exists. If the directory does not exists,
make sure the directory is created.
Example usage:
.. code-block:: python
>>> from pathlib import Path
>>> from hammurabi import Law, Pillar, DirectoryExists
>>>
>>> example_law = Law(
>>> name="Name of the law",
>>> description="Well detailed description what this law does.",
>>> rules=(
>>> DirectoryExists(
>>> name="Create secrets directory",
>>> path=Path("./secrets")
>>> ),
>>> )
>>> )
>>>
>>> pillar = Pillar()
>>> pillar.register(example_law)
"""
def task(self) -> Path:
"""
Create the given directory if not exists.
:return: Return the input path as an output
:rtype: Path
"""
logging.debug('Creating directory "%s" if not exists', str(self.param))
self.param.mkdir()
return self.param
class DirectoryNotExists(SinglePathRule):
"""
Ensure that the given directory does not exists. In case the directory
contains any file or sub-directory, those will be removed too.
Example usage:
.. code-block:: python
>>> from pathlib import Path
>>> from hammurabi import Law, Pillar, DirectoryNotExists
>>>
>>> example_law = Law(
>>> name="Name of the law",
>>> description="Well detailed description what this law does.",
>>> rules=(
>>> DirectoryNotExists(
>>> name="Remove unnecessary directory",
>>> path=Path("./temp")
>>> ),
>>> )
>>> )
>>>
>>> pillar = Pillar()
>>> pillar.register(example_law)
"""
def post_task_hook(self):
"""
Remove the given directory from git index.
"""
self.git_remove(self.param)
def task(self) -> Path:
"""
Remove the given directory.
:return: Return the input path as an output
:rtype: Path
"""
if self.param.exists():
logging.debug('Removing directory "%s"', str(self.param))
shutil.rmtree(self.param)
return self.param
class DirectoryEmptied(SinglePathRule):
"""
Ensure that the given directory's content is removed. Please note the
difference between emptying a directory and recreating it. The latter
results in lost ACLs, permissions and modes.
Example usage:
.. code-block:: python
>>> from pathlib import Path
>>> from hammurabi import Law, Pillar, DirectoryEmptied
>>>
>>> example_law = Law(
>>> name="Name of the law",
>>> description="Well detailed description what this law does.",
>>> rules=(
>>> DirectoryEmptied(
>>> name="Empty results directory",
>>> path=Path("./test-results")
>>> ),
>>> )
>>> )
>>>
>>> pillar = Pillar()
>>> pillar.register(example_law)
"""
def task(self) -> Path:
"""
Iterate through the entries of the given directory and remove them.
If an entry is a file simply remove it, otherwise remove the whole
subdirectory and its content.
:return: Return the input path as an output
:rtype: Path
"""
with os.scandir(self.param) as entries:
for entry in map(Path, entries):
if entry.is_file() or entry.is_symlink():
logging.debug('Removing file "%s"', str(entry))
entry.unlink()
elif entry.is_dir():
logging.debug('Removing directory "%s"', str(entry))
shutil.rmtree(entry)
return self.param
|
file = open("output_data.txt", "w")
with open("file_data.txt", "r") as myfile:
data = myfile.readlines()
rev_data = data[::-1]
file.writelines(rev_data)
print(rev_data)
if file.mode=="r":
contents = file.read()
print(contents)
print(len(contents))
print(type(contents))
file.close()
|
import turtle
name = []
marks = []
students = [
{"name":"charan","marks":[213]},
{"name":"mitra","marks":[321]},
{"name":"rahul","marks":[123]},
{"name":"nithin","marks":[202]},
{"name":"shreeya","marks":[316]},
{"name":"sai","marks":[167]},
{"name":"adithya","marks":[234]},
{"name":"kaushik","marks":[300]}
]
def drawbar(student, marks):
student.begin_fill()
student.left(90)
student.forward(marks)
student.write(" " + str(marks))
student.right(90)
student.forward(40)
student.right(90)
student.forward(marks)
student.left(90)
student.end_fill()
def names(stu,name):
stu.forward(10)
stu.write(name,font=('Times New Roman',15))
stu.forward(30)
#f=open("student_grades.txt","r")
#if f.mode=="r":
# contents = f.read()
maxmarks = max(marks)
num_stu = len(name)
border = 10
wn = turtle.Screen()
wn.setworldcoordinates(0-border, 0-border, 40*num_stu+border, maxmarks+border)
wn.bgcolor("black")
student = turtle.Turtle()
student.color("white")
student.fillcolor("navy")
student.pensize(3)
student.speed(0)
stu = turtle.Turtle()
stu.color("white")
for i in marks:
drawbar(student, i)
stu.goto(0,0)
for j in name:
names(stu,j)
wn.exitonclick()
|
#To use the functions in another file in python
import arithmetic_functions
x = int(input("Enter the first number: "))
y = int(input("Enetr the second number: "))
# ADD
z = arithmetic_functions.add(x,y)
print("The sum of x and y is : %d"%(z))
# DIFFERENCE
z = arithmetic_functions.sub(x,y)
print("The differnce of x and y is : %d"%(z))
# MULTIPLY
z = arithmetic_functions.mul(x,y)
print("The product of x and y is : %d"%(z))
# DIVISION
z = arithmetic_functions.div(x,y)
print("The division of x and y is : %f"%(z))
# EXPONENTIAL
z = arithmetic_functions.exp(x,y)
print("The power of x to y is : %d"%(z))
# AVERAGE
z = arithmetic_functions.avg(x,y)
print("The average of x and y is : %f"%(z))
# REMAINDER
z = arithmetic_functions.rem(x,y)
print("The remainder for x and y is : %d"%(z))
|
def basiccalculator(s):
if not s:
return 0
num = 0
stack = []
sign = '+'
for i in range(len(s)):
if s[i].isdigit():
num = num*10 + int(s[i])
elif (not s[i].isdigit() and not s[i].isspace()) or i == len(s)-1:
if sign =='-':
stack.append(-num)
elif sign =='+':
stack.append(num)
elif sign == '*':
stack.append(stack.pop()*num)
else:
tmp = stack.pop()
if tmp//num <0 and tmp%num !=0:
stack.append(tmp//num+1)
else:
stack.append(tmp//num)
sign = s[i]
num =0
return sum(stack)
s1 = " 3+5 / 2 "
print(basiccalculator(s1))
|
num="90"
if(num===90):
print("number is greater than 100")
else:
print("number is less than 100")
|
# # December 4
import time
T1 = time.time()
import numpy as np
# Import input
with open('dec4_input.txt','r') as fin:
lower_limit,upper_limit = fin.read().split('-')
# Initialise password counters to 0
pw_counter = 0
pw_counter2 = 0
# Loop through all numbers which fulfill the "no decreasing digits" rule
for k1 in range(int(lower_limit[0]),int(upper_limit[0])+1):
for k2 in range(k1,10):
for k3 in range(k2,10):
for k4 in range(k3,10):
for k5 in range(k4,10):
for k6 in range(k5,10):
# compute the number and the diff of its digits
num = k1*1e5+k2*1e4+k3*1e3+k4*1e2+k5*1e1+k6
num_diff = np.diff([k1,k2,k3,k4,k5,k6])
# stop the loop if the upper limit is reached
if num>=int(upper_limit):
continue
# If the number is above the lower limit and contains at least a double digit
elif num>int(lower_limit) and 0 in num_diff:
# increment pw counter part 1
pw_counter+=1
# Convert the diff result to a string and count the zeros (adjacent equal numbers)
diff_string=''.join([str(x) for x in num_diff])
zeros = diff_string.count('0')
# Check if there is any pair of equal numbers that is not adjacent to one more and increment pw counter part 2
if zeros < 5 and zeros > diff_string.count('000')*3 and zeros > diff_string.count('00')*2:
pw_counter2+=1
print('Possible passwords part 1:')
print(pw_counter)
print('Possible passwords part 2:')
print(pw_counter2)
print('Execution time:')
print(time.time()-T1)
|
'''
349. Intersection of Two Arrays
DescriptionHintsSubmissionsDiscussSolution
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
'''
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
#declaring an empty array for comparing
result = []
#final array initialization
finalResult = []
for i in nums1:
for j in nums2:
if i == j :
result.append(i)
#removing duplicates
finalResult = set(result)
return list(finalResult)
|
list1 = []
x = 0
count = 0
limit = int(input("How many numbers would you like to sort?"))
while x < limit:
if x == 0:
num = float(input("Please input your numbers"))
list1.append(num)
x = x + 1
else:
num = float(input())
list1.append(num)
x = x + 1
while count < limit:
n = 1
while n < limit:
x = list1[n-1] - list1[n]
if x < 0:
pass
else:
temp = list1[n]
list1.remove(temp)
list1.insert(n-1, temp)
n = n+1
count = count + 1
print(list1)
|
import random
import operator
class Student(object):
def __init__(self, name, age, marks, rollNumber):
self.name = name
self.age = age
self.marks = marks
self.rollNumber = rollNumber
def __str__(self):
return "Name - {0}, Age - {1}, Marks - {2}, Roll Number - {3}".format(
self.name, self.age, self.marks, self.rollNumber)
students = []
for x in range(100):
students.append(Student(name="Student "+str(x), age=x*2, marks=x, rollNumber=x*10))
# Scramble our list
st_new = students[:]
random.shuffle(st_new)
for st in st_new:
print(st)
print("---------Name--------")
# name
sorted_list_1 = sorted(st_new, key=operator.attrgetter('name'))
for st in sorted_list_1:
print(st)
print("---------Name--------")
print("---------Age, Name--------")
sorted_list_2 = sorted(st_new, key=operator.attrgetter('age', 'name'))
for st in sorted_list_2:
print(st)
print("---------Age, Name--------")
|
names = ["Alex","John","Mary","Steve","John", "Steve"]
name_check=[]
for n in names:
if not n in name_check:
name_check.append(n)
names= name_check
print(names)
|
list =[]
def display3():
print("Here is your list of stores: ")
for i in range(0,len(list)):
print(f'{i+1} - {list[i].title}')
def display2():
print("Here is your shopping List")
for i in range(0,len(list)):
print(f"{list[i].title}")
for m in range(0,len(list[i].item_list)):
print(f"{list[i].item_list[m]}")
class Shopping:
def __init__(self,title,address):
self.title = title
self.address = address
self.item_list = []
def __str__(self):
return f"{self.item_list}"
class Items:
def __init__(self,item_title,item_price,item_quantity):
self.item_title = item_title
self.item_price = item_price
self.item_quantity = item_quantity
def __repr__(self):
return f"{self.item_title} - Price: {self.item_price} - Quantity: {self.item_quantity}"
def intro():
print("""
Press 1 to add store location:
Press 2 to add items to store:
Press 3 to view grocery list:
Press q to stop:
""")
while True:
intro()
choice = input("Please make your selection: ")
if choice == "1":
while True:
shopping_title = input("Enter your location name or press \"q\" to stop: ")
if shopping_title != "q":
shopping_address = input("Please enter your location address: ")
address = Shopping(shopping_title,shopping_address)
list.append(address)
display3()
else:
break
elif choice == "3":
display2()
elif choice == "2":
display3()
while True:
location = int(input("Enter the shopping location you want to add or press \"0\" to stop: "))
if location != 0:
item_title = input("Please enter your item's name: ")
item_price = input("Please enter your item's price: ")
item_quantity = input("Please enter your item's quantity: ")
item = Items(item_title,item_price,item_quantity)
list[location-1].item_list.append(item)
else:
break
elif choice == "q":
break
|
"""
Code Challenge
Name:
Webscrapping ICC Cricket Page
Filename:
icccricket.py
Problem Statement:
Write a Python code to Scrap data from ICC Ranking's
page and get the ranking table for ODI's (Men).
Create a DataFrame using pandas to store the information.
Hint:
#https://www.icc-cricket.com/rankings/mens/team-rankings/odi
https://www.icc-cricket.com/rankings/mens/team-rankings/t20i
#https://www.icc-cricket.com/rankings/mens/team-rankings/test
"""
from bs4 import BeautifulSoup
import requests
url= [ 'https://www.icc-cricket.com/rankings/mens/team-rankings/odi',
'https://www.icc-cricket.com/rankings/mens/team-rankings/t20i',
]
file_name= ["icc_odi.csv","icc_t20.csv"]
for index, link in enumerate(url):
#specify the url
icc = link
source = requests.get(icc).text
soup = BeautifulSoup(source,"lxml")
#print (soup.prettify())
#all_tables=soup.find_all('table')
right_table= soup.find('table', class_='table') ## use class underscore
print (right_table.tbody)
#Generate lists
pos=[] ## Rank
A=[] ## Team
B=[] ## Weighted
C=[] ## Points
D=[] ## Rating
for row in right_table.tbody.findAll('tr'):
cells = row.findAll('td')
pos.append(cells[0].text.strip())
A.append(cells[1].text.strip())
B.append(cells[2].text.strip())
C.append(cells[3].text.strip())
D.append(cells[4].text.strip())
from collections import OrderedDict
col_names = ["Rank","Team","Weighted Matches","Points","Rating"]
col_data = OrderedDict(zip(col_names,[pos,A,B,C,D]))
# If you want to store the data in a csv file
import pandas as pd
df2 = pd.DataFrame(col_data)
df2.to_csv(file_name[index])
print('All Done, You are Awesome')
##################################################################################
|
"""File for storing the Coordinate class"""
from math import sqrt
class Coordinate:
"""Class for storing the x and y coordinates of a region"""
def __init__(self, xray, yankee):
"""Creates a cordinate from a given x and y"""
self.xray = xray
self.yankee = yankee
@classmethod
def distance_coord(cls, coordinate1, coordinate2):
"""Creates a coordinate representing the vector between two coordinates"""
return cls(coordinate1.xray - coordinate2.xray, coordinate1.yankee - coordinate2.yankee)
def pretty_print(self):
"""Returns stylized string with the coordinates information"""
return "({}, {})".format(self.xray, self.yankee)
def distance_to(self, other):
"""Returns the distance between two coordinates"""
return sqrt((self.xray - other.xray)**2 +
(self.yankee - other.yankee)**2)
|
"""File for storing the Police class"""
from random import randint
from .fightable import Fightable
from .fleable import Fleable
from .forfeitable import Forfeitable
class Police(Fightable, Fleable, Forfeitable):
"""The police npc"""
def __init__(self, target_region, target_fuel_cost):
self.name = "Police"
self.id = 2
self.stolen_item = None
self.target_region = target_region
self.target_fuel_cost = target_fuel_cost
self.over = False
self.outcome = ""
def can_encounter(self, player):
"""decides if a player can encounter this npc"""
self.stolen_item = player.get_random_item()
return self.stolen_item is not None
def give_flea_reward(self, player):
"""handles the flee reward"""
player.ship.use_fuel(self.target_fuel_cost)
self.outcome = "You escaped the Police!"
def give_fight_reward(self, player):
"""handles the rewards"""
player.move_to_region(self.target_region, self.target_fuel_cost)
self.outcome = "You outgunned the Police!"
def give_forfeit_punishment(self, player):
"""Determines what happens if player forfeits"""
player.move_to_region(self.target_region, self.target_fuel_cost)
player.remove_item(self.stolen_item, player.get_item_count(self.stolen_item))
self.outcome = "You have turned over your " + self.stolen_item.name.lower()
def give_flea_punishment(self, player):
"""Determines what happens if the player fails to flee"""
player.ship.use_fuel(self.target_fuel_cost)
player.remove_item(self.stolen_item, player.get_item_count(self.stolen_item))
player.ship.lose_health(2.5)
player.spend_credits(250)
self.outcome = "The Police caught you!"
def give_fight_punishment(self, player):
"""Determines what happens if the player fails to fight"""
player.ship.use_fuel(self.target_fuel_cost)
player.remove_item(self.stolen_item, player.get_item_count(self.stolen_item))
player.ship.lose_health(5)
player.spend_credits(250)
self.outcome = "The Police outgunned you!"
def fight(self, player):
"""Determines how fight goes"""
self.over = True
roll = player.fighter_skill + randint(0, 17)
player.lower_karma()
if roll >= 17:
self.give_fight_reward(player)
return True
self.give_fight_punishment(player)
return False
def flee(self, player):
"""Determines how fleeing goes"""
player.lower_karma()
self.over = True
roll = player.pilot_skill + randint(0, 17)
if roll >= 17:
self.give_flea_reward(player)
return True
self.give_flea_punishment(player)
return False
def forfeit(self, player):
"""Handles what happens when the player forfeits"""
self.over = True
self.give_forfeit_punishment(player)
return True
def to_dict(self):
"""Creates a dictionary representation of this object"""
holder = {}
holder["name"] = self.name
holder["id"] = self.id
holder["over"] = self.over
holder["outcome"] = self.outcome
holder["stolen_item"] = self.stolen_item.name.lower()
return holder
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def func ( x ) :
return x*x
print func(3)
#Делаем присваивание имени
A = func
print A(3)
#Делаем присваивание имени функции
func = u"This is not function"
print func
print A(3)
#Работа функции как объекта 1-ого типа
def oper( L, function ) :
Res = []
for K in L :
Res.append ( function( K ) )
return Res
#Упращаем функцию oper
def oper1( L, function ) :
Res = [function(K) for K in L ]
return Res
X = [ 1, 34, 67, 100 ]
#Помним, что A = func
func = A
print oper( X, func )
#Возвращаем функцию как результ другой функции
#################################
def func1(Selector) :
if Selector < 0 :
def func2( x ) :
return x*x
return func2
else :
def func3( x ) :
return x*x*x
return func3
#################################
print oper( X, func1(-1) )
print oper(X, func1(1))
print oper1( X, func1(-1) )
print oper1(X, func1(1))
#Упрощаем, записываем функции func1,
#в виде двух лябда функций вместо
#func2 и func3
#################################
#Возвращаем функцию как результ другой функции
#################################
def func10(Selector) :
if Selector < 0 :
return lambda X : X*X
else :
return lambda X : X*X*X
#Можно делать и так
func20 = lambda x : x*x*x*x
print oper1( X, func10(-1) )
print oper1(X, func10(1))
print oper1(X, func20)
#################################
#################################
|
subjectEntities=[]
def addSubject(id, subjectName, stream):
"store the subject inside the subject data list. return True if operation is successful"
for subject in subjectEntities:
if subject["id"]==id:
return False;
if subject["subjectName"]==subjectName :
print("Two subjects can not have same name")
return False;
#add the new Subject
newSubject={}
newSubject["id"]=id
newSubject["subjectName"]=subjectName
newSubject["stream"]=stream
subjectEntities.append(newSubject)
return True;
def modifySubject(id, subjectName, stream):
"modify content of a already stored subject. return True if operation is successful"
for subject in subjectEntities:
if(subject["id"]==id):
selectedSubject=subject
selectedSubject["subjectName"]=subjectName
selectedSubject["stream"]=stream
return True;
return False;
def deleteSubject(id):
"delete a subject from the system. return True if operation is successful"
for subject in subjectEntities:
if(subject["id"]==id):
selectedSubject=subject
subjectEntities.remove(selectedSubject)
return True;
return False;
def showSubject(subjectName):
"prints dictionary with subject details"
for subject in subjectEntities:
if(subject["subjectName"]==subjectName):
selectedSubjectCopy=subject.copy()
break
del selectedSubjectCopy["id"]
print("Subject Name: "+selectedSubjectCopy["subjectName"])
print("Stream: "+selectedSubjectCopy["stream"])
return;
def getSubjectById(id):
"return the subjct that has given id. Otherwise return None"
for subject in subjectEntities:
if(subject["id"]==id):
return subject.copy();
return None;
def getSubjectBySubjectName(subjectName):
"return the subjct that has given id. Otherwise return None"
subjectEntityList=[]
for subject in subjectEntities:
if(subject["subjectName"]==subjectName):
subjectEntityList.append(subject.copy()) # give a copy of the dictionary as returned value.
return subjectEntityList;
def getSubjectId(name):
"return subject id when name is given"
for subject in subjectEntities:
if subject["subjectName"]==name:
return(subject["id"]);
|
from StudentDataCenter import*
from StudentSubjectRelation import getRelationshipsByStudentId
###########################################################################
def isValidStudentId(studentId):
if studentId[:2]!="ST" or not(studentId[2:].isdigit()):
print("Student Id is invalid")
return False
return True
def isValidStudentName(studentName):
for letter in studentName:
if letter.isdigit():
print("Student name should not have numbers included")
return False
if letter.isspace():
print("Student name should not have white spaces")
return False
return True
def isValidDOB(date):
"""when a date is given in DD/MM/YYYY format as a string, checks whether the date is valid."""
"If date is valid return True. Else False"
import datetime
if len(date)!=len("DD/MM/YYYY"):
print("DOB should match with DD/MM/YYYY format")
return False
date=date.strip().split("/",2)
for i in date:
if not(i.isdigit()):
print("DOB should match with DD/MM/YYYY format")
return False
year=int(date[2])
month=int(date[1])
day=int(date[0])
try:
datetime.datetime(year,month,day)
return True
except ValueError:
print("DOB should match with DD/MM/YYYY format")
return False
###########################################################################
def addStudentHandler(studentName,dob):
if (isValidDOB(dob))and(isValidStudentName(studentName)):
addStudent(studentName,dob)
return
def modifyStudentHandler(studentId,newName,dob):
if (isValidDOB(dob)) and (isValidStudentName(newName)) and (isValidStudentId(studentId)):
if getStudentById(studentId)==None:
print("Student with",studentId,"does not exist")
else:
if getStudentId(newName)!=None:
print("Two students can not have same name")
else:
isStudentModified=modifyStudent(studentId,newName,dob)
if isStudentModified:
print("Student modified correctly")
return
def removeStudentHandler(studentId):
if isValidStudentId(studentId):
if getStudentById(studentId)==None:
print("Student with",studentId,"does not exist")
return
relations=getRelationshipsByStudentId(studentId)
if relations==[]:
isDeleted=deleteStudent(studentId)
if isDeleted:
print("Student deleted successfully")
else:
print("Can not be deleted. Student has scores stored in the system")
return
def helpStudentHandler(studentId):
if isValidStudentId(studentId):
if getStudentById(studentId)==None:
print("Student with",studentId,"does not exist")
else:
showStudent(studentId)
return
|
def multiply(number, otherNumber) :
""" Takes two integers and returns product """
if otherNumber == 0 :
return 0
product = number + multiply(number, otherNumber - 1)
return product
print(multiply(4, 5))
print(multiply(1, 2))
print(multiply(4, 1))
print(multiply(10, 8))
print(multiply(0, 6))
print(multiply(3, 0))
|
def ones (number):
result=""
if number==1:
result=" One"
if number == 2:
result= " Two"
if number == 3:
result= " Three"
if number == 4:
result= " Four"
if number == 5:
result= " Five"
if number == 6:
result= " Six"
if number == 7:
result= " Seven"
if number == 8:
result= " Eight"
if number == 9:
result= " Nine"
if number == 10:
result= " Ten"
if number == 11:
result= " Eleven"
if number == 12:
result= " Twelve"
if number == 13:
result= " Thirteen"
if number == 14:
result=" Fourteen"
if number == 15:
result= " Fifteen"
if number == 16:
result= " Sixteen"
if number == 17:
result= " Seventeen"
if number == 18:
result= " Eighteen"
if number == 19:
result= " Nineteen"
return result
def tens(number):
result=""
if number==20:
result=' Twenty'
if number==30:
result=" Thirty"
if number==40:
result=" Fourty"
if number==50:
result=" Fifty"
if number==60:
result=" Sixty"
if number==70:
result=" Seventy"
if number==80:
result=" Eighty"
if number==90:
result=" Ninety"
return result
num=int(input("Enter any number: "))
answer=""
if num>=1000 and num<=9999:
answer+=ones(int(num/1000))+" Thousand"
num=num%1000
if num>=100:
answer+=ones(int(num/100))+" Hundred"
num=num%100
if num>=20:
answer += tens(int(num/10)*10)
num=num%10
if num>0 and num<=19:
answer+=ones(num)
print (answer)
|
a=1
b= int (input ("Enter a number:"))
while a<=10:
print ( b, "x", a, "=", (a*b))
a=a+1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.