text stringlengths 37 1.41M |
|---|
# coding=utf-8
# 日期:2020-03-09
# 作者:YangZai
# 功能:函数的定义,调用,形参和实参
# 8-1 消息
def display_message(message):
print(message)
message = '本章学习函数。'
display_message(message)
print()
# 8-2 喜欢的图书
def favorite_book(title):
print('One of my favorite book is ' + title + '.')
favorite_book('Alice in Wonderland')
print()
# 8-3 T恤
def make_shirt(size, sample):
print(size + '码,字样:' + sample)
# 位置实参调用
make_shirt('L', 'YangZai')
# 关键字实参调用
make_shirt(sample = 'YangZai', size = 'XL')
print()
# 8-4 大号T恤,函数参数设置默认值
def make_big_shirt(size = 'XL', sample = 'I love Python'):
print(size + '码,字样:' + sample)
# 默认字样和尺码T恤
make_big_shirt()
# 默认字样中号T恤
make_big_shirt('L')
# 印有其他字样的T恤(尺码无关紧要)
make_big_shirt(sample = 'YangZai')
print()
# 8-5 城市
def describe_city(name, country = 'china'):
print(name.title() + ' is in ' + country.title())
describe_city('Dongguan')
describe_city('ShenZhen', 'China')
describe_city('Reykjavik', 'Iceland')
print()
# 8-6 城市名
def city_country(name, country):
string = '"' + name.title() + ', ' + country.title() + '"'
return string
s1 = city_country('dongguan', 'china')
s2 = city_country('jieyang', 'china')
s3 = city_country('Shenzhen', 'China')
print(s1)
print(s2)
print(s3)
print()
# 8-7 专辑,返回字典和设置可选参数
def make_album(singer, name, number=''):
album = {'singer' : singer, 'name' : name}
if number:
album['number'] = number
return album
album_1 = make_album('林俊杰', '和自己对话')
album_2 = make_album('陈鸿宇', '浓烟下的诗歌电台')
album_3 = make_album('林俊杰', '伟大的渺小', 2)
print(album_1)
print(album_2)
print(album_3)
print()
# 8-8 用户的专辑
print("(enter 'q' at any time to quit)")
while True:
singer = input('Singer:')
if singer == 'q':
break
name = input('Album Name:')
if name == 'q':
break
album = make_album(singer, name)
print(album)
print()
# 8-9 魔术师
# 显示列表
def show_magicians(magicians):
print('Magicians:', end = ' ')
if len(magicians) == 0:
print('None.')
for i in range(len(magicians)):
if i == len(magicians) - 1:
print(magicians[i], end = '.\n')
else:
print(magicians[i], end = ', ')
magicians = []
show_magicians(magicians)
magicians.append('YangZai')
show_magicians(magicians)
magicians.append('Yang')
show_magicians(magicians)
print()
# 8-10 了不起的魔术师
# 修改列表
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] += '(the Great)'
make_great(magicians)
show_magicians(magicians)
print()
# 8-11 不变的魔术师
# 向函数传递列表副本
def edit_magicians(edit_magicians):
for i in range(len(edit_magicians)):
edit_magicians[i] += '(the Great)'
return edit_magicians
edit = edit_magicians(magicians[:])
show_magicians(magicians)
show_magicians(edit)
print()
# 8-12 三明治,传递任意数量的实参
def gather(*food):
print('三明治的食材有:', end = ' ')
for f in food:
print(f, end = ', ')
print()
gather('火腿', '洋葱')
gather('面包')
gather('番茄', '午餐肉', '生菜')
print()
# 8-13 用户简介,任意数量的关键字实参
def build_profile(first, last, **user_info):
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
my_profile = build_profile('zhan', 'tianyou',
profession = 'programmer',
age = 26,
height = '173cm')
print(my_profile, end = '\n\n')
# 8-14 汽车
def build_car(manufacturer, model, **car_info):
car = {}
car['manufacturer'] = manufacturer
car['model'] = model
for key, value in car_info.items():
car[key] = value
return car
my_car = build_car('subaru', 'outback', color = 'blue', tow_package = True)
print(my_car) |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
newNode = Node(insertVal)
if not head:
newNode.next = newNode
return newNode
prev = head
cur = head.next
seen = set()
while prev != cur and not prev.val <= insertVal <= cur.val:
if prev.val >= cur.val and (insertVal >= prev.val or insertVal <= cur.val) and cur in seen:
newNode.next = cur
prev.next = newNode
return head
seen.add(prev)
prev = cur
cur = cur.next
newNode.next = cur
prev.next = newNode
return head |
class Solution:
def toLowerCase(self, s: str) -> str:
return "".join([c.lower() if (ord('A') <= ord(c) and ord(c) <= ord('Z')) else c for c in s ]) |
lst = [1,3,5,2,6,4,8,9]
start = 0
for i in range(0,7):
var = []
for i in range(0,3):;
if start == len(lst):
start = 0
var.append(lst[start])
start +=1
print(var)
|
#check whether a number is prime or not.
num = 7
def check_prime(num):
i = 1
count = 0
while i <= num:
if num % i == 0:
print(f"divisible by {i}")
count = count + 1
i = i + 1
if count == 2:
print("prime")
else:
print("Not prime")
if __name__ == '__main__':
check_prime(num) |
# Method Single Pass Approach
# Time: O(n)
# Space: O(1)
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
# The replacement must be in-place and use only constant extra memory.
# Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
# 1,2,3 → 1,3,2
# 3,2,1 → 1,2,3
# 1,1,5 → 1,5,1
class Solution:
def nextPermutation(self, nums: 'List[int]') -> 'None':
"""
Do not return anything, modify nums in-place instead.
"""
i=j=len(nums)-1
while i>0 and nums[i-1]>=nums[i]: # if i==0 nums[i-1]???
i-=1
if i==0: # nums are in descending order
nums.reverse()
return
k=i-1 # find the last "ascending" position
while nums[j]<=nums[k]:
j-=1
nums[k],nums[j]=nums[j],nums[k]
# reverse the second part
l,r=k+1,len(nums)-1
while l<r:
nums[l],nums[r]=nums[r],nums[l]
l+=1
r-=1
if __name__='main':
Solution().nextPermutation([1,2,3]) |
# Method 1 DFS recursive
# Time: O(n)
# Space: O(logn)
#
# Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1:
def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> 'bool':
# check both are empty trees
if p is None and q is None:
return True
# check both node exit then check value
if p is not None and q is not None:
return p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
# otherwise neither node exits
return False
if __name__ == "__main__":
root1, root1.left, root1.right = TreeNode(1), TreeNode(2), TreeNode(3)
root2, root2.left, root2.right = TreeNode(1), TreeNode(2), TreeNode(3)
print (Solution1().isSameTree(root1, root2))
if __name__ == "__main__":
root1, root1.left = TreeNode(1), TreeNode(2)
root2, root2.right = TreeNode(1), TreeNode(2)
print (Solution1().isSameTree(root1, root2))
# Method 2 DFS + stack
# Time: O(n)
# Space: O(logn)
#
class Solution2:
def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> 'bool':
stack=[(p,q)]
while stack:
n1,n2=stack.pop()
# n1 and n2 exit
if n1 and n2 and n1.val==n2.val:
stack.append((n1.right,n2.right))
stack.append((n1.left,n2.left))
# both n1 and n2 are none
elif not n1 and not n2:
continue
# either node is none or value not same
else:
return False
return True # as stack pop to empty is true
if __name__ == "__main__":
root1, root1.left = TreeNode(1), TreeNode(2)
root2, root2.right = TreeNode(1), TreeNode(2)
print (Solution2().isSameTree(root1, root2))
# Method 3 BFS + queue
# Time: O(n) ??
# Space: O(logn)??
class Solution3:
def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> 'bool':
queue = [(p, q)]
while queue:
node1, node2 = queue.pop(0)
if not node1 and not node2:
continue
elif None in [node1, node2]:
return False
else:
if node1.val != node2.val:
return False
queue.append((node1.left, node2.left))
queue.append((node1.right, node2.right))
return True
if __name__ == "__main__":
root1, root1.left = TreeNode(1), TreeNode(2)
root2, root2.right = TreeNode(1), TreeNode(2)
print (Solution3().isSameTree(root1, root2))
|
#Method 1 swap????
#Time O(n)
#Space O(1) inplace
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head: 'ListNode') -> 'None':
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
# find the mid point
slow = fast=head
while fast and fast.next: #what does it have fast? meaning? why can find the middle
slow=slow.next
fast=fast.next.next
# reverse the second half in place 1->2->3->4->5->6 to 1->2->3->6->5->4
pre,node=None,slow
while node:
pre,node.next,node=node,pre,node.next
# Merge in-place; Note : the last node of "first" and "second" are the same ;1->2->3->6->5->4 to 1->6->2->5->3->4
first, second = head, pre
while second.next:
first.next, first=second,first.next
second.next,second = first,second.next
return |
def largest_digit(s):
max_digit = -1
for digit in s:
if digit.isdigit() and int(digit) > max_digit:
max_digit = int(digit)
if max_digit >= 0:
return max_digit
else:
return None
print(largest_digit("sdk2skl")) |
from SEAL.SplineFunction import SplineFunction
from SEAL.lib import create_interpolation_knots, create_cubic_hermite_coefficients, approximate_derivatives
def linear_spline_interpolation(parameter_values, data_values):
"""
Computes the linear spline interpolation to the given
m data points (x_i, y_i).
:param parameter_values: np.ndarray, shape (m, )
:param data_values: np.ndarray, shape (m, 2)
:return: SplineFunction of degree 1 representing the linear spline interpolation.
"""
t_values = create_interpolation_knots(parameter_values, interpol_type='linear')
p = 1
f = SplineFunction(p, t_values, data_values)
return f
def cubic_hermite_interpolation(parameter_values, function_values, derivatives=None):
cubic_hermite_knots = create_interpolation_knots(parameter_values, interpol_type='cubic')
p = 3
if derivatives is None:
derivatives = approximate_derivatives(parameter_values, function_values)
cubic_hermite_coeff = create_cubic_hermite_coefficients(parameter_values, function_values, derivatives)
return SplineFunction(p, cubic_hermite_knots, cubic_hermite_coeff)
|
#ex 3
def f():
name=str(input("Enter Name : "))
age=int(input("Enter age : "))
return 100-age+2021
print("The person turn 100 yrs in "+str(f())) |
texts = input("Enter the string\n")
result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
if len(result)==0:
print("FALSE")
else:
print("TRUE") |
import winsound
frequency = 2500 # Set Frequency To 2500 Hertz
duration1 = 500 # Set Duration To 1000 ms == 1 second
duration2 = 1000 # Set Duration To 1000 ms == 1 second
duration3 = 1500 # Set Duration To 1000 ms == 1 second
#-----------------------------------------------------------------------------------#
# this function makes a beep sound for short/long/verylong durations
def alarm(s):
if s=="short":
winsound.Beep(frequency, duration1)
elif s=="long":
winsound.Beep(frequency, duration2)
else :
winsound.Beep(frequency, duration3)
|
#Python 3
#Mastermind
#James Moorhead
#CS160
import random
##initiating empty master compare list##
master = []
##initiating empty guess list##
guess = []
##this is computers random start code##
while len(master) <4:
master.append(random.choice(['r','g','b','y']))
##get user input
first =(input('Please guess the 4 secret colors! (Valid Guesses Include: R, G, B, Y) '))
for i in (first):
guess.append(i)
for i , j in enumerate(master):
print(i,j)
print(guess)
print(master)
|
q1=int(input())
s=list(map(int,input().split()))
a=[]
for i in s:
a.append(i)
a.sort()
if s==a:
print("yes")
else:
print("no")
|
r=int(input())
p=list(map(int,input().split()))
y=sorted(p,reverse=True)
if y==[0,0,0,0,0]:
print(0)
else:
for i in y:
print(i,end="")
|
import re
def check_password(p):
# print errors if any
num = pwd.isdigit() or type(pwd) is float;
length = len(pwd) < 8;
digits = re.search(r"[0-9]", pwd);
upper = re.search(r"[A-Z]", pwd);
lower = re.search(r"[a-z]", pwd);
error = False;
if num:
print("error: {0} is not string".format(pwd));
return False;
if not digits:
print("error: should contain at least one digit");
error = True;
if not upper:
print("error: should contain at least one uppercase letter");
error = True;
if not lower:
print("error: should contain at least one lowercase letter");
error = True;
if length:
print("error: too short, min length is 8");
error = True;
if error:
return False
else:
print ("Looks good!")
return True;
pwd = input("enter password:");
check_password(pwd);
|
import matplotlib.pyplot as plt
import numpy as np
def w0(x: np.ndarray, y: np.ndarray):
return y.mean() - w1(x, y)*x.mean()
def w1(x: np.ndarray, y: np.ndarray):
return ((x*y).mean() - x.mean()*y.mean())/((x**2).mean() - x.mean()**2)
def hypothesis(xval, w0, w1):
return w0 + w1*xval
x = np.array([0, 30, 50, 80, 100, 130, 180])
y = np.array([0, 3.5, 5.0, 6.8, 7.4, 8.0, 12.0])
plt.figure()
plt.plot(x, y, '.')
xnew = np.linspace(x.min(), x.max(), 2)
plt.plot(xnew, hypothesis(xnew, w0(x, y), w1(x, y)))
plt.show()
print("Hypothesis gasoline prices: ")
for i in range(len(x)):
xval = x[i]
print(f"(s, chyp, ctrue) = ({xval}, {hypothesis(xval, w0(x, y), w1(x, y))}, {y[i]})") |
array1 = [1, 2, 3, 4, 5]
def printArray(thingToPrint):
print(thingToPrint)
for x in thingToPrint:
print(x)
#main
printArray(array1)
|
def indentationExample():
x = 4
if x != 0:
print(str(x))
x = 3
else:
x = 2
|
'''
Pytorch implementation of MLP training on MNIST.
'''
import torch
import torch.nn as nn
hidden_dim = 256
learning_rate = 0.005
class MLP(nn.Module):
def __init__(self, x_dim, hidden_dim, y_dim):
super(MLP, self).__init__()
self.lin1 = nn.Linear(x_dim, hidden_dim)
self.lin2 = nn.Linear(hidden_dim, y_dim)
self.dropout = nn.Dropout(0.3)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, x):
x1 = self.lin1(x)
hidden = self.lin2(x1)
x2 = self.dropout(hidden)
out = self.softmax(x2)
return out
mlp = MLP(len(x), hidden_dim, len(y))
opt = torch.optim.SGD(mlp.parameters(), lr = learning_rate)
#one training step
def train(x, y):
opt.zero_grad()
#use log likelihood loss because last layer is log softmax
criterion = nn.NLLLoss()
predicted = mlp(x)
loss = criterion(predicted, y)
loss.backward()
opt.step()
|
# READ IMAGES - VIDEO - WEBCAM
# 1.2 -> READ VIDEO
import cv2
# For Reading Video we have to create a VideCapture Object in its parameter we give the path of video
# cap = cv2.VideoCapture("Video Location")
cap = cv2.VideoCapture("Resources/abc.mp4")
# Since Video is a Sequence of images we have to use a loop for display
while True:
# The success variable is boolean type it captures the image if true
success, img = cap.read()
cv2.imshow("Video", img)
# Now we add a delay and wait for 'q' press to break the loop
if cv2.waitKey(1) & 0xFF == ord('q'):
break
|
digit = input("Enter a number to convert to words: ")
units = {
1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen",
18:"eighteen",19:"nineteen"}
tens = {
20:"twenty", 30:"thirty", 40:"fourty", 50:"fifty", 60:"sixty", 70:"seventy",
80:"eight", 90:"ninety"}
hundred = { 100:"one hundred", 200:"two hundred"}
def number_to_words(problem):
if len(digit) <= 2 and int(digit) in units.keys():
print(units[int(digit)])
elif len(digit) == 2 and int(digit) in tens.keys():
print(tens[int(digit)])
elif len(digit) == 2:
split_number = []
for letters in digit:
split_number.append(letters)
if len(split_number) == 2:
first_letter = split_number[0] + '0'
second_letter = split_number[1]
for num in tens.keys():
first_letter = int(first_letter)
if first_letter == num:
global split_tens
split_tens = tens[first_letter]
for num in units.keys():
second_letter = int(second_letter)
if second_letter == num:
global split_unit
split_unit = units[second_letter]
print(split_tens,'-', split_unit)
split_number = []
for letters in digit:
split_number.append(letters)
if len(split_number) == 3 and split_number[1] == '0':
first_letter = split_number[0]
second_letter = split_number[1] + '0'
merged_letters = first_letter + second_letter
third_letter = split_number[2]
for num in hundred.keys():
merged_letters = int(merged_letters)
if merged_letters == num:
global split_hundred
split_hundred = hundred[merged_letters]
for num in units.keys():
third_letter = int(third_letter)
if third_letter == num:
global split_units
split_units = units[third_letter]
print(split_hundred, 'and',split_units)
elif len(digit) == 3:
split_number = []
for letters in digit:
split_number.append(letters)
if len(split_number) == 3:
first_letter = split_number[0] + "00"
second_letter = split_number[1] + "0"
third_letter = split_number[2]
# print(first_letter, second_letter, third_letter)
for num in split_number:
first_letter = int(first_letter)
second_letter = int(second_letter)
third_letter = int(third_letter)
if first_letter == hundred.keys():
pass
if second_letter == tens.keys():
pass
if third_letter == units.keys():
pass
print(hundred[first_letter], "and", tens[second_letter], units[third_letter])
'''
>>>> Ify check this one out.
roots = {1:"one", 2:"two", 3:"three", 4:"four", 5:"five",
6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten",
11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen",
16:"sixteen", 17:"seventeen", 18:"eighteen",19:"nineteen", 20:"twenty",
30:"thirty", 40:"fourty", 50:"fifty", 60:"sixty", 70:"seventy", 80:"eighty", 90:"ninety"}
def number_to_words(digit):
# digit = input("Type a number: ")
if int(digit) in roots.keys():
print (roots[int(digit)])
elif len(digit) == 2:
print (roots[int(digit[0]+'0')]+"-"+number_to_words(digit[-1]))
elif len(digit) == 3:
if int(digit[1:]) == 0:
print (roots[int(digit[0])]+ " hundred")
else:
print ((roots[int(digit[0])]+ " hundred and "+number_to_words(digit[1:])))
print ("Try again")
# number_to_words(digit)
'''
number_to_words(digit)
|
from tkinter import *
class Frame1(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, bg="red")
self.parent = parent
self.widgets()
def widgets(self):
self.text = Text(self)
self.text.insert(INSERT, "Hello World\t")
self.text.insert(END, "This is the first frame")
self.text.grid(row=0, column=0, padx=20, pady=20) # margins
class MainW(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.mainWidgets()
def mainWidgets(self):
self.label1 = Label(self, text="Main window label", bg="green")
self.label1.grid(row=0, column=0)
self.label2 = Label(self, text="Main window label", bg="yellow")
self.label2.grid(row=1, column=0)
self.window = Frame1(self)
self.window.grid(row=0, column=10, rowspan=2)
if __name__=="__main__":
app = MainW(None)
app.mainloop() |
class Set(object):
def __init__(self):
self.matches = []
def Clone(self):
s = Set()
s.matches = [m for m in self.matches]
return s
def AddMatch(self, match):
self.matches.append(match)
def Diff(self):
"""
Take all diff values, put them in a list.
Return the sorted list.. later, I'll write a comparison
algorithm.
Return the max diff value, the worst match, and then
the second max value, i.e. the 2nd worst match. This
would allow me to prefer a set that has 3 great matches
and one bad one, over a set that has potentially 4 bad matches..
Consider two cases:
0.5,0.6,0.5,0.6
0.1,0.0,0.2,0.6
In the previous algorithm, they are the same... here, the second
one could be preferred.
"""
diffs = []
for m in self.matches:
diffs.append(m.Diff())
diffs.sort()
return diffs
def DiffStats(self):
diffMax = 0
diffAvg = 0
diffCnt = 0
diffs = []
for match in self.matches:
diff = match.Diff()
diffCnt = diffCnt + 1
diffAvg = diffAvg + diff
if diff > diffMax:
diffMax = diff
diffs.append(diff)
diffAvg = diffAvg / diffCnt
diffs.sort()
return diffMax, diffAvg, diffs
def Display(self):
for match in self.matches:
match.Display()
print("")
def showDiffs(self):
diffs = ["%4.2f" % match.Diff() for match in self.matches]
print("Diffs: " + "\t".join(diffs))
def __repr__(self):
return " ".join([str(m) for m in self.matches])
|
def function1():
print "you chose 1"
def function2():
print "you chose 2"
def function3():
print "you chose 3"
#
# switch is our dictionary of functions
switch = {
'one':function1,
'two':function2,
'three':function3
}
#
#chice can either be 'one', 'two', or 'three
choice = raw_input('Enter one, two, or three: ')
#call one of the functions
try:
result = switch[choice]
except KeyError:
print 'I didn\'t understand your choice.'
else:
result() |
people = 14
cats = 20
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people >= cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drolled on!"
if people >= dogs:
print "The world is dry!"
dogs +=5
if people >= dogs:
print "People are greather than equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs." |
import random # import lib to generate random numbers
from urllib import urlopen # import lib to open a URL and get resulting text
import sys #this is so that we can use argv to get passed in arguments
WORD_URL = "http://learncodethehardway.org/words.txt" # set a constant to Zed's URL
WORDS = [] # initialize words list
PHRASES = { # this is a dictionary of questions and answers
"class ###(###):":
"Make a class named ### that is-a ###.",
"class ###(object):\n\tdef __init__(self, ***)" :
"class ### has-a __init__ that takes self and *** parameters.",
"class ###(object):\n\tdef ***(self, @@@)":
"class ### has-a function named *** that takes self and @@@ parameters.",
"*** = ###()":
"Set *** to an instance of class ###.",
"***.***(@@@)":
"From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
# do they want to drill phrases first?
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip()) # this gives a nice list of works with the '/n' stripped off
def convert(snippet, phrase): # i.e., key, value
# analysis of next line
# count the nunber of times that "###" appears in the snippet
# randomly grab that number of words from the list of words and return as a list
# loop through the list and capitalize each word
class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("###"))]
# analysis of next line
# count the nunber of times that "***" appears in the snippet
# randomly grab that number of words from the list of words and return as a list
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0,snippet.count("@@@")): # for every time "@@@" appears in the snippet...
param_count = random.randint(1,3) # generate a random param count of 1, 2, or 3
param_names.append(', '.join(random.sample(WORDS, param_count))) # make a random list of 1, 2, or 3 param names
for sentence in snippet, phrase:
# result = sentence[:]
result = sentence
# fake class names
for word in class_names:
result = result.replace("###", word, 1)
# fake other names
for word in other_names:
result = result.replace("***", word, 1)
# fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
#keep going until they hit CTRL-D
try:
while True:
snippets = PHRASES.keys() # make a list just the keys from the Q&A database
random.shuffle(snippets) # shuffle the list of keys in to a random order
for snippet in snippets: # go through the list of questions
phrase = PHRASES[snippet] # snippet is the key that gets the value phrase from the ditionary PHRASES
# snippet is the key, phrase if the value
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question # cool, you can flip then all in one line
print question
raw_input("> ")
print "ANSWER: %s\n" % answer
except EOFError:
print "\nBye"
|
import sys
import os
from main import ParagraphSearch as pc
if len(sys.argv) <= 3:
print('Too few arguments. At least site, depth and one or more keywords needed.')
if len(sys.argv) >= 5:
print('Too many arguments.')
else:
website = sys.argv[1]
depth = int(sys.argv[2])
keywords = sys.argv[3]
pc.ParagraphSearch(website, depth, keywords)
|
import os
import vdm
# Get a number value from input, or return a default.
def getNumVal(message, default):
n = input(message)
try:
if int(n) < 0:
print("Using default {}".format(default))
return default
return int(n)
except ValueError:
print("Using default {}".format(default))
return default
help = """
Welcome to STRAIGHT-TO-VDM, a program to
create VDM files for all demos in a single directory.
STRAIGHT-TO-VDM currently supports bookmarks created by:
* In game demo support | SAVED AS: <demo_name>.json
* PREC | SAVED AS: killstreaks.txt
Please note this will overwrite VDMs currently written in your directory.
Will you be processing prec or in-game bookmarks? (enter PREC or IG)
"""
print(help)
support = input("PREC or IG > ")
if support.lower()[0] == "p":
support = "prec"
elif support.lower()[0] == "i":
support = "ds"
else:
print("Unknown option: {}. Please type prec or ig".format(support))
print("Proceeding with {} support".format(support))
print("Write the path to your {}. Ideally, an absolute path (begins with drive). This is where VDMs will be saved.".format("directory" if support == "ds" else "killstreaks.txt"))
src = input("> ")
src = os.path.abspath(src)
d = vdm.Directory(src, JSONFilter=vdm.HasEvents, Type=support)
print("I am about to ask you to fill some parameters - each has a default and you can choose to enter nothing or a non-number value to use the default.")
startm = getNumVal("1. How many ticks before a bookmark do you wish to start your recording? (Default 500)\n>", 500)
endm = getNumVal("2. How many ticks after a bookmark do you wish to end your recording? (Default 0: End on bookmark)\n>", 0)
skipm = getNumVal("3. (Advanced) How many ticks before recording starts do you wish to stop fast-forwarding? (Default 1)\n>", 1)
onlybmarks = input("4. (Advanced) Skip automatically generated Killstreak bookmarks and only process manually made bookmarks? y/n\n>")
if onlybmarks.lower() == "y":
vdm.EventFilter = vdm.IsBookmark
d.filter(vdm.PassesEventFilter)
print("Proceeding by only processing manual bookmarks")
else:
print("Proceeding by processing all events")
for fI, file in d:
L = vdm.EventList(file, d)
for eI, event in L:
vdm.RecordEvent(event, eI, L, START_MARGIN=startm, END_MARGIN=endm, SKIP_MARGIN=skipm)
L.write()
print("Finished.")
_ = input("Press any key to exit.")
|
# encoding=utf-8
"""
HJ13 句子逆序
"""
# Get input
input_str = input()
# Split with space and revese
input_list = input_str.split()
input_list.reverse()
# print every word in reversed list
for word_tmp in input_list:
print(word_tmp, end=" ")
|
# encoding=utf-8
"""
HJ3 明明的随机数
"""
# Initial input list
input_list = list()
# Initial input flag and counter
input_flag = True
list_tmp = list()
while input_flag:
# input length at 1st line
try:
len_tmp = input()
if (len_tmp != ""):
# get the length
len_tmp = int(len_tmp)
# initial a list
list_elem_tmp = list()
for counter_tmp in range(0, len_tmp):
# get every element for this list
elem_tmp = input()
if elem_tmp !="":
elem_tmp = int(elem_tmp)
if elem_tmp not in list_elem_tmp:
list_elem_tmp.append(elem_tmp)
else:
pass
else:
pass
# Append this list to list of list
list_elem_tmp.sort()
list_tmp.append(list_elem_tmp)
else:
raise EOFError("")
except Exception:
# Go to end if no length input
input_flag = False
# print every elem
for list_elem in list_tmp:
for elem_tmp in list_elem:
print(elem_tmp) |
#Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes
# are displayed on the 24 h digital clock?
N = int(input("Enter the minutes passed since midnight:"))
hours = (N//60)
minutes = (N%60)
print(f'The hour displayed in the 24 h digital clock is {hours}')
print(f'The minutes displayed in the 24 h digital clock is {minutes}')
|
num=int(input('Enter the number of factorial: '))
product = 1
for i in range(1, num+1):
product= (product * i)
print(f'THe factorial of {num} is {product}')
# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
|
import random
class Card :
def __init__(self, typeCard, mp, detail):
self.typeCard = typeCard
self.mp = mp
self.detail = detail
def show(self) :
print ("[{}] Mp {} [ Detail : {} ]".format(self.typeCard, self.mp, self.detail))
class Deck :
def __init__(self):
self.cards = []
self.build()
def build(self) :
self.cards.append(Card('At card', 0 ,'At+1'))
self.cards.append(Card('At card', 1 ,'At+2'))
self.cards.append(Card('At card', 0 ,'At+1'))
self.cards.append(Card('AD card', 0 ,'Hp+3'))
self.cards.append(Card('AD card', 0 ,'Mp+2'))
self.cards.append(Card('AD card', 0 ,'Mp+1'))
self.cards.append(Card('Df card', 0 ,'Shield+2'))
self.cards.append(Card('Df card', 0 ,'Shield+1'))
self.cards.append(Card('Df card', 1 ,'Shield+3'))
self.cards.append(Card('AD card', 2 ,'Hp+5'))
self.cards.append(Card('Df card', 2 ,'Shield+4'))
self.cards.append(Card('At card', 2 ,'At+3'))
def show(self) :
for c in self.cards :
c.show()
def shuffle(self) :
for i in range(len(self.cards)) :
r = random.randint(0,i)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
def drawCard(self) :
if self.cards == [] :
self.build()
return self.cards.pop()
|
#importing necessary libraries
import numpy as np
from numpy import genfromtxt
from sklearn.neural_network import MLPClassifier
from sklearn import preprocessing, model_selection
# for mean squared error calculation
def mse( y_true, y_pred):
y_err = y_true - y_pred
y_sqr = y_err * y_err
y_sum = np.sum(y_sqr)
y_mse = y_sum / y_sqr.size
return y_mse
#this is for showing real data
np.set_printoptions(suppress=True)
# this part is for readind .csv files and turning them into numpy arrays
data = genfromtxt('simple_pos.csv', delimiter=',', skip_header=1)
#this part slices arrays into two parts
#labels
#month(0),hour(1),maintenance(2),failure(3),weekday(4),temprature(5),position(6)
X = data[:, 0:6]
#feature
y = data[:, 6]
#scaling the label data for effective clustering
X = preprocessing.scale(X)
print(X.shape)
print(X)
#spliting data as training data and testing data
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)
#preparing classification object
mlp = MLPClassifier(random_state=0, hidden_layer_sizes=[100], max_iter=1)
# the part where training and observing error happens
# Note: to stop training at a certain point, it is required to create a keyboard
# interrupt to stop the whlie loop with CTRL-C
i = 1
cont = True
min_error = 1
while(i <= 2000):
mlp.partial_fit(X_train, y_train, np.unique(y_train))
y_pred = mlp.predict(X_train)
mse_err = mse(y_train, y_pred)
print("iteration: " + str(i) + " Mean Squared Error: " + str(mse_err))
i = i + 1
#to see the accuracy of the prepared model
accuracy = mlp.score(X_test, y_test)
print(accuracy)
|
from Card import Card
class Deck(object):
card_suit = ["Clubs", "Diamonds", "Hearts", "Spades"]
card_rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
def __init__(self):
self.deck = []
self.new_deck()
def __len__(self):
return len(self.deck)
def new_deck(self):
for suit in Deck.card_suit:
for rank in Deck.card_rank:
c = Card(suit, rank)
self.deck.append(c)
def print_cards_in_deck(self):
for card in self.deck:
print '{card}'.format(card=card.get_card_string())
def insert_card(self, card):
self.deck.append(card)
def remove_last_card(self):
return self.deck.pop()
def remove_card_at_index(self, idx):
return self.deck.pop(idx)
|
#To find the frequency of each digit(0-9) in a string of alphabets and numbers.
x=str(raw_input("Enter String input :"))
arr=[]
for t in range(0,10):
arr.append(int(0))
for no in range(0,10):
cnt=0
for i in range(0, len(x)):
d=str(no)
if x[i]==d :
cnt+=1
arr[no]=cnt
for t in range(0,10):
print "The number of %d's in the sting is :"% t,arr[t]
|
#Python program that matches a word containing 'z or Z', not at start or end of the word. (Example : Aaazwwwiiii is valid and zAswiz is invalid)
import re
pat = '\Bz|Z\B'
word=raw_input("Enter a string :")
def text_match(text):
if re.search(pat, text):
return "Found a match!"
else:
return "Not matched!"
print text_match(word)
|
#Write a program where a user enters a number n. The program prints the sentence “tell me why I don’t like mondays?” n times. Can the program be written using both types of loops?
limit=input("Enter how many times you want to print the statement :")
count=1
print "The statement is being printed by while loop.."
while count <= limit :
print "Tell me why I don't like mondays?"
count+=1
print "The statement is being printed by for loop.."
for count in range(0,limit):
print "Tell me why I don't like mondays?"
|
#Program to check whether the input string is valid for the given grammar.
import sys
global string,i,l
i=0
l=''
string=''
print """\nGrammar :
A -> B C | D
B -> A E | F\n"""
def A():
global l
if l=='':
getch()
if l=='F':
match('F')
match('C')
A1()
return True
elif l=='D':
match('D')
A1()
return True
else:
print "REJECTED"
exit(0)
def A1():
if l=='E':
match('E')
match('C')
A1()
elif l==' ':
match(' ')
else:
print "REJECTED"
exit(0)
def getch():
global i,l
if i<len(string):
l=string[i]
i+=1
def match(c):
if c == l:
getch()
return
print "REJECTED"
exit(0)
print "Note : ' ' is the input to be given for epsilon.\n'id' here is 'i' in input.\n"
while True:
if string=='':
string=raw_input("Enter input string (Type exit to quit.) : ")
if string=='exit':
exit(0)
A()
if l=='$':
print "ACCEPTED"
l=''
i=0
string='' |
#Write a program where the loop runs from 20 to 10 and print these value.
n=20
for i in range(10,21):
print n
n=n-1
print "The loop is complete."
|
import sys
def hex_to_decimal(my_hex_string):
return str(int(my_hex_string, 16))
if __name__ == '__main__':
filename = "input.txt"
if len(sys.argv) == 2:
filename = sys.argv[1]
f = open(filename, 'r')
for line in f:
print(hex_to_decimal(line.strip()))
f.close()
|
def is_prime(n):
if n == 2 or n == 3:
return True
if n < 2 or not n % 2:
return False
if n < 9:
return True
if not n % 3:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
if not n % f:
return False
if not n % (f+2):
return False
f += 6
return True
if __name__ == '__main__':
primes = []
max_count = 1000
j = 0
while len(primes) < max_count:
j += 1
if is_prime(j):
primes.append(j)
print(sum(primes))
|
#-*-coding:utf-8-*-
# number1 = 0
def in_range(n):
# n = 0
if n in range(1,5):
print( '%s is in range' % in_range(n))
else:
print('%s is not in range')
in_range(4)
|
#-*-coding:utf-8-*-
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.andy = Employee('andy','green',150000)
def test_give_default_raise(self):
self.andy.give_raise()
self.assertEqual(self.andy.annual_salary,155000)
def test_give_custom_raise(self):
self.andy.give_raise(10000)
self.assertEqual(self.andy.annual_salary,160000) |
#-*-coding:utf-8--
a = {'a': 1}
def print_a():
print(a)
def fib(n):
print(1 + 'a')
a, b = 0,1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
print("python's __name__ value is: %s, type is: %s" % (__name__, type(__name__)))
if __name__ == '__main__':
print('executing fibo.py', fib2(2))
|
#!/usr/bin/env python2
# CS 212, hw1-2: Jokers Wild
#
# -----------------
# User Instructions
#
# Write a function best_wild_hand(hand) that takes as
# input a 7-card hand and returns the best 5 card hand.
# In this problem, it is possible for a hand to include
# jokers. Jokers will be treated as 'wild cards' which
# can take any rank or suit of the same color. The
# black joker, '?B', can be used as any spade or club
# and the red joker, '?R', can be used as any heart
# or diamond.
#
# EJB: There seems to be an unstated further condition
# here - the wildcard cannot take the same value as
# any other card already in the hand.
#
# The itertools library may be helpful. Feel free to
# define multiple functions if it helps you solve the
# problem.
#
# -----------------
# Grading Notes
#
# Muliple correct answers will be accepted in cases
# where the best hand is ambiguous (for example, if
# you have 4 kings and 3 queens, there are three best
# hands: 4 kings along with any of the three queens).
import itertools
def best_wild_hand(hand):
"Try all values for jokers in all 5-card selections."
wilds = {'?B' : [ r+s for r in '23456789TJQKA' for s in 'CS' ],
'?R' : [ r+s for r in '23456789TJQKA' for s in 'DH' ]}
if not any(map(lambda x: x in hand, wilds.keys())): #EJB: Nice test! No wildcards.
return max(itertools.combinations(hand, 5), key=hand_rank)
replaced_hands = [hand]
for wildcard in wilds.keys():
for replaced_hand in replaced_hands:
while replaced_hand.count(wildcard) != 0: # EJB: I originally had index() here, thinking that it returned -1 for "not found"; but it throws exception.
wild_index = replaced_hand.index(wildcard)
for replacement_card in wilds[wildcard]:
if replacement_card not in replaced_hand: # EJB: Unstated condition: wildcard cannot take value of already-present card.
replaced_hand[wild_index] = replacement_card
replaced_hands.append(replaced_hand[:]) # *Copy* of replaced_hand, else all instances are really the same instance.
#print 'replaced_hands:', replaced_hands
best_combinations = []
for hand in replaced_hands[1:]: # Slice eliminates original hand, which seeded replaced_hands list.
best_combinations.append(max(itertools.combinations(hand, 5), key=hand_rank))
#print best_combinations
#print 'EJB:', sorted(max(best_combinations, key=hand_rank))
return max(best_combinations, key=hand_rank)
def test_best_wild_hand():
assert (sorted(best_wild_hand("6C 7C 8C 9C TC 5C ?B".split())) # One wildcard
== ['7C', '8C', '9C', 'JC', 'TC'])
assert (sorted(best_wild_hand("TD TC 5H 5C 7C ?R ?B".split())) # Two wildcards (of different colour)
== ['7C', 'TC', 'TD', 'TH', 'TS'])
assert (sorted(best_wild_hand("JD TC TH 7C 7D 7S 7H".split())) # No wildcards
== ['7C', '7D', '7H', '7S', 'JD'])
return 'test_best_wild_hand passes'
# ------------------
# Provided Functions
#
# You may want to use some of the functions which
# you have already defined in the unit to write
# your best_hand function.
def hand_rank(hand):
"Return a value indicating the ranking of a hand."
ranks = card_ranks(hand)
if straight(ranks) and flush(hand):
return (8, max(ranks))
elif kind(4, ranks):
return (7, kind(4, ranks), kind(1, ranks))
elif kind(3, ranks) and kind(2, ranks):
return (6, kind(3, ranks), kind(2, ranks))
elif flush(hand):
return (5, ranks)
elif straight(ranks):
return (4, max(ranks))
elif kind(3, ranks):
return (3, kind(3, ranks), ranks)
elif two_pair(ranks):
return (2, two_pair(ranks), ranks)
elif kind(2, ranks):
return (1, kind(2, ranks), ranks)
else:
return (0, ranks)
def card_ranks(hand):
"Return a list of the ranks, sorted with higher first."
ranks = ['--23456789TJQKA'.index(r) for r, s in hand]
ranks.sort(reverse = True)
return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks
def flush(hand):
"Return True if all the cards have the same suit."
suits = [s for r,s in hand]
return len(set(suits)) == 1
def straight(ranks):
"""Return True if the ordered
ranks form a 5-card straight."""
return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5
def kind(n, ranks):
"""Return the first rank that this hand has
exactly n-of-a-kind of. Return None if there
is no n-of-a-kind in the hand."""
for r in ranks:
if ranks.count(r) == n: return r
return None
def two_pair(ranks):
"""If there are two pair here, return the two
ranks of the two pairs, else None."""
pair = kind(2, ranks)
lowpair = kind(2, list(reversed(ranks)))
if pair and lowpair != pair:
return (pair, lowpair)
else:
return None
if __name__ == '__main__':
print test_best_wild_hand()
|
import matplotlib.pyplot as plt
#matplotlib inline
class Solow:
r"""
Implements the Solow growth model with update rule
k_{t+1} = [(s z k^α_t) + (1 - δ)k_t] /(1 + n)
"""
__slots__ = ['k', 'n', 's', 'z', 'δ', 'α']
def __init__(self, n=0.05, # population growth rate
s=0.25, # savings rate
δ=0.1, # depreciation rate
α=0.3, # share of labor
z=2.0, # productivity
k=1.0): # current capital stock
self.n, self.s, self.δ, self.α, self.z = n, s, δ, α, z
self.k = k
def _h(self):
"Evaluate the h function"
# Unpack parameters (get rid of self to simplify notation)
n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
# Apply the update rule
return (s * z * self.k**α + (1 - δ) * self.k) / (1 + n)
def _update(self):
"Update the current state (i.e., the capital stock)."
self.k = self._h()
def _steady_state(self):
"Compute the steady state value of capital."
# Unpack parameters (get rid of self to simplify notation)
n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
# Compute and return steady state
return ((s * z) / (n + δ))**(1 / (1 - α))
def _generate_sequence(self, t):
"Generate and return a time series of length t"
path = []
for i in range(t):
path.append(self.k)
self._update()
return path
s1 = Solow()
s2 = Solow(k=8.0)
T = 60
fig, ax = plt.subplots(figsize=(6, 5))
# Plot the common steady state value of capital
ax.plot([s1._steady_state()]*T, 'k-', label='steady state')
# Plot time series for each economy
for s in s1, s2:
lb = f'capital series from initial state {s.k}'
ax.plot(s._generate_sequence(T), 'o-', lw=2, alpha=0.6, label=lb)
ax.legend()
plt.show() |
try :
hoursPrompt = 'Enter hours worked: \n'
hours = int(input(hoursPrompt))
ratePrompt = 'Enter rate: \n'
rate = int(input(ratePrompt))
otHours = 0
pay = 0
if hours <= 40 :
pay = hours * rate
elif hours > 40 :
otHours = hours - 40
pay = rate * 40 + (otHours * rate * 1.5)
print(pay)
except :
print('Please enter an integer')
|
import re
inp = input('Enter a regular expression: ')
count = 0
fhand = open('mbox.txt')
for line in fhand:
if re.search(inp, line): count += 1
print('There are', count, 'matches for', inp, 'in mbox.txt.')
|
def count(word, letter):
number = 0
for index in word:
if index == letter:
number += 1
return number
print(count('banana', 'a'))
|
r=float(input("Input Radius : "))
area=3.14*r*r
perimeter=2*3.14*r
print("Area of Circle: ",area)
print("Perimeter of Circle: ",perimeter)
|
import tkinter as tk
from tkinter import ttk
# initializes the window
root = tk.Tk()
# creates window header
root.title('Calculator')
# output will be show at the top of the GUI
text1 = tk.Text(root,height=1,width=20)
text1.grid(row=0, column=0, columnspan=3,rowspan=1,padx=10,pady=10)
# entry input
entry= tk.Entry(root, text='Input')
entry.grid(row=1,column=0,columnspan=3,rowspan=1,padx=10,pady=10)
# operations
def button_click(number):
entry.delete(0,END)
entry.insert(0,number)
def button_add():
pass
def button_sub():
pass
def button_mult():
pass
def button_div():
pass
def button_clear():
pass
# number buttons
button0 = tk.Button(root,text = "0",padx=40,pady=20,command=lambda: button_click(0))
button1 = tk.Button(root,text = "1",padx=40,pady=20,command=lambda: button_click(1))
button2 = tk.Button(root,text = "2",padx=40,pady=20,command=lambda: button_click(2))
button3 = tk.Button(root,text = "3",padx=40,pady=20,command=lambda: button_click(3))
button4 = tk.Button(root,text = "4",padx=40,pady=20,command=lambda: button_click(4))
button5 = tk.Button(root,text = "5",padx=40,pady=20,command=lambda: button_click(5))
button6= tk.Button(root,text = "6",padx=40,pady=20,command=lambda: button_click(6))
button7 = tk.Button(root,text = "7",padx=40,pady=20,command=lambda: button_click(7))
button8 = tk.Button(root,text = "8",padx=40,pady=20,command=lambda: button_click(8))
button9 = tk.Button(root,text = "9",padx=40,pady=20,command=lambda: button_click(9))
equalsbutton= tk.Button(root,text = "=",padx=40,pady=20,command=lambda: button_equals(1))
addbutton= tk.Button(root,text = "+",padx=40,pady=20,command=lambda: button_add(1))
subbutton= tk.Button(root,text = "-",padx=40,pady=20,command=lambda: button_sub(1))
divbutton= tk.Button(root,text = "/",padx=40,pady=20,command=lambda: button_div(1))
multbutton= tk.Button(root,text = "x",padx=40,pady=20,command=lambda: button_mult(1))
clearbutton=tk.Button(root,text = "CLEAR",padx=115,pady=20,command=lambda: button_clear(1))
button1.grid(row=2,column=0)
button2.grid(row=2,column=1)
button3.grid(row=2,column=2)
button4.grid(row=3,column=0)
button5.grid(row=3,column=1)
button6.grid(row=3,column=2)
button7.grid(row=4,column=0)
button8.grid(row=4,column=1)
button9.grid(row=4,column=2)
button0.grid(row=5,column=0)
addbutton.grid(row=5,column=1)
subbutton.grid(row=5,column=2)
equalsbutton.grid(row=6,column=0)
divbutton.grid(row=6,column=1)
multbutton.grid(row=6,column=2)
clearbutton.grid(row=7,column=0,columnspan=3,rowspan=3)
# keeps the window running
root.mainloop() |
import math
import cmath
class MyMath:
_complex = False # Инкапсуляция
pi = 3.14
@classmethod
def get_name(cls):
return cls.__name__ # Инкапсуляция
@staticmethod
def sin(x):
return math.sin(x)
@classmethod
def get_complex(cls):
return cls._complex # Инкапсуляция
@classmethod
def sqrt(cls, x):
cres = cmath.sqrt(x)
if x >= 0:
return math.sqrt(x)
else:
if cls.get_complex(): # Полиморфизм
return cres.real, cres.imag
else:
raise ValueError('You are working with real numbers')
class MyComplexMath(MyMath): # Наследование
_complex = True # Инкапсуляция
|
class Shape:
def __init__(self, width, height):
self.width = width
self.height = height
class Triangle(Shape):
def area(self):
return self.width * self.height / 2
class Rectangle(Shape):
def area(self):
return self.width * self.height
print('Enter width and heigth through a space: ', end = '')
x, y = map(int, input().split())
print('Triangle area is ', Triangle(x, y).area())
print('Rectangle area is ', Rectangle(x, y).area())
|
import unittest
import a2
class TestA2(unittest.TestCase):
def test_move_1(self):
"""Test move out of range of the maze"""
maze = a2.Maze([['.','#'],['.','@'],['#','.']], \
a2.Rat('J',1,0), a2.Rat('P',0,0))
actual = maze.move(maze.rat_1,a2.NO_CHANGE,a2.LEFT)
expected = False
self.assertEqual(actual,expected)
actual = maze.move(maze.rat_1,a2.NO_CHANGE,a2.RIGHT)
expected = True
self.assertEqual(actual,expected)
actual = maze.move(maze.rat_1,a2.DOWN,a2.NO_CHANGE)
actual = maze.move(maze.rat_1,a2.DOWN,a2.NO_CHANGE)
expected = False
self.assertEqual(actual,expected)
def test_str_1(self):
"""Test __str__ when 2 rats at the same position"""
maze = a2.Maze([['.','#'],['.','@'],['#','.']], \
a2.Rat('J',1,0), a2.Rat('P',1,0))
actual = str(maze)
expected = ('.#\nJ@\n#.'
'\nJ at (1, 0) ate 0 sprouts.'
'\nP at (1, 0) ate 0 sprouts.')
self.assertEqual(actual,expected)
def test_str_2(self):
"""Test __str__ after move"""
maze = a2.Maze([['.','#'],['.','@'],['#','.']], \
a2.Rat('J',1,0), a2.Rat('P',1,0))
maze.move(maze.rat_1,a2.NO_CHANGE,a2.RIGHT)
actual = str(maze)
expected = ('.#\nPJ\n#.'
'\nJ at (1, 1) ate 1 sprouts.'
'\nP at (1, 0) ate 0 sprouts.')
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main(exit=False)
|
import itertools
"""
Generate n-gram set. With $ appended (prepended) at the end (beginning).
"""
def ngram(word, n):
wordlist = list(word)
k0gram = [''.join(gram) for gram in \
zip(*[wordlist[i:] for i in range(n)])]
if len(k0gram) == 1:
k0gram.append(k0gram[0] + '$')
k0gram[0] = '$' + k0gram[0]
elif (len(k0gram) > 1):
k0gram[0] = '$' + k0gram[0]
k0gram[-1] = k0gram[-1] + '$'
return set(k0gram)
"""
Generate k-skip-n gram set. With | to separate characters.
"""
def skipgram(word, n, k):
wordlist = list(word)
kngram = [list(set(['|'.join(gram) for gram in \
zip(*[wordlist[(i * (skip + 1)):] for i in range(n)])])) \
for skip in range(1, k + 1)]
return set(itertools.chain.from_iterable(kngram))
"""
Generate proposed feature set which combines n-gram and k-skip-n gram.
"""
def sim_feature(word, n=2, k=1):
return set(itertools.chain.from_iterable([list(ngram(word, n))] + [list(skipgram(word, n, k))]))
"""
Calculate the Jaccard index between two words.
"""
def JaccardIndex(s1, s2, n=2, k=1, tailWeight=3):
feature1 = sim_feature(s1, n, k)
feature2 = sim_feature(s2, n, k)
intersection = feature1.intersection(feature2)
intersection_len = len(intersection)
union = feature1.union(feature2)
union_len = len(union)
startWeight = 0
endWeight = 0
for gram in intersection:
if gram.startswith('$'):
startWeight = tailWeight - 1
continue
if gram.endswith('$'):
endWeight = tailWeight - 1
continue
return (intersection_len + startWeight + endWeight) / (union_len + startWeight + endWeight) |
#!/usr/bin/python3
"""
This module defines a class Square based on a previous document.
"""
class Square:
"""The Square class defines a square.
Attributes:
None.
"""
def __init__(self, size):
""" Inititialization of the attributes the Square class has.
Args:
size (int): Size of the square, private attribute.
"""
self.__size = size
|
#!/usr/bin/python3
""" In this module, testing related to Base class will be done. """
import unittest
import sys
from io import StringIO
from models.square import Square
from models.base import Base
class TestSquare(unittest.TestCase):
""" Test the Square class """
def tearDown(self):
""" Create environment """
Base.reset_nb()
def test_init(self):
""" Test cases of normal initialization """
# 4 parameters
s1 = Square(1, 2, 3, 4)
self.assertEqual(s1.id, 4)
# 3 parameters
s2 = Square(1, 2, 3)
self.assertEqual(s2.id, 1)
# 2 parameters
s3 = Square(3, 5)
self.assertEqual(s3.id, 2)
# 1 parameters
s4 = Square(1)
self.assertEqual(s4.id, 3)
def test_failure_parameters(self):
""" Cases additional or none parameters are passed. """
# MESSAGE OR JUST RAISE?
# None parameters
with self.assertRaises(TypeError):
s5 = Square()
# More than required
with self.assertRaises(TypeError):
s6 = Square(1, 2, 3, 4, 5)
def test_failure_value_args(self):
""" Test cases invalid value of args, negatives or zeros. """
# Negatives values in dimension or id
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s7 = Square(-1)
with self.assertRaisesRegex(ValueError, "x must be >= 0"):
s8 = Square(1, -1, 2)
with self.assertRaisesRegex(ValueError, "y must be >= 0"):
s9 = Square(1, 1, -2)
# Value zero in dimension
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s10 = Square(0, 1)
def test_failure_type_args(self):
""" Test cases invalid args are passed, types of data. """
# LIST
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s11 = Square([1])
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s12 = Square(1, [1])
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s13 = Square(1, 2, [1])
# FLOAT
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s14 = Square(1.1)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s15 = Square(1, 1.1)
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s16 = Square(1, 2, 1.1)
# STRING
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s17 = Square("1")
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s18 = Square(1, "1")
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s19 = Square(1, 2, "1")
# DICTIONARY
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s20 = Square({1: 1})
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s21 = Square(1, {1: 1})
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s22 = Square(1, 2, 1.1)
def test_setter_getter(self):
""" Test setting and getting a new value. """
# Functionals
s22 = Square(1)
self.assertEqual(s22.size, 1)
s22.size = 3
self.assertEqual(s22.size, 3)
# Non-functionals
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s22.size = 3.1
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s22.size = "3"
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s22.size = {1}
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s22.size = [2]
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s22.size = 0
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s22.size = -1
def test_area(self):
""" Test cases of normal use of area method. """
# 1 parameters
s23 = Square(3)
self.assertEqual(s23.area(), 9)
# 2 parameters
s24 = Square(3, 4)
self.assertEqual(s24.area(), 9)
# 3 parameters
s25 = Square(3, 5, 2)
self.assertEqual(s25.area(), 9)
# 4 parameters
s26 = Square(3, 6, 7, 2)
self.assertEqual(s26.area(), 9)
def test_display(self):
""" Test case to display the rectangle. """
# 1 parameter
out = StringIO()
sys.stdout = out
s27 = Square(1)
s27.display()
output = out.getvalue()
self.assertEqual(output, "#\n")
# 2 parameters
out = StringIO()
sys.stdout = out
s28 = Square(2, 2)
s28.display()
output = out.getvalue()
self.assertEqual(output, " ##\n ##\n")
# 3 parameters
out = StringIO()
sys.stdout = out
s29 = Square(3, 3, 2)
s29.display()
output = out.getvalue()
self.assertEqual(output, "\n\n ###\n ###\n ###\n")
# 4 parameters
out = StringIO()
sys.stdout = out
s30 = Square(3, 3, 2, 192)
s30.display()
output = out.getvalue()
self.assertEqual(output, "\n\n ###\n ###\n ###\n")
def test_print_object(self):
""" Test case to print Square info. """
# 1 parameter
out = StringIO()
sys.stdout = out
s31 = Square(3)
print(s31)
output = out.getvalue()
self.assertEqual(output, "[Square] (1) 0/0 - 3\n")
# 2 parameters
out = StringIO()
sys.stdout = out
s32 = Square(3, 5)
print(s32)
output = out.getvalue()
self.assertEqual(output, "[Square] (2) 5/0 - 3\n")
# 3 parameters
out = StringIO()
sys.stdout = out
s33 = Square(3, 5, 8)
print(s33)
output = out.getvalue()
self.assertEqual(output, "[Square] (3) 5/8 - 3\n")
# 4 parameters
out = StringIO()
sys.stdout = out
s33 = Square(3, 5, 8, 99)
print(s33)
output = out.getvalue()
self.assertEqual(output, "[Square] (99) 5/8 - 3\n")
def test_update(self):
""" Test case to update rectangles attributes. """
# UPDATE NONE
out = StringIO()
sys.stdout = out
s34 = Square(10, 10, 10, 10)
s34.update()
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (10) 10/10 - 10\n")
# UPDATE ARGS
# update 1 parameter (id)
out = StringIO()
sys.stdout = out
s34.update(98)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 10/10 - 10\n")
# update 2 parameter (id, size)
out = StringIO()
sys.stdout = out
s34.update(98, 5)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 10/10 - 5\n")
# update 3 parameter (id, size, x)
out = StringIO()
sys.stdout = out
s34.update(98, 5, 7)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 7/10 - 5\n")
# update 4 parameter (id, size, x, y)
out = StringIO()
sys.stdout = out
s34.update(98, 5, 7, 9)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 7/9 - 5\n")
# more than 4 parameters passed (ignores the rest)
out = StringIO()
sys.stdout = out
s34.update(89, 51, 71, 91, 10)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (89) 71/91 - 51\n")
# UPDATE KWARGS
# update 1 param (id)
out = StringIO()
sys.stdout = out
s34.update(id=98)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 71/91 - 51\n")
# update 2 parameters (id, size)
out = StringIO()
sys.stdout = out
s34.update(size=20, id=98)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 71/91 - 20\n")
# update 3 parameters (id, size, x)
out = StringIO()
sys.stdout = out
s34.update(size=20, id=98, x=3)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 3/91 - 20\n")
# update 4 parameters (id, size, x, y)
out = StringIO()
sys.stdout = out
s34.update(y=7, id=98, size=20, x=3)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 3/7 - 20\n")
# update more than 4 parameters (id, size, x, y, depth)
out = StringIO()
sys.stdout = out
s34.update(y=7, id=98, size=20, depth=27, x=3)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (98) 3/7 - 20\n")
# UPDATE having both cases
out = StringIO()
sys.stdout = out
s34.update(500, y=17, id=103, size=200, depth=270, x=93)
print(s34)
output = out.getvalue()
self.assertEqual(output, "[Square] (500) 3/7 - 20\n")
# UPDATE with errors
# error with size (id, size)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s34.update(500, 3.1)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s34.update(500, -1)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s34.update(500, 0)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s34.update(size=3.1)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s34.update(size=-1)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s34.update(size=0)
# error with x (id, size, x)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s34.update(500, 10, 3.1)
with self.assertRaisesRegex(ValueError, "x must be >= 0"):
s34.update(500, 10, -1)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s34.update(x=3.1)
with self.assertRaisesRegex(ValueError, "x must be >= 0"):
s34.update(x=-1)
# error with y (id, size, x, y)
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s34.update(500, 10, 10, 3.1)
with self.assertRaisesRegex(ValueError, "y must be >= 0"):
s34.update(500, 10, 10, -1)
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s34.update(y=3.1)
with self.assertRaisesRegex(ValueError, "y must be >= 0"):
s34.update(y=-1)
def test_to_dictionary(self):
""" Test to_dictionary function is addecuate. """
s1 = Square(1, 2, 3, 4)
dictionary = {"id": 4, "size": 1, "x": 2, "y": 3}
self.assertEqual(s1.to_dictionary(), dictionary)
s2 = Square(1, 2, 3)
dictionary = {"id": 1, "size": 1, "x": 2, "y": 3}
self.assertEqual(s2.to_dictionary(), dictionary)
s3 = Square(1, 2)
dictionary = {"id": 2, "size": 1, "x": 2, "y": 0}
self.assertEqual(s3.to_dictionary(), dictionary)
s4 = Square(1)
dictionary = {"id": 3, "size": 1, "x": 0, "y": 0}
self.assertEqual(s4.to_dictionary(), dictionary)
def test_to_json_string(self):
""" Test to JSON string method """
s1 = Square(10, 7, 2)
s2 = Square(2, 4)
Square.save_to_file([s1, s2])
with open("Square.json", "r") as file:
out = StringIO()
sys.stdout = out
print(file.read())
output = out.getvalue()
self.assertIn("\"y\": 2", output)
self.assertIn("\"x\": 7", output)
self.assertIn("\"id\": 1", output)
self.assertIn("\"size\": 10", output)
self.assertIn("\"y\": 0", output)
self.assertIn("\"x\": 4", output)
self.assertIn("\"id\": 2", output)
self.assertIn("\"size\": 2", output)
def test_save_to_file(self):
""" Tests the save to file method. """
Square.save_to_file([])
with open("Square.json", "r") as file:
out = StringIO()
sys.stdout = out
print(file.read())
output = out.getvalue()
self.assertEqual(output, "[]\n")
Square.save_to_file(None)
with open("Square.json", "r") as file:
out = StringIO()
sys.stdout = out
print(file.read())
output = out.getvalue()
self.assertEqual(output, "[]\n")
def test_create(self):
""" Test the create class method. """
r1 = Square(3, 5)
r1_dictionary = r1.to_dictionary()
r2 = Square.create(**r1_dictionary)
self.assertFalse(r1 == r2)
self.assertFalse(r1 is r2)
# Try empty
def test_load_from_file(self):
""" Tests load from file json """
s1 = Square(5)
s2 = Square(7, 9, 1)
list_squares_input = [s1, s2]
Square.save_to_file(list_squares_input)
list_squares_output = Square.load_from_file()
i = 0
for square in list_squares_output:
list_rect = ["[Square] (1) 0/0 - 5\n", "[Square] (2) 9/1 - 7\n"]
out = StringIO()
sys.stdout = out
print(square)
output = out.getvalue()
self.assertEqual(output, list_rect[i])
i += 1
|
#!/usr/bin/python3
"""This module consists of a single function that prints an introduction.
In this module a function called say_my_name is specified and its
functionality consists of saying an specified name and lastname passed
by parameters.
Example:
An example in which the function is implemented is the following.
say_my_name("Walter", "White")
Walter White
"""
def say_my_name(first_name, last_name=""):
""" Prints a the name in a sentence.
Args:
first_name (str): first name to print.
last_name (str): last name to print.
"""
if type(first_name) != str:
raise TypeError("first_name must be a string")
if type(last_name) != str:
raise TypeError("last_name must be a string")
print("My name is {} {}".format(first_name, last_name))
|
#!/usr/bin/python3
""" In this module, testing related to Base class will be done. """
import unittest
from models.base import Base
class TestBase(unittest.TestCase):
""" Test the base class """
def tearDown(self):
""" Create environment. """
Base.reset_nb()
def test_init(self):
""" Test cases of normal initialization """
b1 = Base()
self.assertEqual(b1.id, 1)
b2 = Base(2)
self.assertEqual(b2.id, 2)
b3 = Base() # CHECK THIS CASE that two can be same if choose that num
self.assertEqual(b3.id, 2)
b4 = Base()
self.assertEqual(b4.id, 3)
def test_failure(self):
""" Test cases additional parameter is passed. """
with self.assertRaises(TypeError):
b5 = Base(2, 3)
with self.assertRaises(ValueError):
b6 = Base(-1)
with self.assertRaises(ValueError):
b7 = Base(0)
def test_from_json_string(self):
""" Test the from json to string method, """
list_input = [
{'id': 89, 'size': 10},
{'id': 7, 'size': 1}
]
json_list_input = Base.to_json_string(list_input)
list_output = Base.from_json_string(json_list_input)
self.assertEqual(list_input, list_output)
list_input = [
{'id': 89, 'width': 10, 'height': 4},
{'id': 7, 'width': 1, 'height': 7}
]
json_list_input = Base.to_json_string(list_input)
list_output = Base.from_json_string(json_list_input)
self.assertEqual(list_input, list_output)
self.assertEqual(Base.from_json_string(None), [])
self.assertEqual(Base.from_json_string("[]"), [])
def test_to_json_string(self):
""" Test to JSON string method """
self.assertEqual(Base.to_json_string(None), "[]")
self.assertEqual(Base.to_json_string([]), "[]")
self.assertEqual(Base.to_json_string([{'id': 12}]), "[{\"id\": 12}]")
|
#!/usr/bin/python3
def roman_to_int(roman_string):
decimal = 0
roman_num = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500}
roman_num["M"] = 1000
if roman_string and type(roman_string) == str:
for i in range(len(roman_string)):
if i < len(roman_string) - 1:
if roman_num[roman_string[i]] >= roman_num[roman_string[i+1]]:
decimal += roman_num[roman_string[i]]
else:
decimal -= roman_num[roman_string[i]]
else:
decimal += roman_num[roman_string[i]]
return decimal
|
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
square_matrix = []
for i in matrix:
square_matrix.append(list(map(lambda x: x**2, i)))
return square_matrix
|
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary:
max_value = max(list(a_dictionary.values()))
for key in a_dictionary.keys():
if a_dictionary[key] == max_value:
return key
return None
|
#Finding Nemo: Family comedy, Animated, main character animal, main character fish
#KungFu Panda: Family Comedy, animated, main character animal, main character likes kungfu
#Secret life of pets: family comedy, animated, main character animal
#Coco: family comedy, animated, main character sings
#Frozen: family comedy, animated, main character sings, singing snowman
#Toy Story: family comedy, animated, main character toy, belongs to andy
#Lego Movie: family comedy, animated, main character toy
#Despicable Me: family comedy, animated
#Home alone: family comedy, non animated, christmas movie
#Daddy daycare: family comedy, non animated
#Avengers: scifi action, marvel
#Thor: scifi action, marvel, main character uses hammer
#Spiderman: scifi action, marvel, character has suit (red)
#Ironman: scifi action, marvel, character has suit (red), uses jarvis
#Black panther: scifi action, marvel, character has suit
#Doctor Strange: scifi action, marvel, character controls time
#Joker: scifi action, dc, movie in gotham, released in 2019
#Batman: scifi action, dc, movie in gotham, drives batmobile
#Suicide Squad: scifi action, dc, movie in gotham
#Wonderwoman: scifi action, dc
def ins():
instruction = input("Do you need instructions for this game? ")
if instruction == "YES" or instruction == "yes" or instruction == "Yes" or instruction == "y" or instruction == "Y":
print("Here are the instructions...\nChoose a subgenre (either family comedies or scifi action) and choose a movie. Answer the questions with a yes or a no until the system (hopefully) determines the movie.")
ins()
def main():
genre = str(input("Please choose a movie sub genre (please enter genre in lowercase) "))
if genre == "family comedies" or genre == "family":
animated = str(input("Is your movie animated? "))
if animated == "YES" or animated == "yes" or animated == "Yes" or animated == "y" or animated == "Y":
animal = str(input("Is the main character an animal? "))
if animal == "YES" or animal == "yes" or animal == "Yes" or animal == "y" or animal == "Y":
fish = input ("Is your main character a fish? ")
if fish == "YES" or fish == "yes" or fish == "Yes"or fish == "y" or fish == "Y":
print("Your movie is Finding Nemo\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes" or restart == "y" or restart == "Y":
main()
else:
quit()
else:
kungfu = input("Does your main character like kung fu? ")
if kungfu == "YES" or kungfu == "yes" or kungfu == "Yes":
print("Your movie is Kung Fu Panda\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Secret life of pets\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
sing = input("Does the main character sing? ")
if sing == "YES" or sing == "yes" or sing == "Yes":
snowman = input("Is there a singing snowman in your movie? ")
if snowman == "YES" or snowman == "yes" or snowman == "Yes":
print("Your movie is Frozen\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("your movie is Coco\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
toy = input("are the main characters toys? ")
if toy == "YES" or toy== "yes" or toy == "Yes":
andy = input("Does the main character belong to Andy? ")
if andy == "YES" or andy == "yes" or andy == "Yes":
print("Your movie is Toy Story\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is The Lego Movie\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Despicable me\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
chrst = input("Is your movie popular during christmas? ")
if chrst == "YES" or chrst == "yes" or chrst == "Yes":
print("Your movie is Home Alone\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Daddy Daycare\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
elif genre == "scifi action" or genre == "scifi" or genre == "scifi" or genre == "scifi action":
marvel = input("Is your movie produced my marvel? ")
if marvel == "YES" or marvel == "yes" or marvel == "Yes":
suit = input("Does the main character wear a suit? ")
if suit == "YES" or suit == "yes" or suit == "Yes":
red = input("Is the suit red? ")
if red == "YES" or red == "yes" or red == "Yes":
jarvis = input("Does the main character rely on JARVIS? ")
if jarvis == "YES" or jarvis == "yes" or jarvis == "Yes":
print("Your movie is Iron Man\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Spiderman\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Black Panther\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
time = input("Does the main character control time? ")
if time == "YES" or time == "yes" or time == "Yes":
print("Your movie is Doctor Strange\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
hammer = input("Does the main character use a hammer? ")
if hammer == "YES" or hammer == "yes" or hammer == "Yes":
print("Your movie is Thor\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is The Avengers\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
gotham = input("Does you movie take plce in Gotham? ")
if gotham == "YES" or gotham == "yes" or gotham == "Yes":
release = input("Was your movie released in 2019? ")
if release == "YES" or release == "yes" or release == "Yes":
print("Your movie is The Joker\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
bat = input("Does the main character drive the batmobile? ")
if bat == "YES" or bat == "yes" or bat == "Yes":
print("Your movie is Batman\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Suicide Squad\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
print("Your movie is Wonderwoman\n")
restart = input("Would you like to play again? ")
if restart == "YES" or restart == "yes" or restart == "Yes":
main()
else:
quit()
else:
quit()
main()
|
"""
Search for element d in sorted but rotated array of size n
Return index of elemnt or -1 if not found
[70,71,99,2,12] d=1 => -1 | d=2 => 3 | d=12 => 4 | d=70 => 0 | d=75 => -1 | d=99 => 2 | d=101 => -1
Binary Search
- Check pivot value against leftmost/righmost indexs' value of subarray => sorted half of the array
- ensure d >= min and d < max of the sorted half before looking in unsorted half of the array
Time complexity - O(log(N))
Space complexity - O(1)
"""
from array_rotation import rotateLeft
def sortedRotatedSearch(array, d):
left = 0
right = len(array)
while right > left:
mid = int(left + (right-left)/2)
if array[mid] == d:
return mid
elif array[mid] > array[left] and d < array[mid] and d >= array[left]:
right = mid
else:
left = mid+1
return -1
if __name__ == "__main__":
for i in [1, 2, 12, 70, 71, 75, 99, 101]:
print("Index of {} is {}".format(i, sortedRotatedSearch(rotateLeft([2,12,70,71,99], 2), i))) |
#!/usr/bin/env python
import sys
count = 0
java = 0
python = 0
cpp = 0
for line in sys.stdin:
line = line.strip()
language , count = line.split()
count = int(count)
if language == "java":
java += count
if language == "python":
python += count
if language == "c++":
cpp += count
print("java",java)
print("python",python)
print("c++",cpp)
|
total = 0;
# function returning binary string
def bin_convert(n):
#using bin() for binary conversion
bin1 = bin(n)
# removing "0b" prefix
binary = bin1[2:]
return binary
#function returning palindrome string
def palin(string):
#reversing string using slicing method one step backward
reverse_string = string[::-1]
if reverse_string == string:
return True
else:
return False
for i in range(0,1000000):
#val stores palindrome decimals
val = palin(str(i))
binary = bin_convert(i)
#val2 stores binary palindromes
val2 = palin(str(binary))
if val == True and val2 == True:
total = total + i
print (total)
|
import pandas as pd
import smtplib
from tkinter import*
#username and password
username = "your email"
password = "your password"
#read excel
e = pd.read_excel("data file in xls")
emails = e["email"].values
names = e["name"].values
#set smtp
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
#login in your gmail account
server.login(username,password)
#enter your subject
subject = "enter your subject here"
#abbrevation
abbr = "Hi "
#message of the body
message = '''
this is a sample message by fadhil for testing bulk message sending
Regards,
Fadhil Abdulla'''
#mailing process
for i in range(0,len(emails)):
name = names[i]
email = emails[i]
full_message = abbr + name + message
body = "subject: {}\n\n{}".format(subject,full_message)
#server.sendmail(username,email,body)
print(email+" sent succesfully")
server.quit()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import Image
import ImageDraw
def fractal(draw, x, y, r):
if r > 0:
fractal(draw, x-r/2, y-r/2, r/2);
fractal(draw, x-r/2, y+r/2, r/2);
fractal(draw, x+r/2, y-r/2, r/2);
fractal(draw, x+r/2, y+r/2, r/2);
box(draw, x, y, r);
def box(draw, x, y, r):
## random color
import random
draw.rectangle([x-r/2, y-r/2, x+r/2, y+r/2], fill=random.randint(0, 256))
## hierarchical color
# draw.rectangle([x-r/2, y-r/2, x+r/2, y+r/2], fill=r % 256)
## same color
# draw.rectangle([x-r/2, y-r/2, x+r/2, y+r/2], fill=128)
if __name__ == '__main__':
image_size = 400
im = Image.new('RGB', (image_size, image_size), '#ffffff')
draw = ImageDraw.Draw(im)
fractal(draw, image_size/2, image_size/2, image_size/2)
im.show()
|
import turtle as T
import random
t = T.Turtle()
t.speed(100)
colors = ["blue", "red", "green", "yellow", "black"]
def draw_tree(x):
if(x<10):
return
else:
t.color(random.choice(colors))
t.forward(x)
t.left(30)
draw_tree(3.1*x/4)
t.right(60)
draw_tree(3.1*x/4)
t.left(30)
t.backward(x)
for x in range(4):
draw_tree(110)
t.right(90) |
import math
def check_prime(n):
i = 2
if n == i:
return 1
while i < int(math.sqrt(n)) + 1:
if n % i == 0:
return 0
i += 1
return 1
def largest_prime_factor(n):
list = []
rootn = int(math.sqrt(n))
for i in range(2, rootn):
if n % i == 0 and check_prime(i) == 1:
list.append(i)
return max(list)
print(largest_prime_factor(600851475143)) |
import math
def check_prime(n):
i = 2
if n == i:
return 1
while i < int(math.sqrt(n)) + 1:
if n % i == 0:
return 0
i += 1
return 1 |
def fib_even_sum(n):
list = [1,2]
sum = 0
while list[-1] < n:
list.append(list[-2] + list[-1])
for i in range(len(list)):
if list[i] < n and i % 3 == 1:
sum += list[i]
return sum
print(fib_even_sum(4000000)) |
#Maia Reynolds
#1/17/18
#inputDemo.py - how to use input
name=input("What is your name? ")
print("Hello",name)
age=int(input("How old are you? "))
print("You are",age+1,"years old")
|
#Maia Reynolds
#1/19/18
#isItaTriangle.py - determines if it could be a triangle
a=float(input("Enter Side A: "))
b=float(input("Enter Side B: "))
c=float(input("Enter Side C: "))
large=max(a,b,c)
smaller=((a+b+c)-large)
print(bool(smaller>large)) |
#Maia Reynolds
#1/24/18
#backwardsBinary.py - converts number to binary
number=int(input("Enter number <256: "))
a=(number//128)*10**7
b=((number%128)//64)*10**6
c=((number%128%64)//32)*10**5
d=(number%128%64%32//16)*10**4
e=(number%128%64%32%16//8)*10**3
f=(number%128%64%32%16%8//4)*10**2
g=(number%128%64%32%16%8%4//2)*10
h=(number%128%64%32%16%8%4%2//1)
print("Binary= ",a+b+c+d+e+f+g+h)
|
import collections
import functools
import cPickle
map = dict()
class Solution(object):
def __init__(self):
self.map = dict()
def coinChange(self, coins, num):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if num in self.map:
return self.map.get(num)
if num == 0:
return 0
min_change = -1
for coin in coins:
if(num - coin >= 0 ):
remainingCoinChange = self.coinChange(coins, num-coin);
if remainingCoinChange is not -1:
if min_change is -1 or (remainingCoinChange + 1 < min_change):
min_change = remainingCoinChange + 1
self.map.setdefault(num, min_change)
return min_change
def main():
coins = [370,417,408,156,143,434,168,83,177,280,117]
num = 9953
s = Solution()
print s.coinChange(coins, num)
if __name__ == '__main__':
main()
|
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalpaid=0.00
for month in range(1,13):
monthlyinterestrate = annualInterestRate/12.00
monthlypayment = monthlyPaymentRate * balance
unpaidbalance = round((balance - monthlypayment),2)
totalpaid += monthlypayment
balance = round((unpaidbalance + (monthlyinterestrate * unpaidbalance)),2)
print 'Month: '+ str(month)
print 'Minimum monthly payment: ' + str(round(monthlypayment,2))
print 'Remaining balance: ' + str(round(balance,2))
print 'Total paid: '+ str(round(totalpaid,2))
print 'Remaining balance: ' + str(balance) |
##########################
## Anagrams using Python
##########################
str1=input("Enter first string")
str2=input("Enter second string")
if(sorted(str1)==sorted(str2)):
print(str1," and ",str2," are anagrams")
else
print(str1," and ",str2," are not anagrams")
|
#InsertionSort
def InsertionSort(list):
for slicelast in range(len(list)):
pos=slicelast
while ((pos>0) &(list[pos]<list[pos-1])):
(list[pos],list[pos-1])=(list[pos-1],list[pos])
pos=pos-1
print ("InsertionSort over")
#test code
list=[34,45,12,3,67,91,100]
print ("Original list=", list)
InsertionSort(list)
print ("Sorted list=", list)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 11:58:47 2020
JSON in python
@author: Nikhil Bhargava
"""
import json
data='''{
"name":"Nikhil",
"phone":{
"type":"intl",
"number":"+91 991 006 32000"
},
"email":{
"hide":"yes"
}
}
'''
info=json.loads(data)
print('Name: ',info['name'])
print('Email Hidden: ',info['email']["hide"])
|
###
##Python code for Snake and Ladder Game
###
from PIL import Image
import random
end=100
def showBoard():
#slb.jpg is a picture of Snake and Ladded Board
img=Image.open('slb.jpg')
img.show()
def play():
#Get Both players names
p1Name=input("Player 1, Enter your name: ")
p2Name=input("Player 2, Enter your name: ")
#Reset initial points for both players as 0
pp1=0
pp2=0
#Reset turn variable
turn=0
while(True):
if(turn%2==0):
#Player 1's turn now
print(p1Name,"your turn now ")
#player1 wanna continue
choice=int(input("Press 1 to continue or 0 to quit "))
if(choice==0):
#Player 1 wants to quit
print(p1Name, "scored ",pp1)
print(p2Name, "scored ",pp2)
print("Game ends now. Thanks for playing!")
break
else:
#Player 1 wanna continue so roll a dice to get 1 to 6
dice=random.randint(1,6)
print(p1Name," got ",dice)
#add P1 score
pp1+=dice
pp1=checkLadder(pp1)
pp1=checkSnake(pp1)
#Check if the player goes beyond the board
if(pp1>end):
pp1=end
print(p1Name, " Your score ",pp1)
if(reachedEnd(pp1)):
print(p1Name, "won")
break
else:
#Player 2's turn now
print(p2Name,"your turn now ")
#player2 wanna continue
choice=int(input("Press 1 to continue or 0 to quit "))
if(choice==0):
#Player 2 wants to quit
print(p2Name, "scored ",pp2)
print(p1Name, "scored ",pp1)
print("Game ends now. Thanks for playing!")
break
else:
#Player 2 wanna continue so roll a dice to get 1 to 6
dice=random.randint(1,6)
print(p2Name," got ",dice)
#add P1 score
pp2+=dice
pp2=checkLadder(pp2)
pp2=checkSnake(pp2)
#Check if the player goes beyond the board declare him winner
if(pp2>end):
pp2=end
print(p2Name, " Your score ",pp2)
if(reachedEnd(pp2)):
print(p2Name, "won")
break
#Increment turn to give chance to other player
turn+=1
def reachedEnd(score):
if(score==end):
return True
else:
return False
def checkSnake(score):
if(score==25):
print("Snake")
return 5
elif (score==34):
print("Snake")
return 1
elif (score==47):
print("Snake")
return 19
elif (score==65):
print("Snake")
return 52
elif (score==87):
print("Snake")
return 57
elif (score==91):
print("Snake")
return 61
elif (score==99):
print("Snake")
return 69
else:
#No Snake
return score
def checkLadder(score):
if(score==3):
print("ladder")
return 51
elif (score==6):
print("ladder")
return 27
elif (score==20):
print("ladder")
return 70
elif (score==36):
print("ladder")
return 55
elif (score==63):
print("ladder")
return 95
elif (score==68):
print("ladder")
return 98
else:
#No ladder
return score
showBoard()
play() |
# Write a Python program that asks the user for two numbers.
from tkinter import Tk, messagebox, simpledialog
if __name__ == '__main__':
window = Tk()
window.withdraw()
num1 = simpledialog.askinteger(None, 'Enter a number.')
num2 = simpledialog.askinteger(None, 'Enter another number.')
# Then display the sum of the two numbers
num3 = num1 + num2
messagebox.showinfo(None, 'The sum of your two numbers is ' + str(num3) + '.') |
#!/usr/bin/env python3
# Part. 1
#=======================================
# Import module
# csv -- fileIO operation
import csv
#=======================================
# Part. 2
#=======================================
# Read cwb weather data
cwb_filename = '107061237.csv'
data = []
header = []
with open(cwb_filename) as csvfile:
mycsv = csv.DictReader(csvfile)
header = mycsv.fieldnames
for row in mycsv:
data.append(row)
#=======================================
# Part. 3
#=======================================
# Analyze data depend on your group and store it to target_data like:
# Retrive all data points which station id is "C0X260" as a list.
# target_data = list(filter(lambda item: item['station_id'] == 'C0X260', data))
# Retrive ten data points from the beginning.
# target_data = data[:10]
# first, preprocessing the data.
# In TEMP column, change '-99.000' or '-999.00' with 'None'
for i in range(len(data)):
if data[i]['TEMP'] == '-99.000' or data[i]['TEMP'] == '-999.000':
data[i]['TEMP'] = 'None'
# target_data will be used to store the answer, so we need to get the space first.
# And because the answer need to be arranged in the lexicographical order, I declare them first.
target_data = [['C0A880'], ['C0F9A0'], ['C0G640'], ['C0R190'], ['C0X260']]
# after arranged the order, I made up the remaining space needed in the back of each elements.
# And I assume maximum TEMP of each stations are 'None' first.
for i in range(5):
target_data[i].append('None')
# Start to find the result in each station.
# The methods I used are
# 1. Use for loop to let me can scan through all the station.
# 2. check whether the temperature of station[i] is 'None' or not.
# If the temperature of the station[i] is 'None', we can skip directly to check the next station,
# Because we assume the temperature of the station is 'None' already.
# 3. If the temperature of the station[i] isn't 'None', we need to check which one is bigger,
# the temperature stored in the target_data or the temperature of the station[i].
# Finally, store the bigger one into the target_data.(Remember, station_ID should be the same)
# (NOTE)Because the datatype of the temperature stored in the data list is string, we need to convert it to float.
# (NOTE)If the temperature stored in the target_data is 'None' and the temperature of the station[i] isn't 'None',
# we can assign the temperature of the station[i] to the target data directly.
for i in range(len(data)):
if data[i]['TEMP'] != 'None':
if data[i]['station_id'] == target_data[0][0]: # processing the temperature of 'C0A880' station
if target_data[0][1] == 'None':
target_data[0][1] = float(data[i]['TEMP'])
elif float(data[i]['TEMP']) > target_data[0][1]:
target_data[0][1] = float(data[i]['TEMP'])
elif data[i]['station_id'] == target_data[1][0]: # processing the temperature of 'C0F9A0' station
if target_data[1][1] == 'None':
target_data[1][1] = float(data[i]['TEMP'])
elif float(data[i]['TEMP']) > target_data[1][1]:
target_data[1][1] = float(data[i]['TEMP'])
elif data[i]['station_id'] == target_data[2][0]: # processing the temperature of 'C0G640' station
if target_data[2][1] == 'None':
target_data[2][1] = float(data[i]['TEMP'])
elif float(data[i]['TEMP']) > target_data[2][1]:
target_data[2][1] = float(data[i]['TEMP'])
elif data[i]['station_id'] == target_data[3][0]: # processing the temperature of 'C0R190' station
if target_data[3][1] == 'None':
target_data[3][1] = float(data[i]['TEMP'])
elif float(data[i]['TEMP']) > target_data[3][1]:
target_data[3][1] = float(data[i]['TEMP'])
elif data[i]['station_id'] == target_data[4][0]: # processing the temperature of 'C0X260' station
if target_data[4][1] == 'None':
target_data[4][1] = float(data[i]['TEMP'])
elif float(data[i]['TEMP']) > target_data[4][1]:
target_data[4][1] = float(data[i]['TEMP'])
#=======================================
# Part. 4
#=======================================
# Print result
print(target_data)
#========================================
|
# -*- coding: utf-8 -*-
# The depth of p can also be recursively defined as follows:
# * If pistheroot,thenthedepthof p is 0.
# * Otherwise, the depth of p is one plus the depth of the parent of p.
#
# The height of a position p in a tree T is also defined recursively:
# * If p is a leaf, then the height of p is 0.
# * Otherwise, the height of p is one more than the maximum of the heights of
# p’s children.
# The height of a nonempty tree T is the height of the root of T.
#
# From the definition of height of tree we can know that the height of nonempty
# tree is the longest path in the tree. That means the longest path of
# root-external paths.
# From the definition of depth we can know that the depth of a leaf node is a
# path of the tree.
# And we know that the external node is leaf, so we can get propositon 8.4
|
# -*- coding: utf-8 -*-
# This is exercise of c5.22.
# Develop an experiment to compare the relative efficiency of the extend method
# and the append method. Of course, use these two method to do the same work.
# From the result we can get the conclusion: extend is like about 20 times than
# append method
from timeit import timeit
def gen_an_array(alen):
return [i for i in range(alen)]
def construct_by_append(a):
tmp = []
for item in a:
tmp.append(item)
def construct_by_extend(a):
tmp = []
tmp.extend(a)
stp = """
from __main__ import gen_an_array
from __main__ import construct_by_append
from __main__ import construct_by_extend
a = gen_an_array(10^5 * 10000)
"""
if __name__ == '__main__':
ttl = timeit("construct_by_append(a)", setup=stp, number=1000)
print('construct_by_append: {0:.6f}'.format(ttl/1000))
ttl = timeit("construct_by_extend(a)", setup=stp, number=1000)
print('construct_by_extend: {0:.6f}'.format(ttl/1000))
|
# -*- coding: utf-8 -*-
from array_stack_c6_16 import ArrayStack
from exception import PostfixError
class Postfix(object):
""" evaluate the postfix expression."""
def __init__(self, ps):
self._ps = ps
def _is_number(self, c):
rlt = True
try:
int(c)
except ValueError:
rlt = False
return rlt
def _is_operator(self, c):
if c in ['+', '-', '*', '/']:
return True
else:
return False
def _is_whitespace(self, c):
if c in [' ', '\n', '\b']:
return True
else:
return False
def eval(self):
s = ArrayStack()
for item in self._ps:
if self._is_number(item):
s.push(item)
elif self._is_operator(item):
right = s.pop()
left = s.pop()
whole = left + item + right
s.push(str(eval(whole)))
elif self._is_whitespace(item):
pass
else:
raise PostfixError("Wrong postfix expression!")
return s.pop()
if __name__ == '__main__':
# ps = '5 2 + 8 3 - * 5 /'
ps = '5 2 + 8 *'
pf = Postfix(ps)
print(pf.eval())
|
# -*- coding: utf-8 -*-
#
# the explain of algorithm by stack
# | 1 | x pop
# |-----|
# | 32 | x pop
# |-----| when top item is len one
# | 12 | x pop | 2 | then concate the poped
# |-----| |-----| two items and is one
# | 3 | x pop | 31 | result
# |-----| concate and push |-----|
# | 13 | | 13 | | 13 |
# |-----| -----> |-----| -----> |-----|
# | 2 | | 2 | | 2 |
# |-----| |-----| |-----|
# | 23 | | 23 | results: | 23 |
# |-----| |-----| [[3,2,1],[3,1,2]] |-----|
# | 1 | | 1 | | 1 |
# initial
from array_stack_c6_16 import ArrayStack
def permutation_recursive(l):
""" permutation by using recursive method."""
length = len(l)
if length == 0:
return []
elif length == 1:
return [l[0:1]]
else:
perm = []
for i in range(length):
tmp = l[0:i] + l[i+1:]
for item in permutation_recursive(tmp):
perm.append(l[i:i+1] + item)
return perm
def permutation_stack(l, s):
""" permutation by using nonrecursive method, but with a stack."""
length = len(l)
# initialize the stack
for i in range(length):
s.push(l[i:i+1])
s.push(l[:i] + l[i+1:])
rlt = []
# pop two element every time
while(not s.is_empty()):
top = s.pop()
snd = s.pop()
if len(top) > 1:
for i in range(len(top)):
s.push(snd + top[i:i+1])
s.push(top[:i] + top[i+1:])
else:
rlt.append(snd + top)
return rlt
if __name__ == '__main__':
l = [i for i in range(1, 4)]
s = ArrayStack()
pr = permutation_recursive(l)
print("pr length: {0:d}".format(len(pr)))
print(pr)
ps = permutation_stack(l, s)
print("ps length: {0:d}".format(len(ps)))
print(ps)
|
# -*- coding: utf-8 -*-
import sys
sys.path.append('..')
from priqueues.heap_priority_queue import HeapPriorityQueue
class PriorityQueue(HeapPriorityQueue):
def _down_heap(self, j):
""" Bubbling the element identified by `j` down."""
while self._has_left(j):
small = self._left(j)
if self._has_right(j):
right = self._right(j)
if self._data[small] > self._data[right]:
small = right
if self._data[j] <= self._data[small]:
break
self._swap(j, small)
j = small
if __name__ == '__main__':
pq = PriorityQueue()
pq.add(0, 'richard')
pq.add(0, 'wanyikang')
pq.add(1, 'hsj')
pq.add(2, 'mbs')
pq.add(3, 'zzw')
print('min: {0}, len: {1}'.format(pq.min(), len(pq)))
pq.remove_min()
print('min: {0}, len: {1}'.format(pq.min(), len(pq)))
pq.remove_min()
pq.remove_min()
pq.remove_min()
# pq.remove_min()
print('min: {0}, len: {1}'.format(pq.min(), len(pq)))
|
# -*- coding: utf-8 -*-
from circularly_linked_list import CircularlyLinkedList
class CLList(CircularlyLinkedList):
def count_by_loop(self):
if self._tail is None:
return 0
elif self._tail is self._tail._next:
return 1
else:
rlt = 1
walk = self._tail._next
while walk is not self._tail:
rlt += 1
walk = walk._next
return rlt
if __name__ == '__main__':
cllist = CLList()
for i in range(999):
cllist.add_first(i)
print('count: {0:d}'.format(cllist.count_by_loop()))
|
# -*- coding: utf-8 -*-
# This is exercise of p5.33
# Write a Python program for a matrix class that can add and multiply two-
# dimensional arrays of numbers.
class Matrix(object):
def __init__(self, r, c, empty=True):
super(Matrix, self).__init__()
self._row = r
self._column = c
if empty:
self._m = self._construct_empty_matrix(r, c)
else:
self._m = self._construct_matrix(r, c)
def __getitem__(self, key):
""" Override indexing method."""
return self._m[key]
def __len__(self):
""" Override len method."""
return len(self._m)
def _construct_empty_matrix(self, r, c):
return [[None] * c for i in range(r)]
def _construct_matrix(self, r, c):
return [[i + 1] * c for i in range(r)]
def add(self, m):
rlt = self._construct_empty_matrix(self._row, self._column)
# check dimensions agree
if not m or not m[0]:
print("Illegal parameter m!")
return None
if self._row != len(m) or self._column != len(m[0]):
print("Illegal parameter m!")
return None
# double loop
for i in range(self._row):
for j in range(self._column):
rlt[i][j] = self._m[i][j] + m[i][j]
return rlt
def scalar_multiple(self, c):
rlt = self._construct_empty_matrix(self._row, self._column)
# check if c is a constant
if type(c) is not integer:
print("Illegal parameter c!")
return None
# double loop
for i in range(self._row):
for j in range(self._column):
rlt[i][j]= c * self._m[i][j]
return rlt
def dot_multiple(self, m):
rlt = self._construct_empty_matrix(self._row, len(m[0]))
# check dimensions agree
if not m or not m[0]:
print("Illegal parameter m!")
return None
if self._column != len(m):
print("Illegal parameter m!")
return None
# triple loop
s = self._m
for i in range(self._row):
for j in range(len(m[0])):
ttl = 0
for k in range(self._column):
ttl += s[i][k] * m[k][j]
rlt[i][j] = ttl
return rlt
if __name__ == "__main__":
m1 = Matrix(3, 3, False)
m2 = Matrix(3, 3, False)
m_add = m1.add(m2)
print(m_add)
m1 = Matrix(3, 2, False)
m2 = Matrix(2, 4, False)
m_dot = m1.dot_multiple(m2)
print(m_dot)
|
# -*- coding: utf-8 -*-
def lt(key, other):
""" Compare nonnegative integer key and other base on their binary
expansion."""
if type(key) is not int or type(other) is not int:
raise ValueError('Key and other must both be integer.')
kcopy = key
ocopy = other
kc = oc = 0
while kcopy != 0 or ocopy != 0:
if kcopy & 1:
kc += 1
if ocopy & 1:
oc += 1
kcopy = kcopy >> 1
ocopy = ocopy >> 1
return kc < oc
if __name__ == '__main__':
rlt = lt(8, 6)
print(rlt)
|
# -*- coding: utf-8 -*-
from linked_binary_tree import LinkedBinaryTree
class EulerTour(object):
""" Abstract base class for performing Euler tour of a tree.
_hook_previsit and _hook_postvisit may be overridden by subclasses.
"""
def __init__(self, tree):
""" Prepare an Euler tour template for given tree."""
self._tree = tree
def tree(self):
""" Return reference to the tree being traversed."""
return self._tree
def execute(self):
""" Perform the tour and return any result from post visit of root."""
if len(self._tree) > 0:
return self._tour(self._tree.root(), 0, []) # start the recursion
def _tour(self, p, d, path):
""" Perform tour of subtree rooted at Position p.
:param p : Position of current node being visited
:param d : depth of p in the tree
:param path: list of indices of children in path from root to p
"""
self._hook_previsit(p, d, path)
results = []
path.append(0) # add new index to end of path before recursion
for c in self._tree.children(p):
results.append(self._tour(c, d+1, path)) # recur on subtree
path[-1] += 1
path.pop() # remove extraneous index from end of path
answer = self._hook_postvisit(p, d, path, results)
return answer
def _hook_previsit(self, p, d, path):
""" Visit Position p, before the tour of it's children.
:param p : Position of current position being visited
:param d : depth of p in the tree
:param path : list of indices of children on path from root to p
"""
pass
def _hook_postvisit(self, p, d, path, results):
""" Visit Position p, after the tour of it's children.
:param p : Position of current position being visited
:param d : depth of p in the tree
:param path : list of indices of children on path from root to p
:return : a list of values returned by _hook_postvisit(c) for each
child c of p.
"""
pass
class PreorderPrintIndentedTour(EulerTour):
def _hook_previsit(self, p, d, path):
print(2*d*' ' + str(p.element()))
class PreorderPrintIndentedLabeledTour(EulerTour):
def _hook_previsit(self, p, d, path):
label = '.'.join(str(j+1) for j in path)
print('{0:s}{1:s}{2:s}'.format(2*d*' ', label, str(p.element())))
class ParenthesizeTour(EulerTour):
def _hook_previsit(self, p, d, path):
if path and path[-1] > 0:
print ', ',
print p.element(),
if not self.tree().is_leaf(p):
print '(',
def _hook_postvisit(self, p, d, path, results):
if not self.tree().is_leaf(p):
print ')',
class BinaryEulerTour(EulerTour):
""" Abstract base class for performing Euler tour of a binary tree.
This version includes an additional _hook_invisit that is called after the
tour of the left subtree (if any), yet before the tour of the right subtree
(if any).
Note: Right child is always assigned index 1 in path, even if no left
sibling.
"""
def _tour(self, p, d, path):
results = [None, None] # will update with results of recursions
self._hook_previsit(p, d, path)
if self._tree.left(p) is not None:
path.append(0)
results[0] = self._tour(self._tree.left(p), d+1, path)
path.pop()
self._hook_invisit(p, d, path)
if self._tree.right(p) is not None:
path.append(1)
results[1] = self._tour(self._tree.right(p), d+1, path)
path.pop()
answer = self._hook_postvisit(p, d, path, results)
return answer
def _hook_invisit(self, p, d, path):
""" Visit Position p, between tour of its left and right subtrees."""
pass
class InorderTour(BinaryEulerTour):
def _hook_invisit(self, p, d, path):
print(p.element())
def construct_tree():
t = LinkedBinaryTree()
root = t._add_root('Trees')
l = t._add_left(root, 'General trees')
r = t._add_right(root, 'Binary trees')
t1 = LinkedBinaryTree()
root = t1._add_root('section1')
left = t1._add_left(root, 'paragraph1')
right = t1._add_right(root, 'paragraph2')
t2 = LinkedBinaryTree()
root = t2._add_root('section2')
left = t2._add_left(root, 'paragraph1')
right = t2._add_right(root, 'paragraph2')
t._attach(l, t1, t2)
return t
def construct_num_tree():
t = LinkedBinaryTree()
root = t._add_root(0)
l = t._add_left(root, 1)
r = t._add_right(root, 2)
t1 = LinkedBinaryTree()
root = t1._add_root(3)
left = t1._add_left(root, 5)
right = t1._add_right(root, 6)
t2 = LinkedBinaryTree()
root = t2._add_root(4)
left = t2._add_left(root, 7)
right = t2._add_right(root, 8)
t._attach(l, t1, t2)
return t
if __name__ == '__main__':
t = construct_tree()
ppit = PreorderPrintIndentedTour(t)
ppit.execute()
print('\n')
ppilt = PreorderPrintIndentedLabeledTour(t)
ppilt.execute()
t = construct_num_tree()
pt = ParenthesizeTour(t)
pt.execute()
print('\n')
it = InorderTour(t)
it.execute()
|
# -*- coding: utf-8 -*-
from exception import Empty
class TwoColorStack(object):
""" It consists of two stacks—one “red” and one “blue”—and has as its
operations color-coded versions of the regular stack ADT operations.
"""
DEFAULT_CAPACITY = 10
def __init__(self):
super(TwoColorStack, self).__init__()
self._data = [None] * TwoColorStack.DEFAULT_CAPACITY
self._red_size = 0 # red front is at data[0]
self._blue_size = 0 # blue front is at data[-1]
def red_len(self):
""" Return the number of red elements in the stack."""
return self._red_size
def blue_len(self):
""" Return the number of blue elements in the stack."""
return self._blue_size
def is_red_empty(self):
""" Return True if there is no red elements."""
return self._red_size == 0
def is_blue_empty(self):
""" Return True if there is no blue elements."""
return self._blue_size == 0
def red_push(self, e):
""" Add element e to the top of red stack."""
size = self._red_size + self._blue_size
if size == len(self._data):
self._resize(2 * size)
avail = 0 + self._red_size
self._data[avail] = e
self._red_size += 1
def blue_push(self, e):
""" Add element e to the top of blue stack."""
size = self._red_size + self._blue_size
if size == len(self._data):
self._resize(2 * size)
avail = -1 - self._blue_size
self._data[avail] = e
self._blue_size += 1
def red_pop(self):
""" Remove and return the element from the top of the red stack
Raise Empty exception if the red stack is empty.
"""
if self._red_size == 0:
raise Empty('Red stack is empty!')
avail = 0 + self._red_size - 1
self._data[avail] = None
self._red_size -= 1
# resize the underlying array
size = self._red_size + self._blue_size
if size <= len(self._data) // 4:
self._resize(len(self._data) // 2)
def blue_pop(self):
""" Remove and return the element from the top of the blue stack
Raise Empty exception if the blue stack is empty.
"""
if self._blue_size == 0:
raise Empty('Blue stack is empty')
avail = -1 - self._blue_size + 1
self._data[avail] = None
self._blue_size -= 1
# resize the underlying array
size = self._red_size + self._blue_size
if size <= len(self._data) // 4:
self._resize(len(self._data) // 2)
def red_top(self):
""" Return (but do not remove) the element at the top of the red stack.
Raise Empty exception if the red stack is empty.
"""
if self._red_size == 0:
raise Empty('Red stack is empty!')
avail = 0 + self._red_size - 1
return self._data[avail]
def blue_top(self):
""" Return (but do not remove) the element at the top of the blue
stack. Raise Empty exception if the red stack is empty.
"""
if self._blue_size == 0:
raise Empty('Blue stack is empty!')
avail = -1 - self._blue_size + 1
return self._data[avail]
def _resize(self, cap):
""" Resize the underlying list to length `cap`."""
old = self._data
self._data = [None] * cap
# copy red
for i in range(self._red_size):
self._data[i] = old[i]
# copy blue
for i in range(self._blue_size):
self._data[-1 - i] = old[-1 - i]
return
if __name__ == '__main__':
s = TwoColorStack()
for i in range(10):
s.red_push(i)
for i in range(10, 20):
s.blue_push(i)
print(s._data)
print('red_top: {0:d}, blue_top: {1:d}'.format(s.red_top(), s.blue_top()))
s.red_push(20)
print(s._data)
print('red_top: {0:d}, blue_top: {1:d}'.format(s.red_top(), s.blue_top()))
for i in range(5):
s.red_pop()
for i in range(6):
s.blue_pop()
print(s._data)
print('red_top: {0:d}, blue_top: {1:d}'.format(s.red_top(), s.blue_top()))
print('red_len: {0:d}, blue_len: {1:d}'.format(s.red_len(), s.blue_len()))
|
# -*- coding: utf-8 -*-
from exception import Empty
class SinglyLinkedList(object):
""" ADT of singly linked list that has a sentinel in the inner
implemetation."""
class _Node(object):
""" Node class for SinglyLinkedList."""
__slot__ = '_element', '_next' # streamline the memory management
def __init__(self, element, nxt):
self._element = element
self._next = nxt
def __init__(self):
self._tail = None
self._header = self._Node(None, None)
self._size = 0
def __len__(self):
""" Return the length of the singly linked list."""
return self._size
def is_empty(self):
""" Return Ture if the list is empty."""
return self._size == 0
def head(self):
""" Return the head element of the singly linked list. If the list is
empty then return None.
"""
return self._header._next._element
def tail(self):
""" Return the tail element of the singly linked list. If the list is
empty then return None.
"""
return self._tail._element
def add_first(self, e):
""" Add an element to the first of the linked list."""
newnode = self._Node(e, self._header._next)
self._header._next = newnode
if self._size == 0:
self._tail = newnode
self._size += 1
def remove_first(self):
""" Remove the first element to the linked list and return the first
element."""
if self._size == 0:
raise Empty('singly list is Empty')
node = self._header._next
rlt = node._element
self._header._next = node._next
node._element = node._next = None
self._size -= 1
if self._size == 0:
self._tail = None
return rlt
def add_last(self, e):
""" Add an element to the last of the linked list."""
newnode = self._Node(e, None)
if self._size == 0:
self._header._next = newnode
else:
self._tail._next = newnode
self._tail = newnode
self._size += 1
def __repr__(self):
""" String representation of the singly linked list."""
s = ''
walk = self._header._next
while walk is not None:
s += str(walk._element) + ','
walk = walk._next
return s[:-1]
if __name__ == '__main__':
sllist = SinglyLinkedList()
for i in range(10):
sllist.add_first(i)
print(sllist)
for i in range(-1, -11, -1):
sllist.add_last(i)
print(sllist)
for i in range(15):
sllist.remove_first()
print('head: {0:d}, tail: {1:d}'.format(sllist.head(), sllist.tail()))
print(sllist)
walk = sllist._header._next
for i in range(4):
walk = walk._next
print(walk._element)
|
# -*- coding: utf-8 -*-
from random import shuffle
def insert_sort(l):
""" In-palce insert sort."""
walk = 0
while walk < len(l):
i = walk + 1
j = i - 1
while 0 < i < len(l):
if l[i] < l[j]:
tmp = l[i]
l[i] = l[j]
l[j] = tmp
i -= 1
j = i - 1
walk += 1
return
if __name__ == "__main__":
l = [i for i in range(10)]
shuffle(l)
print(l)
insert_sort(l)
print(l)
|
# -*- coding: utf-8 -*-
from transfer_r6_3 import ArrayStack
def reverse_list(l):
s = ArrayStack()
for item in l:
s.push(item)
for i in range(len(l)):
l[i] = s.pop()
if __name__ == '__main__':
l = [i for i in range(10)]
print(l)
reverse_list(l)
print(l)
|
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from trees.tree import Tree
class LinkedGeneralTree(Tree):
""" An implementation of general tree by linked structure."""
# nested class
class _Node(object):
""" Lightweight, nonpublic class for storing an element."""
# streamline memeory usage
__slots__ = '_element', '_parent', '_children'
def __init__(self, element, parent=None, children=None):
self._element = element
self._parent = parent
if children is None:
self._children = []
class Position(Tree.Position):
""" A class representing the location of a single element."""
def __init__(self, container, node):
""" Constructor of Position class."""
self._container = container
self._node = node
def element(self):
""" Return the element stored at this Position."""
return self._node._element
def __eq__(self, other):
""" Return True if other is a Position representing the same
location."""
return type(other) is type(self) and other._node is self._node
# utility methods
def _validate(self, p):
""" Return associated node, if position is valid."""
if not isinstance(p, self.Position):
raise TypeError('p must be proper Position type')
if p._container is not self:
raise ValueError('p does not belong to this container')
if p._node._parent is p._node: # convention for deprecated nodes
raise ValueError('p is no longer valid')
return p._node
def _make_position(self, node):
""" Return Position instance for given node (or None if no node)."""
return self.Position(self, node) if node is not None else None
# constructor
def __init__(self):
self._root = None
self._size = 0
# public accessors
def root(self):
""" Return Position representing the tree's root (or None if empty)."""
return self._make_position(self._root)
def parent(self, p):
""" Return the Position of p's parent (or None if p is root)."""
node = self._validate(p)
return self._make_position(node._parent)
def num_children(self, p):
""" Return the number of children of Position p."""
node = self._validate(p)
for item in node._children:
print item._element
return len(node._children)
def children(self, p):
""" Generate an iteration of Positions representing p's children."""
node = self._validate(p)
for item in node._children:
pos = self._make_position(item)
yield pos
def __len__(self):
""" Return the total number of elements in the tree."""
return self._size
def __str__(self):
""" str representation of linked binary tree."""
s = ''
for item in self:
s += str(item)
return s
# nonpublic mutators
def _add_root(self, e):
""" Place element e at the root of an empty tree and return new
Position. Raise ValueError if tree nonempty.
"""
if self._root is not None:
raise ValueError('Root exists')
self._size = 1
self._root = self._Node(e)
return self._make_position(self._root)
def _add_child(self, p, e):
""" Create a new child for Position p, storing element e.
NOTE: you can child to the rightmost, because I just append the new
child to the children list.
:return : the Position of new node
:raise : ValueError if Position p is invalid
"""
node = self._validate(p)
self._size += 1
child = self._Node(e, parent=node)
node._children.append(child)
return self._make_position(child)
def _replace(self, p, e):
""" Replace the element at position p with e, and return old element."""
node = self._validate(p)
old = node._element
node._element = e
return old
def _delete(self, p):
"""Delete the node at Position p, and replace it with its child, if
any.
:return : the element that had been stored at Position p.
:raise : ValueError if Position p is invalid or p has two children.
"""
node = self._validate(p)
if self.num_children(p) > 1:
raise ValueError('Position has more than one child')
if node._children:
child = node._children[0]
else:
child = None
if child is not None:
child._parent = node._parent
if node is self._root:
self._root = child # child becomes root
else:
p_chdrn = node._parent._children
walk = 0
while p_chdrn[walk] is not node:
walk += 1
p_chdrn.pop(walk)
self._size -= 1
node._parent = node # convention for deprecated node
return node._element
def _attach(self, p, t_list):
""" Attach trees storing in t_list to the external Position p in the
order with t_list itself. As a side effect, trees in t_list will be set
to empty.
:raise : TypeError if trees in t_list do not match type of this tree
:raise : ValueError if Position p is invalid or not external.
"""
node = self._validate(p)
if not self.is_leaf(p):
raise ValueError('position must be leaf')
for t in t_list:
if type(t) is not type(self):
raise TypeError('Tree types must match')
self._size += len(t)
t._root._parent = node
node._children.append(t._root)
t._root = None
t._size = 0
return
if __name__ == '__main__':
t = LinkedGeneralTree()
rt = t._add_root(0)
l = t._add_child(rt, 1)
r = t._add_child(rt, 2)
print('tree: {0:s}, len: {1:d}'.format(str(t), len(t)))
t1 = LinkedGeneralTree()
root = t1._add_root(3)
left = t1._add_child(root, 5)
right = t1._add_child(root, 6)
t2 = LinkedGeneralTree()
root = t2._add_root(4)
left = t2._add_child(root, 7)
right = t2._add_child(root, 8)
t._attach(l, [t1, t2])
print('tree: {0:s}, len: {1:d}'.format(str(t), len(t)))
chdrn = t.children(t.root())
pos = next(chdrn)
chdrn = t.children(pos)
pos = next(chdrn)
chdrn = t.children(pos)
next(chdrn)
pos = next(chdrn)
t._replace(pos, 'a')
print('tree: {0:s}, len: {1:d}'.format(str(t), len(t)))
print(pos.element())
t._delete(pos)
print('tree: {0:s}, len: {1:d}'.format(str(t), len(t)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.