text
stringlengths 37
1.41M
|
---|
'''
后裔,后裔继承了Game的hp和power,并多了护甲属性。
重新定义另外一个defense方法:
final_hp = hp+defense-enemy_power
enemy_final_hp = enemy_hp-power
两个hp进行对比,血量先为零的人输掉比赛
'''
import random
from pythoncs.mxdx_demo.mxdx_hhgame_demo2 import Game
class houyi(Game):
def __init__(self,my_hp,your_hp):
self.defense = 10
super().__init__(my_hp,your_hp)
def fight(self):
#self.my_hp = 1000
self.my_power = random.randint(0,1000)
#self.your_hp = 1000
self.your_power = random.randint(0,1000)
while True:
my_final_hp = self.my_hp +self.defense- self.your_power
your_final_hp = self.your_hp - self.my_power
if my_final_hp <=0:
print("我输了")
break
elif your_final_hp <=0:
print("你输了")
break
else:
print("游戏继续")
break
houyi = houyi(1000,2000)
houyi.fight()
|
''' 两层分支结构:if else'''
a = 1
if a==0:
print("a=0")
else:
print("a != 0")
''' 多层分支结构:if elif else'''
b = 1
if b==0:
print("b=0")
elif b==1:
print("b=1")
else:
print("b != 0和1")
''' 实现以下分段函数
x+3 (x>1)
y= x+2 (-1<=x<=1)
5*x+3 (x<-1)
'''
#方案一,嵌套分支结构:
# x =0
# if x>1:
# y=x+3
# else:
# if x<-1:
# y=5*x+3
# else:
# y=x+2
# print(f"y={y}")
#方案二,多层分支结构更加推荐的方式:
x =-10
if x>1:
y=x+3
elif -1<=x<=1:
y=x + 2
elif x<-1:
y=5*x+3
print(f"y={y}")
'''循环结构'''
# 1.计算1~100求和
sum1=0
for i in range(0,101):
sum1=sum1+i
print(f"sum1={sum1}")
#使用python实现0~100之间的偶数就和
#range(开始,截至,步长)
sum2=0
for i in range(0,101,2):
sum2=sum2+i
print(f"sum2={sum2}")
#加入分支结构实现1~100之间的偶数求和
sum3=0
for i in range(0,101):
if i%2==0:
sum3=sum3+i
print(f"sum3={sum3}")
#while循环
while a==1:
print("a=1")
a += 1
else:
print("a!=1")
print(f"a={a}")
#break和continue区别
for i in range(0,10):
if i==5:
break
print(f"i={i}")
for j in range(0,10):
if j==5:
continue
print(f"j={j}")
"""
猜数字游戏
计算机出一个0~100的随机数字由人来猜
计算机根据人猜出来的数字来判断大一点/小一点/相等
"""
import random
while True:
your_number = int(input("请输入你的数字:"))
computer_number = random.randint(0, 100)
print(computer_number)
if your_number == computer_number:
print("我们一样大")
break
elif your_number > computer_number:
print("你大我小")
else:
print("你小我大")
|
#!/usr/bin/env python3
"""
This script implements code for finding the k-th element from the end of the
linked list.
"""
from linkedlist import LinkedList
class LinkedListMod(LinkedList):
def __init__(self, data: list):
super().__init__(data)
def __str__(self):
return super().__str__()
def delele_from_end(self, k):
"""
Deletes third element from the end of the LinkedList
"""
ptr_1 = self.head
ptr_2 = self.head
distance = 0
while distance != k:
ptr_2 = ptr_2.next_node
if ptr_2 == None:
print(f"Cannot be done")
return
distance += 1
if ptr_2.next_node is None:
self.head = self.head.next_node
else:
prev = None
while ptr_2.next_node is not None:
print("p")
prev = ptr_1
ptr_1 = ptr_1.next_node
ptr_2 = ptr_2.next_node
prev.next_node = ptr_1.next_node
del ptr_1
def main():
data = [1, 3]
mylinkedlist = LinkedListMod(data)
print(mylinkedlist)
mylinkedlist.delele_from_end(1)
print(mylinkedlist)
if __name__ == "__main__":
main()
|
# Is Unique: Implement an algorithm to determine if a string has all
# unique characters. What if you cannot use additional data structures?
class StringChecker:
def is_unique(self, string: str) -> bool:
"""
Checks if all chars in string is unique
using a set/hashtable
"""
buffer = set()
for char in string:
if char not in buffer:
buffer.add(char)
elif char in buffer:
return False
return True
def is_unique2(self, string: str) -> bool:
"""
Checks if all chars in string is unique
using a list/array
"""
total_chars = 256 # 128 ASCII, 256 for UNICODE
buffer = [0 for i in range(total_chars)]
for char in string:
if buffer[ord(char)] == 0:
buffer[ord(char)] = 1
elif buffer[ord(char)] == 1:
return False
return True
def is_unique3(self, string: str) -> bool:
"""
Checks if all chars in string is unique
without using any extra data structures
"""
string = "".join(sorted(string))
for i in range(len(string)):
if string[i] == string[i - 1]:
return False
return True
if __name__ == "__main__":
words = ("abcde", "hello", "apple", "kite", "padle")
checker = StringChecker()
for word in words:
print(
f"{word} : {checker.is_unique(word)}\
{checker.is_unique2(word)} {checker.is_unique3(word)}"
)
|
#Snabb bonus! Hur vi hanterar och ser på mutables.
#Vi gör ett mutable objekt av något slag - en lista blir gott nog för våra syften.
mutable1 = [1,2,3,4,5]
#Lägger denna i varsin lista
list1 = [mutable1, 2]
list2 = [mutable1, 3]
#MODIFIERAR vi en mutable i en lista ändrar vi på objektet
list2[0].extend([1,2,3,4])
print(f'Contents of list1[0]: {list1[0]}')
print(f'Contents of list2[0]: {list2[0]}')
print(id(1))
print(id(mutable1[0]))
#Vi kan styrka detta genom att kolla ID på vad vi refererar till:
print(f'Memory location of object in list1[0]: {id(list1[0])}')
print(f'Memory location of object in list2[0]: {id(list2[0])}')
#Ändrar vi VAD som ska finnas i index 0 i list2 kommer vi att ha en ny referens till ett nytt objekt
list2[0] = [9, 10]
print(f'Contents of list1[0]: {list1[0]}')
print(f'Contents of list2[0]: {list2[0]}')
print(f'Memory location of object in list1[0]: {id(list1[0])}')
print(f'Memory location of object in list2[0]: {id(list2[0])}')
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 20:14:41 2021
@author: Alec
"""
#Import Libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
#Import Data
salary = pd.read_csv("Employee_Salary.csv")
#Visualize Data
print(salary.head(10))
print(salary.tail(10))
print(salary.describe())
print(salary.info())
#sns.jointplot(x = 'Years of Experience', y = 'Salary', data = salary)
#sns.lmplot(x = 'Years of Experience', y = 'Salary', data = salary)
#sns.jointplot(x = 'Salary', y = 'Years of Experience', data = salary)
#sns.lmplot(x = 'Salary', y = 'Years of Experience', data = salary)
#sns.pairplot(salary)
X = salary[['Years of Experience']]
Y = salary[['Salary']]
X_train = X
Y_train = Y
#Linear Regression Attempt
regressor = LinearRegression(fit_intercept= True)
regressor.fit(X_train, Y_train)
print('Linear Model Coefficient (m)', regressor.coef_)
print('Linear Model Coefficient (b)', regressor.intercept_)
#plt.scatter(X_train, Y_train, color= 'Red')
#plt.plot(X_train, regressor.predict(X_train))
#plt.xlabel('Years of Experience')
#plt.ylabel('Salary')
#plt.title('Years of Experience vs. Salary (Linear)')
#Polynomial Regression
poly_regressor = PolynomialFeatures(degree= 5)
X_columns = poly_regressor.fit_transform(X_train)
regressor = LinearRegression()
regressor.fit(X_columns, Y_train)
print('Linear Model Coefficient (m)', regressor.coef_)
print('Linear Model Coefficient (b)', regressor.intercept_)
Y_predict = regressor.predict(poly_regressor.fit_transform(X_train))
#plt.scatter(X_train, Y_train, color= 'Gray')
#plt.plot(X_train, Y_predict, color= 'Blue')
#plt.xlabel('Years of Experience')
#plt.ylabel('Salary')
#plt.title('Years of Experience vs. Salary (Poly order = 5)')
#Import Data
economy = pd.read_csv('EconomiesOfScale.csv')
print(economy.head(10))
print(economy.tail(10))
print(economy.describe())
print(economy.info())
I = economy[['Number of Units']]
J = economy[['Manufacturing Cost']]
I_train = I
J_train = J
#Polynomial Regression
poly_econ_regressor = PolynomialFeatures(degree = 5)
I_columns = poly_econ_regressor.fit_transform(I_train)
econ_regressor = LinearRegression()
econ_regressor.fit(I_columns, J_train)
print('Linear Model Coefficient (m)', econ_regressor.coef_)
print('Linear Model Coefficient (b)', econ_regressor.intercept_)
J_predict = econ_regressor.predict(poly_econ_regressor.fit_transform(I_train))
plt.scatter(I_train, J_train, color='Green')
plt.plot(I_train, J_predict, 'Red')
plt.xlabel('Number of Units')
plt.ylabel('Manufacturing Cost')
plt.title('Number of Units vs Manufacturing Cost (Poly)')
|
#Question 1
d={}
for i in range(1,5):
key=input("enter the key: ")
value=input("enter the value: ")
d[key]=value
print(d)
#Question 2
a={}
b={}
for i in range(1,4):
b={}
name=input("enter name")
for j in range(1,4):
sub=input("enter subject")
marks=int(input("enter marks"))
db[sub]=marks
a[name]=b
print(a)
stud=input("enter the student's name whose marks u want to see")
print(a[stud])
|
import turtle
def square10():
for i in range(10, 110, 10):
turtle.shape('turtle')
turtle.pendown()
turtle.forward(10 + i)
turtle.left(90)
turtle.forward(10 + i)
turtle.left(90)
turtle.forward(10 + i)
turtle.left(90)
turtle.forward(10 + i)
turtle.left(90)
turtle.penup()
turtle.goto(-i/2, -i/2) |
# Exercise 3_1
# Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Pay
# the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours.
# Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use
# raw_input to read a string and float() to convert the string to a number. Do not worry about error checking
# the user input - assume the user types numbers properly.
# prompt for hours and hourly rate, then convert to float
hrs = raw_input("Enter Hours: ")
h = float(hrs)
rate = raw_input("Enter Hourly Rate: ")
r = float(rate)
# pay hourly rate up to 40 hours
if h <= 40:
pay = h * r
# pay 1.5 times hourly rate for hours greater than 40
else :
pay = r * 40 + ( (h - 40) * 1.5 * r)
print pay |
lst = list(map(int, input().split()))
text = []
temp = set()
temp_length = 0
for elem in lst:
temp.add(elem)
text.append(('YES' if len(temp) == temp_length else 'NO'))
temp_length = len(temp)
print(*text, sep="\n")
|
n = int(input())
step = 1
maxStep = 1
while step <= n:
step = step * 2
step = step // 2
if step == n:
print('YES')
else:
print('NO')
|
a = int(input())
b = int(input())
c = int(input())
d = int(input())
x = -b // a
if a == 0 and b == 0:
print('INF')
elif c == 0 and d == 0 or a == 0 or b / a == d / c:
print('NO')
elif c == 0:
print(x)
else:
print(x)
|
import numpy as np
def read_rigid_body(filename):
'''
Reads in the rigid body file, and saves the number of led markers,
their locations, and the tip locations.
Inputs:
filename -> the rigid body file
Outputs:
num_markers -> the number of markers on the rigid body
led_markers -> the led markers as a list of x,y,z
tip -> the tip x,y,z coordinates
'''
rigid_data = open(filename)
# set number of markers to iterate over
first_line = rigid_data.readline().split()
num_markers = int(first_line[0])
led_markers = np.zeros([3, num_markers])
# iterate thourgh markers, one per line
for i in range(num_markers):
# set led_markers from file input
current_marker = rigid_data.readline().split()
for j in range(0, 3):
led_markers[j][i] = np.float64(current_marker[j])
# set tip from file input
tip = np.zeros([3, 1])
tip_line = rigid_data.readline().split()
for j in range(0, 3):
tip[j] = np.float64(tip_line[j])
return num_markers, led_markers, tip
def read_sample(filename, num_A, num_B):
'''
Parses through the sample readings for each frame.
Inputs:
filename -> the sample readings filename
num_A -> the number of led markers on A
num_B -> the number of led markers on B
Outputs:
a_Frames -> the x,y,z A coordinates for each frame
b_Frames -> the x,y,z B coordinates for each frame
'''
sample_readings = open(filename)
first_line = sample_readings.readline().split(",")
num_markers = int(first_line[0].strip())
num_Samples = int(first_line[1].strip())
num_d = num_markers - num_A - num_B
a_Frames = []
b_Frames = []
# iterate over samples, setting frame markers
for i in range(num_Samples):
a_current_markers = np.zeros([3, num_A])
b_current_markers = np.zeros([3, num_B])
# set a_markers from input file
for j in range(num_A):
point = sample_readings.readline().split()
for k in range(0, 3):
a_current_markers[k][j] = point[k].strip(',')
# set b_markers from input file
for j in range(num_B):
point = sample_readings.readline().split()
for k in range(0, 3):
b_current_markers[k][j] = point[k].strip(',')
# disregard these lines
for j in range(num_d):
sample_readings.readline()
# append markers to a_Frames and b_Frames
a_Frames.append(a_current_markers)
b_Frames.append(b_current_markers)
return a_Frames, b_Frames
def read_mesh(filename):
'''
Reads in the mesh file and saves the triangle vertices as a list.
Inputs:
filename -> the mesh file
Outputs:
tri_coords -> An array that holds the coordinates of each vertex
tri_ind -> An array that holds the indices of the coordinates for each triangle
'''
mesh_data = open(filename)
# get file information from first line
num_Vertices = int(mesh_data.readline().strip())
tri_coords = np.zeros([3, num_Vertices])
# fill triangle coordinates array
for i in range(num_Vertices):
vertex = mesh_data.readline().split()
for j in range(3):
tri_coords[j][i] = vertex[j]
num_Triangles = int(mesh_data.readline().strip())
tri_ind = np.zeros([3, num_Triangles], dtype=int)
# fill triangle indices array
for i in range(num_Triangles):
triangle = mesh_data.readline().split()
for j in range(3):
tri_ind[j][i] = int(triangle[j])
return tri_coords, tri_ind
|
# -*- coding:utf8 -*-
"""
基本的装饰器的用法
"""
# 带参数装饰器的用法
def deco(arg,arg2):
print 'deco start'
def _deco(func):
print '_deco start'
def __deco(*args,**kwargs):
print 'args',arg,arg2
func(*args,**kwargs)
print 'args',func
print '_deco end'
return __deco
print 'deco end'
return _deco
def deco2(arg,arg2):
print 'deco2 start'
def _deco(func):
print '_deco2 start'
def __deco(*args,**kwargs):
print 'args2',arg,arg2
func(*args,**kwargs)
print 'args2',func
print '_deco2 end'
return __deco
print 'deco2 end'
return _deco
# 装饰器嵌套装饰器的顺序
@deco2(arg="yes2",arg2="no2")
@deco(arg="yes",arg2="no")
def show(name):
print "i am ",name
# 用类实现装饰器
# 介绍这个用法,后面的描述器部分会用到
class Foo(object):
def __init__(self,func):
self._func = func
def __call__(self,*args,**kwargs):
print 'before'
self._func(*args,**kwargs)
print 'end'
@Foo
def show(name):
print name
# 用函数实现装饰器
def cached_method(flush_time):
def _cached(func):
def __cached(*args,**kwargs):
print 'before'
print flush_time
func(*args,**kwargs)
print 'end'
return __cached
return _cached
class A(object):
@cached_method(123)
def show(self,name):
print 'i am',name
|
n=int(input('enter the number'))
list=[]
for i in range(n):
list.append(input('enter the next\n'))
print()
for i in range(n):
print(list[i],'\n')
|
def fib(n):
a=0
b=1
print(a)
print(b)
for i in range(2,n):
temp=a+b
if temp<=100:
a=b
b=temp
print(temp)
else:
break
n=int(input("enter the range of fib"))
if n<0:
print("negative number")
else:
fib(n)
|
import time
import curses
class Screen:
def __init__(self, stdscr, row=0, col=0):
self.stdscr = stdscr
# These are the initial coordinates of the cursor.
# These will be updated as text is printed on to the screen.
# init row and col should never be updated once initialised.
self.init_row = row
self.init_col = col
self.row = row
self.col = col
# Initialize curses.
curses.start_color()
curses.use_default_colors()
stdscr.nodelay(1)
# Create an init pair with green color.
curses.init_pair(1, curses.COLOR_GREEN, -1)
# Table heading color
curses.init_pair(2, curses.COLOR_YELLOW, -1)
def start(self):
self.stdscr.refresh()
char = self.stdscr.getch()
if char == 113:
return False
return True
def print(self, text, label=None, same_row=False):
# Clear before writing.
self.stdscr.clrtoeol()
if label == "heading":
self.col = self.init_col
# For heading make sure there is an empty line before.
self.row += 1
self.stdscr.addstr(self.row, self.col, text, curses.color_pair(1))
else:
if self.col == 0:
self.col = 3
# Print only if the text can be displayed in the visible screen.
# Otherwise the window has to be maximised.
if (self.col + len(text)) < self.stdscr.getmaxyx()[1]:
self.stdscr.addstr(self.row, self.col, text)
if not same_row:
self.row += 1
self.col = self.init_col
else:
# Update col cursor position.
self.col += len(text) + 2
def print_table(self, headings, rows):
"""
Send a list of headings and list of dict objects in rows.
Ex:
headings = ['s.no', 'name']
rows = [
{
"s.no": 1,
"name": "John Doe"
},
{
"s.no": 2,
"name": "Red John"
}
]
s.no name
1 John Doe
2 Red John
"""
self.stdscr.clrtoeol()
# Store the max length of each column in the table. This includes the heading and
# the actual text.
headings_col_pos = {}
for heading in headings:
headings_col_pos[heading] = len(heading) + 2
for row in rows:
for key in row.keys():
value = row[key]
if len(value) > headings_col_pos[key]:
headings_col_pos[key] = len(value) + 2
# print headings
for heading in headings:
if (self.col + headings_col_pos[heading]) < self.stdscr.getmaxyx()[1]:
self.stdscr.addstr(self.row, self.col, heading, curses.color_pair(2))
self.col += headings_col_pos[heading] + 3
else:
break
self.row += 1
self.col = self.init_col
# print rows
for row in rows:
for heading in headings:
if (self.col + headings_col_pos[heading]) < self.stdscr.getmaxyx()[1]:
self.stdscr.addstr(self.row, self.col, row[heading])
self.col += headings_col_pos[heading] + 3
else:
break
self.row += 1
self.col = self.init_col
def clear(self):
self.row = self.init_row
self.col = self.init_col
@staticmethod
def sleep(secs, stdscr):
"""
Sleeping for a long time will freeze the screen for the user.
Pressing a `q` button won't get processed until the sleep
time is over.
This custom sleep, sleeps in steps of `freq` values, so that
we can respond to `q` faster.
"""
freq = 0.1
while True:
time.sleep(freq)
secs -= freq
char = stdscr.getch()
if char == 113:
exit(0)
if secs <= 0:
return
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple command that prints out the current n last levels of the CWD
replacing the prefix with a horizontal ellipsis
Usage pwdn [numdirs]
"""
from os import getcwd
from sys import argv, exit
try:
numdir = (len(argv) > 1) and int(argv[1]) or 2
except ValueError:
print "Usage: pwdn [numdirs]"
exit(1)
cwd = getcwd()[1:].split("/")
print "%s%s" % (len(cwd) > numdir and "…/" or "/", '/'.join(cwd[-numdir:]))
exit(0)
|
# n个骰子的点数
'''
把n个骰子扔在地上, 所有骰子朝上一面的点数和为s。
输入n, 打印出s的所有可能的值出现的概率
'''
class Solution:
# 动态规划
# 构造两个数组来存储骰子点数的每一个总数出现的次数
# 在一次循环中, 第一个数组中的第n个数字表示骰子和为n出现的次数
# 在下次循环中, 另一个数组的第n个数字设为前一个数组对应的第n-1、n-2、n-3、n-4、n-5、n-6之和
def PrintProbability(self, number):
if number < 1:
return []
max_val = 6
storage = [[], []]
storage[0] = [0] * (max_val * number + 1)
flag = 0
for i in range(1, max_val+1):
storage[flag][i] = 1
for i in range(2, number+1):
storage[1-flag] = [0] * (max_val * number + 1)
for j in range(i, i*max_val+1):
dice_num = 1
while dice_num < j and dice_num < max_val:
storage[1-flag][j] += storage[flag][j-dice_num]
dice_num += 1
flag = 1 - flag
total = max_val ** number
for i in range(number, number*max_val+1):
percent = storage[flag][i] / float(total)
print("{}: {:e}".format(i, percent))
s = Solution().PrintProbability(5)
|
# 替换字符串
'''
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
'''
class Solution:
def stringReplace(self, s):
init_string = ''
if type(s) != str:
return False
for i in s:
if i == ' ':
init_string += '%20'
else:
init_string += i
return init_string
answer = Solution()
print(answer.stringReplace('we are happy'))
|
# 顺时针打印矩阵
'''
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下矩阵:
[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]
则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
'''
class Solution:
def printmatrix(self, matrix):
output_list = []
start = 0
row = len(matrix)
col = len(matrix[0])
if matrix == None:
return None
if matrix == []:
return []
while start*2 < row and start*2 < col:
endx = col - 1 - start
endy = row - 1 - start
# 从左往右遍历
for i in range(start, endx+1):
number = matrix[start][i]
output_list.append(number)
# 从上到下遍历,需要判断是否只有一行
if start < endy:
for i in range(start+1, endy+1):
number = matrix[i][endx]
output_list.append(number)
# 从右到左遍历,需要判断是否只有一行并且是否只有一列
if start < endy and start < endx:
for i in range(endx-1, start-1, -1):
number = matrix[endy][i]
output_list.append(number)
# 从下往上遍历,需要判断是否只有一行并且只有一列
if start < endy-1 and start < endx:
for i in range(endy-1, start, -1):
number = matrix[i][start]
output_list.append(number)
start += 1
return output_list
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
matrix2 = [[1], [2], [3], [4], [5]]
matrix3 = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
s = Solution()
print(s.printmatrix(matrix3)) |
# 数组中重复的数字
'''
在一个长度为n的数组里的所有数字都在0到n-1的范围内。
数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。
请找出数组中任意一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
'''
class Solution:
# 用字典保存并求解
def duplicate2(self, numbers):
if numbers == None or len(numbers) <= 0:
return False
for i in numbers:
if i < 0 or i > len(numbers) - 1:
return False
repeatedNums = []
dict = {}
for i in range(len(numbers)):
if numbers[i] not in dict.keys():
dict[numbers[i]] = 0
dict[numbers[i]] += 1
for i in dict:
if dict[i] != 1:
repeatedNums.append(i)
return repeatedNums
#
# def duplicate2(self, numbers):
# if numbers == None or len(numbers) <= 0:
# return False
# for i in numbers:
# if i < 0 or i > len(numbers) - 1:
# return False
# repeatedNums = []
# for i in range(len(numbers)):
# while numbers[i] != i:
# if numbers[i] == numbers[numbers[i]]:
# repeatedNums.append(numbers[i])
# break
# else:
# index = numbers[i]
# numbers[i], numbers[index] = numbers[index], numbers[i]
# return repeatedNums
test = [2, 3, 1, 0, 2, 5, 3]
s = Solution()
print(s.duplicate2(test))
|
def build_person(first_name, last_name, middle_name='', age=None):
"""Возвращает информацию о человеке."""
person = {'first_name': first_name, 'last_name': last_name, 'middle_name': middle_name}
if age:
person['age'] = age
return person
men1 = build_person('Вася', 'Пупкин')
men2 = build_person('Дюша', 'Жуйкин', 'Мамин')
men3 = build_person('Кака', 'Кукуйкин', age=100)
print(men1)
print(men2)
print(men3)
|
t=int(raw_input())
out = []
def sort(l,m):
out = []
for item in l:
out.append(item)
for item in m:
out.append(item)
return sorted(out)[::-1]
while t:
n,m = raw_input().split()
ar1 = [int(i) for i in raw_input().strip().split()]
ar2 = [int(i) for i in raw_input().strip().split()]
print n,m
out.append(sort(ar1, ar2))
t=t-1
for item in out:
print " ".join(map(str,item))
|
"""
This is a docstring for the module:
This module demonstrates the merge functionality
in the 2048 game.
"""
def check_merge(iterator):
"""
Check whether the merge has happen at a particular
index or not, and returns the appropriate boolean value
for the same.
"""
if Dictionary[iterator] == 0:
Dictionary[iterator] = 1
for item in xrange(iterator+1):
Dictionary[item] = 1
return 1
else:
return 0
def merge(line):
"""
Return a new merge list for the given input list.
"""
# Start with a result list that contains the same number of 0's as the length of the line argument.
result = [0]*len(line)
# Initialize the dictionary with default value 0
for index in xrange(len(line)):
Dictionary[index] = 0
# Iterate over every value in the list
for index,item in enumerate(line):
# Iterate over the line input looking for non-zero entries
if item != 0:
# Put the first index element directly in the result list
if index == 0:
result[index] = item
# For the rest of the elements, iterate towards the front of the list and start merging
else:
set_flag = 0
for iterator in xrange(index,0,-1):
# For 0 elements
if result[iterator-1] == 0:
result[iterator-1] = item
result[iterator] = 0
set_flag=1
# For elements which are same and merge can be applied
elif result[iterator-1] == item and check_merge(iterator-1):
result[iterator-1] = item + item
result[iterator] = 0
break
elif result[iterator-1] != item and set_flag == 1:
break
elif result[iterator-1] != item and set_flag == 0:
result[index] = item
break
return result
list_1 = map(int,raw_input().split())
# list_1 = [8,8]
# Initialize an empty dictionary
Dictionary = {}
# Printing the result
print merge(list_1) |
def intercambiar(a,b):
a1=b
b1=a
return a1,b1
def primo(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0: #si el resto da 0 no es primo, por lo tanto devuelve Falso
return False
return True
def mcd(a,b):
if a<b:
a,b=intercambiar(a,b)
n=a
d=b
r= n-(d * (n/d))
while r!=0:
n=d
d=r
r= n -(d*(n/d))
print d
def mcdprimo(a,b):
cont=0
if a<b:
a,b=intercambiar(a,b)
n=a
d=b
r= n-(d * (n/d))
while r!=0:
n=d
d=r
r= n -(d*(n/d))
print n
if primo(d)==True:
cont += 1
return d,cont
numero,contador=mcdprimo(1547,560)
print "Hay", contador, "numero(s) primo(s)"
print "Es el numero(s): ", numero
#otra forma de sacar mcd es con modulo (:
def gcd(a,b):
if a<b:
intercambiar (a,b)
cont = 0
while b!=0:
cont += 1
r= a %b
a=b
b=r
print a
|
import random
def coin_toss(repetition):
print 'Starting the program...'
face = ''
head_count = 0
tail_count = 0
num = 1
# this is the part regarding tosisng a coin
for x in range (1, repetition):
coin = round(random.randint(0,1))
if coin == 0:
face = 'head'
head_count+=1
print "Attempt # " + str(num) + ": Throwing a coin... It's a " + str(face) + '! Got ' + str(head_count) + ' head(s) so far and ' + str(tail_count) + ' tails(s) so far'
if coin == 1:
face = 'tails'
tail_count+=1
print "Attempt # " + str(num) + ": Throwing a coin... It's a " + str(face) + '! Got ' + str(head_count) + ' head(s) so far and ' + str(tail_count) + ' tails(s) so far'
num += 1
coin_toss(100)
|
'''Now, create another class called Dog that inherits everything that the Animal does and has, but 1) have the default health be 150 and 2) add a new method called pet, which when invoked, increase the health by 5. Have the Dog walk() three times, run() twice, pet() once, and have it displayHealth().
Now, create another class called Dragon that also inherits everything from Animal, but 1) have the default health be 170 and 2) add a new method called fly, which when invoked, decreased the health by 10. Have the Dragon walk() three times, run() twice, fly() twice, and have it displayHealth(). When the Dragon's displayHealth function is called, have it say 'this is a dragon!' before it displays the default information (by calling the parent's displayHealth function).
Now for the first instance of the animal (instance called 'animal'), try calling fly() or pet() and make sure this doesn't work'''
from animal import Animal
class Dog(Animal):
def __init__(self, name):
super(Dog, self).__init__(name)
self.health = 150
def pet(self):
self.health += 5
return self
dog = Dog('Mimi')
print dog.walk().walk().walk().run().run().pet().displayHealth()
class Dragon(Animal):
def __init__(self, name):
super(Dragon, self).__init__(name)
self.health = 170
def fly(self):
self.health -=10
return self
def displayHealth(self):
print "This is a Dragon"
super(Dragon, self).displayHealth()
dragon = Dragon('Pete')
print dragon.walk().walk().walk().run().run().fly().fly().displayHealth()
|
class Patient(object):
def __init__(self, id, name, allergies):
self.id = id
self.name = name
self.allergies = allergies
self.bedNumber = 0
class Hospital(object):
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
self.patient_list = []
def admit(self, patient):
if len(self.patient_list) >= self.capacity:
print "Hospital is full"
else:
self.patient_list.append(patient)
print "Admission is complete"
print "Patient count is " + str(len(self.patient_list))
patient.bedNumber = patient.id
print "Patient bed number: " + str(patient.bedNumber)
return self
def display(self):
print "Number of patients: " + str(len(self.patient_list))
print "Patients: "
for i in range(0, len(self.patient_list)):
print "ID: ", str(self.patient_list[i].id)
print "Name: ", str(self.patient_list[i].name)
print "Allergies: ", str(self.patient_list[i].allergies)
print "Bed #: ", str(self.patient_list[i].bedNumber)
return self
def discharge(self, id):
for i in range(0, len(self.patient_list)-1):
if(self.patient_list[i].id == id):
print "Patient " + str(self.patient_list[i].name) + " has been discharged"
self.patient_list[i].bedNumber = 0
print "Patient bed number is now " + str(self.patient_list[i].bedNumber)
self.patient_list.remove(self.patient_list[i])
return self
mmc = Hospital('Manati', 300)
mmc.display()
patient1 = Patient("1", "Melissa", "Eggs")
patient2 = Patient("2", "Sky", "None")
mmc.admit(patient1)
mmc.admit(patient2)
mmc.display()
mmc.discharge("1")
mmc.display()
|
# 物件導向的最基礎,我們定義class,然後用它宣告我們的物件/實體(instance)
# class 可以定義attribute(成員)、method(方法),還有一些既定方法像是初始化__init__
# class裡的method,跟function基本上是一樣的,但第一個參數是self,會指向此實體本身
# 定義一個class叫做Person
# 我們習慣把class的名稱定義成UpperCaseCamelCase,字的開頭大寫
# 如果有多個字組成則在每個字的開頭大寫連起來
class Person:
# 定義class attribute,所有實體會共用它
kind = 'Person'
# 初始化,當宣告實體的時候這個方法會被呼叫
# 用self.xxx來定義實體的 attribute,每個被宣告的實體會有自己的attribute
def __init__(self, name, age):
self.name = name
self.age = age
# 定義實體的方法
def say_hi(self):
print(
f'Hi, my name is {self.name}, I am {self.age} years old'
)
# 使用定義好的Class宣導實體(instance)
mike = Person('Mike', 5) # 帶進去的參數Mike與5分辨對應__init__裡的name與age
john = Person('John', 10)
# 呼叫實體的方法
mike.say_hi() # output: Hi, my name is Mike, I am 5 years old
john.say_hi() # output: Hi, my name is John, I am 10 years old
# 印出實體attribute
print(mike.name) # output: Mike
print(john.name) # output: John
# class attribute是共用的,不管是class本身或是instance都能使用
print(mike.kind) # Person
print(Person.kind) # Person
# 宣告新的class叫Student,繼承Person
class Student(Person):
# 如果需要的話可以定義新的初始化函數,它會覆蓋掉原本Person定義好的
def __init__(self, name, age, degree):
# 使用super去呼叫parent的初始化函數,Student的parent是Person
super().__init__(name, age)
# 新的class多一個degree這個attribute
self.degree = degree
# 定義新的方法
def tell_my_degree(self):
print(f'I earned my {self.degree} degree')
# 宣告實體
susan = Student('Susan', 22, 'master')
# 繼承的class所宣告出的實體可以呼叫parent class定義的方法
susan.say_hi() # ouptut: Hi, my name is Susan, I am 22 years old
susan.tell_my_degree() # output: I earned my master degree
print(susan.name) # output: Susan
print(susan.degree) # output: master
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
class Interface: # Classe que cria a interface gráfica do programa
def __init__(self, maze):
# Funções dos botões
def move_up():
self.maze.moveMouse(1)
def move_right():
self.maze.moveMouse(2)
def move_down():
self.maze.moveMouse(4)
def move_left():
self.maze.moveMouse(8)
def toggle_wall_up():
self.maze.toggleWall([self.maze.mouse.x, self.maze.mouse.y], 1)
def toggle_wall_right():
self.maze.toggleWall([self.maze.mouse.x, self.maze.mouse.y], 2)
def toggle_wall_down():
self.maze.toggleWall([self.maze.mouse.x, self.maze.mouse.y], 4)
def toggle_wall_left():
self.maze.toggleWall([self.maze.mouse.x, self.maze.mouse.y], 8)
# Declaração da estrutura
self.master = Tk()
self.master.wm_state('normal')
self.maze = maze
self.outer_frame = Frame(self.master)
self.outer_frame.pack()
self.canvas_frame = Frame(self.outer_frame)
# Labirinto em si
self.w = Canvas(self.canvas_frame, width = 660, height = 660)
self.canvas_frame.grid(row = 0, column = 0, rowspan = 2)
self.draw()
# Separadores para organização
self.separator_frame = Frame(self.outer_frame)
# self.outer_frame.grid_columnconfigure(1, minsize = 50)
# self.outer_frame.grid_columnconfigure(3, minsize = 50)
self.separator_frame.grid(row = 0, column = 1)
self.separator_frame.grid(row = 0, column = 3)
# Botões de setinhas
# self.arrows_frame = Frame(self.outer_frame)
# up = Button(self.arrows_frame, text = "Up", command = move_up)
# up.grid(row = 0, column = 1)
# up.config(height = 5, width = 10)
# right = Button(self.arrows_frame, text = "Right", command = move_right)
# right.grid(row = 1, column = 2)
# right.config(height = 5, width = 10)
# down = Button(self.arrows_frame, text = "Down", command = move_down)
# down.grid(row = 2, column = 1)
# down.config(height = 5, width = 10)
# left = Button(self.arrows_frame, text = "Left", command = move_left)
# left.grid(row = 1, column = 0)
# left.config(height = 5, width = 10)
# self.arrows_frame.grid(row = 0, column = 2)
# # Botões de paredes
# self.walls_frame = Frame(self.outer_frame)
# up_wall = Button(self.walls_frame, text = "Up Wall", command = toggle_wall_up)
# up_wall.grid(row = 0, column = 1)
# up_wall.config(height = 5, width = 10)
# right_wall = Button(self.walls_frame, text = "Right Wall", command = toggle_wall_right)
# right_wall.grid(row = 1, column = 2)
# right_wall.config(height = 5, width = 10)
# down_wall = Button(self.walls_frame, text = "Down Wall", command = toggle_wall_down)
# down_wall.grid(row = 2, column = 1)
# down_wall.config(height = 5, width = 10)
# left_wall = Button(self.walls_frame, text = "Left Wall", command = toggle_wall_left)
# left_wall.grid(row = 1, column = 0)
# left_wall.config(height = 5, width = 10)
# self.walls_frame.grid(row = 1, column = 2)
# Necessário para a GUI atualizar
self.master.update_idletasks()
self.master.update()
def draw(self): # Função que (re)desenha todo labirinto(não usar sempre, é lenta)
wall = "black"
cell = "white"
empty_wall = "light gray"
target_color = "red"
mouse_color = "yellow"
mouse_front = "green"
self.w.delete("all")
for j in range(16):
for i in range(16):
self.w.create_rectangle(40*i + 5, 40*j + 5, 40*i + 15, 40*j + 15, fill = wall, outline = wall)
if self.maze.maze[j][i]&1 != 0:
self.w.create_rectangle(40*i + 15, 40*j + 5, 40*i + 45, 40*j + 15, fill = wall, outline = wall)
else:
self.w.create_rectangle(40*i + 15, 40*j + 5, 40*i + 45, 40*j + 15, fill = empty_wall, outline = empty_wall)
self.w.create_rectangle(40*16 + 5, 40*j + 5, 40*16 + 15, 40*j + 15, fill = wall, outline = wall)
for i in range(16):
if self.maze.maze[j][i]&8 != 0:
self.w.create_rectangle(40*i + 5, 40*j + 15, 40*i + 15, 40*j + 45, fill = wall, outline = wall)
else:
self.w.create_rectangle(40*i + 5, 40*j + 15, 40*i + 15, 40*j + 45, fill = empty_wall, outline = empty_wall)
alvo = False
for target in self.maze.targets:
if target[0] == j and target[1] == i:
alvo = True
if self.maze.mouse.x == i and self.maze.mouse.y == j:
if self.maze.mouse.d == 1:
self.w.create_rectangle(40*i + 15, 40*j + 25, 40*i + 45, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 25, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 2:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 35, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 35, 40*j + 15, 40*i + 45, 40*j + 45, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 4:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 35, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 35, 40*i + 45, 40*j + 45, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 8:
self.w.create_rectangle(40*i + 35, 40*j + 15, 40*i + 45, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 35, 40*j + 45, fill = mouse_front, outline = mouse_front)
self.w.create_text(40*i + 30, 40*j + 30, text = 'M')
elif alvo:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 45, fill = target_color, outline = target_color)
else:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 45, fill = cell, outline = cell)
# self.w.create_text(40*i + 30, 40*j + 30, text = self.maze.cellValue[j][i]) # Mostra o valor das paredes na célula
self.w.create_rectangle(40*16 + 5, 40*j + 15, 40*16 + 15, 40*j + 45, fill = wall, outline = wall)
for i in range(16):
self.w.create_rectangle(40*i + 5, 40*16 + 5, 40*i + 15, 40*16 + 15, fill = wall, outline = wall)
self.w.create_rectangle(40*i + 15, 40*16 + 5, 40*i + 45, 40*16 + 15, fill = wall, outline = wall)
self.w.create_rectangle(40*16 + 5, 40*16 + 5, 40*16 + 15, 40*16 + 15, fill = wall, outline = wall)
self.w.pack()
def update(self): # Função usada para atualizar a GUI
self.master.update_idletasks()
self.master.update()
def update_cells(self, lista): # Atualiza apenas uma lista de células que foi mudada, bem mais rápido que todo o labirinto
cell = "white"
target_color = "red"
mouse_color = "yellow"
mouse_front = "green"
for [i, j] in lista:
alvo = False
for target in self.maze.targets:
if target[0] == j and target[1] == i:
alvo = True
if self.maze.mouse.x == i and self.maze.mouse.y == j:
if self.maze.mouse.d == 1:
self.w.create_rectangle(40*i + 15, 40*j + 25, 40*i + 45, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 25, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 2:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 35, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 35, 40*j + 15, 40*i + 45, 40*j + 45, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 4:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 35, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 35, 40*i + 45, 40*j + 45, fill = mouse_front, outline = mouse_front)
elif self.maze.mouse.d == 8:
self.w.create_rectangle(40*i + 25, 40*j + 15, 40*i + 45, 40*j + 45, fill = mouse_color, outline = mouse_color)
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 25, 40*j + 45, fill = mouse_front, outline = mouse_front)
self.w.create_text(40*i + 30, 40*j + 30, text = 'M')
elif alvo:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 45, fill = target_color, outline = target_color)
else:
self.w.create_rectangle(40*i + 15, 40*j + 15, 40*i + 45, 40*j + 45, fill = cell, outline = cell)
# self.w.create_text(40*i + 30, 40*j + 30, text = self.maze.cellValue[j][i]) # Mostra o valor das paredes na célula
self.master.update_idletasks()
self.master.update()
def update_wall(self, position, parede, add = 1): # Atualiza(adiciona ou remove) a situação de uma parede
wall = "black"
empty_wall = "light gray"
i = position[0]
j = position[1]
if add == 1:
if parede == 1:
self.w.create_rectangle(40*i + 15, 40*j + 5, 40*i + 45, 40*j + 15, fill = wall, outline = wall)
elif parede == 2:
self.w.create_rectangle(40*i + 45, 40*j + 15, 40*i + 55, 40*j + 45, fill = wall, outline = wall)
elif parede == 4:
self.w.create_rectangle(40*i + 15, 40*j + 45, 40*i + 45, 40*j + 55, fill = wall, outline = wall)
else:
self.w.create_rectangle(40*i + 5, 40*j + 15, 40*i + 15, 40*j + 45, fill = wall, outline = wall)
else:
if parede == 1:
self.w.create_rectangle(40*i + 15, 40*j + 5, 40*i + 45, 40*j + 15, fill = empty_wall, outline = empty_wall)
elif parede == 2:
self.w.create_rectangle(40*i + 45, 40*j + 15, 40*i + 55, 40*j + 45, fill = empty_wall, outline = empty_wall)
elif parede == 4:
self.w.create_rectangle(40*i + 15, 40*j + 45, 40*i + 45, 40*j + 55, fill = empty_wall, outline = empty_wall)
else:
self.w.create_rectangle(40*i + 5, 40*j + 15, 40*i + 15, 40*j + 45, fill = empty_wall, outline = empty_wall)
self.master.update_idletasks()
self.master.update()
|
# coding:utf-8
import urllib
import urllib2
def main():
# 设置请求头
req_headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36"
}
"""编码工作使用urllib的urlencode()函数,帮我们将key:value这样的键值对转换成"key=value"这样的字符串,
解码工作可以使用urllib的unquote()函数。(注意,不是urllib2.urlencode() )"""
keyword = raw_input("请输入要查询的内容:")
#只支持字典格式
word = {"wd" : keyword,
"ie":"utf-8"
}
#将中文转码
wd = urllib.urlencode(word)
print (wd)
# 设置baidu查询请求信息
url = "http://www.baidu.com/s?" + wd
request = urllib2.Request(url, headers=req_headers)
# 获取响应的内容
response = urllib2.urlopen(request)
# 读取出来
html_Reader = response.read()
file_write = open("baidu查询.html".decode("utf-8"), "wb")
try:
file_write.write(html_Reader)
except Exception as exc:
print (exc)
finally:
file_write.close()
if __name__ == "__main__":
main()
|
def insertion_sort(arr):
n = len(arr)
for i in range(1,n): #0. indeksi listenin en büyük elemanı olarak aldık.
key = arr[i] #key değişkeni temp görevinde kullanılır.
j = i-1 #sıralı kısmın son indeksindeki elemanını tutmuş oluyoruz.
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j = j-1
arr[j+1] = key #son veriyi doğru yere koymuş oluyoruz.
l1 = [3,10,2,6,5,9]
insertion_sort(l1)
for k in range(0,len(l1)):
print(l1[k])
print('\n\n\n')
def shell_sort(arr):
n = len(arr)
gap = n//2
while(gap > 0):
for i in range(gap,n):
temp = arr[i]
j = i
while j>=gap and arr[j-gap]>temp:
arr[j] = arr[j-gap]
j = j-gap
arr[j] = temp
gap = gap // 2
return arr
l2 = [15,2,55,33,15,20,147,85,6,1,5,8,9,122,5,4,3]
shell_sort(l2)
for k in range(0,len(l2)):
print(l2[k])
|
from bs4 import BeautifulSoup
import lxml
import urllib.request
from collections import Counter
from string import punctuation
# Store the website input as a variable and excecute BS4 on it
website = input("What is the URL you want to read faster? ")
web_page = urllib.request.urlopen(website)
soup = BeautifulSoup(web_page,"lxml")
# We get the words within all paragraphs
text_p = (''.join(s.findAll(text=True))for s in soup.findAll('p'))
c_p = Counter((x.rstrip(punctuation).lower() for y in text_p for x in y.split()))
# We get the words within divs
text_div = (''.join(s.findAll(text=True))for s in soup.findAll('div'))
c_div = Counter((x.rstrip(punctuation).lower() for y in text_div for x in y.split()))
# We sum the two countesr and get a list with words count from most to less common
total = c_div + c_p
tot_len = len(total)
print("There are", tot_len, "words on this page.")
word_spd_avg = tot_len/250
print("At the average reading speed, it would take you", word_spd_avg, "minutes to read this article.")
|
#!/usr/bin/python
from __future__ import print_function
import use_lldb_suite
import six
import sys
import time
class ProgressBar(object):
"""ProgressBar class holds the options of the progress bar.
The options are:
start State from which start the progress. For example, if start is
5 and the end is 10, the progress of this state is 50%
end State in which the progress has terminated.
width --
fill String to use for "filled" used to represent the progress
blank String to use for "filled" used to represent remaining space.
format Format
incremental
"""
light_block = six.unichr(0x2591).encode("utf-8")
solid_block = six.unichr(0x2588).encode("utf-8")
solid_right_arrow = six.unichr(0x25BA).encode("utf-8")
def __init__(self,
start=0,
end=10,
width=12,
fill=six.unichr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True):
super(ProgressBar, self).__init__()
self.start = start
self.end = end
self.width = width
self.fill = fill
self.blank = blank
self.marker = marker
self.format = format
self.incremental = incremental
self.step = 100 / float(width) # fix
self.reset()
def __add__(self, increment):
increment = self._get_progress(increment)
if 100 > self.progress + increment:
self.progress += increment
else:
self.progress = 100
return self
def complete(self):
self.progress = 100
return self
def __str__(self):
progressed = int(self.progress / self.step) # fix
fill = progressed * self.fill
blank = (self.width - progressed) * self.blank
return self.format % {
'fill': fill,
'blank': blank,
'marker': self.marker,
'progress': int(
self.progress)}
__repr__ = __str__
def _get_progress(self, increment):
return float(increment * 100) / self.end
def reset(self):
"""Resets the current progress to the start point"""
self.progress = self._get_progress(self.start)
return self
class AnimatedProgressBar(ProgressBar):
"""Extends ProgressBar to allow you to use it straighforward on a script.
Accepts an extra keyword argument named `stdout` (by default use sys.stdout)
and may be any file-object to which send the progress status.
"""
def __init__(self,
start=0,
end=10,
width=12,
fill=six.unichr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True,
stdout=sys.stdout):
super(
AnimatedProgressBar,
self).__init__(
start,
end,
width,
fill,
blank,
marker,
format,
incremental)
self.stdout = stdout
def show_progress(self):
if hasattr(self.stdout, 'isatty') and self.stdout.isatty():
self.stdout.write('\r')
else:
self.stdout.write('\n')
self.stdout.write(str(self))
self.stdout.flush()
class ProgressWithEvents(AnimatedProgressBar):
"""Extends AnimatedProgressBar to allow you to track a set of events that
cause the progress to move. For instance, in a deletion progress bar, you
can track files that were nuked and files that the user doesn't have access to
"""
def __init__(self,
start=0,
end=10,
width=12,
fill=six.unichr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True,
stdout=sys.stdout):
super(
ProgressWithEvents,
self).__init__(
start,
end,
width,
fill,
blank,
marker,
format,
incremental,
stdout)
self.events = {}
def add_event(self, event):
if event in self.events:
self.events[event] += 1
else:
self.events[event] = 1
def show_progress(self):
isatty = hasattr(self.stdout, 'isatty') and self.stdout.isatty()
if isatty:
self.stdout.write('\r')
else:
self.stdout.write('\n')
self.stdout.write(str(self))
if len(self.events) == 0:
return
self.stdout.write('\n')
for key in list(self.events.keys()):
self.stdout.write(str(key) + ' = ' + str(self.events[key]) + ' ')
if isatty:
self.stdout.write('\033[1A')
self.stdout.flush()
if __name__ == '__main__':
p = AnimatedProgressBar(end=200, width=200)
while True:
p + 5
p.show_progress()
time.sleep(0.3)
if p.progress == 100:
break
print() # new line
|
"""
As a software developer at Spotify, you've been asked to re-implement their playlist structure into a Linked List
structure. You've been told that along with displaying the current song in the playlist, listeners must also be able to
go back a song and skip to the next song.
You'll first need to create the playlist from a text file. The text file is in the format of Song Title, Artist.
This is the solution version for the Spotify Playlist.
Created by Emma Lubes, eml5244, for the Academic Success Center Supplemental Instruction Program.
"""
from dataclasses import dataclass
from typing import Any, Union
# TODO: Create the dataclass for you linked node structure.
# Hint: Keep in mind whether or not the structure should be able to change!
@dataclass(frozen=True)
class LinkedNode:
value: Any
next: Union["LinkedNode", None]
"""
Reads through the file to end up with a list of song dictionaries
e.g. [{"Sandstorm", Darude}, {"All Star", Smash Mouth}]
"""
def read_file(filename):
all_songs = []
with open(filename) as f:
# TODO: Iterate through the file, put each song and artist into their own dictionary, and then append the
# TODO: dictionary to the full list of songs
for line in f:
song_info = {}
line = line.strip().split(", ")
song = line[0]
artist = line[1]
song_info[song] = artist
all_songs.append(song_info)
return all_songs
def main():
read_file("playlist.txt")
main()
|
import random
def main():
number_of_quick_picks = int(input("How many quick picks? "))
for i in range(0, number_of_quick_picks):
quick_pick = generate_quick_pick()
print(
"{:2} {:2} {:2} {:2} {:2}".format(quick_pick[0], quick_pick[1], quick_pick[2], quick_pick[3],
quick_pick[4]))
def generate_quick_pick():
length = 45
quick_pick = []
for i in range(0, 6):
random_number = [random.randint(1, length)]
while random_number[0] in quick_pick:
random_number = [random.randint(1, length)]
quick_pick = quick_pick + random_number
quick_pick.sort()
return quick_pick
main()
|
"""
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
when input value is not of the correct data type during a mathematical operation
making said operation impossible
2. When will a ZeroDivisionError occur?
when attempting to divide by zero, as it is an indefinite number
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
print("cannot divide by 0")
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
# except ZeroDivisionError:
# print("Cannot divide by zero!")
print("Finished.")
|
import itertools
class Environment:
"""
This class is responsible for modelling the sample space of the problem.
"""
def __init__(self, a):
self.address_list = a
self.sample_space = list()
def create(self):
for item in itertools.permutations(self.address_list):
self.sample_space.append(item)
def get_sample_space(self):
return self.sample_space
|
# 링크드리스트를 이용한 중복값 대처
class LinkedTuple:
def __init__(self):
self.items = list()
def add(self, key, value):
self.items.append((key, value))
def get(self, key):
for k, v in self.items: # items for문을 돌렸을때
if key == k: # 내가 찾고자 하는값이 동일할경우
return v # 해당 값을 반환해라
# 충돌방지
class LinkedDict:
def __init__(self):
self.items = [] # [Linked Tuple() 이 8개 들어가있음 ]
for i in range(8):
self.items.append(LinkedTuple())
def put(self, key, value):
index = hash(key) % len(self.items) #이전에 했던것처럼 index값을 먼저 생성
self.items[index].add(key,value) #이미 Linkedtuple에서 .add 메소드를 생성
def get(self, key):
index = hash(key) % len(self.items)
return self.items[index].get(key)
|
import random
print("Welkom bij het raad spel")
score = 0
for x in range(20):
if x != 0 and x != 19:
nogEens = input("Wil je nog eens raden (Y/N) ").lower()
if nogEens == "n":
print("Ok vaarwel")
exit()
print("Ronde " + str(x+1))
rndNumber = random.randint(1,10)
for y in range(10):
print("")
print("Poging " + str(y+1))
raade = int(input("Wat denk je dat het getal is? Of als je wilt stoppen type -1 "))
if raade == -1:
exit()
print("Je hebt {} geraden".format(raade))
if raade == rndNumber:
print("Hoera je hebt het geraden, +1 score")
score += 1
break
if abs(raade - rndNumber) <= 20:
print("Je bent heel warm")
elif abs(raade - rndNumber) <= 50:
print("Je bent warm")
if raade > rndNumber:
print("Lager")
if raade < rndNumber:
print("Hoger")
if y == 9:
print("Je hebt het helaas niet geraden volgende ronde")
print("")
print("Score is " + str(score))
|
from random import randint
if __name__ == '__main__':
P = 23 # modulus
G = 5 # base
print('The Value of P is :%d'%(P))
print('The Value of G is :%d'%(G))
# Alice will choose the private key a
a = randint(1,9)
print('The Private Key a for Alice is :%d'%(a))
# key
#pow() with three arguments (x**y) % z
x = int(pow(G,a,P)) # G**a mod P
# Bob will choose the private key b
b = randint(1,9)
print('The Private Key b for Bob is :%d'%(b))
# key
y = int(pow(G,b,P))
# Secret key for Alice
ka = int(pow(y,a,P))
# Secret key for Bob
kb = int(pow(x,b,P))
print('Secret key for Alice is : {}'.format(ka))
print('Secret Key for Bob is : {}'.format(kb))
'''
Step 1: Alice and Bob get public numbers P = 23, G = 9
Step 2: Alice selected a private key a = 4 and
Bob selected a private key b = 3
Step 3: Alice and Bob compute public values
Alice: x =(9^4 mod 23) = (6561 mod 23) = 6
Bob: y = (9^3 mod 23) = (729 mod 23) = 16
Step 4: Alice and Bob exchange public numbers
Step 5: Alice receives public key y =16 and
Bob receives public key x = 6
Step 6: Alice and Bob compute symmetric keys
Alice: ka = y^a mod p = 65536 mod 23 = 9
Bob: kb = x^b mod p = 216 mod 23 = 9
Step 7: 9 is the shared secret
''' |
#! /usr/bin/python3
from typing import List
import tokenizer
import parser
def tokenize_orig(contents):
list = []
i = 0
while(i != len(contents)-1):
c = contents[i]
if c == ' ' or c == '\t':
i += 1
continue
if c == '{' or c == '}':
list.append(c)
if c == '[' or c == ']':
list.append(c)
if c == ',':
list.append(c)
if c == '"' or c == "'":
quotation_char = c
word = ""
# extract word between quotation
while True:
i += 1
word += contents[i]
if contents[i+1] == quotation_char:
i += 1
break
list.append(word)
if c == ':':
list.append(c)
i += 1
return list
def main():
with open('./test.json') as f:
contents = f.read()
# print(contents)
list: List[tokenizer.Token] = tokenizer.tokenize(contents)
# for i, l in enumerate(list):
# print('#{}: {} '.format(i, l))
obj = parser.parse_main(list, 0)
print(obj)
def check_token():
with open('./test.json') as f:
contents = f.read()
list: List[tokenizer.Token] = tokenizer.tokenize(contents)
for i, l in enumerate(list):
print('#{}: {} '.format(i, l))
if __name__ == '__main__':
main()
|
'''
498. Diagonal Traverse
Medium
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Solution:
Get the diagonal sequence as the original sequences first, then reverse the even rows and form them all into one list.
Relatively simple.
'''
class Solution(object):
def findDiagonalOrder(self, matrix):
if not matrix:
return []
if not matrix[0]:
return []
M = len(matrix)
N = len(matrix[0])
if N == 1:
rst = []
for i in matrix:
rst += i
return rst
#Do a traverse from the top left point to the bottom right point
#And construct the original sequence.
sequence = []
for i in range(N):
tmp = []
currentNode = [0, i]
while currentNode[1] >= 0 and currentNode[0] < M:
tmp.append(matrix[currentNode[0]][currentNode[1]])
currentNode[0] += 1
currentNode[1] -= 1
sequence.append(tmp)
for i in range(1, M):
tmp = []
currentNode = [i, N - 1]
while currentNode[0] < M and currentNode[1] >= 0:
tmp.append(matrix[currentNode[0]][currentNode[1]])
currentNode[0] += 1
currentNode[1] -= 1
sequence.append(tmp)
rst = []
for i in range(len(sequence)):
if not i % 2:
rst += sequence[i][::-1]
else:
rst += sequence[i]
return rst
S = Solution()
matrix = [[2,5],[8,4],[0,-1]]
print S.findDiagonalOrder(matrix) |
'''
780. Reaching Points
Hard
A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).
Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.
Examples:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: True
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: False
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: True
Solution:
Reverse thinking. Instead of computing sx and sy, we can compute the tx and ty but
subtract to each other.
Simply different angles of observing the question can bring us the easier solution.
There are only two kinds of operations, x,y -> x+y,y or x,y -> x,x+y, so at the end
result, we can transform them into x,y -> x-y,y or x,y -> x,y-x, in this case, we do not
have too many cases to verify, since all of them should follow the procedure.
'''
'''
class Solution(object):
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
def solve(tx,ty):
if tx<sx or ty<sy: return False
if tx==sx: return True if (ty-sy)%sx==0 else False
if ty==sy: return True if (tx-sx)%sy ==0 else False
return solve(tx-ty,ty)|solve(tx,ty-tx)
return solve(tx,ty)
'''
class Solution(object):
def reachingPoints(self, sx, sy, tx, ty):
if sx == tx and sy == ty:
return True
if tx == 0 or ty == 0:
return False
if tx == sx:
if (ty-sy) % sx == 0 or ty % sx == 0:
return True
if ty == sy:
if (tx-sx) % sy == 0 or tx % sy == 0:
return True
if tx > ty:
return self.reachingPoints(sx,sy,tx-ty,ty)
else:
return self.reachingPoints(sx,sy,tx,ty-tx)
return True
if __name__ == '__main__':
s = Solution()
print s.reachingPoints(1,2,1000000000000,2) |
'''
518. Coin Change 2
Medium
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
SolutionL
Another DP problem, only change is to find how many ways to form such amount of money by the coins,
which is like dungeon game, bottom-up algorithm.
'''
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
arr = [0] * (amount + 1)
index = 0
arr[0] = 1
while index < len(coins):
for i in range(amount+1):
if arr[i] != 0 and i + coins[index] < (amount+1):
arr[i+coins[index]] += arr[i]
index += 1
return arr[-1]
s = Solution()
coins = [1,2,5]
s.change(100,coins) |
'''
814. Binary Tree Pruning
Medium
We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
Example 1:
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.
Example 2:
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
Solution:
Just use recursive, check for each subtree, if not containing any one, set the current node
to None.
Very simple recusive problems.
'''
class TreeNode(object):
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def contain_one(self,root):
if root is None:
return False
if root.val == 1:
return True
else:
if root.left is None:
if root.right is None:
return False
return self.contain_one(root.right)
else:
if root.right is None:
return self.contain_one(root.left)
return self.contain_one(root.right) or self.contain_one(root.left)
def pruneTree(self, root):
if not self.contain_one(root):
root = None
else:
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
return root
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(0)
root.left.left = TreeNode(0)
root.left.left = TreeNode(0)
root.right = TreeNode(1)
root.right.left = TreeNode(0)
root.right.right = TreeNode(1)
s = Solution()
root1 = s.pruneTree(root)
def printT(root):
if root is not None:
printT(root.left)
print root.val
printT(root.right)
printT(root1)
printT(root)
|
'''
1072. Flip Columns For Maximum Number of Equal Rows
Medium
Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.
Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.
Solution:
Every row can be transfered to start with 0.
If a row already starts with 0, great, maintain that, if it starts with 1, flip every elemtn
in this row.
Then we simply count the times that each form appears, then return the max apperance time.
'''
class Solution(object):
def maxEqualRowsAfterFlips(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
construct = {}
for i in matrix:
tmp = ''
if i[0] == 0:
for k in i:
tmp += str(k)
else:
for k in i:
tmp += str(1-k)
if tmp in construct:
construct[tmp] += 1
else:
construct[tmp] = 1
return max(construct.values())
if __name__ == '__main__':
s = Solution()
matrix = [[0,0,0],[0,0,1],[1,1,0]]
print s.maxEqualRowsAfterFlips(matrix) |
'''
Method 1: DP algorithm with O(n) time and O(1) space
For each day, there are 3 possible actions: buy, sell, nothing. Let us define
buy[i] = maxProfit of prices[:i+1] with the action buy at day i,
sell[i] = maxProfit of prices[:i+1] with the action sell at day i,
nothing[i] = maxProfit of prices[:i+1] with the action nothing at day i.
The base cases are buy[0] = -prices[0], sell[0] = nothing[0] = 0.
The recursive relationships are
buy[i] = max(nothing[i-1] - prices[i], buy[i-1])
# if buy at day i then the action at day i-1 must be nothing
sell[i] = max(buy[i-1]+prices[i], sell[i-1])
nothing[i] = max(sell[i-1], buy[i-1], nothing[i-1]).
'''
# Insightful approach
def maxProfit(self, prices):
if n < 2:
return 0
prev_buy, prev_sell, prev_nothing = -prices[0], 0, 0
for i in range(1, n):
buy = max(prev_nothing - prices[i], prev_buy)
sell = max(prev_buy + prices[i], prev_sell)
nothing = max(prev_sell, prev_buy, prev_nothing)
prev_buy, prev_sell, prev_nothing = buy, sell, nothing
return max(sell, nothing)
|
'''
846. Hand of Straights
Medium
Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.
Solution:
Since we have to make every card to be part of one group with size w, we have to form each of the element
into a group.
Simple approach is sort the list first, then start iteration.
For each iteration, we extract the first element `tmp` of the remaining cards, them find all elements that
are in the same grouop as tmp, so we find tmp+1, tmp+2....tmp+w, and we remove them.
If any of the above element is not in the remaining cards, retrun False.
Then start a new iteration, repeat the operations until the cards are empty. Return True at the end.
'''
class Solution(object):
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
if len(hand) < W:
return False
hand = sorted(hand)
while hand:
tmp = hand[0]
for k in range(W):
if tmp+k not in hand:
return False
else:
hand.remove(tmp+k)
return True
if __name__ == '__main__':
s = Solution()
hand = [1,2,3,6,2,3,4,7,8]
w = 3
print s.isNStraightHand(hand,w) |
'''
845. Longest Mountain in Array
Medium
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Solution:
When I tried to use expand center, TLE, sad.
The solution below is one-pass solution, very smart and intuitive.
Start from the beginning, go over the array to find longest potential mountain.
If the current number is smaller than the next one, increase the current index by 1, for
this is a potential left part of a mountain. Use a while loop to find the whole left part
of the mountain.
Then we have the peak, continue the index increasing, once an element is bigger than the next
one, plus 1, again use a while loop to find the right most point that is potential part of the
mountain.
Then update the base and answer. Base means the first index of a mountain.
Two while loop is very efficient and smart. Can solve the proble in one-pass iteration.
Also the procedure can be regarded greedy however not so greedy, since one mountain can not overlap
with another mountain, so the longest mountain we have found, stays seperated.
'''
class Solution(object):
def longestMountain(self, A):
N = len(A)
ans = base = 0
while base < N:
end = base
if end + 1 < N and A[end] < A[end + 1]: #if base is a left-boundary
#set end to the peak of this potential mountain
while end+1 < N and A[end] < A[end+1]:
end += 1
if end + 1 < N and A[end] > A[end + 1]: #if end is really a peak..
#set 'end' to right-boundary of mountain
while end+1 < N and A[end] > A[end+1]:
end += 1
#record candidate answer
ans = max(ans, end - base + 1)
base = max(end, base + 1)
return ans
if __name__ == '__main__':
s = Solution()
A = [2,1,4,7,3,2,5]
print s.longestMountain(A)
|
'''
538. Convert BST to Greater Tree
Easy
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
Solution:
Simple traverse. Recursive is very slow, maybe iteration can do better job.
'''
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def convertBST(self, root):
self.currentVal = 0
"""
:type root: TreeNode
:rtype: TreeNode
"""
def traverseAdd(root):
if not root:
return
traverseAdd(root.right)
self.currentVal += root.val
root.val = self.currentVal
traverseAdd(root.left)
traverseAdd(root)
return root
def traverse(root):
if not root:
return
traverse(root.left)
print root.val,
traverse(root.right)
s = Solution()
root = TreeNode(7)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.left.left = TreeNode(1)
root.left.right = TreeNode(5)
root.left.right.left = TreeNode(4)
root.right = TreeNode(11)
root.right.left = TreeNode(9)
root.right.left.left = TreeNode(8)
root.right.left.right = TreeNode(10)
root.right.right = TreeNode(13)
root.right.right.left = TreeNode(12)
root.right.right.right = TreeNode(14)
traverse(s.convertBST(root)) |
'''
1143. Longest Common Subsequence
Medium
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Solution:
Classic DP problem.
If i and j equals, plus 1 to the [i-1][j-1]
If not, find the max of [i-1][j] and [i][j-1].
'''
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
dp = [[0 for i in xrange(len(text2)+1)] for k in xrange(len(text1)+1)]
for i in range(len(text1)):
for j in range(len(text2)):
if text1[i] == text2[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1])
return dp[-1][-1]
s = Solution()
print s.longestCommonSubsequence("abcde","ab") |
'''
76. Minimum Window Substring
Hard
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
Solution:
Use two pointers.
One left pointer and one right pointer, combine the two pointers can give us a substring starts
at left, and ends in right.
Maintain the counter of t, modify the dictionary or counter while go through each combinartion of
left and right.
If the right pointer has come to the tail of the s string, stop and return the minString.
Not fast but solvable.
'''
class Solution(object):
def minWindow(self, s, t):
from collections import Counter
length_t = len(t)
left = right = 0
t_dict = Counter(t)
s_dict = Counter(s)
string_min = s
for i in t_dict:
if t_dict[i] > s_dict[i]:
return ''
while left <= len(s) - len(t):
signal = 0
while max(t_dict.values()) > 0:
if right >= len(s):
signal = 1
break
if s[right] in t:
t_dict[s[right]] -= 1
right += 1
if signal:
return string_min
if len(string_min) > right - left:
string_min = s[left:right]
if s[left] in t:
t_dict[s[left]] += 1
left += 1
return string_min
if __name__ == '__main__':
S = Solution()
s = "ADOBECODEBANC"
t = "ABC"
print S.minWindow(s,t) |
def find_next(sudoku, i, j):
for i in range(i,9):
for k in range(j,9):
if sudoku[i][k] == 0:
return i,k
return -1,-1
def isValid(sudoku, i, j):
nums = all([e != grid[i][x] for x in range(9)])
print nums
if __name__ == '__main__':
sudoku = [[5,1,7,6,0,0,0,3,4],[2,8,9,0,0,4,0,0,0],[3,4,6,2,0,5,0,9,0],[6,0,2,0,0,0,0,1,0],[0,3,8,0,0,6,0,4,7],[0,0,0,0,0,0,0,0,0],[0,9,0,0,0,0,0,7,8],[7,0,3,4,0,0,5,6,0],[0,0,0,0,0,0,0,0,0]]
|
'''
640. Solve the Equation
Medium
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
Solution:
The only fun part of this problem is to replace '-' to '+-', then we can parse the string by simply split it by '+'.
Determine 1 and -1 is tricky and bothering.
'''
class Solution(object):
def solveEquation(self, equation):
equation = equation.replace('-', '+-')
leftPoly, rightPoly = equation.split('=')
leftPolyParams = leftPoly.split('+')
currentX = 0
currentConst = 0
for i in leftPolyParams:
if i == '':
continue
if i[-1] == 'x':
if i[:len(i)-1] == '':
currentX += 1
elif i[:len(i)-1] == '-':
currentX -= 1
else:
currentX += int(i[:len(i)-1])
else:
currentConst += int(i)
rightPolyParams = rightPoly.split('+')
for i in rightPolyParams:
if i == '':
continue
if i[-1] =='x':
if i[:len(i)-1] == '':
currentX -= 1
elif i[:len(i)-1] == '-':
currentX += 1
else:
currentX -= int(i[:len(i)-1])
else:
currentConst -= int(i)
if currentX == 0 and currentConst == 0:
return "Infinite solutions"
elif currentX == 0:
return "No solution"
value = (-1) * (currentConst / currentX)
return "x=" + str(value)
s = Solution()
equation = "-x=x+2"
print s.solveEquation(equation) |
'''
971. Flip Binary Tree To Match Preorder Traversal
Medium
Given a binary tree with N nodes, each node has a different value from {1, ..., N}.
A node in this binary tree can be flipped by swapping the left child and the right child of that node.
Consider the sequence of N values reported by a preorder traversal starting from the root. Call such a sequence of N values the voyage of the tree.
(Recall that a preorder traversal of a node means we report the current node's value, then preorder-traverse the left child, then preorder-traverse the right child.)
Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyage we are given.
If we can do so, then return a list of the values of all nodes flipped. You may return the answer in any order.
If we cannot do so, then return the list [-1].
Example 1:
Input: root = [1,2], voyage = [2,1]
Output: [-1]
Example 2:
Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]
Example 3:
Input: root = [1,2,3], voyage = [1,2,3]
Output: []
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flipMatchVoyage(self, root, voyage):
"""
:type root: TreeNode
:type voyage: List[int]
:rtype: List[int]
"""
preorder = []
def traverse(root):
if not root:
return
preorder.append(root.val)
traverse(root.left)
traverse(root.right)
traverse(root)
def determineSwap(root, preorderList, givenOrder):
if len(preorderList) != len(givenOrder) or not preorderList or not givenOrder:
return -1
if preorderList[0] != givenOrder[0]:
return -1
if not root.left and not root.right:
return []
elif not root.left:
return determineSwap(root.right, preorderList[1:], givenOrder[1:])
elif not root.right:
return determineSwap(root.left, preorderList[1:], givenOrder[1:])
rightIndex = preorderList.index(root.right.val)
if preorderList[1] == givenOrder[1]:
if preorderList[rightIndex] == givenOrder[rightIndex]:
swapLeftNodes = determineSwap(root.left, preorderList[1:rightIndex], givenOrder[1:rightIndex])
swapRightNodes = determineSwap(root.right, preorderList[rightIndex:], givenOrder[rightIndex:])
if swapLeftNodes == -1 or swapRightNodes == -1:
return -1
return swapLeftNodes + swapRightNodes
else:
return -1
elif preorderList[1] == givenOrder[len(givenOrder) - rightIndex + 1]:
if preorderList[rightIndex] == givenOrder[1]:
swapLeftNodes = determineSwap(root.left, preorderList[1:rightIndex], givenOrder[len(givenOrder) - rightIndex + 1:])
swapRightNodes = determineSwap(root.right, preorderList[rightIndex:], givenOrder[1:len(givenOrder) - rightIndex + 1])
if swapLeftNodes == -1 or swapRightNodes == -1:
return -1
return [root.val] + swapLeftNodes + swapRightNodes
else:
return -1
else:
return -1
rst = determineSwap(root, preorder, voyage)
if rst == -1:
return [-1]
else:
return rst
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(8)
s = Solution()
#Acutall = [1,2,4,5,3,6,8]
voyage = [1,3,8,6,2,5,4]
print s.flipMatchVoyage(root, voyage) |
'''
79. Word Search
Medium
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
Solution:
Another classic backtrack problem. The trick here is to set the character that has
passed before to invalid or illegal character.
Should write this easily.
'''
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
from collections import deque
def isValid(row, col):
if 0 <= row < len(board) and 0 <= col < len(board[0]):
return True
return False
def backtrack(row, col, index):
if index == len(word):
return True
diff_x = [0,0,1,-1]
diff_y = [1,-1,0,0]
res = False
for i in range(4):
current_row = diff_x[i] + row
current_col = diff_y[i] + col
if isValid(current_row, current_col):
if board[current_row][current_col] == word[index]:
tmp = board[row][col]
board[row][col] = '#'
if backtrack(current_row, current_col, index + 1):
res = True
break
board[row][col] = tmp
return res
for i in range(len(board)):
for k in range(len(board[0])):
if board[i][k] == word[0]:
tmp = board[i][k]
board[i][k] = '#'
if backtrack(i,k,1):
return True
board[i][k] = tmp
return False
if __name__ == '__main__':
board = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]
word = 'ABCCED'
s = Solution()
print s.exist(board, word)
|
'''
552. Student Attendance Record II
Hard
Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109 + 7.
A student attendance record is a string that only contains the following three characters:
'A' : Absent.
'L' : Late.
'P' : Present.
A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).
Example 1:
Input: n = 2
Output: 8
Explanation:
There are 8 records with length 2 will be regarded as rewardable:
"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
Only "AA" won't be regarded as rewardable owing to more than one absent times.
Solution:
Recurrence formula:
Let Q(n) be the solution of the the question, namely the number of all rewardable records.
Let R(n) be the number of all rewardable records without A.
Thinking the problem as replacing Ps and As on an array of Ls instead. Since the constraint is no more than 3 continuous Ls is allowed. For a n-size array, let's just look into the first 3 places, since there must be at least on replacement been taken place there:
First, let's consider the case we replacing with P. There're 3 cases:
P??: meaning we replace the first L with P. Doing so will shrink the problem size by one, so the number of this case is Q(n-1);
LP?: meaning we replace the second L with P. The first place got to be L since the case where P in the first place is being considered above. So the number of this case is Q(n-2);
LLP: meaning we replace the third L with P. Leaving us the number of Q(n-3);
Now let's consider the case we replacing with A:
A??: This we narrow down the problem size by one, and for the rest places there must be no As. So the number is R(n-1);
LA?: this will be R(n-2);
LLA: this will be R(n-3);
It's easy to see that the recurrence formula of R is just similar to the first 3 cases combined, namely:
R(n) = R(n-1) + R(n-2) + R(n-3)
So the recurrence formula of Q is:
Q(n) = Q(n-1) + Q(n-2) + Q(n-3) + R(n-1) + R(n-2) + R(n-3)
= Q(n-1) + Q(n-2) + Q(n-3) + R(n)
'''
from collections import deque
class Solution(object):
def checkRecord(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 1000000007
withA = deque([1, 3, 8])
withoutA = deque([1, 2, 4])
if n < 3:
return withA[n]
for i in range(3, n+1):
withoutA.append(sum(withoutA) % MOD)
withA.append((sum(withA) + withoutA[-1]) % MOD)
withoutA.popleft()
withA.popleft()
return withA[-1]
s = Solution()
s.checkRecord(10) |
'''
3. Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution:
My original solution is brute force with set usage. Not efficient but solved the problem.
The efficient algorithm use list's function find. When there's no target in the list, the find
function would return -1.
We first initialize the curlen to be 0, in the iteration, the s[i-curlen:i] is the length of
string with distinct characters with the before element.
So, s[i-curlen:i] is the max length of the string with non-repeated characters
Then we call the find function, s[i-curlen:i].find(num), which means that find the same character
in the previous string. If not found, the function would return -1, if not, it will return the
relative position(The first element is 0, second is 1, ignore the original index).
So the curlen[i] - s[i-curlen:i].find(num) which means the current string length with non-repeated characters,
because it is the previous length minus the position where the same character appeared.
Then make the maxlen to be the bigger one in the two lenth.
'''
def lengthOfLongestSubstring_efficient(s):
curlen = maxlen = 0
for i,num in enumerate(s):
print curlen,i,num
curlen -= s[i-curlen:i].find(num)
maxlen = max(maxlen,curlen)
return maxlen
def lengthOfLongestSubstring_window(s):
window = 0
first,second = 0,0
while second <= len(s):
if len(s[first:second]) == len(set(s[first:second])):
window = max(second-first,window)
second += 1
else:
second -= 1
window = max(second-first,window)
first += 1
return window
if __name__ == '__main__':
s = "abcabcbb"
print lengthOfLongestSubstring_efficient(s) |
'''
861. Score After Flipping Matrix
Medium
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Solution:
There are only two kinds of move, flip the whole column or whole row.
For the row flip, we change each digit in the same row, however we flip this row, the bigger number would be 1 being the first digit.
Since the digits are only consist of 0 and 1, once we flip the whole row, we flip the first digit, and with the bigger first digit, we
can always find the bigger number with the exact same one.
For the column flip, we change every number on the same digit. For this flip, we could decide which can bring us the bigger score, flip the
column or stays the same. We do not consider the original numbers since the digits have same base, to decide flip or not, we can simply
count how many 1s would there be after the operations.
To simplify the decision, we can count the numbers of 1s and 0s for each column, and add the bigger number * base to the score.
To solve the problem, first iterate through the A list, determine whether the number should be flipped. Then go over every column, to find
the bigger number of 1s and 0s.
'''
class Solution(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A:
return 0
for i in A:
if i[0] == 0:
for k in range(len(i)):
i[k] = 1-i[k]
score = 0
for i in range(len(A[0])):
cntZero = 0
cntOne = 0
for k in range(len(A)):
if A[k][i] == 1:
cntOne += 1
else:
cntZero += 1
currentBase = pow(2, len(A[0]) - 1 - i)
score += (currentBase * max(cntZero, cntOne))
return score
A = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
s = Solution()
print s.matrixScore(A) |
'''
202. Happy Number
Easy
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Solution:
Use set to record the appeared number.
'''
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
if n == 1:
return True
appeared = set([n])
while n != 1:
digits = str(n)
nextNum = 0
for i in digits:
nextNum += int(i) * int(i)
if nextNum in appeared:
return False
appeared.add(nextNum)
n = nextNum
return True
s = Solution()
print s.isHappy(20) |
'''
25. Reverse Nodes in k-Group
Hard
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
Solution:
Put every node into a list, reverse them in groups with k length.
Or when we put the value into the list, we do the reverse ahead.
Another solution is Recursion, very efficient.
Reverse the first K node, and then call the reverseKGroup function on the current node's next
node. Point the current node to the function's return node.
Very intuitive method.
'''
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
arr = []
if head is None:
return None
while head is not None:
arr.append(head.val)
head = head.next
rst = []
for i in range(len(arr)/k+1):
tmp_arr = arr[i*k:(i+1)*k]
if tmp_arr != [] and len(tmp_arr) == k:
tmp_arr.reverse()
rst += tmp_arr
rst_node = ListNode(rst[0])
result = rst_node
for i in range(1,len(rst)):
rst_node.next = ListNode(rst[i])
rst_node = rst_node.next
return result
if __name__ == '__main__':
s = Solution()
head = ListNode(1)
x = head
for i in range(2,10):
head.next = ListNode(i)
head = head.next
print s.reverseKGroup(x,4) |
'''
828. Unique Letter String
Hard
A character is unique in string S if it occurs exactly once in it.
For example, in string S = "LETTER", the only unique characters are "L" and "R".
Let's define UNIQ(S) as the number of unique characters in string S.
For example, UNIQ("LETTER") = 2.
Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S.
If there are two or more equal substrings at different positions in S, we consider them different.
Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.
Example 1:
Input: "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
Input: "ABA"
Output: 8
Explanation: The same as example 1, except uni("ABA") = 1.
Solution:
Intuition:
Let's think about how a character can be found as a unique character.
Think about string "XAXAXXAX" and focus on making the second "A" a unique character.
We can take "XA(XAXX)AX" and between "()" is our substring.
We can see here, to make the second "A" counted as a uniq character, we need to:
insert "(" somewhere between the first and second A
insert ")" somewhere between the second and third A
For step 1 we have "A(XA" and "AX(A", 2 possibility.
For step 2 we have "A)XXA", "AX)XA" and "AXX)A", 3 possibilities.
So there are in total 2 * 3 = 6 ways to make the second A a unique character in a substring.
In other words, there are only 6 substring, in which this A contribute 1 point as unique string.
Instead of counting all unique characters and struggling with all possible substrings,
we can count for every char in S, how many ways to be found as a unique char.
We count and sum, and it will be out answer.
Explanation:
index[26][2] record last two occurrence index for every upper characters.
Initialise all values in index to -1.
Loop on string S, for every character c, update its last two occurrence index to index[c].
Count when loop. For example, if "A" appears twice at index 3, 6, 9 seperately, we need to count:
For the first "A": (6-3) * (3-(-1))"
For the second "A": (9-6) * (6-3)"
For the third "A": (N-9) * (9-6)"
Complexity:
One pass, time complexity O(N).
Space complexity O(1).
Since the problem is asking for each character's distinct subarray, the solution works.
I think this is a math problem.
Below is my dp solution, TLE but I think it is working, just not this case.
'''
class Solution(object):
def uniqueLetterString(self, S):
import string
index = {}
res = 0
for i, c in enumerate(S):
k, j = index.setdefault(c, [-1,-1])
res += (i - j) * (j - k)
index[c] = [j, i]
for c in index:
k, j = index[c]
res += (len(S) - j) * (j - k)
return res % (10**9 + 7)
'''
class Solution(object):
def uniqueLetterString(self, S):
"""
:type S: str
:rtype: int
"""
if not S:
return 0
import copy
from collections import Counter
initial = Counter()
initial[S[0]] = 1
previousCounters = [initial]
arr = [[0 for i in S] for k in S]
arr[0][0] = 1
for i in range(1,len(S)):
counterNow = copy.deepcopy(previousCounters[-1])
counterNow[S[i]] += 1
if counterNow[S[i]] == 1:
arr[0][i] = arr[0][i-1] + 1
elif counterNow[S[i]] == 2:
arr[0][i] = arr[0][i-1] - 1
else:
arr[0][i] = arr[0][i-1]
previousCounters.append(counterNow)
for i in range(1,len(S)):
char = S[i-1]
for counterIndex in range(i, len(S)):
counter = previousCounters[counterIndex]
counter[char] -= 1
if counter[char] == 1:
arr[i][counterIndex] = arr[i-1][counterIndex] + 1
elif counter[char] == 0:
arr[i][counterIndex] = arr[i-1][counterIndex] - 1
else:
arr[i][counterIndex] = arr[i-1][counterIndex]
rst = 0
for i in arr:
rst += sum(i)
return rst % (pow(10,9) + 7)
'''
s = Solution()
S = "ABA"
print s.uniqueLetterString(S) |
'''
42. Trapping Rain Water
Hard
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Solution:
We maintain two max value and two pointers on left and right side. Use the iteration on this one.
Not DP solution, simple two pointers.
If the current left is less than current right value, which means that the left value should be
processed, because we have to determine which is the lower boarder of the that we need to compute
the current trapped water.
If the left is lower, update the left_max if needed, if the left_max is updated, don't compute the
ans(don't add.), if not, which means the current height is lower than the left_max, then there would
be some trapped water, add the amount to the global variable.
Very intuitive, should review this in the future.
'''
class Solution(object):
ans = 0
def trap(self,height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
while left < right:
if height[left] < height[right]:
if left_max <= height[left]:
left_max = height[left]
else:
self.ans += (left_max - height[left])
left += 1
else:
if right_max <= height[right]:
right_max = height[right]
else:
self.ans += (right_max - height[right])
right -= 1
return self.ans
if __name__ == '__main__':
height = [0,1,0,2,1,0,1,3,2,1,2,1]
#[0,1,0,2,1,0,1,3,2,1,2,1]
index = 2
s = Solution()
print s.trap(height) |
import random
instructions = '''
Programming Assignment 2:
DIRECTED ACYCLIC GRAPHS
This program takes as input a directed graph and outputs information about the graph.
INPUTS
======
- A positive integer n, the number of vertices in the graph:
the names of the vertices will be 1, 2, 3, ..., n.
- The next few lines will contain the edges of the graph as
i, j
where 1 <= i <=n and 1 <= j <= n and i != j.
Example of valid input:
5
1, 2
3, 4
3, 1
OUTPUTS
=======
- 'YES' or 'NO' depending on whether the graph is a DAG
and in the case it is a DAG...
- a linear ordering of the DAG
- the length of the longest path in the DAG starting from vertex 1
'''
def get_vertices():
'''
Used for user input of vertices.
'''
num_vertices = int(input('\nEnter number of vertices: '))
return [x for x in range(1, num_vertices + 1)]
def get_edges():
'''
Used for user input of edges.
'''
edges = set()
while True:
a = input('\nEnter value of edge: ')
if not a:
if not edges:
continue
break
edge = tuple([int(x.strip(',')) for x in a.split()])
edges.add(edge)
return edges
def bellman_ford(vertices, edges):
'''
Slight variation of Bellman Ford algorithm, subtracting edge weights instead of
adding them. In doing this, the longest path can be found, and if 'negative'
cycles are found using the negative versions of the edge weights in the last
loop, that means the graph is cyclic.
'''
dist = {}
prev = {}
for v in vertices:
dist[v] = 999999
prev[v] = None
s = 1 # assumes starting vertex is vertex number 1
dist[s] = 0
is_cyclic = False
for i in range(len(vertices) - 1):
for e in edges:
u, v = e[0], e[1]
if dist[v] > dist[u] - 1: # subtract 1 to get longest path (add for shortest)
dist[v] = dist[u] - 1
prev[v] = u
for e in edges:
u, v = e[0], e[1]
if dist[v] > dist[u] - 1:
is_cyclic = True
return dist, prev, is_cyclic
def get_linear_ordering(vertices, edges):
'''
To get linear ordering, find vertex with minimum number of outgoing edges, add it
to the list, remove it from the graph, then repeat (find a new vertex with the
minimum number of outgoing edges and so forth) until all vertices have been removed
from the graph.
'''
vertex_list = vertices.copy()
edge_list = edges.copy()
linear_ordering = []
while True:
adjacency_index = { v: 0 for v in vertex_list }
for (u, v) in edge_list:
adjacency_index[v] += 1
v_with_min_outgoing_edges = min(adjacency_index, key=adjacency_index.get)
linear_ordering.append(v_with_min_outgoing_edges)
vertex_list.remove(v_with_min_outgoing_edges)
edges_to_remove = []
for (u, v) in edge_list:
if v_with_min_outgoing_edges in (u, v):
edges_to_remove.append((u, v))
for (u, v) in edges_to_remove:
edge_list.remove((u, v))
if not vertex_list:
break
return linear_ordering
def find_longest_path(prev):
'''
Recursively finds the longest path using the prev dictionary returned from Bellman Ford
'''
def _find_path(val):
if val in [1, 999999, ]:
return [val]
if val is None:
return []
return _find_path(prev[val]) + [val]
longest_path = []
for i in range(len(prev), 0, -1):
if i not in longest_path:
path = _find_path(i)
if len(path) > len(longest_path) and path[0] == 1:
longest_path = path
return longest_path
if __name__ == '__main__':
print(instructions)
vertices = get_vertices()
edges = get_edges()
dist, prev, is_cyclic = bellman_ford(vertices, edges)
if is_cyclic:
print("\nNO")
exit()
else:
print("\nYES")
linear_ordering = get_linear_ordering(vertices, edges)
print('\nLinear ordering: ', linear_ordering)
path = find_longest_path(prev)
print('\nLongest path starting from vertex 1: {}'.format(path))
print('\nLength of longest path starting from vertex 1: {} vertices ({} edges)\n'.format(len(path), len(path) - 1))
|
import math
x = float(input("Ingrese valor de x: "))
cifras = float(input("Ingrese cuantas cifras significativas: "))
es = 0.5*(10**(2-cifras))
ea = es+1
n = 1
ant = x
while ea>es:
f = x
for i in range(1,(n+1)):
signo = (-1)**i
f += signo*round((x**((2*i)+1))/math.factorial((2*i)+1),6)
ea = round(abs((f-ant)/f)*100)
print('{:^10}{:^10}{:^10}'.format('Iteracion','x','error'))
print('{:^10}{:^10}{:^10}'.format(n,f,ea))
ant = f
n +=1
print("Respuesta: x=",f," con error de: ",ea) |
# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите
# у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = 15
b = a ** 2
print("a = ", a, "\na*a = ", b)
number1 = int(input("Введите первое число:"))
number2 = int(input("Введите второе число:"))
string1 = input("Введите первую строку:")
string2 = input("Введите вторую строку:")
print("Введенные значения:\n {} \n {} \n {} \n {}".format(number1, number2, string1, string2))
|
# 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
#
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# Необходимо предусмотреть условие его завершения.
#
# Например, в первом задании выводим целые числа, начиная с 3,
# а при достижении числа 10 завершаем цикл.
# Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
from itertools import count
try:
start = int(input('Введите стартовое число:'))
end = int(input('Введите конечное число:'))
except ValueError:
print('Не целое число!')
exit()
for el in count(start):
if el > end:
break
else:
print(el)
|
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты:
# name, surname, position (должность), income (доход).
# Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы:
# оклад и премия, например, {"wage": wage, "bonus": bonus}.
# Создать класс Position (должность) на базе класса Worker.
# В классе Position реализовать методы получения полного имени сотрудника (get_full_name)
# и дохода с учетом премии (get_total_income). Проверить работу примера на реальных данных
# (создать экземпляры класса Position, передать данные, проверить значения атрибутов, вызвать методы экземпляров).
class Worker:
def __init__(self, name, surname, position, wage, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = {"wage": wage, "bonus": bonus}
class Position(Worker):
def __init__(self, name, surname, position, wage, bonus):
super().__init__(name, surname, position, wage, bonus)
def get_full_name(self):
return f'ФИO: {self.surname} {self.name}'
def get_total_income(self):
return sum(self._income.values())
director = Position('Владимир Владимирович', 'Путин', 'Директор', 20000, 7000)
technick = Position('Иван Петрович', 'Иванов', 'Техник', 17000, 2000)
print(director.get_full_name())
print(f'Общий доход: {director.get_total_income()}')
print(technick.get_full_name())
print(f'Общий доход: {technick.get_total_income()}')
print(technick.position)
|
#
# @lc app=leetcode id=83 lang=python3
#
# [83] Remove Duplicates from Sorted List
#
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head and head.next:
head.next = self.deleteDuplicates(head.next)
return head.next if head.next.val == head.val else head
return head
# @lc code=end
|
# test_1
print("test_1:")
the_world_is_flat = True
if the_world_is_flat:
print("Be careful not to fall off!")
# test_2
print("test_2:")
# this is the first comment
spam = 1 # and this is the second comment
# ... and not a third!
text = "# This is not a comment because it's inside quotes."
if spam == 1:
print(text)
# test_3
print("test_3:")
sum = 5+5
print(sum)
result1 = 8 / 5
print(result1)
result2 = 17 / 3
print(result2)
# test_4
word = 'Pythonn'
print("test_4:")
print(word)
print(word[5])
print(word[-1])
print('\n')
# test_5
print("test_5:")
s = 'I love my country.'
print(s)
print("length:")
L = len(s)
print(L)
print('\n')
# test_6
# Fibonacci series:
# the sum of two elements defines the next
print("test_6")
a, b = 0, 1
while a < 10:
print(a)
a, b = b, a + b
# test_7
#print("test_7")
#a, b = 0, 1
#while a < 1000:
# print(a, end=',')
# a, b = b, a+b
|
def filp(s):
ret, n, ls = [], len(s), list(s)
for i in range(1, n):
if ls[i] == '+' and ls[i - 1] == '+':
ls[i] = ls[i - 1] = '-'
ret.append(''.join(ls))
ls[i] = ls[i - 1] = '+'
print ret
if __name__ == '__main__':
filp('++++')
|
'''
Load, Modify (Transform Color Image to GrayScale) and Save an Image.
'''
import cv2
# path of the image to load
img_path = 'my_images/Halloween.png'
# load the image
original_img = cv2.imread(img_path)
original_img = cv2.resize(original_img, (800, 800))
# Modify the image i.e tranform the image into grayscale
# cvtColor(src_img, dst_img, tranformation)
# tranformation - cv2.COLOR_BGR2GRAY
grayscale_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
# Create a window to display images
cv2.namedWindow("Original Image", cv2.WINDOW_AUTOSIZE)
cv2.namedWindow("Transformed Image", cv2.WINDOW_AUTOSIZE)
# Display Image
cv2.imshow("Original Image", original_img)
cv2.imshow("Transformed Image", grayscale_img)
cv2.waitKey(0)
# Save the GrayScale Image
cv2.imwrite("../images/gray.png", grayscale_img) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 10:25:09 2020
@author: tushar
"""
import numpy as np
True == 1 # Evaluates to True, similarly False is 0
'pyscript' == 'PyScript' # False
list1 = []
list2 = []
list3 = list1
list1 == list2 # True - values are same
list1 is list2 # False - object ids are not same
list1 == list3 and list1 is list3 # Both True
'abc' > 'bac' # False, since ord('a') < ord('b') [first characters]
'a' > 'b' # False for the reason above
'abc' < 'abcd' # True
'abc' > 'abcd' # False
'abc' == 'abcd' # False: when unequal size, return len(string1) < len(string2)
my_house = np.array([1,2,3,4])
your_house = np.array([4,3,2,1])
my_house > your_house # [F F T T]
np.logical_and(my_house>3, your_house<3) # F F F T
|
from collections import defaultdict
def count_subnode(index):
def DFS(now):
count = 1
if children1[now]:
count += DFS(children1[now])
if children2[now]:
count += DFS(children2[now])
return count
return DFS(index)
T = int(input())
for tc in range(1, T + 1):
E, N = map(int, input().split())
li = tuple(map(int, input().split()))
children1 = defaultdict(int)
children2 = defaultdict(int)
for i in range(0, len(li), 2):
parent = li[i]
child = li[i + 1]
if children1[parent]:
children2[parent] = child
else:
children1[parent] = child
print('#%d' % tc, count_subnode(N))
|
f = open('input.txt', 'r')
input = lambda: f.readline().rstrip()
class Node:
def __init__(self, value=None):
self.value = value
self.after = None
self.before = None
class DoubleLinkedList:
def __init__(self):
self.length = 0
self.head = self.tail = Node(0)
self.head.after = self.tail
self.head.before = self.head
def find(self, index):
now = self.head
for _ in range(index + 1):
now = now.after
return now
def connect(self, value):
self.length += 1
new = Node(value)
self.tail.after = new
new.before = self.tail
self.tail = new
def insert(self, index):
self.length += 1
left = self.find(index-1)
now = self.find(index)
if not left.value:
lval = self.head.after.value
else:
lval = left.value
if not now:
nval = self.head.after.value
else:
nval = now.value
new = Node(lval + nval)
new.after = now
new.before = left
left.after = new
if now:
now.before = new
else:
self.tail = new
def print_all(self):
string = ''
now = self.head.after
for _ in range(self.length):
string += str(now.value) + ' '
now = now.after
print(string)
def print_reverse(self):
string = ''
now = self.tail
for _ in range(min(10, self.length)):
string += str(now.value) + ' '
now = now.before
print(string)
T = int(input())
for tc in range(1, T + 1):
N, M, K = map(int, input().split())
l_list = DoubleLinkedList()
for value in map(int, input().split()):
l_list.connect(value)
index = 0
for _ in range(K):
index = (index + M)
if index > l_list.length:
index %= l_list.length
l_list.insert(index)
print('#%d'%tc,end=' ')
l_list.print_reverse()
|
#1717 집합의 표현
#####입력 모드
# 0 : txt모드 , 1: 제출용
INPUTMODE = 0
if not INPUTMODE:
f = open("input.txt","r")
input = lambda : f.readline().rstrip()
else:
import sys
input = lambda : sys.stdin.readline().rstrip()
################################
def findParent(e):
if e == parent[e]:
return e
else:
parent[e] = findParent(parent[e])
return parent[e]
def union(x, y):
x = findParent(x)
y = findParent(y)
if x != y:
if x > y:
parent[x] = y
else:
parent[y] = x
def isUnion(x, y):
x = findParent(x)
y = findParent(y)
if x == y:
return True
return False
n, m = map(int,input().split())
parent = [i for i in range(n+1)]
for _ in range(m):
move, a, b = map(int,input().split())
if move == 0:
union(a,b)
else:
if isUnion(a,b):
print('YES')
else:
print('NO')
|
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
def bfs(graph, start):
visited = []
queue = [start]
while queue:
n = queue.pop(0)
if n not in visited:
visited.append(n)
queue += graph[n] - set(visited)
#인접 노드들을 큐에 넣는 과정
return visited
def bfs_paths(graph, start, goal):
queue = [(start,[start])] #큐에는 (현재 노드, 밟아온 경로)를 저장
result = []
while queue:
n, path = queue.pop(0)
if n == goal:
# 현재 노드가 최종 목표라면 종료하고 result에 추가
result.append(path)
else:
for m in graph[n] - set(path):
#현재 노드와 인접한 노드 중 밟아온 노드를 제외한 노드를 선택
queue.append((m,path + [m]))
#지금까지 밟아 온 경로에 선택된 노드를 추가
print(queue)
return result
#print(bfs(graph, 'A'))
print(bfs_paths(graph,'A','F'))
|
"""
This file defines a foobotweb class for polling data out of the foobot for the user
making HTTP requests.
It implements login, logout first and then implements the different data extraction methods.
Author - bhanu13
Basic Authorization and X-AUTH-TOKEN
Time - Date ISO 8601
"""
import requests
import json
import time
import getpass
from datetime import tzinfo, timedelta, datetime
class FoobotWeb(object):
login_URL = ""
owner_URL = ""
device_URL = ""
headers = dict()
devicedata = dict()
def __init__(self, username = None):
if not username:
username = str(raw_input("Please enter your Foobot username:\n"))
self.username = username
print "Please enter your Foobot password"
self.password = getpass.getpass()
if self.login():
if self.deviceinfo():
print "Setup Complete"
def login(self):
self.login_URL = "https://api.foobot.io/v2/user/%s/login/" % self.username
r = requests.get(self.login_URL, auth=(self.username, self.password))
if r.status_code != requests.codes.ok:
print "Invalid Login Information."
return False
token = r.headers["X-AUTH-TOKEN"]
self.headers["X-AUTH-TOKEN"] = token
return True
def deviceinfo(self):
self.owner_URL = "https://api.foobot.io/v2/owner/%s/" % self.username
URL = self.owner_URL + "/device/"
r = requests.get(URL, headers = self.headers)
if r.status_code != requests.codes.ok:
print "Unable to get device info."
return False
self.devicedata = json.loads(r.content)
self.uuid = self.devicedata[0][u"uuid"]
print "Your user ID is %s" % self.uuid
self.device_URL = "https://api.foobot.io/v2/device/%s/" % str(self.uuid)
return True
def GetDatapointLast(self, period = 0, sampling = 0, save = False):
URL = self.device_URL + "datapoint/%s/last/%s/" % (period, sampling)
URL = str(URL)
r = requests.get(URL, headers = self.headers)
if r.status_code != requests.codes.ok:
print "Some Error in GetDatapointLast"
return None
data = json.loads(r.content)
# print data
file_name = 'data_%s_%s.json' % (period, sampling)
if save:
self.SaveData(name = file_name, data = data)
print data
return data
def GetLastHour(self, save = False):
data = self.GetDatapointLast(3600, 300)
if data and save:
starttime = data["start"]
starttime = datetime.fromtimestamp(starttime)
file_name = "last_hour" + starttime.isoformat()
self.SaveData(name = file_name, data = data)
def GetLastDay(self, save = False):
data = self.GetDatapointLast(86400, 3600)
if data and save:
starttime = data["start"]
starttime = datetime.fromtimestamp(starttime)
file_name = "last_day" + starttime.isoformat()
self.SaveData(name = file_name, data = data)
def GetDataInterval(self, starttime = datetime.now() - timedelta(minutes=-30), endtime = datetime.now(), sampling = 0, save = False):
starttime = self.formattime(starttime)
endtime = self.formattime(endtime)
URL = self.device_URL + "datapoint/%s/%s/%s/" % (starttime, endtime, sampling) # Get Method Works
print URL
r = requests.get(URL, headers = self.headers)
if r.status_code != requests.codes.ok:
print "Some Error in getting data for the given time interval"
return
data = json.loads(r.content)
print data
if save and data:
file_name = "data_from_%s_%s" % (starttime, endtime)
self.SaveData(name = file_name, data = data)
def formattime(self, time):
class TZ(tzinfo):
def utcoffset(self, dt):
return timedelta(minutes=+330) # For India
time = time.replace(tzinfo = TZ(), microsecond=0)
return time.isoformat('T')
def SaveData(self, name, data):
if name and data:
with open('data/%s.json' % name, 'w') as outfile:
json.dump(data, outfile)
# def GetDatapoints(self, start = None, end = None, sampling = 0):
# today == date.fromtimestamp(time.time())
|
def reverse(s):
str = ""
for i in s:
str=i+str
return str
string = "A man, a plan, a canal: Panama"
st = string.replace(" ", "")
t =st.casefold()
y=''
for x in t:
if(((x >="a")and(x<="z"))or('0'<=x <='9')):
y +=x
else:
continue
#print("String after removal of special characters is ::",y)
if (y==""):
print("string is empty")
str1 = reverse(y)
#print( "String after reverse function is :: ",str1)
if(y==str1):
print("String is palendrome ")
else:
print("String s not palendrome")
|
class Car:
def __init__(self, name):
self.name = name
def carname(self):
print('Hello, this car is manufactured by :: ', self.name)
p = Car('Maruti')
p.carname()
|
#function to remove all unwanted characters
def fun(line):
empty =""
# print(line)
for x in line:
if(((x >="a")and(x<="z"))or('0'<=x <='9')or(x>="A")and(x<="Z")):
empty +=x
else:
continue
return empty
#program starts Here
#Read a file line by line using readline() till we get "" or end of text
f1 = open("read" ,"r")
line = f1.readline()
while line != "":
# call fun function to check and remove all spaces and special characters
str = fun(line)
#reverse the string
string = str[::-1]
# print(str)
# print(string)
#check if the original string is equals to new reversed string
if(str.casefold()==string.casefold()):
print("String is palendrome" , str)
else:
print("string is not palendrome",str)
line = f1.readline()
|
val = str(input("Enter a word : "));
val1 =str(val[::-1]);
print("\n Reversed String =",val);
if val == val1:
print(val, "is palyndrome")
else:
print(val, "not palyndrome")
|
"""
Interface and implementation for hash functions.
"""
from abc import ABCMeta, abstractmethod
import mmh3
import random
class _Hash(object):
"""
Interface for Hash Object.
"""
@abstractmethod
def hash(self, key):
"""
Map the given key to an integer.
:param key: a hashable object
:return:
:rtype: int
"""
raise NotImplementedError('To be overwritten!')
class MurmurHash(_Hash):
"""
Murmur Hash Function.
"""
def __init__(self):
self._seed = random.randint(0, 1 << 31)
def hash(self, key):
"""
Return the hash value of key.
:param key: can be any hashable object
:return:
:rtype: int
"""
v = mmh3.hash(str(key.__hash__()), self._seed)
return -(v + 1) if v < 0 else v
|
def solution(arr1, arr2):
answer = []
row = len(arr1)
col = len(arr1[0])
for i in range(row):
ans = []
for j in range(col):
sum_ = arr1[i][j] + arr2[i][j]
ans.append(sum_)
answer.append(ans)
return answer
|
import math
def solution(n):
# answer = 0
# if math.sqrt(n) == int(math.sqrt(n)):
# return
return (math.sqrt(n) + 1) ** 2 if math.sqrt(n) == int(math.sqrt(n)) else -1
|
#Uses python3
import sys
import math
def distance(xi, yi, xj, yj):
return ((xi - xj)**2 + (yi - yj)**2)**0.5
def minimum_distance(vertices, adj, weight):
result = 0.
X = set()
X.add(0)
while len(X) != vertices:
minimum=float('inf')
for u in X:
for v in adj[u]:
if v not in X and weight[u][v] < minimum:
minimum = weight[u][v]
edge=v
result += minimum
X.add(edge)
return result
if __name__ == '__main__':
user_input = sys.stdin.read()
data = list(map(int, user_input.split()))
n = data[0]
x = data[1::2]
y = data[2::2]
adj = [[] for _ in range(n)]
weight = [[0] * n for _ in range(n)]
for i in range(n):
adj[i] = list(v for v in range(n) if v != i)
for j in range(n):
if i != j:
w = distance(x[i], y[i], x[j], y[j])
weight[i][j] = w
weight[j][i] = w
print("{0:.9f}".format(minimum_distance(n, adj, weight))) |
# python3
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise_product_fast(numbers):
n=len(numbers)
fir=0
sec=0
for first in range(n):
if fir<numbers[first]:
fir=numbers[first]
max_index=first
for second in range(n):
if sec<numbers[second] and second!=max_index:
sec=numbers[second]
return fir*sec
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product_fast(input_numbers))
|
import os
import random
# export=GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials
def synthesize_text(text, output_filename, output_dir, voice=None):
"""
Synthesizes speech from the input string of text.
Female voice = 0, Male voice = 1
output filename doesn't need extension
"""
from google.cloud import texttospeech_v1beta1 as texttospeech
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.types.SynthesisInput(text=text)
genders = (texttospeech.enums.SsmlVoiceGender.FEMALE, texttospeech.enums.SsmlVoiceGender.MALE)
if not voice:
gender = genders[random.randrange(0, 2)]
else:
gender = genders[voice]
# Note: the voice can also be specified by name.
# Names of voices can be retrieved with client.list_voices().
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
ssml_gender=gender)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = client.synthesize_speech(input_text, voice, audio_config)
# The response's audio_content is binary.
mp3_filepath = os.path.join(output_dir, "%s.mp3" % output_filename)
with open(mp3_filepath, 'wb') as out:
out.write(response.audio_content)
print('Audio content written to file %s' % mp3_filepath)
wav_name = os.path.join(output_dir, "%s.wav" % output_filename)
print('Audio content re-written to file %s' % wav_name)
os.system("mpg321 -w %s %s" % (wav_name, mp3_filepath))
print('Deleting mp3')
os.remove(mp3_filepath)
#synthesize_text('Welcome to the story collector. By dialing 8 you can record a new story that will be come a part of Redial. You will have one minute to record a first person story. Pretend that you are telling your story to a friend.', 'record', '/home/pi/Desktop/telephone-project/recordings/instructions')
synthesize_text('Welcome to Redial. This old phone houses personal stories that are told and retold by people, just like you! You will hear a story and then retell the story in your own words back to the phone. You can see how the stories change overtime by visiting retellproject.com. To get started, dial a number from one to eight to hear and retell a story. Dial nine to record your own story or leave a comment. Dial zero to here these instructions again.', 'operator', '/home/pi/Desktop/telephone-project/recordings/instructions')
#synthesize_text('Now retell the story in your own words while mantaining the first person perspective. Focus more on how the story teller felt and less on the specific words. Recording will start in 3, 2, 1.', 'retell', '/home/pi/Desktop/telephone-project/recordings/instructions')
#synthesize_text('You will hear a story and then retell the story. Story will start in 3, 2, 1.', 'listen', '/home/pi/Desktop/telephone-project/recordings/instructions')
|
import numpy as np
class InvalidReturnsException(Exception):
'''Exception thrown when initialized with invalid returns dict'''
pass
class Simulator(object):
'''Represents an object that runs simulations.'''
def __init__(self, returns, nrows, ncols, seed=0):
'''Constructor.
Args:
returns: a dict where the key is a tuple representing a range in [0, 1)
and the value is the return if the simulated random value is
within that range. All the ranges must completely cover [0, 1)
and be non-overlapping. Invalid returns dicts will throw an
InvalidReturnsException
nrows: the number of rows in the simulation array
ncols: the number of columns in the simulation array
seed: (optional) a seed for the random number generator
'''
self.returns = returns
try:
self.ranges = self.returns.keys()
self.ranges.sort(key=lambda rng: rng[0])
except AttributeError:
raise InvalidReturnsException("Could not set and sort ranges in returns.")
self._validate_returns()
self.nrows, self.ncols = nrows, ncols
# Initialize random seed
np.random.seed(seed)
def _validate_returns(self):
'''Validate the returns dict. Throws an InvalidReturnsException if
the ranges that are the keys overlap or do not completely cover the
interval [0, 1)
'''
for i in range(len(self.ranges) - 1):
if self.ranges[i][1] != self.ranges[i+1][0]:
raise InvalidReturnsException("Nonoverlapping ranges in returns")
if self.ranges[-1][1] != 1:
raise InvalidReturnsException("Last returns range must end in 1")
if self.ranges[0][0] != 0:
raise InvalidReturnsException("First return range must start with 0")
def run(self):
'''Run the simulation, returning the result'''
# Create a random array of trials, and an array of returns initialized to zero
trials = np.random.rand(self.nrows, self.ncols)
returns = np.zeros_like(trials)
# Go through each range specify the returns dict, and if the trial value is
# within that range, set the value of that trial's return to the return value
# of that range
for interval in self.ranges:
returns[np.logical_and(trials >= interval[0], trials < interval[1])] = self.returns[interval]
return returns
|
import sys
import numpy as np
''' Asks the user to input a valid list of positions. '''
def get_positions():
try:
pos_input = raw_input('Please provide a list of positions, select from 1, 10, 100, 1000.')
pos_input = pos_input.replace(' ', '')
except (KeyboardInterrupt,EOFError):
sys.exit()
if (pos_input == 'quit' or pos_input == 'Quit' or pos_input == 'q' or pos_input == 'QUIT'):
sys.exit()
try:
return get_list(pos_input)
except (InvalidListException, InvalidIntegerException):
print("Invalid input - please input positive integers and format your input into a list. ")
return get_positions()
except InvalidPositionException:
print("Positions can only be chosen from 1, 10, 100, or 1000")
return get_positions()
''' Asks the user to input the number of trials. '''
def get_num_trials():
try:
num_trials_input=raw_input('Please input the number of trials of simulations. ')
num_trials_input=num_trials_input.replace(' ', '')
except (KeyboardInterrupt,EOFError):
sys.exit()
if (pos_input == 'quit' or pos_input == 'Quit' or pos_input == 'q' or pos_input == 'QUIT'):
sys.exit()
try:
return get_int(num_trials_input)
except InvalidIntegerException:
print("The input must be a positive integer")
return get_num_trials()
''' Check if a position in user's input list of is valid. '''
def get_position(pos):
if pos.isdigit():
if (int(pos) == 1 or int(pos) == 10 or int(pos) == 100 or int(pos) == 1000):
return int(pos)
else:
raise InvalidPositionException()
else:
raise InvalidIntegerException()
''' Get an integer from the input. '''
def get_int(input_str):
if input_str.isdigit():
return int(input_str)
else:
raise InvalidIntegerException()
''' Out of the input string, Create a list of positive integers separated by commas. '''
def get_list(input_str):
input_list = []
if input_str[0] == '[' and input_str[-1] == ']':
input_str = input_str.replace(' ', '')
input_str = input_str[1:-1]
input_str_split = input_str.split(',')
for int_str in input_str_split:
buff = get_position(int_str)
input_list.append(buff)
return input_list
else:
raise InvalidListException()
class InvalidPositionException(Exception):
def __str__(self):
return 'The positions in the list must be 1, 10, 100, or 1000.'
# Gives a warning when the input is not a executable position.
class InvalidListException(Exception):
def __str__(self):
return 'Please format your input into a list.'
# Gives a warning when the input is not formatted as a list
class InvalidIntegerException(Exception):
def __str__(self):
return 'This input list should contain positive integers only.'
# Gives a warning when the input contains other datatypes.
|
"""defines an investment class, an instance of which consists of the number of positions to take within the given investment amount, along with a probability of the amount being lost in a single day of trading.
Also contains a member method which simulates a single day of trading on our investment and returns the outcome"""
import numpy as np
class investment:
def __init__(self,investment_amount,position,pr_lose):
self.numShares = position
self.position_value = investment_amount/position
self.pr_lose = pr_lose
def simulate_day(self):
"""simulate a single day of trading on an instance of an investment"""
outcome=0
rands = np.random.random_sample(self.numShares)
#determine outcome of each share in our position and take the sum of all outcomes
for share in range(0,self.numShares):
if rands[share] >= self.pr_lose:
outcome += 2*self.position_value
return outcome
|
"""
This module is the main program of hw8. It mainly deal with the user input and call
other modules to generate the results
"""
import numpy as np
import math
import matplotlib.pyplot as plt
from user_defined_exceptions import *
from user_input_class import *
import make_investment_class
#author: Muhe Xie
#netID: mx419
#date: 11/01/2015
def start_investment():
'''This function will read the input of user and call related modules to calculate and output the investment result'''
while True:
try:
print "Please Enter a list of positions (input should like [1,10,100,1000] or any subset of the list, do not input repeated number), enter \'quit\' to exit:"
str_list_input = raw_input()
if str_list_input == "quit": #quit the program
print "Goodbye"
return
if str_list_input == "": #test empty input
raise Empty_Input_Error
position_list_object = User_Input_String(str_list_input) #use user input class to deal with the user input
#list of positions
positions_list = position_list_object.get_positions()
#list of position values
positions_value_list = position_list_object.get_position_values()
break
except Empty_Input_Error:
print "The input is empty, please re-enter the list"
except Input_Format_Error:
print "The input format is wrong, please re-enter the list"
except Repeated_Number_Error:
print "Repeated numbers, please re-enter the list"
except Invalid_Input_Error:
print "The input number is not valid, please re-enter the list"
while True:
try:
print "Please Enter the number of trials, i.e. 10000(recommended) enter \'quit\' to exit:"
num_trial_input = raw_input()
if num_trial_input == "quit": #quit the program
print "Goodbye"
return
if not re.match(r"\s*[0-9]+\s*",num_trial_input):
raise Input_Format_Error
if num_trial_input == "": #test empty input
raise Empty_Input_Error
if int(num_trial_input) == 0:
raise Zero_Input_Error
num_trial = int(num_trial_input)
break
except Empty_Input_Error:
print "The input is empty, please re-enter the list"
except Input_Format_Error:
print "The input format is wrong, please re-enter the list"
except Zero_Input_Error:
print "The input is 0, please re-enter the list"
#create an instance of make_single_day_investment to do the experiment
execute_investment = make_investment_class.make_single_day_inverstment(positions_list, positions_value_list, num_trial)
print "please wait..."
#this function will generate the final results, include the pdfs and the results.txt
execute_investment.generate_result_of_n_trials()
print "Congratulations! the results are saved succeffully, thanks for trying ,bye"
if __name__ == "__main__":
try:
start_investment()
except KeyboardInterrupt:
print "the program has been interrupted by KeyboardInterrupt, thanks for trying,Goodbye"
except EOFError:
print "the program has been interrupted by EOFERROR, thanks for trying, Goodbye"
except TypeError:
print "the program has been interrupted by TypeError, thanks for trying, Goodbye"
except OverflowError:
print "the program has been interrupted by OverflowError, thanks for trying, Goodbye"
|
import numpy as np
class Simulation():
'''
class Simulation takes inputs postions, num_trials, and budget. It also has
a function investment
'''
def __init__(self, positions, num_trials, budget):
self.positions = positions
self.num_trials = num_trials
if budget >= 0:
self.budget = budget
else:
raise ValueError('budget cannot be negative')
# A function used to calculate the outcome of the investment for each day
def investment(self):
daily_ret = []
for position in self.positions:
position_value = self.budget / position
cumu_ret = []
for trial in range(self.num_trials):
# number of 1s, representing the number of times we gain.
revenue_numbers = (np.random.choice([0, 1], size = position, p = [0.49, 0.51])).sum()
cumu_ret.append(revenue_numbers*position_value*2)
daily = [(cumu/float(self.budget)) - 1 for cumu in cumu_ret] # calculate daily returns
daily_ret.append(daily)
return daily_ret
|
'''
Created on Nov 7, 2015
@author: jj1745
'''
import sys
from simulation import writeResult, plotResult
class InvalidNumTrialsException(Exception):
'''exception of invalid num_trials input'''
def __str__(self):
return 'Your input of num_trials is not valid'
class NonPositiveException(Exception):
def __str__(self):
return 'Your input is not a positive integer'
class InvalidPositionsException(Exception):
'''exception of invalid positions input'''
def __str__(self):
return 'Your input of positions is not valid'
def getTrials(input):
'''
covert user input into a integer for num_trials
'''
if input.isdigit():
n = int(input)
if n <= 0:
raise NonPositiveException() #input must be a positive integer
else:
return n
else:
raise InvalidNumTrialsException()
def checkPositions(input_list):
'''
check if the entered positions is correct
it can only be [1,10,100,1000] (no whitespace)
'''
if input_list == '[1,10,100,1000]':
return True
else:
raise InvalidPositionsException()
def getPositions(input_list):
'''
given that the input_list is valid: [1,10,100,1000],
convert it into a list of integers
'''
output = []
stripped = input_list[1:-1]
value_list = stripped.split(',')
for v in value_list:
output.append(int(v)) #output a list of integers
return output
def obtainPositionsFromUser():
'''
Ask inputs from user for a list of positions
The user must enter [1,10,100,1000]. Otherwise it will ask again
'''
try:
text = raw_input('PLease enter a list of positions, e.g. [1,10,100,1000]. No whitespace allowed')
if checkPositions(text):
return getPositions(text)
except InvalidPositionsException:
print 'Please enter a valid list of positions'
obtainPositionsFromUser() #recursively call this function if user input is not valid
except (EOFError, KeyboardInterrupt):
sys.exit()
def obtainTrialsFromUser():
'''
Ask inputs from user for num_trials
The user must enter a positive integer. Otherwise it will ask again
'''
try:
text = raw_input('PLease enter the number of trials. It should be a positive integer')
return getTrials(text)
except InvalidNumTrialsException:
print 'Please enter a valid number'
obtainTrialsFromUser() #call the function recursively if input is not valid
except NonPositiveException:
print 'Please enter a positive integer'
obtainTrialsFromUser()
except (EOFError, KeyboardInterrupt):
sys.exit()
if __name__ == '__main__':
positions = obtainPositionsFromUser()
num_trials = obtainTrialsFromUser()
writeResult(positions, num_trials)
plotResult(positions,num_trials)
print 'Your simulation results have been saved. Thanks!'
|
import numpy as np
#import Simulation
import Exceptions as x
import sys
class Interface:
'''
class to take in data from user. Handles exceptions by trying to get input from user until it is good input
'''
def __init__(self):
self.numTrial=10000
self.pos=[]
def getPositions(self):
'''
sets class variable array pos to the input of the user. Input must be seperated by commas, each entry must divide 1000. Prompt is given to enter input until a valid input is given.
Type exit or quit to exit program.
'''
allGoodNumbers=False
userInput=""
numbers=[]
while not allGoodNumbers:
allGoodNumbers=True
try:
userInput = raw_input("Enter your positions, seperated by a comma: ")
except (KeyboardInterrupt,EOFError):
sys.exit()
if userInput=="quit" or userInput=="Quit" or userInput == "exit" or userInput =="Exit":
sys.exit()
numbers= userInput.split(",")
for number in numbers:
try:
if (int(number) >1000 or int(number)<1 ):
raise x.BadBounds
number=int(number)
except x.BadBounds:
print "Entry must be between 1 and 1000"
allGoodNumbers=False
except ValueError:
print "Not a number! Try again!"
allGoodNumbers=False
if allGoodNumbers:
if not 1000%int(number)==0:
print "positions must divide evenly into 1000"
allGoodNumbers=False
self.pos = [int(numeric_string) for numeric_string in numbers]
def getNumTrials(self):
'''
Takes input from user until it is valid. Valid input is positive whole numbers
'''
allGood=False
while not allGood:
allGood=True
try:
userInput = raw_input("how many trials do you want to run: ")
except (KeyboardInterrupt,EOFError):
sys.exit()
if userInput=="quit" or userInput=="Quit" or userInput == "exit" or userInput =="Exit":
sys.exit()
try:
a= int(userInput)/1.
if int(userInput)<0:
raise ValueError
except ValueError :
print "Must be positive number"
allGood=False
except:
print "Must be a whole number"
allGood=False
self.numTrial= int(userInput)
return int(userInput)
|
from __future__ import division
import numpy as np
import random
# DS-GA 1007
# HW8
# Author: Sida Ye
class Investment_account(object):
"""
Class Investment_account takes input purchase_value. It also has
a method invest_sim to simulate the daily return based on position
and number of trials.
"""
def __init__(self, purchase_value):
if purchase_value >= 0:
self.purchase_value = purchase_value
else:
raise ValueError('Value must be greater than 0!')
def invest_sim(self, position, num_trials):
position_value = self.purchase_value / position
cumu_ret = []
for trial in range(num_trials):
gain = sum(np.random.uniform(0, 1, size=position) > 0.49) # number of random variable which is greater than 0.49
cumu_ret.append(position_value * gain * 2)
daily_ret = [(ret/self.purchase_value)-1 for ret in cumu_ret] # calculate the daily return
return daily_ret
|
'''author: Siyi Xie(sx444)'''
'''This is the main program to accept the input from users and call other modules to properly generate the results'''
import numpy as np
import matplotlib.pyplot as plt
import investment_simulation
from user_defined_exceptions import *
import re
def conduct_simulation():
'''this is to accept the input from the user, call other modules to generate the outputs'''
while True:
try:
# accept the positions input from the user
positions_str = raw_input("You can choose the positions: (example: [1, 10, 100, 1000])")
if positions_str == 'quit':
return
if positions_str == '':
raise Empty_Input_Error
break
except Empty_Input_Error:
continue
while True:
try:
# accept the number of trials input from the user
num_trials = raw_input("how many times to randomly repeat the test? (example: 10,000)")
if num_trials == 'quit':
return
if num_trials == '':
raise Empty_Input_Error
break
except Empty_Input_Error:
continue
simulate = investment_simulation.simulation(positions_str, num_trials)
simulate.repeat_and_present()
if __name__ == "__main__":
try:
conduct_simulation()
except KeyboardInterrupt:
pass
except EOFError:
pass
except TypeError:
pass
|
import numpy as np
import sys
class Investment(object):
'''this class includes the functions and initialization method for the
list of positions and number of simulations that will be input by the user'''
def __init__(self, positions, num_trials):
'''Initializes the position list and number of simulations'''
self.positions = positions
self.position_vals = []
self.num_trials = num_trials
try:
self.num_trials = int(num_trials)
except:
raise TypeError
else:
if self.num_trials <= 0:
raise ValueError
for i in self.positions:
self.position_vals.append(int(i)/1000)
def generate_outcome(self, pos_val):
'''generates the outcome of betting a total of $1000, given a position value
ie. if the position value is 1, it generates the outcome of making
1000 bets of $1'''
num_shares = 1000/pos_val
n = 0
sum = 0
while n < num_shares:
'''x represents a random number between 0 and 1, which simulates the
probability measure that the user wins the bet or loses the bet, based
on the value of x'''
x = np.random.random_sample()
if x >= 0.51:
sum = sum + (pos_val*2)
n = n + 1
return sum
def repeat_investment(self, pos_val):
'''this function inputs a position value, and outputs a list of the return
for each simulation (num_trials)'''
position = 1000/pos_val
daily_ret = []
n = 0
while n< self.num_trials:
daily_ret.append((self.generate_outcome(pos_val)/1000.) - 1)
n = n + 1
return daily_ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.